From python-3000-checkins at python.org Tue Apr 1 08:17:46 2008 From: python-3000-checkins at python.org (martin.v.loewis) Date: Tue, 1 Apr 2008 08:17:46 +0200 (CEST) Subject: [Python-3000-checkins] r62086 - in python/branches/py3k: Lib/lib2to3 Lib/lib2to3/tests/test_fixers.py Lib/test/test_mmap.py Message-ID: <20080401061746.DA6261E4006@bag.python.org> Author: martin.v.loewis Date: Tue Apr 1 08:17:46 2008 New Revision: 62086 Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/lib2to3/ (props changed) python/branches/py3k/Lib/lib2to3/tests/test_fixers.py python/branches/py3k/Lib/test/test_mmap.py Log: Merged revisions 61440-61441,61443,61445-61448,61451-61452,61455-61457,61459-61464,61466-61467,61469-61470,61476-61477,61479,61481-61482,61485,61487,61490,61493-61494,61497,61499-61502,61505-61506,61508,61511-61514,61519,61521-61522,61530-61531,61533-61537,61541-61555,61557-61558,61561-61562,61566-61569,61572-61574,61578-61579,61583-61584,61588-61589,61592,61594,61598-61601,61603-61604,61607-61612,61617,61619-61620,61624,61626,61628-61630,61635-61638,61640-61643,61645,61648,61653-61655,61659-61662,61664,61666,61668-61671,61673,61675,61679-61680,61682,61685-61686,61689-61695,61697-61699,61701-61703,61706,61710,61713,61717,61723,61726-61730,61736,61738,61740,61742,61745-61752,61754-61760,61762-61764,61768,61770-61772,61774-61775,61784-61787,61789-61792,61794-61795,61797-61806,61808-61809,61811-61812,61814-61819,61824,61826-61833,61835-61840,61843-61845,61848,61850,61854-61862,61865-61866,61868,61872-61873,61876-61877,61883-61888,61890-61891,61893-61899,61901-61903,61905-61912,61914,61917,61920-61921,61927,61930,61932-61934,61939,61941-61942,61944-61951,61955,61960-61963,61980,61982-61983,61991,61994-61996,62001-62003,62008-62010,62016-62017,62022,62024,62027,62031-62034,62041,62045-62046,62055-62058,62060-62066,62068-62074,62076-62085 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ................ r62080 | martin.v.loewis | 2008-03-31 07:20:55 +0200 (Mo, 31 M?r 2008) | 9 lines Merged revisions 61990-62079 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r62017 | david.wolever | 2008-03-28 21:54:37 +0100 (Fr, 28 M?r 2008) | 1 line Fixed an out-of-date comment. ........ ................ r62084 | benjamin.peterson | 2008-03-31 23:57:13 +0200 (Mo, 31 M?r 2008) | 2 lines PyErr_Warn is decrepated. Use PyErr_WarnEx ................ r62085 | neal.norwitz | 2008-04-01 07:40:43 +0200 (Di, 01 Apr 2008) | 4 lines Be sure to close the file. 2 places were deleting the file, so it was probably fine, but the last change may be required for the test to pass on Windows. Should we always close the mmap too? ................ Modified: python/branches/py3k/Lib/lib2to3/tests/test_fixers.py ============================================================================== --- python/branches/py3k/Lib/lib2to3/tests/test_fixers.py (original) +++ python/branches/py3k/Lib/lib2to3/tests/test_fixers.py Tue Apr 1 08:17:46 2008 @@ -3139,7 +3139,7 @@ def setUp(self): FixerTestCase.setUp(self) - # Need to replace fix_import's isfile and isdir method + # Need to replace fix_import's exists method # so we can check that it's doing the right thing self.files_checked = [] self.always_exists = True Modified: python/branches/py3k/Lib/test/test_mmap.py ============================================================================== --- python/branches/py3k/Lib/test/test_mmap.py (original) +++ python/branches/py3k/Lib/test/test_mmap.py Tue Apr 1 08:17:46 2008 @@ -158,6 +158,7 @@ pass else: self.fail("Able to resize readonly memory map") + f.close() del m, f self.assertEqual(open(TESTFN, "rb").read(), b'a'*mapsize, "Readonly memory map data file was modified") @@ -214,6 +215,7 @@ "Copy-on-write test data file should not be modified.") # Ensuring copy-on-write maps cannot be resized self.assertRaises(TypeError, m.resize, 2*mapsize) + f.close() del m, f # Ensuring invalid access parameter raises exception @@ -433,7 +435,7 @@ f = open(TESTFN, "rb") m = mmap.mmap(f.fileno(), mapsize, prot=mmap.PROT_READ) self.assertRaises(TypeError, m.write, "foo") - + f.close() def test_error(self): self.assert_(issubclass(mmap.error, EnvironmentError)) From python-3000-checkins at python.org Tue Apr 1 09:37:59 2008 From: python-3000-checkins at python.org (neal.norwitz) Date: Tue, 1 Apr 2008 09:37:59 +0200 (CEST) Subject: [Python-3000-checkins] r62087 - python/branches/py3k/Modules/itertoolsmodule.c Message-ID: <20080401073759.3DEE11E4007@bag.python.org> Author: neal.norwitz Date: Tue Apr 1 09:37:58 2008 New Revision: 62087 Modified: python/branches/py3k/Modules/itertoolsmodule.c Log: Fix a refleak Modified: python/branches/py3k/Modules/itertoolsmodule.c ============================================================================== --- python/branches/py3k/Modules/itertoolsmodule.c (original) +++ python/branches/py3k/Modules/itertoolsmodule.c Tue Apr 1 09:37:58 2008 @@ -2133,7 +2133,7 @@ if (robj != Py_None) { if (!PyLong_Check(robj)) { PyErr_SetString(PyExc_TypeError, "Expected int as r"); - return NULL; + goto error; } r = PyLong_AsSsize_t(robj); if (r == -1 && PyErr_Occurred()) From python-3000-checkins at python.org Tue Apr 1 09:38:42 2008 From: python-3000-checkins at python.org (neal.norwitz) Date: Tue, 1 Apr 2008 09:38:42 +0200 (CEST) Subject: [Python-3000-checkins] r62088 - python/branches/py3k/Lib/test/test_xmlrpc_net.py Message-ID: <20080401073842.374511E4007@bag.python.org> Author: neal.norwitz Date: Tue Apr 1 09:38:41 2008 New Revision: 62088 Modified: python/branches/py3k/Lib/test/test_xmlrpc_net.py Log: Be more forgiving if we get an error, there are lots of potential socket errors Modified: python/branches/py3k/Lib/test/test_xmlrpc_net.py ============================================================================== --- python/branches/py3k/Lib/test/test_xmlrpc_net.py (original) +++ python/branches/py3k/Lib/test/test_xmlrpc_net.py Tue Apr 1 09:38:41 2008 @@ -17,9 +17,7 @@ try: t0 = server.currentTime.getCurrentTime() except socket.error as e: - if e.errno != errno.ECONNRESET: - raise - print(" test_current_time: socket got reset, skipping test", + print(" test_current_time: skipping test, got error: %s" % e, file=sys.stderr) return From python-3000-checkins at python.org Tue Apr 1 10:08:09 2008 From: python-3000-checkins at python.org (neal.norwitz) Date: Tue, 1 Apr 2008 10:08:09 +0200 (CEST) Subject: [Python-3000-checkins] r62089 - python/branches/py3k/Python/compile.c Message-ID: <20080401080809.96EA51E401B@bag.python.org> Author: neal.norwitz Date: Tue Apr 1 10:08:09 2008 New Revision: 62089 Modified: python/branches/py3k/Python/compile.c Log: Fix refleak with nested classes. Fix originally by Amaury in r62015. Modified: python/branches/py3k/Python/compile.c ============================================================================== --- python/branches/py3k/Python/compile.c (original) +++ python/branches/py3k/Python/compile.c Tue Apr 1 10:08:09 2008 @@ -1551,6 +1551,7 @@ { /* use the class name for name mangling */ Py_INCREF(s->v.ClassDef.name); + Py_XDECREF(c->u->u_private); c->u->u_private = s->v.ClassDef.name; /* force it to have one mandatory argument */ c->u->u_argcount = 1; From python-3000-checkins at python.org Tue Apr 1 23:23:34 2008 From: python-3000-checkins at python.org (amaury.forgeotdarc) Date: Tue, 1 Apr 2008 23:23:34 +0200 (CEST) Subject: [Python-3000-checkins] r62093 - python/branches/py3k/Lib/test/test_queue.py Message-ID: <20080401212334.CEE341E4004@bag.python.org> Author: amaury.forgeotdarc Date: Tue Apr 1 23:23:34 2008 New Revision: 62093 Modified: python/branches/py3k/Lib/test/test_queue.py Log: Prevent test_queue from leaking: one worker thread was not stopped. The version in trunk/ is correct; the problem with 3.0 is that None cannot be used as a marker in a PriorityQueue, because it cannot be compared with ints. Modified: python/branches/py3k/Lib/test/test_queue.py ============================================================================== --- python/branches/py3k/Lib/test/test_queue.py (original) +++ python/branches/py3k/Lib/test/test_queue.py Tue Apr 1 23:23:34 2008 @@ -144,7 +144,7 @@ def worker(self, q): while True: x = q.get() - if x is None: + if x < 0: q.task_done() return with self.cumlock: @@ -160,7 +160,8 @@ q.join() self.assertEquals(self.cum, sum(range(100)), "q.join() did not block until all tasks were done") - q.put(None) # instruct the threads to close + for i in (0,1): + q.put(-1) # instruct the threads to close q.join() # verify that you can join twice def test_queue_task_done(self): From python-3000-checkins at python.org Wed Apr 2 04:27:22 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Wed, 2 Apr 2008 04:27:22 +0200 (CEST) Subject: [Python-3000-checkins] r62101 - python/branches/py3k Message-ID: <20080402022722.72B7D1E4004@bag.python.org> Author: benjamin.peterson Date: Wed Apr 2 04:27:22 2008 New Revision: 62101 Modified: python/branches/py3k/ (props changed) Log: Blocked revisions 62095,62099 via svnmerge ........ r62095 | amaury.forgeotdarc | 2008-04-01 17:37:33 -0500 (Tue, 01 Apr 2008) | 5 lines Fix and enable a skipped test: with python 2.6, enumerating bytes yields 1-char strings, not numbers. Don't merge this into the py3k branch. ........ r62099 | amaury.forgeotdarc | 2008-04-01 19:25:14 -0500 (Tue, 01 Apr 2008) | 14 lines Correct the apparent refleak in test_io: When cls is an ABCMeta, every call to isinstance(x, cls) records type(x) in the cls._abc_cache of cls_abc_negative_cache. So we clear these caches at the end of the test. inspect.isabstract() is not the correct test for all ABCs, because there is no @abstractmethod in io.py (why?) isinstance(cls, ABCMeta) would be more exact, but it fails with an infinite recursion. So I used a hack to determine whether a class is an ABCMeta. The true correction would be to turn cls._abc_cache &co into a WeakSet, as py3k does. But classic classes are not weak referenceable... Of course, this change should not be merged into the py3k branch. ........ From python-3000-checkins at python.org Wed Apr 2 09:06:15 2008 From: python-3000-checkins at python.org (neal.norwitz) Date: Wed, 2 Apr 2008 09:06:15 +0200 (CEST) Subject: [Python-3000-checkins] r62104 - python/branches/py3k Message-ID: <20080402070615.C30141E4027@bag.python.org> Author: neal.norwitz Date: Wed Apr 2 09:06:14 2008 New Revision: 62104 Modified: python/branches/py3k/ (props changed) Log: Blocked revisions 62103 via svnmerge ........ r62103 | neal.norwitz | 2008-04-01 22:54:27 -0700 (Tue, 01 Apr 2008) | 3 lines Apply same patch from 3k branch to try and prevent this test from hanging on various platforms, most recently the Alpha Tru64. ........ From python-3000-checkins at python.org Wed Apr 2 17:06:49 2008 From: python-3000-checkins at python.org (trent.nelson) Date: Wed, 2 Apr 2008 17:06:49 +0200 (CEST) Subject: [Python-3000-checkins] r62106 - in python/branches/py3k: PCbuild/readme.txt Message-ID: <20080402150649.EEC981E4004@bag.python.org> Author: trent.nelson Date: Wed Apr 2 17:06:49 2008 New Revision: 62106 Modified: python/branches/py3k/ (props changed) python/branches/py3k/PCbuild/readme.txt Log: Merged revisions 62105 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62105 | trent.nelson | 2008-04-02 16:01:00 +0100 (Wed, 02 Apr 2008) | 1 line Update information pertaining to building external components, as well as notes on x64 builds. This file now accurately describes the build process as is; however, there's still a lot of room for improvement, especially with regards to how we build Tcl/Tk, Tix, and OpenSSL. Watch this space for further improvements. ........ Modified: python/branches/py3k/PCbuild/readme.txt ============================================================================== --- python/branches/py3k/PCbuild/readme.txt (original) +++ python/branches/py3k/PCbuild/readme.txt Wed Apr 2 17:06:49 2008 @@ -1,10 +1,17 @@ Building Python using VC++ 9.0 ------------------------------ -This directory is used to build Python for Win32 platforms, e.g. Windows -2000, XP and Vista. It requires Microsoft Visual C++ 9.0 -(a.k.a. Visual Studio .NET 2008). -(For other Windows platforms and compilers, see ../PC/readme.txt.) +This directory is used to build Python for Win32 and x64 platforms, e.g. +Windows 2000, XP, Vista and Windows Server 2008. In order to build 32-bit +debug and release executables, Microsoft Visual C++ 2008 Express Edition is +required at the very least. In order to build 64-bit debug and release +executables, Visual Studio 2008 Standard Edition is required at the very +least. In order to build all of the above, as well as generate release builds +that make use of Profile Guided Optimisation (PG0), Visual Studio 2008 +Professional Edition is required at the very least. The official Python +releases are built with this version of Visual Studio. + +For other Windows platforms and compilers, see ../PC/readme.txt. All you need to do is open the workspace "pcbuild.sln" in Visual Studio, select the desired combination of configuration and platform and eventually @@ -59,7 +66,7 @@ are linked to a CRT "side by side" assembly which must be present on the target machine. This is avalible under the VC/Redist folder of your visual studio distribution. On XP and later operating systems that support -side-by-side assemblies it is not enough to have the msvcrt80.dll present, +side-by-side assemblies it is not enough to have the msvcrt90.dll present, it has to be there as a whole assembly, that is, a folder with the .dll and a .manifest. Also, a check is made for the correct version. Therefore, one should distribute this assembly with the dlls, and keep @@ -95,79 +102,19 @@ winsound play sounds (typically .wav files) under Windows -The following subprojects will generally NOT build out of the box. They -wrap code Python doesn't control, and you'll need to download the base -packages first and unpack them into siblings of PCbuilds's parent -directory; for example, if your PCbuild is ..\dist\py3k\PCbuild\, -unpack into new subdirectories of ..\dist\. - +Python-controlled subprojects that wrap external projects: +_bsddb + Wraps Berkeley DB 4.4.20, which is currently built by _bsddb44.vcproj. + project (see below). +_sqlite3 + Wraps SQLite 3.3.4, which is currently built by sqlite3.vcproj (see below). _tkinter - Python wrapper for the Tk windowing system. Requires building - Tcl/Tk first. Following are instructions for Tcl/Tk 8.4.16. - - NOTE: The 64 build builds must land in tcltk64 instead of tcltk. - - Get source - ---------- - In the dist directory, run - svn export http://svn.python.org/projects/external/tcl8.4.16 - svn export http://svn.python.org/projects/external/tk8.4.16 - svn export http://svn.python.org/projects/external/tix-8.4.0 - - Build with build_tkinter.py - --------------------------- - The PCbuild directory contains a Python script which automates all - steps. Run the script in a Visual Studio 2008 command prompt with - - python build_tkinter.py Win32 - - Use x64 instead of Win32 for the x64 platform. - - NOTE: Tcl/Tk 8.4 doesn't compile for x64. - - Build Tcl first - --------------- - Use "Start -> All Programs -> Microsoft Visual Studio 2008 - -> Visual Studio Tools -> Visual Studio 2008 Command Prompt" - to get a shell window with the correct environment settings - cd dist\tcl8.4.16\win - nmake -f makefile.vc - nmake -f makefile.vc INSTALLDIR=..\..\tcltk install - - XXX Should we compile with OPTS=threads? - - Optional: run tests, via - nmake -f makefile.vc test - - On WinXP Pro, wholly up to date as of 30-Aug-2004: - all.tcl: Total 10678 Passed 9969 Skipped 709 Failed 0 - Sourced 129 Test Files. - - Build Tk - -------- - cd dist\tk8.4.16\win - nmake -f makefile.vc TCLDIR=..\..\tcl8.4.16 - nmake -f makefile.vc TCLDIR=..\..\tcl8.4.16 INSTALLDIR=..\..\tcltk install - - XXX Should we compile with OPTS=threads? - - XXX Our installer copies a lot of stuff out of the Tcl/Tk install - XXX directory. Is all of that really needed for Python use of Tcl/Tk? - - Optional: run tests, via - nmake -f makefile.vc TCLDIR=..\..\tcl8.4.16 test - - On WinXP Pro, wholly up to date as of 30-Aug-2004: - all.tcl: Total 8420 Passed 6826 Skipped 1581 Failed 13 - Sourced 91 Test Files. - Files with failing tests: canvImg.test scrollbar.test textWind.test winWm.test - - Built Tix - --------- - cd dist\tix-8.4.0\win - nmake -f python9.mak - nmake -f python9.mak install - + Wraps the Tk windowing system. Unlike _bsddb and _sqlite3, there's no + corresponding tcltk.vcproj-type project that builds Tcl/Tk from vcproj's + within our pcbuild.sln, which means this module expects to find a + pre-built Tcl/Tk in either ..\..\tcltk for 32-bit or ..\..\tcltk64 for + 64-bit (relative to this directory). See below for instructions to build + Tcl/Tk. bz2 Python wrapper for the libbz2 compression library. Homepage http://sources.redhat.com/bzip2/ @@ -176,6 +123,10 @@ svn export http://svn.python.org/projects/external/bzip2-1.0.3 + ** NOTE: if you use the Tools\buildbot\external(-amd64).bat approach for + obtaining external sources then you don't need to manually get the source + above via subversion. ** + A custom pre-link step in the bz2 project settings should manage to build bzip2-1.0.3\libbz2.lib by magic before bz2.pyd (or bz2_d.pyd) is linked in PCbuild\. @@ -186,63 +137,6 @@ All of this managed to build libbz2.lib in bzip2-1.0.3\$platform-$configuration\, which the Python project links in. - -_bsddb - To use the version of bsddb that Python is built with by default, invoke - (in the dist directory) - - svn export http://svn.python.org/projects/external/db-4.4.20 - - Next open the solution file db-4.4.20\build_win32\Berkeley_DB.sln with - Visual Studio and convert the projects to the new format. VS 2008 - builds the necessary libraries in a pre-link step of _bsddb. You - have to add "$(VCInstallDir)vcpackages" to the search path first - (Tools -> Options -> Projects and Solutions -> VC++ Directories, - Platform: Win32, Show directories for: Executable files). - - The _bsddb subprojects depends only on the db_static project of - Berkeley DB. You have to choose either "Release", "Release AMD64", "Debug" - or "Debug AMD64" as configuration. For the AND64 builds, you need to - create the "x64" platform first (in Solution Platforms\Configuration - Manager...) - - Alternatively, if you want to start with the original sources, - go to Sleepycat's download page: - http://www.sleepycat.com/downloads/releasehistorybdb.html - - and download version 4.4.20. - - With or without strong cryptography? You can choose either with or - without strong cryptography, as per the instructions below. By - default, Python is built and distributed WITHOUT strong crypto. - - Unpack the sources; if you downloaded the non-crypto version, rename - the directory from db-4.4.20.NC to db-4.4.20. - - Now apply any patches that apply to your version. - - Open - db-4.4.20\docs\ref\build_win\intro.html - - and follow the "Windows->Building Berkeley DB with Visual C++ .NET" - instructions for building the Sleepycat - software. Note that Berkeley_DB.dsw is in the build_win32 subdirectory. - Build the "db_static" project, for "Release" mode. - - To run extensive tests, pass "-u bsddb" to regrtest.py. test_bsddb3.py - is then enabled. Running in verbose mode may be helpful. - -_sqlite3 - Python wrapper for SQLite library. - - Get the source code through - - svn export http://svn.python.org/projects/external/sqlite-source-3.3.4 - - To use the extension module in a Python build tree, copy sqlite3.dll into - the PCbuild folder. The source directory in svn also contains a .def file - from the binary release of sqlite3. - _ssl Python wrapper for the secure sockets library. @@ -250,6 +144,10 @@ svn export http://svn.python.org/projects/external/openssl-0.9.8g + ** NOTE: if you use the Tools\buildbot\external(-amd64).bat approach for + obtaining external sources then you don't need to manually get the source + above via subversion. ** + Alternatively, get the latest version from http://www.openssl.org. You can (theoretically) use any version of OpenSSL you like - the build process will automatically select the latest version. @@ -285,6 +183,69 @@ build_ssl.py/MSVC isn't clever enough to clean OpenSSL - you must do this by hand. +The subprojects above wrap external projects Python doesn't control, and as +such, a little more work is required in order to download the relevant source +files for each project before they can be built. The buildbots do this each +time they're built, so the easiest approach is to run either external.bat or +external-amd64.bat in the ..\Tools\buildbot directory from ..\, i.e.: + + C:\..\svn.python.org\projects\python\trunk\PCbuild>cd .. + C:\..\svn.python.org\projects\python\trunk>Tools\buildbot\external.bat + +This extracts all the external subprojects from http://svn.python.org/external +via Subversion (so you'll need an svn.exe on your PATH) and places them in +..\.. (relative to this directory). The external(-amd64).bat scripts will +also build a debug build of Tcl/Tk; there aren't any equivalent batch files +for building release versions of Tcl/Tk lying around in the Tools\buildbot +directory. If you need to build a release version of Tcl/Tk it isn't hard +though, take a look at the relevant external(-amd64).bat file and find the +two nmake lines, then call each one without the 'DEBUG=1' parameter, i.e.: + +The external-amd64.bat file contains this for tcl: + nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 clean all install + +So for a release build, you'd call it as: + nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 clean all install + + XXX Should we compile with OPTS=threads? + XXX Our installer copies a lot of stuff out of the Tcl/Tk install + XXX directory. Is all of that really needed for Python use of Tcl/Tk? + +This will be cleaned up in the future; ideally Tcl/Tk will be brought into our +pcbuild.sln as custom .vcproj files, just as we've recently done with the +_bsddb44.vcproj and sqlite3.vcproj files, which will remove the need for +Tcl/Tk to be built separately via a batch file. + +XXX trent.nelson 02-Apr-08: + Having the external subprojects in ..\.. relative to this directory is a + bit of a nuisance when you're working on py3k and trunk in parallel and + your directory layout mimics that of Python's subversion layout, e.g.: + + C:\..\svn.python.org\projects\python\trunk + C:\..\svn.python.org\projects\python\branches\py3k + C:\..\svn.python.org\projects\python\branches\release25-maint + + I'd like to change things so that external subprojects are fetched from + ..\external instead of ..\.., then provide some helper scripts or batch + files that would set up a new ..\external directory with svn checkouts of + the relevant branches in http://svn.python.org/projects/external/, or + alternatively, use junctions to link ..\external with a pre-existing + externals directory being used by another branch. i.e. if I'm usually + working on trunk (and have previously created trunk\external via the + provided batch file), and want to do some work on py3k, I'd set up a + junction as follows (using the directory structure above as an example): + + C:\..\python\trunk\external <- already exists and has built versions + of the external subprojects + + C:\..\python\branches\py3k>linkd.exe external ..\..\trunk\external + Link created at: external + + Only a slight tweak would be needed to the buildbots such that bots + building trunk and py3k could make use of the same facility. (2.5.x + builds need to be kept separate as they're using Visual Studio 7.1.) +/XXX trent.nelson 02-Apr-08 + Building for Itanium -------------------- From python-3000-checkins at python.org Wed Apr 2 23:21:40 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Wed, 2 Apr 2008 23:21:40 +0200 (CEST) Subject: [Python-3000-checkins] r62115 - python/branches/py3k Message-ID: <20080402212140.CD66B1E401D@bag.python.org> Author: benjamin.peterson Date: Wed Apr 2 23:21:29 2008 New Revision: 62115 Modified: python/branches/py3k/ (props changed) Log: Blocked revisions 62097 via svnmerge ........ r62097 | guido.van.rossum | 2008-04-01 18:57:36 -0500 (Tue, 01 Apr 2008) | 3 lines Remove the advertising clause from the BSD license in timing.h. I have the email trail to prove that George Neville-Neil approved this. ........ From python-3000-checkins at python.org Wed Apr 2 23:49:45 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Wed, 2 Apr 2008 23:49:45 +0200 (CEST) Subject: [Python-3000-checkins] r62116 - in python/branches/py3k: Doc/library/logging.rst Lib/logging/handlers.py Lib/test/test_code.py Lib/test/test_collections.py Lib/test/test_io.py Lib/test/test_lib2to3.py Lib/test/test_signal.py Lib/test/test_socket.py Lib/test/test_support.py Misc/NEWS README Message-ID: <20080402214945.A3D891E4004@bag.python.org> Author: benjamin.peterson Date: Wed Apr 2 23:49:44 2008 New Revision: 62116 Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/logging.rst python/branches/py3k/Lib/logging/handlers.py python/branches/py3k/Lib/test/test_code.py python/branches/py3k/Lib/test/test_collections.py python/branches/py3k/Lib/test/test_io.py python/branches/py3k/Lib/test/test_lib2to3.py python/branches/py3k/Lib/test/test_signal.py python/branches/py3k/Lib/test/test_socket.py python/branches/py3k/Lib/test/test_support.py python/branches/py3k/Misc/NEWS python/branches/py3k/README Log: Merged revisions 62090-62091,62096,62100,62102,62110-62114 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62090 | brett.cannon | 2008-04-01 07:37:43 -0500 (Tue, 01 Apr 2008) | 3 lines Generalize test.test_support.test_stdout() with a base context manager so that it is easy to capture stderr if desired. ........ r62091 | brett.cannon | 2008-04-01 07:46:02 -0500 (Tue, 01 Apr 2008) | 3 lines Add ``if __name__ == '__main__'`` to some test files where it didn't take a lot of effort to do so. ........ r62096 | amaury.forgeotdarc | 2008-04-01 17:52:48 -0500 (Tue, 01 Apr 2008) | 4 lines Newly enabled test appears to leak: it registers the same codec on each iteration. Do it only once at load time. ........ r62100 | amaury.forgeotdarc | 2008-04-01 19:55:04 -0500 (Tue, 01 Apr 2008) | 4 lines A DocTestSuite cannot run multiple times: it clears its globals dictionary after the first run. Rebuild the DocTestSuite on each iteration. ........ r62102 | jeffrey.yasskin | 2008-04-01 23:07:44 -0500 (Tue, 01 Apr 2008) | 3 lines Try to make test_signal less flaky. I still see some flakiness in test_itimer_prof. ........ r62110 | vinay.sajip | 2008-04-02 16:09:27 -0500 (Wed, 02 Apr 2008) | 1 line Fix: #2315, #2316, #2317: TimedRotatingFileHandler - changed logic to better handle daylight savings time, deletion of old log files, and fixed a bug in calculating rollover when no logging occurs for a longer interval than the rollover period. ........ r62111 | vinay.sajip | 2008-04-02 16:10:23 -0500 (Wed, 02 Apr 2008) | 1 line Added updates with respect to recent changes to TimedRotatingFileHandler. ........ r62112 | vinay.sajip | 2008-04-02 16:17:25 -0500 (Wed, 02 Apr 2008) | 1 line Added updates with respect to recent changes to TimedRotatingFileHandler. ........ r62113 | amaury.forgeotdarc | 2008-04-02 16:18:46 -0500 (Wed, 02 Apr 2008) | 2 lines Remove debug prints; the buildbot now passes the tests ........ r62114 | benjamin.peterson | 2008-04-02 16:20:35 -0500 (Wed, 02 Apr 2008) | 2 lines Suggested proposed changes to Python be considered on some mailing lists first ........ Modified: python/branches/py3k/Doc/library/logging.rst ============================================================================== --- python/branches/py3k/Doc/library/logging.rst (original) +++ python/branches/py3k/Doc/library/logging.rst Wed Apr 2 23:49:44 2008 @@ -1649,10 +1649,11 @@ The system will save old log files by appending extensions to the filename. The extensions are date-and-time based, using the strftime format - ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the rollover - interval. If *backupCount* is nonzero, at most *backupCount* files will be - kept, and if more would be created when rollover occurs, the oldest one is - deleted. + ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the + rollover interval. If *backupCount* is nonzero, at most *backupCount* files + will be kept, and if more would be created when rollover occurs, the oldest + one is deleted. The deletion logic uses the interval to determine which + files to delete, so changing the interval may leave old files lying around. .. method:: TimedRotatingFileHandler.doRollover() Modified: python/branches/py3k/Lib/logging/handlers.py ============================================================================== --- python/branches/py3k/Lib/logging/handlers.py (original) +++ python/branches/py3k/Lib/logging/handlers.py Wed Apr 2 23:49:44 2008 @@ -19,12 +19,12 @@ based on PEP 282 and comments thereto in comp.lang.python, and influenced by Apache's log4j system. -Copyright (C) 2001-2007 Vinay Sajip. All Rights Reserved. +Copyright (C) 2001-2008 Vinay Sajip. All Rights Reserved. To use, simply 'import logging' and log away! """ -import logging, socket, os, pickle, struct, time, glob +import logging, socket, os, pickle, struct, time, re from stat import ST_DEV, ST_INO try: @@ -173,15 +173,19 @@ if self.when == 'S': self.interval = 1 # one second self.suffix = "%Y-%m-%d_%H-%M-%S" + self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$" elif self.when == 'M': self.interval = 60 # one minute self.suffix = "%Y-%m-%d_%H-%M" + self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}$" elif self.when == 'H': self.interval = 60 * 60 # one hour self.suffix = "%Y-%m-%d_%H" + self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}$" elif self.when == 'D' or self.when == 'MIDNIGHT': self.interval = 60 * 60 * 24 # one day self.suffix = "%Y-%m-%d" + self.extMatch = r"^\d{4}-\d{2}-\d{2}$" elif self.when.startswith('W'): self.interval = 60 * 60 * 24 * 7 # one week if len(self.when) != 2: @@ -190,9 +194,11 @@ raise ValueError("Invalid day specified for weekly rollover: %s" % self.when) self.dayOfWeek = int(self.when[1]) self.suffix = "%Y-%m-%d" + self.extMatch = r"^\d{4}-\d{2}-\d{2}$" else: raise ValueError("Invalid rollover interval specified: %s" % self.when) + self.extMatch = re.compile(self.extMatch) self.interval = self.interval * interval # multiply by units requested self.rolloverAt = currentTime + self.interval @@ -235,16 +241,24 @@ daysToWait = self.dayOfWeek - day else: daysToWait = 6 - day + self.dayOfWeek + 1 - self.rolloverAt = self.rolloverAt + (daysToWait * (60 * 60 * 24)) + newRolloverAt = self.rolloverAt + (daysToWait * (60 * 60 * 24)) + dstNow = t[-1] + dstAtRollover = time.localtime(newRolloverAt)[-1] + if dstNow != dstAtRollover: + if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour + newRolloverAt = newRolloverAt - 3600 + else: # DST bows out before next rollover, so we need to add an hour + newRolloverAt = newRolloverAt + 3600 + self.rolloverAt = newRolloverAt #print "Will rollover at %d, %d seconds from now" % (self.rolloverAt, self.rolloverAt - currentTime) def shouldRollover(self, record): """ - Determine if rollover should occur + Determine if rollover should occur. record is not used, as we are just comparing times, but it is needed so - the method siguratures are the same + the method signatures are the same """ t = int(time.time()) if t >= self.rolloverAt: @@ -252,6 +266,29 @@ #print "No need to rollover: %d, %d" % (t, self.rolloverAt) return 0 + def getFilesToDelete(self): + """ + Determine the files to delete when rolling over. + + More specific than the earlier method, which just used glob.glob(). + """ + dirName, baseName = os.path.split(self.baseFilename) + fileNames = os.listdir(dirName) + result = [] + prefix = baseName + "." + plen = len(prefix) + for fileName in fileNames: + if fileName[:plen] == prefix: + suffix = fileName[plen:] + if self.extMatch.match(suffix): + result.append(fileName) + result.sort() + if len(result) < self.backupCount: + result = [] + else: + result = result[:len(result) - self.backupCount] + return result + def doRollover(self): """ do a rollover; in this case, a date/time stamp is appended to the filename @@ -270,14 +307,29 @@ os.rename(self.baseFilename, dfn) if self.backupCount > 0: # find the oldest log file and delete it - s = glob.glob(self.baseFilename + ".20*") - if len(s) > self.backupCount: - s.sort() - os.remove(s[0]) + #s = glob.glob(self.baseFilename + ".20*") + #if len(s) > self.backupCount: + # s.sort() + # os.remove(s[0]) + for s in self.getFilesToDelete(): + os.remove(s) #print "%s -> %s" % (self.baseFilename, dfn) self.mode = 'w' self.stream = self._open() - self.rolloverAt = self.rolloverAt + self.interval + newRolloverAt = self.rolloverAt + self.interval + currentTime = int(time.time()) + while newRolloverAt <= currentTime: + newRolloverAt = newRolloverAt + self.interval + #If DST changes and midnight or weekly rollover, adjust for this. + if self.when == 'MIDNIGHT' or self.when.startswith('W'): + dstNow = time.localtime(currentTime)[-1] + dstAtRollover = time.localtime(newRolloverAt)[-1] + if dstNow != dstAtRollover: + if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour + newRolloverAt = newRolloverAt - 3600 + else: # DST bows out before next rollover, so we need to add an hour + newRolloverAt = newRolloverAt + 3600 + self.rolloverAt = newRolloverAt class WatchedFileHandler(logging.FileHandler): """ Modified: python/branches/py3k/Lib/test/test_code.py ============================================================================== --- python/branches/py3k/Lib/test/test_code.py (original) +++ python/branches/py3k/Lib/test/test_code.py Wed Apr 2 23:49:44 2008 @@ -122,3 +122,7 @@ from test.test_support import run_doctest from test import test_code run_doctest(test_code, verbose) + + +if __name__ == '__main__': + test_main() Modified: python/branches/py3k/Lib/test/test_collections.py ============================================================================== --- python/branches/py3k/Lib/test/test_collections.py (original) +++ python/branches/py3k/Lib/test/test_collections.py Wed Apr 2 23:49:44 2008 @@ -317,13 +317,12 @@ self.failIf(issubclass(str, MutableSequence)) import doctest, collections -NamedTupleDocs = doctest.DocTestSuite(module=collections) def test_main(verbose=None): - import collections as CollectionsModule + NamedTupleDocs = doctest.DocTestSuite(module=collections) test_classes = [TestNamedTuple, NamedTupleDocs, TestOneTrickPonyABCs, TestCollectionABCs] test_support.run_unittest(*test_classes) - test_support.run_doctest(CollectionsModule, verbose) + test_support.run_doctest(collections, verbose) if __name__ == "__main__": Modified: python/branches/py3k/Lib/test/test_io.py ============================================================================== --- python/branches/py3k/Lib/test/test_io.py (original) +++ python/branches/py3k/Lib/test/test_io.py Wed Apr 2 23:49:44 2008 @@ -574,6 +574,22 @@ self.buffer = bytearray() return output + codecEnabled = False + + @classmethod + def lookupTestDecoder(cls, name): + if cls.codecEnabled and name == 'test_decoder': + return codecs.CodecInfo( + name='test_decoder', encode=None, decode=None, + incrementalencoder=None, + streamreader=None, streamwriter=None, + incrementaldecoder=cls) + +# Register the previous decoder for testing. +# Disabled by default, tests will enable it. +codecs.register(StatefulIncrementalDecoder.lookupTestDecoder) + + class StatefulIncrementalDecoderTest(unittest.TestCase): """ Make sure the StatefulIncrementalDecoder actually works. @@ -899,14 +915,6 @@ def testSeekAndTell(self): """Test seek/tell using the StatefulIncrementalDecoder.""" - def lookupTestDecoder(name): - if self.codecEnabled and name == 'test_decoder': - return codecs.CodecInfo( - name='test_decoder', encode=None, decode=None, - incrementalencoder=None, - streamreader=None, streamwriter=None, - incrementaldecoder=StatefulIncrementalDecoder) - def testSeekAndTellWithData(data, min_pos=0): """Tell/seek to various points within a data stream and ensure that the decoded data returned by read() is consistent.""" @@ -927,9 +935,8 @@ self.assertEquals(f.read(), decoded[i:]) f.close() - # Register a special incremental decoder for testing. - codecs.register(lookupTestDecoder) - self.codecEnabled = 1 + # Enable the test decoder. + StatefulIncrementalDecoder.codecEnabled = 1 # Run the tests. try: @@ -948,7 +955,7 @@ # Ensure our test decoder won't interfere with subsequent tests. finally: - self.codecEnabled = 0 + StatefulIncrementalDecoder.codecEnabled = 0 def testEncodedWrites(self): data = "1234567890" Modified: python/branches/py3k/Lib/test/test_lib2to3.py ============================================================================== --- python/branches/py3k/Lib/test/test_lib2to3.py (original) +++ python/branches/py3k/Lib/test/test_lib2to3.py Wed Apr 2 23:49:44 2008 @@ -13,3 +13,7 @@ def test_main(): run_unittest(suite()) + + +if __name__ == '__main__': + test_main() Modified: python/branches/py3k/Lib/test/test_signal.py ============================================================================== --- python/branches/py3k/Lib/test/test_signal.py (original) +++ python/branches/py3k/Lib/test/test_signal.py Wed Apr 2 23:49:44 2008 @@ -28,6 +28,15 @@ os._exit(0) +def ignoring_eintr(__func, *args, **kwargs): + try: + return __func(*args, **kwargs) + except IOError as e: + if e.errno != signal.EINTR: + raise + return None + + class InterProcessSignalTests(unittest.TestCase): MAX_DURATION = 20 # Entire test should last at most 20 sec. @@ -77,8 +86,11 @@ if test_support.verbose: print("test runner's pid is", pid) - child = subprocess.Popen(['kill', '-HUP', str(pid)]) - self.wait(child) + child = ignoring_eintr(subprocess.Popen, ['kill', '-HUP', str(pid)]) + if child: + self.wait(child) + if not self.a_called: + time.sleep(1) # Give the signal time to be delivered. self.assertTrue(self.a_called) self.assertFalse(self.b_called) self.a_called = False @@ -87,6 +99,7 @@ child = subprocess.Popen(['kill', '-USR1', str(pid)]) # This wait should be interrupted by the signal's exception. self.wait(child) + time.sleep(1) # Give the signal time to be delivered. self.fail('HandlerBCalled exception not thrown') except HandlerBCalled: self.assertTrue(self.b_called) @@ -94,8 +107,9 @@ if test_support.verbose: print("HandlerBCalled exception caught") - child = subprocess.Popen(['kill', '-USR2', str(pid)]) - self.wait(child) # Nothing should happen. + child = ignoring_eintr(subprocess.Popen, ['kill', '-USR2', str(pid)]) + if child: + self.wait(child) # Nothing should happen. try: signal.alarm(1) @@ -103,14 +117,18 @@ # since alarm is going to raise a KeyboardException, which # will skip the call. signal.pause() + # But if another signal arrives before the alarm, pause + # may return early. + time.sleep(1) except KeyboardInterrupt: if test_support.verbose: print("KeyboardInterrupt (the alarm() went off)") except: - self.fail('Some other exception woke us from pause: %s' % + self.fail("Some other exception woke us from pause: %s" % traceback.format_exc()) else: - self.fail('pause returned of its own accord') + self.fail("pause returned of its own accord, and the signal" + " didn't arrive after another second.") def test_main(self): # This function spawns a child process to insulate the main Modified: python/branches/py3k/Lib/test/test_socket.py ============================================================================== --- python/branches/py3k/Lib/test/test_socket.py (original) +++ python/branches/py3k/Lib/test/test_socket.py Wed Apr 2 23:49:44 2008 @@ -15,14 +15,6 @@ from weakref import proxy import signal -# Temporary hack to see why test_socket hangs on one buildbot -if os.environ.get('COMPUTERNAME') == "GRAPE": - def verbose_write(arg): - print(arg, file=sys.__stdout__) -else: - def verbose_write(arg): - pass - PORT = 50007 HOST = 'localhost' MSG = b'Michael Gilfix was here\n' @@ -30,21 +22,15 @@ class SocketTCPTest(unittest.TestCase): def setUp(self): - verbose_write(self) self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - verbose_write(str(self) + " socket created") global PORT PORT = test_support.bind_port(self.serv, HOST, PORT) - verbose_write(str(self) + " start listening") self.serv.listen(1) - verbose_write(str(self) + " started") def tearDown(self): - verbose_write(str(self) + " close") self.serv.close() self.serv = None - verbose_write(str(self) + " done") class SocketUDPTest(unittest.TestCase): Modified: python/branches/py3k/Lib/test/test_support.py ============================================================================== --- python/branches/py3k/Lib/test/test_support.py (original) +++ python/branches/py3k/Lib/test/test_support.py Wed Apr 2 23:49:44 2008 @@ -381,19 +381,23 @@ @contextlib.contextmanager -def captured_stdout(): - """Run the with statement body using a StringIO object as sys.stdout. - Example use:: +def captured_output(stream_name): + """Run the 'with' statement body using a StringIO object in place of a + specific attribute on the sys module. + Example use (with 'stream_name=stdout'):: with captured_stdout() as s: print "hello" assert s.getvalue() == "hello" """ import io - orig_stdout = sys.stdout - sys.stdout = io.StringIO() - yield sys.stdout - sys.stdout = orig_stdout + orig_stdout = getattr(sys, stream_name) + setattr(sys, stream_name, io.StringIO()) + yield getattr(sys, stream_name) + setattr(sys, stream_name, orig_stdout) + +def captured_stdout(): + return captured_output("stdout") #======================================================================= Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Wed Apr 2 23:49:44 2008 @@ -29,6 +29,19 @@ as a build_py replacement to automatically run 2to3 on modules that are going to be installed. +- Issue #2315: logging.handlers: TimedRotatingFileHandler now accounts for + daylight savings time in calculating the next rollover. + +- Issue #2316: logging.handlers: TimedRotatingFileHandler now calculates + rollovers correctly even when nothing is logged for a while. + +- Issue #2317: logging.handlers: TimedRotatingFileHandler now uses improved + logic for removing old files. + +- Issue #2495: tokenize.untokenize now inserts a space between two consecutive + string literals; previously, ["" ""] was rendered as [""""], which is + incorrect python code. + - A new pickle protocol (protocol 3) is added with explicit support for bytes. This is the default protocol. It intentionally cannot be unpickled by Python 2.x. @@ -57,6 +70,115 @@ What's New in Python 3.0a3? =========================== +- Issue #1681432: Add triangular distribution to the random module + +- Issue #2136: urllib2's auth handler now allows single-quoted realms in the + WWW-Authenticate header. + +- Issue #2434: Enhanced platform.win32_ver() to also work on Python + installation which do not have the win32all package installed. + +- Added support to platform.uname() to also report the machine + and processor information on Windows XP and later. As a result, + platform.machine() and platform.processor() will report this + information as well. + +- The library implementing the 2to3 conversion, lib2to3, was added + to the standard distribution. + +- Issue #1747858: Fix chown to work with large uid's and gid's on 64-bit + platforms. + +- Issue #1202: zlib.crc32 and zlib.adler32 no longer return different values + on 32-bit vs. 64-bit python interpreters. Both were correct, but they now + both return a signed integer object for consistency. + +- Issue #1158: add %f format (fractions of a second represented as + microseconds) to datetime objects. Understood by both strptime and + strftime. + +- Issue #705836: struct.pack(">f", x) now raises OverflowError on all + platforms when x is too large to fit into an IEEE 754 float; previously + it only raised OverflowError on non IEEE 754 platforms. + +- Issue #1106316: pdb.post_mortem()'s parameter, "traceback", is now + optional: it defaults to the traceback of the exception that is currently + being handled (is mandatory to be in the middle of an exception, otherwise + it raises ValueError). + +- Issue #1193577: A .shutdown() method has been added to SocketServers + which terminates the .serve_forever() loop. + +- Bug #2220: handle rlcompleter attribute match failure more gracefully. + +- Issue #2225: py_compile, when executed as a script, now returns a non- + zero status code if not all files could be compiled successfully. + +- Bug #1725737: In distutil's sdist, exclude RCS, CVS etc. also in the + root directory, and also exclude .hg, .git, .bzr, and _darcs. + +- Issue #1872: The struct module typecode for _Bool has been changed + from 't' to '?'. + +- The bundled libffi copy is now in sync with the recently released + libffi3.0.4 version, apart from some small changes to + Modules/_ctypes/libffi/configure.ac. + On OS X, preconfigured libffi files are used. + On all linux systems the --with-system-ffi configure option defaults + to "yes". + +- Issue 1577: shutil.move() now calls os.rename() if the destination is a + directory instead of copying-then-remove-source. + +Tests +----- + +- test_nis no longer fails when test.test_support.verbose is true and NIS is + not set up on the testing machine. + +- Output comparison tests are no longer supported. + +- Rewrite test_errno to use unittest and no longer be a no-op. + +- GHOP 234: Convert test_extcall to doctest. + +- GHOP 290: Convert test_dbm and test_dummy_threading to unittest. + +- GHOP 293: Convert test_strftime, test_getargs, and test_pep247 to unittest. + +- Issue #2055: Convert test_fcntl to unittest. + +- Issue 1960: Convert test_gdbm to unittest. + +- GHOP 294: Convert test_contains, test_crypt, and test_select to unittest. + +- GHOP 238: Convert test_tokenize to use doctest. + +- GHOP 237: Rewrite test_thread using unittest. + +- Patch #2232: os.tmpfile might fail on Windows if the user has no + permission to create files in the root directory. + +Build +----- + +- A new script 2to3 is now installed, to run the 2.x to 3.x converter. + +- Python/memmove.c and Python/strerror.c have been removed; both functions are + in the C89 standard library. + +- Patch #2284: Add -x64 option to rt.bat. + +C API +----- + +- Patch #2477: Added PyParser_ParseFileFlagsEx() and + PyParser_ParseStringFlagsFilenameEx() + +What's New in Python 2.6 alpha 1? +================================= + +>>>>>>> .merge-right.r62114 *Release date: 29-Feb-2008* Core and Builtins @@ -64,8 +186,40 @@ - Issue #2282: io.TextIOWrapper was not overriding seekable() from io.IOBase. -- Issue #2115: Important speedup in setting __slot__ attributes. Also - prevent a possible crash: an Abstract Base Class would try to access a slot +- Issue #2067: file.__exit__() now calls subclasses' close() method. + +- Patch #1759: Backport of PEP 3129 class decorators. + +- Issue #1881: An internal parser limit has been increased. Also see + issue 215555 for a discussion. + +- Added the future_builtins module, which contains hex() and oct(). + These are the PEP 3127 version of these functions, designed to be + compatible with the hex() and oct() builtins from Python 3.0. They + differ slightly in their output formats from the existing, unchanged + Python 2.6 builtins. The expected usage of the future_builtins + module is: + from future_builtins import hex, oct + +- Issue #1600: Modifed PyOS_ascii_formatd to use at most 2 digit + exponents for exponents with absolute value < 100. Follows C99 + standard. This is a change on Windows, which would use 3 digits. + Also, added 'n' to the formats that PyOS_ascii_formatd understands, + so that any alterations it does to the resulting string will be + available in stringlib/formatter.h (for float.__format__). + +- Implemented PEP 3101, Advanced String Formatting. This adds a new + builtin format(); a format() method for str and unicode; a + __format__() method to object, str, unicode, int, long, float, and + datetime; the class string.Formatter; and the C API + PyObject_Format(). + +- Fixed several potential crashes, all caused by specially crafted __del__ + methods exploiting objects in temporarily inconsistent state. + +>>>>>>> .merge-right.r62114 +- Issue #2115: Important speedup in setting __slot__ attributes. Also + prevent a possible crash: an Abstract Base Class would try to access a slot on a registered virtual subclass. - Fixed repr() and str() of complex numbers with infinity or nan as real or @@ -106,6 +260,11 @@ - Issue #1969: split and rsplit in bytearray are inconsistent +- Issue #1920: "while 0" statements were completely removed by the compiler, + even in the presence of an "else" clause, which is supposed to be run when + the condition is false. Now the compiler correctly emits bytecode for the + "else" suite. + - map() and no longer accepts None for the first argument. Use zip() instead. @@ -496,9 +655,15 @@ - Removed these C APIs: PyNumber_Coerce(), PyNumber_CoerceEx(), PyMember_Get, PyMember_Set +- ``PySet_Add()`` can now modify a newly created frozenset. Similarly to + ``PyTuple_SetItem``, it can be used to populate a brand new frozenset; but + it does not steal a reference to the added item. + - Removed these C slots/fields: nb_divide, nb_inplace_divide +- Added ``PySet_Check()`` and ``PyFrozenSet_Check()`` to the set API. + - Removed these macros: staticforward, statichere, PyArg_GetInt, PyArg_NoArgs, _PyObject_Del @@ -534,4 +699,34 @@ Tools/Demos ----------- +- Bug #1542693: remove semi-colon at end of PyImport_ImportModuleEx macro + so it can be used as an expression. + + +Windows +------- + +- Patch #1706: Drop support for Win9x, WinME and NT4. Python now requires + Windows 2000 or greater. The _WINVER and NTDDI_VERSION macros are set to + Win2k for x86/32bit builds and WinXP for AMD64 builds. + +- Conditionalize definition of _CRT_SECURE_NO_DEPRECATE + and _CRT_NONSTDC_NO_DEPRECATE. + +- Bug #1216: Restore support for Visual Studio 2002. + + +Mac +--- + +- cfmfile now raises a DeprecationWarning. + +- buildtools now raises a DeprecationWarning. + +- Removed the macfs module. It had been deprecated since Python 2.5. This + lead to the deprecation of macostools.touched() as it relied solely on macfs + and was a no-op under OS X. + +---- + **(For information about older versions, consult the HISTORY file.)** Modified: python/branches/py3k/README ============================================================================== --- python/branches/py3k/README (original) +++ python/branches/py3k/README Wed Apr 2 23:49:44 2008 @@ -88,9 +88,11 @@ Proposals for enhancement ------------------------------ -If you have a proposal to change Python, it's best to submit a Python -Enhancement Proposal (PEP) first. All current PEPs, as well as guidelines for -submitting a new PEP, are listed at http://www.python.org/dev/peps/. +If you have a proposal to change Python, you may want to send an email to the +comp.lang.python or python-ideas mailing lists for inital feedback. A Python +Enhancement Proposal (PEP) may be submitted if your idea gains ground. All +current PEPs, as well as guidelines for submitting a new PEP, are listed at +http://www.python.org/dev/peps/. Converting From Python 2.x to 3.0 --------------------------------- From python-3000-checkins at python.org Thu Apr 3 00:44:10 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Thu, 3 Apr 2008 00:44:10 +0200 (CEST) Subject: [Python-3000-checkins] r62117 - python/branches/py3k/Misc/NEWS Message-ID: <20080402224410.DD67D1E4004@bag.python.org> Author: benjamin.peterson Date: Thu Apr 3 00:44:10 2008 New Revision: 62117 Modified: python/branches/py3k/Misc/NEWS Log: Fixed NEWS due to my bad merging skills Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Thu Apr 3 00:44:10 2008 @@ -29,19 +29,6 @@ as a build_py replacement to automatically run 2to3 on modules that are going to be installed. -- Issue #2315: logging.handlers: TimedRotatingFileHandler now accounts for - daylight savings time in calculating the next rollover. - -- Issue #2316: logging.handlers: TimedRotatingFileHandler now calculates - rollovers correctly even when nothing is logged for a while. - -- Issue #2317: logging.handlers: TimedRotatingFileHandler now uses improved - logic for removing old files. - -- Issue #2495: tokenize.untokenize now inserts a space between two consecutive - string literals; previously, ["" ""] was rendered as [""""], which is - incorrect python code. - - A new pickle protocol (protocol 3) is added with explicit support for bytes. This is the default protocol. It intentionally cannot be unpickled by Python 2.x. @@ -70,115 +57,6 @@ What's New in Python 3.0a3? =========================== -- Issue #1681432: Add triangular distribution to the random module - -- Issue #2136: urllib2's auth handler now allows single-quoted realms in the - WWW-Authenticate header. - -- Issue #2434: Enhanced platform.win32_ver() to also work on Python - installation which do not have the win32all package installed. - -- Added support to platform.uname() to also report the machine - and processor information on Windows XP and later. As a result, - platform.machine() and platform.processor() will report this - information as well. - -- The library implementing the 2to3 conversion, lib2to3, was added - to the standard distribution. - -- Issue #1747858: Fix chown to work with large uid's and gid's on 64-bit - platforms. - -- Issue #1202: zlib.crc32 and zlib.adler32 no longer return different values - on 32-bit vs. 64-bit python interpreters. Both were correct, but they now - both return a signed integer object for consistency. - -- Issue #1158: add %f format (fractions of a second represented as - microseconds) to datetime objects. Understood by both strptime and - strftime. - -- Issue #705836: struct.pack(">f", x) now raises OverflowError on all - platforms when x is too large to fit into an IEEE 754 float; previously - it only raised OverflowError on non IEEE 754 platforms. - -- Issue #1106316: pdb.post_mortem()'s parameter, "traceback", is now - optional: it defaults to the traceback of the exception that is currently - being handled (is mandatory to be in the middle of an exception, otherwise - it raises ValueError). - -- Issue #1193577: A .shutdown() method has been added to SocketServers - which terminates the .serve_forever() loop. - -- Bug #2220: handle rlcompleter attribute match failure more gracefully. - -- Issue #2225: py_compile, when executed as a script, now returns a non- - zero status code if not all files could be compiled successfully. - -- Bug #1725737: In distutil's sdist, exclude RCS, CVS etc. also in the - root directory, and also exclude .hg, .git, .bzr, and _darcs. - -- Issue #1872: The struct module typecode for _Bool has been changed - from 't' to '?'. - -- The bundled libffi copy is now in sync with the recently released - libffi3.0.4 version, apart from some small changes to - Modules/_ctypes/libffi/configure.ac. - On OS X, preconfigured libffi files are used. - On all linux systems the --with-system-ffi configure option defaults - to "yes". - -- Issue 1577: shutil.move() now calls os.rename() if the destination is a - directory instead of copying-then-remove-source. - -Tests ------ - -- test_nis no longer fails when test.test_support.verbose is true and NIS is - not set up on the testing machine. - -- Output comparison tests are no longer supported. - -- Rewrite test_errno to use unittest and no longer be a no-op. - -- GHOP 234: Convert test_extcall to doctest. - -- GHOP 290: Convert test_dbm and test_dummy_threading to unittest. - -- GHOP 293: Convert test_strftime, test_getargs, and test_pep247 to unittest. - -- Issue #2055: Convert test_fcntl to unittest. - -- Issue 1960: Convert test_gdbm to unittest. - -- GHOP 294: Convert test_contains, test_crypt, and test_select to unittest. - -- GHOP 238: Convert test_tokenize to use doctest. - -- GHOP 237: Rewrite test_thread using unittest. - -- Patch #2232: os.tmpfile might fail on Windows if the user has no - permission to create files in the root directory. - -Build ------ - -- A new script 2to3 is now installed, to run the 2.x to 3.x converter. - -- Python/memmove.c and Python/strerror.c have been removed; both functions are - in the C89 standard library. - -- Patch #2284: Add -x64 option to rt.bat. - -C API ------ - -- Patch #2477: Added PyParser_ParseFileFlagsEx() and - PyParser_ParseStringFlagsFilenameEx() - -What's New in Python 2.6 alpha 1? -================================= - ->>>>>>> .merge-right.r62114 *Release date: 29-Feb-2008* Core and Builtins @@ -186,40 +64,8 @@ - Issue #2282: io.TextIOWrapper was not overriding seekable() from io.IOBase. -- Issue #2067: file.__exit__() now calls subclasses' close() method. - -- Patch #1759: Backport of PEP 3129 class decorators. - -- Issue #1881: An internal parser limit has been increased. Also see - issue 215555 for a discussion. - -- Added the future_builtins module, which contains hex() and oct(). - These are the PEP 3127 version of these functions, designed to be - compatible with the hex() and oct() builtins from Python 3.0. They - differ slightly in their output formats from the existing, unchanged - Python 2.6 builtins. The expected usage of the future_builtins - module is: - from future_builtins import hex, oct - -- Issue #1600: Modifed PyOS_ascii_formatd to use at most 2 digit - exponents for exponents with absolute value < 100. Follows C99 - standard. This is a change on Windows, which would use 3 digits. - Also, added 'n' to the formats that PyOS_ascii_formatd understands, - so that any alterations it does to the resulting string will be - available in stringlib/formatter.h (for float.__format__). - -- Implemented PEP 3101, Advanced String Formatting. This adds a new - builtin format(); a format() method for str and unicode; a - __format__() method to object, str, unicode, int, long, float, and - datetime; the class string.Formatter; and the C API - PyObject_Format(). - -- Fixed several potential crashes, all caused by specially crafted __del__ - methods exploiting objects in temporarily inconsistent state. - ->>>>>>> .merge-right.r62114 -- Issue #2115: Important speedup in setting __slot__ attributes. Also - prevent a possible crash: an Abstract Base Class would try to access a slot +- Issue #2115: Important speedup in setting __slot__ attributes. Also + prevent a possible crash: an Abstract Base Class would try to access a slot on a registered virtual subclass. - Fixed repr() and str() of complex numbers with infinity or nan as real or @@ -260,11 +106,6 @@ - Issue #1969: split and rsplit in bytearray are inconsistent -- Issue #1920: "while 0" statements were completely removed by the compiler, - even in the presence of an "else" clause, which is supposed to be run when - the condition is false. Now the compiler correctly emits bytecode for the - "else" suite. - - map() and no longer accepts None for the first argument. Use zip() instead. @@ -655,15 +496,9 @@ - Removed these C APIs: PyNumber_Coerce(), PyNumber_CoerceEx(), PyMember_Get, PyMember_Set -- ``PySet_Add()`` can now modify a newly created frozenset. Similarly to - ``PyTuple_SetItem``, it can be used to populate a brand new frozenset; but - it does not steal a reference to the added item. - - Removed these C slots/fields: nb_divide, nb_inplace_divide -- Added ``PySet_Check()`` and ``PyFrozenSet_Check()`` to the set API. - - Removed these macros: staticforward, statichere, PyArg_GetInt, PyArg_NoArgs, _PyObject_Del @@ -699,34 +534,4 @@ Tools/Demos ----------- -- Bug #1542693: remove semi-colon at end of PyImport_ImportModuleEx macro - so it can be used as an expression. - - -Windows -------- - -- Patch #1706: Drop support for Win9x, WinME and NT4. Python now requires - Windows 2000 or greater. The _WINVER and NTDDI_VERSION macros are set to - Win2k for x86/32bit builds and WinXP for AMD64 builds. - -- Conditionalize definition of _CRT_SECURE_NO_DEPRECATE - and _CRT_NONSTDC_NO_DEPRECATE. - -- Bug #1216: Restore support for Visual Studio 2002. - - -Mac ---- - -- cfmfile now raises a DeprecationWarning. - -- buildtools now raises a DeprecationWarning. - -- Removed the macfs module. It had been deprecated since Python 2.5. This - lead to the deprecation of macostools.touched() as it relied solely on macfs - and was a no-op under OS X. - ----- - **(For information about older versions, consult the HISTORY file.)** From python-3000-checkins at python.org Thu Apr 3 00:51:27 2008 From: python-3000-checkins at python.org (barry.warsaw) Date: Thu, 3 Apr 2008 00:51:27 +0200 (CEST) Subject: [Python-3000-checkins] r62118 - python/branches/py3k/Misc/RPM/python-2.6.spec python/branches/py3k/Misc/RPM/python-3.0.spec Message-ID: <20080402225127.0C9211E401F@bag.python.org> Author: barry.warsaw Date: Thu Apr 3 00:51:13 2008 New Revision: 62118 Added: python/branches/py3k/Misc/RPM/python-3.0.spec - copied unchanged from r62117, python/branches/py3k/Misc/RPM/python-2.6.spec Removed: python/branches/py3k/Misc/RPM/python-2.6.spec Log: release.py wants to rename the spec file. Deleted: /python/branches/py3k/Misc/RPM/python-2.6.spec ============================================================================== --- /python/branches/py3k/Misc/RPM/python-2.6.spec Thu Apr 3 00:51:13 2008 +++ (empty file) @@ -1,385 +0,0 @@ -########################## -# User-modifiable configs -########################## - -# Is the resulting package and the installed binary named "python" or -# "python2"? -#WARNING: Commenting out doesn't work. Last line is what's used. -%define config_binsuffix none -%define config_binsuffix 2.6 - -# Build tkinter? "auto" enables it if /usr/bin/wish exists. -#WARNING: Commenting out doesn't work. Last line is what's used. -%define config_tkinter no -%define config_tkinter yes -%define config_tkinter auto - -# Use pymalloc? The last line (commented or not) determines wether -# pymalloc is used. -#WARNING: Commenting out doesn't work. Last line is what's used. -%define config_pymalloc no -%define config_pymalloc yes - -# Enable IPV6? -#WARNING: Commenting out doesn't work. Last line is what's used. -%define config_ipv6 yes -%define config_ipv6 no - -# Location of the HTML directory. -%define config_htmldir /var/www/html/python - -################################# -# End of user-modifiable configs -################################# - -%define name python -%define version 2.6a1 -%define libvers 2.6 -%define release 1pydotorg -%define __prefix /usr - -# kludge to get around rpm define weirdness -%define ipv6 %(if [ "%{config_ipv6}" = yes ]; then echo --enable-ipv6; else echo --disable-ipv6; fi) -%define pymalloc %(if [ "%{config_pymalloc}" = yes ]; then echo --with-pymalloc; else echo --without-pymalloc; fi) -%define binsuffix %(if [ "%{config_binsuffix}" = none ]; then echo ; else echo "%{config_binsuffix}"; fi) -%define include_tkinter %(if [ \\( "%{config_tkinter}" = auto -a -f /usr/bin/wish \\) -o "%{config_tkinter}" = yes ]; then echo 1; else echo 0; fi) -%define libdirname %(( uname -m | egrep -q '_64$' && [ -d /usr/lib64 ] && echo lib64 ) || echo lib) - -# detect if documentation is available -%define include_docs %(if [ -f "%{_sourcedir}/html-%{version}.tar.bz2" ]; then echo 1; else echo 0; fi) - -Summary: An interpreted, interactive, object-oriented programming language. -Name: %{name}%{binsuffix} -Version: %{version} -Release: %{release} -Copyright: Modified CNRI Open Source License -Group: Development/Languages -Source: Python-%{version}.tar.bz2 -%if %{include_docs} -Source1: html-%{version}.tar.bz2 -%endif -BuildRoot: %{_tmppath}/%{name}-%{version}-root -BuildPrereq: expat-devel -BuildPrereq: db4-devel -BuildPrereq: gdbm-devel -BuildPrereq: sqlite-devel -Prefix: %{__prefix} -Packager: Sean Reifschneider - -%description -Python is an interpreted, interactive, object-oriented programming -language. It incorporates modules, exceptions, dynamic typing, very high -level dynamic data types, and classes. Python combines remarkable power -with very clear syntax. It has interfaces to many system calls and -libraries, as well as to various window systems, and is extensible in C or -C++. It is also usable as an extension language for applications that need -a programmable interface. Finally, Python is portable: it runs on many -brands of UNIX, on PCs under Windows, MS-DOS, and OS/2, and on the -Mac. - -%package devel -Summary: The libraries and header files needed for Python extension development. -Prereq: python%{binsuffix} = %{PACKAGE_VERSION} -Group: Development/Libraries - -%description devel -The Python programming language's interpreter can be extended with -dynamically loaded extensions and can be embedded in other programs. -This package contains the header files and libraries needed to do -these types of tasks. - -Install python-devel if you want to develop Python extensions. The -python package will also need to be installed. You'll probably also -want to install the python-docs package, which contains Python -documentation. - -%if %{include_tkinter} -%package tkinter -Summary: A graphical user interface for the Python scripting language. -Group: Development/Languages -Prereq: python%{binsuffix} = %{PACKAGE_VERSION}-%{release} - -%description tkinter -The Tkinter (Tk interface) program is an graphical user interface for -the Python scripting language. - -You should install the tkinter package if you'd like to use a graphical -user interface for Python programming. -%endif - -%package tools -Summary: A collection of development tools included with Python. -Group: Development/Tools -Prereq: python%{binsuffix} = %{PACKAGE_VERSION}-%{release} - -%description tools -The Python package includes several development tools that are used -to build python programs. This package contains a selection of those -tools, including the IDLE Python IDE. - -Install python-tools if you want to use these tools to develop -Python programs. You will also need to install the python and -tkinter packages. - -%if %{include_docs} -%package docs -Summary: Python-related documentation. -Group: Development/Documentation - -%description docs -Documentation relating to the Python programming language in HTML and info -formats. -%endif - -%changelog -* Mon Dec 20 2004 Sean Reifschneider [2.4-2pydotorg] -- Changing the idle wrapper so that it passes arguments to idle. - -* Tue Oct 19 2004 Sean Reifschneider [2.4b1-1pydotorg] -- Updating to 2.4. - -* Thu Jul 22 2004 Sean Reifschneider [2.3.4-3pydotorg] -- Paul Tiemann fixes for %{prefix}. -- Adding permission changes for directory as suggested by reimeika.ca -- Adding code to detect when it should be using lib64. -- Adding a define for the location of /var/www/html for docs. - -* Thu May 27 2004 Sean Reifschneider [2.3.4-2pydotorg] -- Including changes from Ian Holsman to build under Red Hat 7.3. -- Fixing some problems with the /usr/local path change. - -* Sat Mar 27 2004 Sean Reifschneider [2.3.2-3pydotorg] -- Being more agressive about finding the paths to fix for - #!/usr/local/bin/python. - -* Sat Feb 07 2004 Sean Reifschneider [2.3.3-2pydotorg] -- Adding code to remove "#!/usr/local/bin/python" from particular files and - causing the RPM build to terminate if there are any unexpected files - which have that line in them. - -* Mon Oct 13 2003 Sean Reifschneider [2.3.2-1pydotorg] -- Adding code to detect wether documentation is available to build. - -* Fri Sep 19 2003 Sean Reifschneider [2.3.1-1pydotorg] -- Updating to the 2.3.1 release. - -* Mon Feb 24 2003 Sean Reifschneider [2.3b1-1pydotorg] -- Updating to 2.3b1 release. - -* Mon Feb 17 2003 Sean Reifschneider [2.3a1-1] -- Updating to 2.3 release. - -* Sun Dec 23 2001 Sean Reifschneider -[Release 2.2-2] -- Added -docs package. -- Added "auto" config_tkinter setting which only enables tk if - /usr/bin/wish exists. - -* Sat Dec 22 2001 Sean Reifschneider -[Release 2.2-1] -- Updated to 2.2. -- Changed the extension to "2" from "2.2". - -* Tue Nov 18 2001 Sean Reifschneider -[Release 2.2c1-1] -- Updated to 2.2c1. - -* Thu Nov 1 2001 Sean Reifschneider -[Release 2.2b1-3] -- Changed the way the sed for fixing the #! in pydoc works. - -* Wed Oct 24 2001 Sean Reifschneider -[Release 2.2b1-2] -- Fixed missing "email" package, thanks to anonymous report on sourceforge. -- Fixed missing "compiler" package. - -* Mon Oct 22 2001 Sean Reifschneider -[Release 2.2b1-1] -- Updated to 2.2b1. - -* Mon Oct 9 2001 Sean Reifschneider -[Release 2.2a4-4] -- otto at balinor.mat.unimi.it mentioned that the license file is missing. - -* Sun Sep 30 2001 Sean Reifschneider -[Release 2.2a4-3] -- Ignacio Vazquez-Abrams pointed out that I had a spruious double-quote in - the spec files. Thanks. - -* Wed Jul 25 2001 Sean Reifschneider -[Release 2.2a1-1] -- Updated to 2.2a1 release. -- Changed idle and pydoc to use binsuffix macro - -####### -# PREP -####### -%prep -%setup -n Python-%{version} - -######## -# BUILD -######## -%build -./configure --enable-unicode=ucs4 %{ipv6} %{pymalloc} --prefix=%{__prefix} -make - -########## -# INSTALL -########## -%install -# set the install path -echo '[install_scripts]' >setup.cfg -echo 'install_dir='"${RPM_BUILD_ROOT}%{__prefix}/bin" >>setup.cfg - -[ -d "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != "/" ] && rm -rf $RPM_BUILD_ROOT -mkdir -p $RPM_BUILD_ROOT%{__prefix}/%{libdirname}/python%{libvers}/lib-dynload -make prefix=$RPM_BUILD_ROOT%{__prefix} install - -# REPLACE PATH IN PYDOC -if [ ! -z "%{binsuffix}" ] -then - ( - cd $RPM_BUILD_ROOT%{__prefix}/bin - mv pydoc pydoc.old - sed 's|#!.*|#!%{__prefix}/bin/env python'%{binsuffix}'|' \ - pydoc.old >pydoc - chmod 755 pydoc - rm -f pydoc.old - ) -fi - -# add the binsuffix -if [ ! -z "%{binsuffix}" ] -then - ( cd $RPM_BUILD_ROOT%{__prefix}/bin; rm -f python[0-9a-zA-Z]*; - mv -f python python"%{binsuffix}" ) - ( cd $RPM_BUILD_ROOT%{__prefix}/man/man1; mv python.1 python%{binsuffix}.1 ) - ( cd $RPM_BUILD_ROOT%{__prefix}/bin; mv -f pydoc pydoc"%{binsuffix}" ) - ( cd $RPM_BUILD_ROOT%{__prefix}/bin; mv -f idle idle"%{binsuffix}" ) -fi - -######## -# Tools -echo '#!%{__prefix}/bin/env python%{binsuffix}' >${RPM_BUILD_ROOT}%{__prefix}/bin/idle%{binsuffix} -echo 'import os, sys' >>${RPM_BUILD_ROOT}%{__prefix}/bin/idle%{binsuffix} -echo 'os.execvp("%{__prefix}/bin/python%{binsuffix}", ["%{__prefix}/bin/python%{binsuffix}", "%{__prefix}/lib/python%{libvers}/idlelib/idle.py"] + sys.argv[1:])' >>${RPM_BUILD_ROOT}%{__prefix}/bin/idle%{binsuffix} -echo 'print "Failed to exec Idle"' >>${RPM_BUILD_ROOT}%{__prefix}/bin/idle%{binsuffix} -echo 'sys.exit(1)' >>${RPM_BUILD_ROOT}%{__prefix}/bin/idle%{binsuffix} -chmod 755 $RPM_BUILD_ROOT%{__prefix}/bin/idle%{binsuffix} -cp -a Tools $RPM_BUILD_ROOT%{__prefix}/%{libdirname}/python%{libvers} - -# MAKE FILE LISTS -rm -f mainpkg.files -find "$RPM_BUILD_ROOT""%{__prefix}"/%{libdirname}/python%{libvers}/lib-dynload -type f | - sed "s|^${RPM_BUILD_ROOT}|/|" | - grep -v -e '_tkinter.so$' >mainpkg.files -find "$RPM_BUILD_ROOT""%{__prefix}"/bin -type f | - sed "s|^${RPM_BUILD_ROOT}|/|" | - grep -v -e '/bin/idle%{binsuffix}$' >>mainpkg.files - -rm -f tools.files -find "$RPM_BUILD_ROOT""%{__prefix}"/%{libdirname}/python%{libvers}/idlelib \ - "$RPM_BUILD_ROOT""%{__prefix}"/%{libdirname}/python%{libvers}/Tools -type f | - sed "s|^${RPM_BUILD_ROOT}|/|" >tools.files -echo "%{__prefix}"/bin/idle%{binsuffix} >>tools.files - -###### -# Docs -%if %{include_docs} -mkdir -p "$RPM_BUILD_ROOT"%{config_htmldir} -( - cd "$RPM_BUILD_ROOT"%{config_htmldir} - bunzip2 < %{SOURCE1} | tar x -) -%endif - -# fix the #! line in installed files -find "$RPM_BUILD_ROOT" -type f -print0 | - xargs -0 grep -l /usr/local/bin/python | while read file -do - FIXFILE="$file" - sed 's|^#!.*python|#!%{__prefix}/bin/env python'"%{binsuffix}"'|' \ - "$FIXFILE" >/tmp/fix-python-path.$$ - cat /tmp/fix-python-path.$$ >"$FIXFILE" - rm -f /tmp/fix-python-path.$$ -done - -# check to see if there are any straggling #! lines -find "$RPM_BUILD_ROOT" -type f | xargs egrep -n '^#! */usr/local/bin/python' \ - | grep ':1:#!' >/tmp/python-rpm-files.$$ || true -if [ -s /tmp/python-rpm-files.$$ ] -then - echo '*****************************************************' - cat /tmp/python-rpm-files.$$ - cat <<@EOF - ***************************************************** - There are still files referencing /usr/local/bin/python in the - install directory. They are listed above. Please fix the .spec - file and try again. If you are an end-user, you probably want - to report this to jafo-rpms at tummy.com as well. - ***************************************************** - at EOF - rm -f /tmp/python-rpm-files.$$ - exit 1 -fi -rm -f /tmp/python-rpm-files.$$ - -######## -# CLEAN -######## -%clean -[ -n "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && rm -rf $RPM_BUILD_ROOT -rm -f mainpkg.files tools.files - -######## -# FILES -######## -%files -f mainpkg.files -%defattr(-,root,root) -%doc Misc/README Misc/cheatsheet Misc/Porting -%doc LICENSE Misc/ACKS Misc/HISTORY Misc/NEWS -%{__prefix}/man/man1/python%{binsuffix}.1* - -%attr(755,root,root) %dir %{__prefix}/include/python%{libvers} -%attr(755,root,root) %dir %{__prefix}/%{libdirname}/python%{libvers}/ -%{__prefix}/%{libdirname}/python%{libvers}/*.txt -%{__prefix}/%{libdirname}/python%{libvers}/*.py* -%{__prefix}/%{libdirname}/python%{libvers}/pdb.doc -%{__prefix}/%{libdirname}/python%{libvers}/profile.doc -%{__prefix}/%{libdirname}/python%{libvers}/curses -%{__prefix}/%{libdirname}/python%{libvers}/distutils -%{__prefix}/%{libdirname}/python%{libvers}/encodings -%{__prefix}/%{libdirname}/python%{libvers}/plat-linux2 -%{__prefix}/%{libdirname}/python%{libvers}/site-packages -%{__prefix}/%{libdirname}/python%{libvers}/test -%{__prefix}/%{libdirname}/python%{libvers}/xml -%{__prefix}/%{libdirname}/python%{libvers}/email -%{__prefix}/%{libdirname}/python%{libvers}/email/mime -%{__prefix}/%{libdirname}/python%{libvers}/sqlite3 -%{__prefix}/%{libdirname}/python%{libvers}/compiler -%{__prefix}/%{libdirname}/python%{libvers}/bsddb -%{__prefix}/%{libdirname}/python%{libvers}/hotshot -%{__prefix}/%{libdirname}/python%{libvers}/logging -%{__prefix}/%{libdirname}/python%{libvers}/lib-old - -%files devel -%defattr(-,root,root) -%{__prefix}/include/python%{libvers}/*.h -%{__prefix}/%{libdirname}/python%{libvers}/config - -%files -f tools.files tools -%defattr(-,root,root) - -%if %{include_tkinter} -%files tkinter -%defattr(-,root,root) -%{__prefix}/%{libdirname}/python%{libvers}/lib-tk -%{__prefix}/%{libdirname}/python%{libvers}/lib-dynload/_tkinter.so* -%endif - -%if %{include_docs} -%files docs -%defattr(-,root,root) -%{config_htmldir}/* -%endif From python-3000-checkins at python.org Thu Apr 3 01:33:28 2008 From: python-3000-checkins at python.org (barry.warsaw) Date: Thu, 3 Apr 2008 01:33:28 +0200 (CEST) Subject: [Python-3000-checkins] r62119 - in python/branches/py3k: Include/patchlevel.h Lib/distutils/__init__.py Lib/idlelib/idlever.py Misc/NEWS Misc/RPM/python-3.0.spec README Message-ID: <20080402233328.61E211E4016@bag.python.org> Author: barry.warsaw Date: Thu Apr 3 01:33:27 2008 New Revision: 62119 Modified: python/branches/py3k/Include/patchlevel.h python/branches/py3k/Lib/distutils/__init__.py python/branches/py3k/Lib/idlelib/idlever.py python/branches/py3k/Misc/NEWS python/branches/py3k/Misc/RPM/python-3.0.spec python/branches/py3k/README Log: release.py induced and manual editing steps for 3.0a4. Modified: python/branches/py3k/Include/patchlevel.h ============================================================================== --- python/branches/py3k/Include/patchlevel.h (original) +++ python/branches/py3k/Include/patchlevel.h Thu Apr 3 01:33:27 2008 @@ -15,14 +15,16 @@ /* Higher for patch releases */ /* Version parsed out into numeric values */ +/*--start constants--*/ #define PY_MAJOR_VERSION 3 #define PY_MINOR_VERSION 0 #define PY_MICRO_VERSION 0 #define PY_RELEASE_LEVEL PY_RELEASE_LEVEL_ALPHA -#define PY_RELEASE_SERIAL 3 +#define PY_RELEASE_SERIAL 4 /* Version as a string */ -#define PY_VERSION "3.0a3+" +#define PY_VERSION "3.0a4" +/*--end constants--*/ /* Subversion Revision number of this file (not of the repository) */ #define PY_PATCHLEVEL_REVISION "$Revision$" Modified: python/branches/py3k/Lib/distutils/__init__.py ============================================================================== --- python/branches/py3k/Lib/distutils/__init__.py (original) +++ python/branches/py3k/Lib/distutils/__init__.py Thu Apr 3 01:33:27 2008 @@ -18,4 +18,7 @@ # In general, major and minor version should loosely follow the Python # version number the distutils code was shipped with. # -__version__ = "2.6.0" + +#--start constants-- +__version__ = "3.0a4" +#--end constants-- Modified: python/branches/py3k/Lib/idlelib/idlever.py ============================================================================== --- python/branches/py3k/Lib/idlelib/idlever.py (original) +++ python/branches/py3k/Lib/idlelib/idlever.py Thu Apr 3 01:33:27 2008 @@ -1 +1 @@ -IDLE_VERSION = "3.0a3" +IDLE_VERSION = "3.0a4" Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Thu Apr 3 01:33:27 2008 @@ -7,7 +7,7 @@ What's New in Python 3.0a4? =========================== -*Release date: XX-XXX-2008* +*Release date: 02-Apr-2008* Core and Builtins ----------------- Modified: python/branches/py3k/Misc/RPM/python-3.0.spec ============================================================================== --- python/branches/py3k/Misc/RPM/python-3.0.spec (original) +++ python/branches/py3k/Misc/RPM/python-3.0.spec Thu Apr 3 01:33:27 2008 @@ -33,8 +33,10 @@ ################################# %define name python -%define version 2.6a1 -%define libvers 2.6 +#--start constants-- +%define version 3.0a4 +%define libver 3.0 +#--end constants-- %define release 1pydotorg %define __prefix /usr Modified: python/branches/py3k/README ============================================================================== --- python/branches/py3k/README (original) +++ python/branches/py3k/README Thu Apr 3 01:33:27 2008 @@ -1,4 +1,4 @@ -This is Python version 3.0 alpha 3 +This is Python version 3.0 alpha 4 ================================== For notes specific to this release, see RELNOTES in this directory. @@ -21,13 +21,14 @@ Release Schedule ---------------- -The release plan is to have a series of alpha releases in 2007, beta -releases in 2008, and a final release in August 2008. The alpha -releases are primarily aimed at developers who want a sneak peek at -the new langauge, especially those folks who plan to port their code -to Python 3000. The hope is that by the time of the final release, -many 3rd party packages will already be available in a 3.0-compatible -form. +The release plan is to have a series of alpha releases in 2007 and 2008, +beta releases in 2008, and a final release in August 2008. The alpha +releases are primarily aimed at developers who want a sneak peek at the +new langauge, especially those folks who plan to port their code to +Python 3000. The hope is that by the time of the final release, many +3rd party packages will already be available in a 3.0-compatible form. + +See PEP 361 for release details: http://www.python.org/dev/peps/pep-0361/ Documentation @@ -38,12 +39,12 @@ http://docs.python.org/dev/3.0/ All documentation is also available online at the Python web site -(http://docs.python.org/, see below). It is available online for occasional -reference, or can be downloaded in many formats for faster access. The -documentation is downloadable in HTML, PostScript, PDF, LaTeX (through 2.5), and -reStructuredText (2.6+) formats; the LaTeX and reStructuredText versions are -primarily for documentation authors, translators, and people with special -formatting requirements. +(http://docs.python.org/, see below). It is available online for +occasional reference, or can be downloaded in many formats for faster +access. The documentation is downloadable in HTML, PostScript, PDF, +LaTeX (through 2.5), and reStructuredText (2.6+) formats; the LaTeX and +reStructuredText versions are primarily for documentation authors, +translators, and people with special formatting requirements. This is a work in progress; please help improve it! @@ -86,7 +87,7 @@ release under development). Proposals for enhancement ------------------------------- +------------------------- If you have a proposal to change Python, you may want to send an email to the comp.lang.python or python-ideas mailing lists for inital feedback. A Python From python-3000-checkins at python.org Thu Apr 3 06:13:12 2008 From: python-3000-checkins at python.org (barry.warsaw) Date: Thu, 3 Apr 2008 06:13:12 +0200 (CEST) Subject: [Python-3000-checkins] r62125 - python/branches/py3k/Include/patchlevel.h Message-ID: <20080403041312.8813F1E4004@bag.python.org> Author: barry.warsaw Date: Thu Apr 3 06:13:12 2008 New Revision: 62125 Modified: python/branches/py3k/Include/patchlevel.h Log: Post tag version tweak Modified: python/branches/py3k/Include/patchlevel.h ============================================================================== --- python/branches/py3k/Include/patchlevel.h (original) +++ python/branches/py3k/Include/patchlevel.h Thu Apr 3 06:13:12 2008 @@ -23,7 +23,7 @@ #define PY_RELEASE_SERIAL 4 /* Version as a string */ -#define PY_VERSION "3.0a4" +#define PY_VERSION "3.0a4+" /*--end constants--*/ /* Subversion Revision number of this file (not of the repository) */ From python-3000-checkins at python.org Thu Apr 3 18:27:28 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Thu, 3 Apr 2008 18:27:28 +0200 (CEST) Subject: [Python-3000-checkins] r62128 - in python/branches/py3k: Lib/test/test_unicode.py Python/ast.c Message-ID: <20080403162728.068881E4012@bag.python.org> Author: benjamin.peterson Date: Thu Apr 3 18:27:27 2008 New Revision: 62128 Modified: python/branches/py3k/Lib/test/test_unicode.py python/branches/py3k/Python/ast.c Log: #2541 Allow unicode escapes in raw strings Modified: python/branches/py3k/Lib/test/test_unicode.py ============================================================================== --- python/branches/py3k/Lib/test/test_unicode.py (original) +++ python/branches/py3k/Lib/test/test_unicode.py Thu Apr 3 18:27:27 2008 @@ -68,6 +68,8 @@ self.assertRaises(SyntaxError, eval, '\'\\Ufffffffe\'') self.assertRaises(SyntaxError, eval, '\'\\Uffffffff\'') self.assertRaises(SyntaxError, eval, '\'\\U%08x\'' % 0x110000) + # Test that raw mode does unicode escapes + self.assertEqual(r"\u0020", " ") def test_repr(self): if not sys.platform.startswith('java'): Modified: python/branches/py3k/Python/ast.c ============================================================================== --- python/branches/py3k/Python/ast.c (original) +++ python/branches/py3k/Python/ast.c Thu Apr 3 18:27:27 2008 @@ -3231,7 +3231,7 @@ return NULL; } } - if (!*bytesmode && !rawmode) { + if (!*bytesmode) { return decode_unicode(s, len, rawmode, c->c_encoding); } if (*bytesmode) { From python-3000-checkins at python.org Thu Apr 3 20:39:00 2008 From: python-3000-checkins at python.org (trent.nelson) Date: Thu, 3 Apr 2008 20:39:00 +0200 (CEST) Subject: [Python-3000-checkins] r62130 - python/branches/py3k Message-ID: <20080403183900.955B41E402C@bag.python.org> Author: trent.nelson Date: Thu Apr 3 20:39:00 2008 New Revision: 62130 Modified: python/branches/py3k/ (props changed) Log: [XXX: this is a temporary block, given the addition/deletion of new files I'll unblock and merge it to py3k myself once I've observed trunk buildbots' behaviour.] Blocked revisions 62129 via svnmerge ........ r62129 | trent.nelson | 2008-04-03 19:27:06 +0100 (Thu, 03 Apr 2008) | 16 lines Reimplement kill_python. The existing version had a number of flaws, namely, it didn't work for x64 and it wasn't precise about which python_d.exe it was killing -- it just killed the first one it came across that happened to have 'pcbuild\python_d.exe' or 'build\python_d.exe' in it's path. The new version has been rewritten from the ground up and now lives in PCbuild, instead of Tools\buildbot, and it has also been incorporated into the Visual Studio solution (pcbuild.sln) as 'kill_python'. The solution has also been altered such that kill_python is called where necessary in the build process in order to prevent any linking errors due to open file locks. In lieu of this, all of the existing bits and pieces in Tools\buildbot that called out to kill_python at various points have also been removed as they are now obsolete. Tested on both Win32 and x64. Change set (included to improve usefulness of svnmerge log entry): M PCbuild\pythoncore.vcproj M PCbuild\pcbuild.sln M PCbuild\release.vsprops A PCbuild\kill_python.vcproj M PCbuild\debug.vsprops A PCbuild\kill_python.c D Tools\buildbot\kill_python.bat D Tools\buildbot\kill_python.mak M Tools\buildbot\build.bat D Tools\buildbot\Makefile M Tools\buildbot\build-amd64.bat M Tools\buildbot\buildmsi.bat D Tools\buildbot\kill_python.c ........ From python-3000-checkins at python.org Thu Apr 3 21:48:41 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Thu, 3 Apr 2008 21:48:41 +0200 (CEST) Subject: [Python-3000-checkins] r62132 - python/branches/py3k Message-ID: <20080403194841.4FD761E4003@bag.python.org> Author: benjamin.peterson Date: Thu Apr 3 21:48:41 2008 New Revision: 62132 Modified: python/branches/py3k/ (props changed) Log: Blocked revisions 62123,62126 via svnmerge ........ r62123 | barry.warsaw | 2008-04-02 23:10:02 -0500 (Wed, 02 Apr 2008) | 2 lines Updating for 2.6a2 ........ r62126 | barry.warsaw | 2008-04-02 23:14:19 -0500 (Wed, 02 Apr 2008) | 1 line Post tag version tweak ........ From python-3000-checkins at python.org Thu Apr 3 22:44:04 2008 From: python-3000-checkins at python.org (trent.nelson) Date: Thu, 3 Apr 2008 22:44:04 +0200 (CEST) Subject: [Python-3000-checkins] r62134 - python/branches/py3k Message-ID: <20080403204404.1D2641E4003@bag.python.org> Author: trent.nelson Date: Thu Apr 3 22:44:03 2008 New Revision: 62134 Modified: python/branches/py3k/ (props changed) Log: Unblock revision 62129. From python-3000-checkins at python.org Thu Apr 3 22:47:31 2008 From: python-3000-checkins at python.org (trent.nelson) Date: Thu, 3 Apr 2008 22:47:31 +0200 (CEST) Subject: [Python-3000-checkins] r62135 - in python/branches/py3k: PCbuild/debug.vsprops PCbuild/kill_python.c PCbuild/kill_python.vcproj PCbuild/pcbuild.sln PCbuild/pythoncore.vcproj PCbuild/release.vsprops Tools/buildbot/Makefile Tools/buildbot/build-amd64.bat Tools/buildbot/build.bat Tools/buildbot/buildmsi.bat Tools/buildbot/kill_python.bat Tools/buildbot/kill_python.c Tools/buildbot/kill_python.mak Message-ID: <20080403204731.220731E4003@bag.python.org> Author: trent.nelson Date: Thu Apr 3 22:47:30 2008 New Revision: 62135 Added: python/branches/py3k/PCbuild/kill_python.c - copied unchanged from r62133, python/trunk/PCbuild/kill_python.c python/branches/py3k/PCbuild/kill_python.vcproj - copied unchanged from r62133, python/trunk/PCbuild/kill_python.vcproj Removed: python/branches/py3k/Tools/buildbot/Makefile python/branches/py3k/Tools/buildbot/kill_python.bat python/branches/py3k/Tools/buildbot/kill_python.c python/branches/py3k/Tools/buildbot/kill_python.mak Modified: python/branches/py3k/ (props changed) python/branches/py3k/PCbuild/debug.vsprops python/branches/py3k/PCbuild/pcbuild.sln python/branches/py3k/PCbuild/pythoncore.vcproj python/branches/py3k/PCbuild/release.vsprops python/branches/py3k/Tools/buildbot/build-amd64.bat python/branches/py3k/Tools/buildbot/build.bat python/branches/py3k/Tools/buildbot/buildmsi.bat Log: Merged revisions 62129,62131,62133 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62129 | trent.nelson | 2008-04-03 19:27:06 +0100 (Thu, 03 Apr 2008) | 16 lines Reimplement kill_python. The existing version had a number of flaws, namely, it didn't work for x64 and it wasn't precise about which python_d.exe it was killing -- it just killed the first one it came across that happened to have 'pcbuild\python_d.exe' or 'build\python_d.exe' in it's path. The new version has been rewritten from the ground up and now lives in PCbuild, instead of Tools\buildbot, and it has also been incorporated into the Visual Studio solution (pcbuild.sln) as 'kill_python'. The solution has also been altered such that kill_python is called where necessary in the build process in order to prevent any linking errors due to open file locks. In lieu of this, all of the existing bits and pieces in Tools\buildbot that called out to kill_python at various points have also been removed as they are now obsolete. Tested on both Win32 and x64. Change set (included to improve usefulness of svnmerge log entry): M PCbuild\pythoncore.vcproj M PCbuild\pcbuild.sln M PCbuild\release.vsprops A PCbuild\kill_python.vcproj M PCbuild\debug.vsprops A PCbuild\kill_python.c D Tools\buildbot\kill_python.bat D Tools\buildbot\kill_python.mak M Tools\buildbot\build.bat D Tools\buildbot\Makefile M Tools\buildbot\build-amd64.bat M Tools\buildbot\buildmsi.bat D Tools\buildbot\kill_python.c ........ r62131 | trent.nelson | 2008-04-03 19:48:53 +0100 (Thu, 03 Apr 2008) | 1 line Add the correct OutputFile values for debug builds. Fixes r62129's commit. ........ r62133 | trent.nelson | 2008-04-03 21:00:08 +0100 (Thu, 03 Apr 2008) | 1 line Make kill_python a little more forgiving if it can't obtain a snapshot of module information for a given python[_d].exe process. Failing here was too pessimistic; the python[_d].exe process may be owned by another user, which is the case in some buildbot environments. ........ Modified: python/branches/py3k/PCbuild/debug.vsprops ============================================================================== --- python/branches/py3k/PCbuild/debug.vsprops (original) +++ python/branches/py3k/PCbuild/debug.vsprops Thu Apr 3 22:47:30 2008 @@ -8,4 +8,8 @@ Name="VCCLCompilerTool" PreprocessorDefinitions="_DEBUG" /> - \ No newline at end of file + + Modified: python/branches/py3k/PCbuild/pcbuild.sln ============================================================================== --- python/branches/py3k/PCbuild/pcbuild.sln (original) +++ python/branches/py3k/PCbuild/pcbuild.sln Thu Apr 3 22:47:30 2008 @@ -11,6 +11,7 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pythoncore", "pythoncore.vcproj", "{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}" ProjectSection(ProjectDependencies) = postProject {F0E0541E-F17D-430B-97C4-93ADF0DD284E} = {F0E0541E-F17D-430B-97C4-93ADF0DD284E} + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31} = {6DE10744-E396-40A5-B4E2-1B69AA7C8D31} {C73F0EC1-358B-4177-940F-0846AC8B04CD} = {C73F0EC1-358B-4177-940F-0846AC8B04CD} EndProjectSection EndProject @@ -20,6 +21,9 @@ EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "w9xpopen", "w9xpopen.vcproj", "{E9E0A1F6-0009-4E8C-B8F8-1B8F5D49A058}" + ProjectSection(ProjectDependencies) = postProject + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31} = {6DE10744-E396-40A5-B4E2-1B69AA7C8D31} + EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "make_buildinfo", "make_buildinfo.vcproj", "{C73F0EC1-358B-4177-940F-0846AC8B04CD}" EndProject @@ -36,6 +40,7 @@ EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_bsddb", "_bsddb.vcproj", "{B4D38F3F-68FB-42EC-A45D-E00657BB3627}" ProjectSection(ProjectDependencies) = postProject + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31} = {6DE10744-E396-40A5-B4E2-1B69AA7C8D31} {62172C7D-B39E-409A-B352-370FF5098C19} = {62172C7D-B39E-409A-B352-370FF5098C19} {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} = {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} EndProjectSection @@ -117,8 +122,16 @@ EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_bsddb44", "_bsddb44.vcproj", "{62172C7D-B39E-409A-B352-370FF5098C19}" + ProjectSection(ProjectDependencies) = postProject + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31} = {6DE10744-E396-40A5-B4E2-1B69AA7C8D31} + EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "sqlite3", "sqlite3.vcproj", "{A1A295E5-463C-437F-81CA-1F32367685DA}" + ProjectSection(ProjectDependencies) = postProject + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31} = {6DE10744-E396-40A5-B4E2-1B69AA7C8D31} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "kill_python", "kill_python.vcproj", "{6DE10744-E396-40A5-B4E2-1B69AA7C8D31}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -524,6 +537,22 @@ {A1A295E5-463C-437F-81CA-1F32367685DA}.Release|Win32.Build.0 = Release|Win32 {A1A295E5-463C-437F-81CA-1F32367685DA}.Release|x64.ActiveCfg = Release|x64 {A1A295E5-463C-437F-81CA-1F32367685DA}.Release|x64.Build.0 = Release|x64 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Debug|Win32.ActiveCfg = Debug|Win32 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Debug|Win32.Build.0 = Debug|Win32 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Debug|x64.ActiveCfg = Debug|x64 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Debug|x64.Build.0 = Debug|x64 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGInstrument|Win32.ActiveCfg = Release|Win32 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGInstrument|Win32.Build.0 = Release|Win32 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGInstrument|x64.ActiveCfg = Release|x64 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGInstrument|x64.Build.0 = Release|x64 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGUpdate|Win32.ActiveCfg = Release|Win32 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGUpdate|Win32.Build.0 = Release|Win32 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGUpdate|x64.ActiveCfg = Release|x64 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGUpdate|x64.Build.0 = Release|x64 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Release|Win32.ActiveCfg = Release|Win32 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Release|Win32.Build.0 = Release|Win32 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Release|x64.ActiveCfg = Release|x64 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE Modified: python/branches/py3k/PCbuild/pythoncore.vcproj ============================================================================== --- python/branches/py3k/PCbuild/pythoncore.vcproj (original) +++ python/branches/py3k/PCbuild/pythoncore.vcproj Thu Apr 3 22:47:30 2008 @@ -58,8 +58,8 @@ /> + Deleted: /python/branches/py3k/Tools/buildbot/Makefile ============================================================================== --- /python/branches/py3k/Tools/buildbot/Makefile Thu Apr 3 22:47:30 2008 +++ (empty file) @@ -1,6 +0,0 @@ -all: kill_python.exe - ./kill_python.exe - -kill_python.exe: kill_python.c - gcc -o kill_python.exe kill_python.c -lpsapi - Modified: python/branches/py3k/Tools/buildbot/build-amd64.bat ============================================================================== --- python/branches/py3k/Tools/buildbot/build-amd64.bat (original) +++ python/branches/py3k/Tools/buildbot/build-amd64.bat Thu Apr 3 22:47:30 2008 @@ -1,6 +1,5 @@ @rem Used by the buildbot "compile" step. cmd /c Tools\buildbot\external-amd64.bat call "%VS90COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64 -REM cmd /q/c Tools\buildbot\kill_python.bat cmd /c Tools\buildbot\clean-amd64.bat vcbuild PCbuild\pcbuild.sln "Debug|x64" Modified: python/branches/py3k/Tools/buildbot/build.bat ============================================================================== --- python/branches/py3k/Tools/buildbot/build.bat (original) +++ python/branches/py3k/Tools/buildbot/build.bat Thu Apr 3 22:47:30 2008 @@ -1,7 +1,6 @@ @rem Used by the buildbot "compile" step. cmd /c Tools\buildbot\external.bat call "%VS90COMNTOOLS%vsvars32.bat" -cmd /q/c Tools\buildbot\kill_python.bat cmd /c Tools\buildbot\clean.bat vcbuild /useenv PCbuild\pcbuild.sln "Debug|Win32" Modified: python/branches/py3k/Tools/buildbot/buildmsi.bat ============================================================================== --- python/branches/py3k/Tools/buildbot/buildmsi.bat (original) +++ python/branches/py3k/Tools/buildbot/buildmsi.bat Thu Apr 3 22:47:30 2008 @@ -8,7 +8,6 @@ ) @rem build Python -cmd /q/c Tools\buildbot\kill_python.bat vcbuild /useenv PCbuild\pcbuild.sln "Release|Win32" @rem build the documentation Deleted: /python/branches/py3k/Tools/buildbot/kill_python.bat ============================================================================== --- /python/branches/py3k/Tools/buildbot/kill_python.bat Thu Apr 3 22:47:30 2008 +++ (empty file) @@ -1,3 +0,0 @@ -cd Tools\buildbot -nmake /C /S /f kill_python.mak -kill_python.exe Deleted: /python/branches/py3k/Tools/buildbot/kill_python.c ============================================================================== --- /python/branches/py3k/Tools/buildbot/kill_python.c Thu Apr 3 22:47:30 2008 +++ (empty file) @@ -1,68 +0,0 @@ -/* This program looks for processes which have build\PCbuild\python.exe - in their path and terminates them. */ -#include -#include -#include - -int main() -{ - DWORD pids[1024], cbNeeded; - int i, num_processes; - if (!EnumProcesses(pids, sizeof(pids), &cbNeeded)) { - printf("EnumProcesses failed\n"); - return 1; - } - num_processes = cbNeeded/sizeof(pids[0]); - for (i = 0; i < num_processes; i++) { - HANDLE hProcess; - char path[MAX_PATH]; - HMODULE mods[1024]; - int k, num_mods; - hProcess = OpenProcess(PROCESS_QUERY_INFORMATION - | PROCESS_VM_READ - | PROCESS_TERMINATE , - FALSE, pids[i]); - if (!hProcess) - /* process not accessible */ - continue; - if (!EnumProcessModules(hProcess, mods, sizeof(mods), &cbNeeded)) { - /* For unknown reasons, this sometimes returns ERROR_PARTIAL_COPY; - this apparently means we are not supposed to read the process. */ - if (GetLastError() == ERROR_PARTIAL_COPY) { - CloseHandle(hProcess); - continue; - } - printf("EnumProcessModules failed: %d\n", GetLastError()); - return 1; - } - if (!GetModuleFileNameEx(hProcess, NULL, path, sizeof(path))) { - printf("GetProcessImageFileName failed\n"); - return 1; - } - - _strlwr(path); - /* printf("%s\n", path); */ - - /* Check if we are running a buildbot version of Python. - - On Windows, this will always be a debug build from the - PCbuild directory. build\\PCbuild\\python_d.exe - - On Cygwin, the pathname is similar to other Unixes. - Use \\build\\python.exe to ensure we don't match - PCbuild\\python.exe which could be a normal instance - of Python running on vanilla Windows. - */ - if ((strstr(path, "pcbuild\\python_d.exe") != NULL) || - (strstr(path, "\\build\\python.exe") != NULL)) { - printf("Terminating %s (pid %d)\n", path, pids[i]); - if (!TerminateProcess(hProcess, 1)) { - printf("Termination failed: %d\n", GetLastError()); - return 1; - } - return 0; - } - - CloseHandle(hProcess); - } -} Deleted: /python/branches/py3k/Tools/buildbot/kill_python.mak ============================================================================== --- /python/branches/py3k/Tools/buildbot/kill_python.mak Thu Apr 3 22:47:30 2008 +++ (empty file) @@ -1,2 +0,0 @@ -kill_python.exe: kill_python.c - cl -nologo -o kill_python.exe kill_python.c psapi.lib From python-3000-checkins at python.org Fri Apr 4 03:36:37 2008 From: python-3000-checkins at python.org (barry.warsaw) Date: Fri, 4 Apr 2008 03:36:37 +0200 (CEST) Subject: [Python-3000-checkins] r62139 - python/branches/py3k/Misc/NEWS Message-ID: <20080404013637.41BD71E4003@bag.python.org> Author: barry.warsaw Date: Fri Apr 4 03:36:36 2008 New Revision: 62139 Modified: python/branches/py3k/Misc/NEWS Log: post release updates Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Fri Apr 4 03:36:36 2008 @@ -4,6 +4,21 @@ (editors: check NEWS.help for information about editing NEWS using ReST.) +What's New in Python 3.0a5? +=========================== + +*Release date: XX-XXX-2008* + +Core and Builtins +----------------- + +Extension Modules +----------------- + +Library +------- + + What's New in Python 3.0a4? =========================== From python-3000-checkins at python.org Fri Apr 4 04:31:12 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Fri, 4 Apr 2008 04:31:12 +0200 (CEST) Subject: [Python-3000-checkins] r62140 - python/branches/py3k Message-ID: <20080404023112.A944C1E4021@bag.python.org> Author: benjamin.peterson Date: Fri Apr 4 04:31:12 2008 New Revision: 62140 Modified: python/branches/py3k/ (props changed) Log: Blocked revisions 62138 via svnmerge ........ r62138 | barry.warsaw | 2008-04-03 20:34:41 -0500 (Thu, 03 Apr 2008) | 1 line post release updates ........ From python-3000-checkins at python.org Fri Apr 4 10:37:59 2008 From: python-3000-checkins at python.org (thomas.heller) Date: Fri, 4 Apr 2008 10:37:59 +0200 (CEST) Subject: [Python-3000-checkins] r62144 - python/branches/py3k Message-ID: <20080404083759.484861E4023@bag.python.org> Author: thomas.heller Date: Fri Apr 4 10:37:59 2008 New Revision: 62144 Modified: python/branches/py3k/ (props changed) Log: Blocked revisions 62143 via svnmerge ........ r62143 | thomas.heller | 2008-04-04 10:35:44 +0200 (Fr, 04 Apr 2008) | 1 line Issue #2543: Make ctypes compatible (again) with Python 2.3, 2.4, and 2.5. ........ From python-3000-checkins at python.org Fri Apr 4 12:18:23 2008 From: python-3000-checkins at python.org (thomas.heller) Date: Fri, 4 Apr 2008 12:18:23 +0200 (CEST) Subject: [Python-3000-checkins] r62146 - in python/branches/py3k: Misc/NEWS configure configure.in Message-ID: <20080404101823.AEB4B1E4010@bag.python.org> Author: thomas.heller Date: Fri Apr 4 12:18:23 2008 New Revision: 62146 Modified: python/branches/py3k/ (props changed) python/branches/py3k/Misc/NEWS python/branches/py3k/configure python/branches/py3k/configure.in Log: Merged revisions 62145 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62145 | thomas.heller | 2008-04-04 12:07:55 +0200 (Fri, 04 Apr 2008) | 3 lines Issue #2544: On HP-UX systems, use 'gcc -shared' for linking when gcc is used as compiler. ........ Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Fri Apr 4 12:18:23 2008 @@ -18,6 +18,11 @@ Library ------- +Build +----- + +- Issue #2544: On HP-UX systems, use 'gcc -shared' for linking when + gcc is used as compiler. What's New in Python 3.0a4? =========================== Modified: python/branches/py3k/configure ============================================================================== --- python/branches/py3k/configure (original) +++ python/branches/py3k/configure Fri Apr 4 12:18:23 2008 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 61848 . +# From configure.in Revision: 62003 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.61 for python 3.0. # @@ -12846,7 +12846,11 @@ then LDSHARED='$(CC) -shared' else LDSHARED='$(CC) -G'; fi ;; - hp*|HP*) LDSHARED="ld -b";; + hp*|HP*) + if test "$GCC" = "yes" + then LDSHARED='$(CC) -shared' + else LDSHARED='ld -b'; + fi ;; OSF*) LDSHARED="ld -shared -expect_unresolved \"*\"";; Darwin/1.3*) LDSHARED='$(CC) $(LDFLAGS) -bundle' Modified: python/branches/py3k/configure.in ============================================================================== --- python/branches/py3k/configure.in (original) +++ python/branches/py3k/configure.in Fri Apr 4 12:18:23 2008 @@ -1468,7 +1468,11 @@ then LDSHARED='$(CC) -shared' else LDSHARED='$(CC) -G'; fi ;; - hp*|HP*) LDSHARED="ld -b";; + hp*|HP*) + if test "$GCC" = "yes" + then LDSHARED='$(CC) -shared' + else LDSHARED='ld -b'; + fi ;; OSF*) LDSHARED="ld -shared -expect_unresolved \"*\"";; Darwin/1.3*) LDSHARED='$(CC) $(LDFLAGS) -bundle' From python-3000-checkins at python.org Fri Apr 4 21:53:14 2008 From: python-3000-checkins at python.org (thomas.heller) Date: Fri, 4 Apr 2008 21:53:14 +0200 (CEST) Subject: [Python-3000-checkins] r62155 - in python/branches/py3k: Misc/NEWS Modules/_ctypes/libffi/README Modules/_ctypes/libffi/configure Modules/_ctypes/libffi/configure.ac Modules/_ctypes/libffi/include/ffi.h.in Modules/_ctypes/libffi/libffi.pc.in Modules/_ctypes/libffi/src/pa/hpux32.S Modules/_ctypes/libffi/src/x86/darwin64.S Modules/_ctypes/libffi/src/x86/ffi.c Modules/_ctypes/libffi/src/x86/freebsd.S Message-ID: <20080404195314.F24CF1E4010@bag.python.org> Author: thomas.heller Date: Fri Apr 4 21:53:14 2008 New Revision: 62155 Added: python/branches/py3k/Modules/_ctypes/libffi/src/pa/hpux32.S - copied unchanged from r62149, python/trunk/Modules/_ctypes/libffi/src/pa/hpux32.S python/branches/py3k/Modules/_ctypes/libffi/src/x86/darwin64.S - copied unchanged from r62149, python/trunk/Modules/_ctypes/libffi/src/x86/darwin64.S python/branches/py3k/Modules/_ctypes/libffi/src/x86/freebsd.S - copied unchanged from r62149, python/trunk/Modules/_ctypes/libffi/src/x86/freebsd.S Removed: python/branches/py3k/Modules/_ctypes/libffi/libffi.pc.in Modified: python/branches/py3k/ (props changed) python/branches/py3k/Misc/NEWS python/branches/py3k/Modules/_ctypes/libffi/README python/branches/py3k/Modules/_ctypes/libffi/configure python/branches/py3k/Modules/_ctypes/libffi/configure.ac python/branches/py3k/Modules/_ctypes/libffi/include/ffi.h.in python/branches/py3k/Modules/_ctypes/libffi/src/x86/ffi.c Log: Merged revisions 62149, 62153, 62154 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk Sync with files from the just released libffi 3.0.5 version. More files from libffi 3.0.5. Removed libffi.pc.in because it is not needed for ctypes. News entry for: Sync with files from the just released libffi 3.0.5 version. Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Fri Apr 4 21:53:14 2008 @@ -18,6 +18,10 @@ Library ------- +- The bundled libffi copy is now in sync with the recently released + libffi3.0.5 version, apart from some small changes to + Modules/_ctypes/libffi/configure.ac. + Build ----- Modified: python/branches/py3k/Modules/_ctypes/libffi/README ============================================================================== --- python/branches/py3k/Modules/_ctypes/libffi/README (original) +++ python/branches/py3k/Modules/_ctypes/libffi/README Fri Apr 4 21:53:14 2008 @@ -1,7 +1,7 @@ Status ====== -libffi-3.0.4 was released on February 24, 2008. Check the libffi web +libffi-3.0.5 was released on April 3, 2008. Check the libffi web page for updates: . @@ -158,6 +158,11 @@ History ======= +3.0.5 Apr-3-08 + Fix libffi.pc file. + Fix #define ARM for IcedTea users. + Fix x86 closure bug. + 3.0.4 Feb-24-08 Fix x86 OpenBSD configury. Modified: python/branches/py3k/Modules/_ctypes/libffi/configure ============================================================================== --- python/branches/py3k/Modules/_ctypes/libffi/configure (original) +++ python/branches/py3k/Modules/_ctypes/libffi/configure Fri Apr 4 21:53:14 2008 @@ -1,6 +1,6 @@ #! /bin/sh # Guess values for system-dependent variables and create Makefiles. -# Generated by GNU Autoconf 2.61 for libffi 3.0.4. +# Generated by GNU Autoconf 2.61 for libffi 3.0.5. # # Report bugs to . # @@ -728,8 +728,8 @@ # Identity of this package. PACKAGE_NAME='libffi' PACKAGE_TARNAME='libffi' -PACKAGE_VERSION='3.0.4' -PACKAGE_STRING='libffi 3.0.4' +PACKAGE_VERSION='3.0.5' +PACKAGE_STRING='libffi 3.0.5' PACKAGE_BUGREPORT='http://gcc.gnu.org/bugs.html' # Factoring default headers for most tests. @@ -1459,7 +1459,7 @@ # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF -\`configure' configures libffi 3.0.4 to adapt to many kinds of systems. +\`configure' configures libffi 3.0.5 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... @@ -1530,7 +1530,7 @@ if test -n "$ac_init_help"; then case $ac_init_help in - short | recursive ) echo "Configuration of libffi 3.0.4:";; + short | recursive ) echo "Configuration of libffi 3.0.5:";; esac cat <<\_ACEOF @@ -1640,7 +1640,7 @@ test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF -libffi configure 3.0.4 +libffi configure 3.0.5 generated by GNU Autoconf 2.61 Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, @@ -1654,7 +1654,7 @@ This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. -It was created by libffi $as_me 3.0.4, which was +It was created by libffi $as_me 3.0.5, which was generated by GNU Autoconf 2.61. Invocation command line was $ $0 $@ @@ -2477,7 +2477,7 @@ # Define the identity of the package. PACKAGE='libffi' - VERSION='3.0.4' + VERSION='3.0.5' cat >>confdefs.h <<_ACEOF @@ -23327,7 +23327,7 @@ # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" -This file was extended by libffi $as_me 3.0.4, which was +This file was extended by libffi $as_me 3.0.5, which was generated by GNU Autoconf 2.61. Invocation command line was CONFIG_FILES = $CONFIG_FILES @@ -23384,7 +23384,7 @@ _ACEOF cat >>$CONFIG_STATUS <<_ACEOF ac_cs_version="\\ -libffi config.status 3.0.4 +libffi config.status 3.0.5 configured by $0, generated by GNU Autoconf 2.61, with options \\"`echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\" Modified: python/branches/py3k/Modules/_ctypes/libffi/configure.ac ============================================================================== --- python/branches/py3k/Modules/_ctypes/libffi/configure.ac (original) +++ python/branches/py3k/Modules/_ctypes/libffi/configure.ac Fri Apr 4 21:53:14 2008 @@ -1,8 +1,11 @@ dnl Process this with autoconf to create configure +# +# file from libffi - slightly patched for ctypes +# AC_PREREQ(2.59) -AC_INIT([libffi], [3.0.4], [http://gcc.gnu.org/bugs.html]) +AC_INIT([libffi], [3.0.5], [http://gcc.gnu.org/bugs.html]) AC_CONFIG_HEADERS([fficonfig.h]) AC_CANONICAL_SYSTEM Modified: python/branches/py3k/Modules/_ctypes/libffi/include/ffi.h.in ============================================================================== --- python/branches/py3k/Modules/_ctypes/libffi/include/ffi.h.in (original) +++ python/branches/py3k/Modules/_ctypes/libffi/include/ffi.h.in Fri Apr 4 21:53:14 2008 @@ -57,7 +57,9 @@ #endif /* Specify which architecture libffi is configured for. */ +#ifndef @TARGET@ #define @TARGET@ +#endif /* ---- System configuration information --------------------------------- */ Deleted: /python/branches/py3k/Modules/_ctypes/libffi/libffi.pc.in ============================================================================== --- /python/branches/py3k/Modules/_ctypes/libffi/libffi.pc.in Fri Apr 4 21:53:14 2008 +++ (empty file) @@ -1,10 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -includedir=${libdir}/@PACKAGE_NAME at -@PACKAGE_VERSION@/include - -Name: @PACKAGE_NAME@ -Description: Library supporting Foreign Function Interfaces -Version: @PACKAGE_VERSION@ -Libs: -lffi -Cflags: -I${includedir} Modified: python/branches/py3k/Modules/_ctypes/libffi/src/x86/ffi.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/libffi/src/x86/ffi.c (original) +++ python/branches/py3k/Modules/_ctypes/libffi/src/x86/ffi.c Fri Apr 4 21:53:14 2008 @@ -349,14 +349,14 @@ { FFI_INIT_TRAMPOLINE (&closure->tramp[0], &ffi_closure_SYSV, - (void*)closure); + (void*)codeloc); } #ifdef X86_WIN32 else if (cif->abi == FFI_STDCALL) { FFI_INIT_TRAMPOLINE_STDCALL (&closure->tramp[0], &ffi_closure_STDCALL, - (void*)closure, cif->bytes); + (void*)codeloc, cif->bytes); } #endif else From python-3000-checkins at python.org Sat Apr 5 01:25:28 2008 From: python-3000-checkins at python.org (amaury.forgeotdarc) Date: Sat, 5 Apr 2008 01:25:28 +0200 (CEST) Subject: [Python-3000-checkins] r62157 - in python/branches/py3k: Lib/test/test_builtin.py Python/pythonrun.c Message-ID: <20080404232528.080D11E4012@bag.python.org> Author: amaury.forgeotdarc Date: Sat Apr 5 01:25:27 2008 New Revision: 62157 Modified: python/branches/py3k/Lib/test/test_builtin.py python/branches/py3k/Python/pythonrun.c Log: Issue2221: in Idle, exec('xx') raised a SystemError('error return without exception set') instead of the expected NameError This happens when sys.stdout is redirected to something that cannot flush(). the flush_io() function must be exception-neutral: don't raise, and don't clear exceptions. Next step: exec() is not supposed to flush sys.stdout... Modified: python/branches/py3k/Lib/test/test_builtin.py ============================================================================== --- python/branches/py3k/Lib/test/test_builtin.py (original) +++ python/branches/py3k/Lib/test/test_builtin.py Sat Apr 5 01:25:27 2008 @@ -448,6 +448,17 @@ del l['__builtins__'] self.assertEqual((g, l), ({'a': 1}, {'b': 2})) + def test_exec_redirected(self): + savestdout = sys.stdout + sys.stdout = None # Whatever that cannot flush() + try: + # Used to raise SystemError('error return without exception set') + exec('a') + except NameError: + pass + finally: + sys.stdout = savestdout + def test_filter(self): self.assertEqual(list(filter(lambda c: 'a' <= c <= 'z', 'Hello World')), list('elloorld')) self.assertEqual(list(filter(None, [1, 'hello', [], [3], '', None, 9, 0])), [1, 'hello', [3], 9]) Modified: python/branches/py3k/Python/pythonrun.c ============================================================================== --- python/branches/py3k/Python/pythonrun.c (original) +++ python/branches/py3k/Python/pythonrun.c Sat Apr 5 01:25:27 2008 @@ -1467,6 +1467,11 @@ flush_io(void) { PyObject *f, *r; + PyObject *type, *value, *traceback; + + /* Save the current exception */ + PyErr_Fetch(&type, &value, &traceback); + f = PySys_GetObject("stderr"); if (f != NULL) { r = PyObject_CallMethod(f, "flush", ""); @@ -1483,6 +1488,8 @@ else PyErr_Clear(); } + + PyErr_Restore(type, value, traceback); } static PyObject * From python-3000-checkins at python.org Sat Apr 5 06:47:46 2008 From: python-3000-checkins at python.org (neal.norwitz) Date: Sat, 5 Apr 2008 06:47:46 +0200 (CEST) Subject: [Python-3000-checkins] r62162 - in python/branches/py3k: Doc/library/signal.rst Doc/whatsnew/2.6.rst Lib/distutils/core.py Lib/distutils/tests/test_core.py Lib/sqlite3/test/transactions.py Lib/test/test_signal.py Lib/test/test_threading.py Lib/threading.py Tools/buildbot/buildmsi.bat Message-ID: <20080405044746.701531E4012@bag.python.org> Author: neal.norwitz Date: Sat Apr 5 06:47:45 2008 New Revision: 62162 Added: python/branches/py3k/Lib/distutils/tests/test_core.py - copied, changed from r62142, python/trunk/Lib/distutils/tests/test_core.py Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/signal.rst python/branches/py3k/Doc/whatsnew/2.6.rst python/branches/py3k/Lib/distutils/core.py python/branches/py3k/Lib/sqlite3/test/transactions.py python/branches/py3k/Lib/test/test_signal.py python/branches/py3k/Lib/test/test_threading.py python/branches/py3k/Lib/threading.py python/branches/py3k/Tools/buildbot/buildmsi.bat Log: Merged revisions 61440-61441,61443,61445-61448,61451-61452,61455-61457,61459-61464,61466-61467,61469-61470,61476-61477,61479,61481-61482,61485,61487,61490,61493-61494,61497,61499-61502,61505-61506,61508,61511-61514,61519,61521-61522,61530-61531,61533-61537,61541-61555,61557-61558,61561-61562,61566-61569,61572-61574,61578-61579,61583-61584,61588-61589,61592,61594,61598-61601,61603-61604,61607-61612,61617,61619-61620,61624,61626,61628-61630,61635-61638,61640-61643,61645,61648,61653-61655,61659-61662,61664,61666,61668-61671,61673,61675,61679-61680,61682,61685-61686,61689-61695,61697-61699,61701-61703,61706,61710,61713,61717,61723,61726-61730,61736,61738,61740,61742,61745-61752,61754-61760,61762-61764,61768,61770-61772,61774-61775,61784-61787,61789-61792,61794-61795,61797-61806,61808-61809,61811-61812,61814-61819,61824,61826-61833,61835-61840,61843-61845,61848,61850,61854-61862,61865-61866,61868,61872-61873,61876-61877,61883-61888,61890-61891,61893-61899,61901-61903,61905-61912,61914,61917,61920-61921,61927,61930,61932-61934,61939,61941-61942,61944-61951,61955,61960-61963,61980,61982-61983,61991,61994-61996,62001-62003,62008-62010,62016-62017,62022,62024,62027,62031-62034,62041,62045-62046,62055-62058,62060-62066,62068-62074,62076-62079,62081-62083,62086-62089,62092-62094,62098,62101,62104,62106-62109,62115-62122,62124-62125,62127-62128,62130,62132,62134-62137,62139-62142,62144,62146-62148,62150-62152,62155-62161 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62127 | trent.nelson | 2008-04-03 08:39:17 -0700 (Thu, 03 Apr 2008) | 1 line Remove the building of Berkeley DB step; _bsddb44.vcproj takes care of this for us now. ........ r62136 | amaury.forgeotdarc | 2008-04-03 16:07:55 -0700 (Thu, 03 Apr 2008) | 9 lines #1733757: the interpreter would hang on shutdown, if the function set by sys.settrace calls threading.currentThread. The correction somewhat improves the code, but it was close. Many thanks to the "with" construct, which turns python code into C calls. I wonder if it is not better to sys.settrace(None) just after running the __main__ module and before finalization. ........ r62141 | jeffrey.yasskin | 2008-04-03 21:51:19 -0700 (Thu, 03 Apr 2008) | 5 lines Doh! os.read() raises an OSError, not an IOError when it's interrupted. And fix some flakiness in test_itimer_prof, which could detect that the timer had reached 0 before the signal arrived announcing that fact. ........ r62142 | fred.drake | 2008-04-03 22:41:30 -0700 (Thu, 03 Apr 2008) | 4 lines - Issue #2385: distutils.core.run_script() makes __file__ available, so the controlled environment will more closely mirror the typical script environment. This supports setup.py scripts that refer to data files. ........ r62147 | fred.drake | 2008-04-04 04:31:14 -0700 (Fri, 04 Apr 2008) | 6 lines my previous change did what I said it should not: it changed the current directory to the directory in which the setup.py script lived (which made __file__ wrong) fixed, with test that the script is run in the current directory of the caller ........ r62148 | fred.drake | 2008-04-04 04:38:51 -0700 (Fri, 04 Apr 2008) | 2 lines stupid, stupid, stupid! ........ r62150 | jeffrey.yasskin | 2008-04-04 09:48:19 -0700 (Fri, 04 Apr 2008) | 2 lines Oops again. EINTR is in errno, not signal. ........ r62158 | andrew.kuchling | 2008-04-04 19:42:20 -0700 (Fri, 04 Apr 2008) | 1 line Minor edits ........ r62159 | andrew.kuchling | 2008-04-04 19:47:07 -0700 (Fri, 04 Apr 2008) | 1 line Markup fix; explain what interval timers do; typo fix ........ r62160 | andrew.kuchling | 2008-04-04 20:38:39 -0700 (Fri, 04 Apr 2008) | 1 line Various edits ........ r62161 | neal.norwitz | 2008-04-04 21:26:31 -0700 (Fri, 04 Apr 2008) | 9 lines Prevent test_sqlite from hanging on older versions of sqlite. The problem is that when trying to do the second insert, sqlite seems to sleep for a very long time. Here is the output from strace: read(6, "SQLite format 3\0\4\0\1\1\0@ \0\0\0\1\0\0\0\0"..., 1024) = 1024 nanosleep({4294, 966296000}, I don't know which version this was fixed in, but 3.2.1 definitely fails. ........ Modified: python/branches/py3k/Doc/library/signal.rst ============================================================================== --- python/branches/py3k/Doc/library/signal.rst (original) +++ python/branches/py3k/Doc/library/signal.rst Sat Apr 5 06:47:45 2008 @@ -82,7 +82,7 @@ .. data:: ITIMER_REAL - Decrements interval timer in real time, and delivers SIGALRM upon expiration. + Decrements interval timer in real time, and delivers :const:`SIGALRM` upon expiration. .. data:: ITIMER_VIRTUAL @@ -143,12 +143,18 @@ .. function:: setitimer(which, seconds[, interval]) - Sets given itimer (one of :const:`signal.ITIMER_REAL`, - :const:`signal.ITIMER_VIRTUAL` or :const:`signal.ITIMER_PROF`) especified + Sets given interval timer (one of :const:`signal.ITIMER_REAL`, + :const:`signal.ITIMER_VIRTUAL` or :const:`signal.ITIMER_PROF`) specified by *which* to fire after *seconds* (float is accepted, different from :func:`alarm`) and after that every *interval* seconds. The interval timer specified by *which* can be cleared by setting seconds to zero. + When an interval timer fires, a signal is sent to the process. + The signal sent is dependent on the timer being used; + :const:`signal.ITIMER_REAL` will deliver :const:`SIGALRM`, + :const:`signal.ITIMER_VIRTUAL` sends :const:`SIGVTALRM`, + and :const:`signal.ITIMER_PROF` will deliver :const:`SIGPROF`. + The old values are returned as a tuple: (delay, interval). Attempting to pass an invalid interval timer will cause a @@ -159,7 +165,7 @@ .. function:: getitimer(which) - Returns current value of a given itimer especified by *which*. + Returns current value of a given interval timer specified by *which*. .. versionadded:: 2.6 Modified: python/branches/py3k/Doc/whatsnew/2.6.rst ============================================================================== --- python/branches/py3k/Doc/whatsnew/2.6.rst (original) +++ python/branches/py3k/Doc/whatsnew/2.6.rst Sat Apr 5 06:47:45 2008 @@ -133,8 +133,11 @@ therefore posted a call for issue trackers, asking volunteers to set up different products and import some of the bugs and patches from SourceForge. Four different trackers were examined: Atlassian's `Jira -`__, `Launchpad `__, ` `Roundup -`__, and Trac `__. The committee eventually settled on Jira +`__, +`Launchpad `__, +`Roundup `__, and +Trac `__. +The committee eventually settled on Jira and Roundup as the two candidates. Jira is a commercial product that offers a no-cost hosted instance to free-software projects; Roundup is an open-source project that requires volunteers @@ -146,19 +149,18 @@ for Jython and for the Python web site. It will surely find other uses in the future. -Hosting is kindly provided by `Upfront `__ of XXX. Martin von -Loewis put a lot of effort into importing existing bugs and patches -from SourceForge; his scripts for this import are at XXX. +Hosting is kindly provided by `Upfront Systems `__ of Stellenbosch, South Africa. Martin von Loewis put a +lot of effort into importing existing bugs and patches from +SourceForge; his scripts for this import operation are at +http://svn.python.org/view/tracker/importer/. .. seealso:: - XXX Roundup web site. + http://bugs.python.org: The Python bug tracker. - bugs.python.org + http://bugs.jython.org: The Jython bug tracker. - bugs.jython.org - - Python web site bug tracker + http://roundup.sourceforge.net/: Roundup downloads and documentation. New Documentation Format: ReStructured Text @@ -728,6 +730,21 @@ .. ====================================================================== +.. _pep-3116: + +PEP 3116: New I/O Library +===================================================== + +XXX write this. + +.. seealso:: + + :pep:`3116` - New I/O + PEP written by Daniel Stutzbach, Mike Verdone, and Guido van Rossum. + XXX code written by who? + +.. ====================================================================== + .. _pep-3118: PEP 3118: Revised Buffer Protocol @@ -895,8 +912,9 @@ :pep:`3141` - A Type Hierarchy for Numbers PEP written by Jeffrey Yasskin. - XXX link: Discusses Scheme's numeric tower. + `Scheme's numerical tower `__, from the Guile manual. + `Scheme's number datatypes `__ from the R5RS Scheme specification. The :mod:`fractions` Module @@ -1229,7 +1247,7 @@ * The :mod:`datetime` module's :meth:`strftime` methods now support a ``%f`` format code that expands to the number of microseconds in the object, zero-padded on - the left to six places. (Contributed by XXX.) + the left to six places. (Contributed by Skip Montanaro.) .. Patch 1158 @@ -1527,7 +1545,8 @@ numbers following a triangular distribution. The returned values are between *low* and *high*, not including *high* itself, and with *mode* as the mode, the most frequently occurring value - in the distribution. (Contributed by Raymond Hettinger. XXX check) + in the distribution. (Contributed by Wladmir van der Laan and + Raymond Hettinger.) .. Patch 1681432 @@ -1544,7 +1563,7 @@ have a read-only :attr:`queue` attribute that returns the contents of the scheduler's queue, represented as a list of named tuples with the fields ``(time, priority, action, argument)``. - (Contributed by Raymond Hettinger XXX check.) + (Contributed by Raymond Hettinger.) .. Patch 1861 @@ -1554,7 +1573,7 @@ objects; ``pollobj.modify(fd, eventmask)`` takes a file descriptor or file object and an event mask, - (Contributed by XXX.) + (Contributed by Christian Heimes.) .. Patch 1657 @@ -1571,7 +1590,7 @@ :cfunc:`PySignal_SetWakeupFd`, for setting the descriptor. Event loops will use this by opening a pipe to create two descriptors, - one for reading and one for writing. The writeable descriptor + one for reading and one for writing. The writable descriptor will be passed to :func:`set_wakeup_fd`, and the readable descriptor will be added to the list of descriptors monitored by the event loop via :cfunc:`select` or :cfunc:`poll`. @@ -1586,6 +1605,16 @@ and allows changing whether signals can interrupt system calls or not. (Contributed by Ralf Schmitt.) + The :func:`setitimer` and :func:`getitimer` functions have also been + added on systems that support these system calls. :func:`setitimer` + allows setting interval timers that will cause a signal to be + delivered to the process after a specified time, measured in + wall-clock time, consumed process time, or combined process+system + time. (Contributed by Guilherme Polo.) + + .. Patch 2240 + + * The :mod:`smtplib` module now supports SMTP over SSL thanks to the addition of the :class:`SMTP_SSL` class. This class supports an interface identical to the existing :class:`SMTP` class. Both Modified: python/branches/py3k/Lib/distutils/core.py ============================================================================== --- python/branches/py3k/Lib/distutils/core.py (original) +++ python/branches/py3k/Lib/distutils/core.py Sat Apr 5 06:47:45 2008 @@ -207,7 +207,7 @@ _setup_stop_after = stop_after save_argv = sys.argv - g = {} + g = {'__file__': script_name} l = {} try: try: Copied: python/branches/py3k/Lib/distutils/tests/test_core.py (from r62142, python/trunk/Lib/distutils/tests/test_core.py) ============================================================================== --- python/trunk/Lib/distutils/tests/test_core.py (original) +++ python/branches/py3k/Lib/distutils/tests/test_core.py Sat Apr 5 06:47:45 2008 @@ -1,8 +1,10 @@ """Tests for distutils.core.""" -import StringIO +import io import distutils.core import os +import shutil +import sys import test.test_support import unittest @@ -16,21 +18,60 @@ setup() """ +setup_prints_cwd = """\ + +import os +print(os.getcwd()) + +from distutils.core import setup +setup() +""" + class CoreTestCase(unittest.TestCase): + def setUp(self): + self.old_stdout = sys.stdout + self.cleanup_testfn() + def tearDown(self): - os.remove(test.test_support.TESTFN) + sys.stdout = self.old_stdout + self.cleanup_testfn() - def write_setup(self, text): - return fn + def cleanup_testfn(self): + path = test.test_support.TESTFN + if os.path.isfile(path): + os.remove(path) + elif os.path.isdir(path): + shutil.rmtree(path) + + def write_setup(self, text, path=test.test_support.TESTFN): + open(path, "w").write(text) + return path def test_run_setup_provides_file(self): # Make sure the script can use __file__; if that's missing, the test # setup.py script will raise NameError. - fn = test.test_support.TESTFN - open(fn, "w").write(setup_using___file__) - distutils.core.run_setup(fn) + distutils.core.run_setup( + self.write_setup(setup_using___file__)) + + def test_run_setup_uses_current_dir(self): + # This tests that the setup script is run with the current directory + # as it's own current directory; this was temporarily broken by a + # previous patch when TESTFN did not use the current directory. + sys.stdout = io.StringIO() + cwd = os.getcwd() + + # Create a directory and write the setup.py file there: + os.mkdir(test.test_support.TESTFN) + setup_py = os.path.join(test.test_support.TESTFN, "setup.py") + distutils.core.run_setup( + self.write_setup(setup_prints_cwd, path=setup_py)) + + output = sys.stdout.getvalue() + if output.endswith("\n"): + output = output[:-1] + self.assertEqual(cwd, output) def test_suite(): Modified: python/branches/py3k/Lib/sqlite3/test/transactions.py ============================================================================== --- python/branches/py3k/Lib/sqlite3/test/transactions.py (original) +++ python/branches/py3k/Lib/sqlite3/test/transactions.py Sat Apr 5 06:47:45 2008 @@ -112,6 +112,10 @@ self.failUnlessEqual(len(res), 1) def CheckRaiseTimeout(self): + if sqlite.sqlite_version_info < (3, 2, 2): + # This will fail (hang) on earlier versions of sqlite. + # Determine exact version it was fixed. 3.2.1 hangs. + return self.cur1.execute("create table test(i)") self.cur1.execute("insert into test(i) values (5)") try: @@ -127,6 +131,10 @@ This tests the improved concurrency with pysqlite 2.3.4. You needed to roll back con2 before you could commit con1. """ + if sqlite.sqlite_version_info < (3, 2, 2): + # This will fail (hang) on earlier versions of sqlite. + # Determine exact version it was fixed. 3.2.1 hangs. + return self.cur1.execute("create table test(i)") self.cur1.execute("insert into test(i) values (5)") try: Modified: python/branches/py3k/Lib/test/test_signal.py ============================================================================== --- python/branches/py3k/Lib/test/test_signal.py (original) +++ python/branches/py3k/Lib/test/test_signal.py Sat Apr 5 06:47:45 2008 @@ -31,8 +31,8 @@ def ignoring_eintr(__func, *args, **kwargs): try: return __func(*args, **kwargs) - except IOError as e: - if e.errno != signal.EINTR: + except EnvironmentError as e: + if e.errno != errno.EINTR: raise return None @@ -363,12 +363,15 @@ def test_itimer_prof(self): self.itimer = signal.ITIMER_PROF signal.signal(signal.SIGPROF, self.sig_prof) - signal.setitimer(self.itimer, 0.2) + signal.setitimer(self.itimer, 0.2, 0.2) for i in range(100000000): if signal.getitimer(self.itimer) == (0.0, 0.0): break # sig_prof handler stopped this itimer + # profiling itimer should be (0.0, 0.0) now + self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0)) + # and the handler should have been called self.assertEqual(self.hndl_called, True) def test_main(): Modified: python/branches/py3k/Lib/test/test_threading.py ============================================================================== --- python/branches/py3k/Lib/test/test_threading.py (original) +++ python/branches/py3k/Lib/test/test_threading.py Sat Apr 5 06:47:45 2008 @@ -237,6 +237,35 @@ """]) self.assertEqual(rc, 42) + def test_finalize_with_trace(self): + # Issue1733757 + # Avoid a deadlock when sys.settrace steps into threading._shutdown + import subprocess + rc = subprocess.call([sys.executable, "-c", """if 1: + import sys, threading + + # A deadlock-killer, to prevent the + # testsuite to hang forever + def killer(): + import os, time + time.sleep(2) + print('program blocked; aborting') + os._exit(2) + t = threading.Thread(target=killer) + t.setDaemon(True) + t.start() + + # This is the trace function + def func(frame, event, arg): + threading.currentThread() + return func + + sys.settrace(func) + """]) + self.failIf(rc == 2, "interpreted was blocked") + self.failUnless(rc == 0, "Unexpected error") + + def test_enumerate_after_join(self): # Try hard to trigger #1703448: a thread is still returned in # threading.enumerate() after it has been join()ed. Modified: python/branches/py3k/Lib/threading.py ============================================================================== --- python/branches/py3k/Lib/threading.py (original) +++ python/branches/py3k/Lib/threading.py Sat Apr 5 06:47:45 2008 @@ -577,15 +577,16 @@ # since it isn't if dummy_threading is *not* being used then don't # hide the exception. - _active_limbo_lock.acquire() try: - try: + with _active_limbo_lock: del _active[_get_ident()] - except KeyError: - if 'dummy_threading' not in _sys.modules: - raise - finally: - _active_limbo_lock.release() + # There must not be any python code between the previous line + # and after the lock is released. Otherwise a tracing function + # could try to acquire the lock again in the same thread, (in + # currentThread()), and would block. + except KeyError: + if 'dummy_threading' not in _sys.modules: + raise def join(self, timeout=None): if not self._initialized: Modified: python/branches/py3k/Tools/buildbot/buildmsi.bat ============================================================================== --- python/branches/py3k/Tools/buildbot/buildmsi.bat (original) +++ python/branches/py3k/Tools/buildbot/buildmsi.bat Sat Apr 5 06:47:45 2008 @@ -3,9 +3,6 @@ cmd /c Tools\buildbot\external.bat @rem build release versions of things call "%VS90COMNTOOLS%vsvars32.bat" -if not exist ..\db-4.4.20\build_win32\release\libdb44s.lib ( - vcbuild db-4.4.20\build_win32\Berkeley_DB.sln /build Release /project db_static -) @rem build Python vcbuild /useenv PCbuild\pcbuild.sln "Release|Win32" From python-3000-checkins at python.org Sat Apr 5 08:16:51 2008 From: python-3000-checkins at python.org (neal.norwitz) Date: Sat, 5 Apr 2008 08:16:51 +0200 (CEST) Subject: [Python-3000-checkins] r62163 - in python/branches/py3k: PC/VS8.0/build_ssl.py PCbuild/build_ssl.py Message-ID: <20080405061651.1836A1E4002@bag.python.org> Author: neal.norwitz Date: Sat Apr 5 08:16:50 2008 New Revision: 62163 Modified: python/branches/py3k/PC/VS8.0/build_ssl.py python/branches/py3k/PCbuild/build_ssl.py Log: Change \u which is causing a syntax error. I'm not sure if that should be, but at least this should let the build get farther on amd64 machines. Modified: python/branches/py3k/PC/VS8.0/build_ssl.py ============================================================================== --- python/branches/py3k/PC/VS8.0/build_ssl.py (original) +++ python/branches/py3k/PC/VS8.0/build_ssl.py Sat Apr 5 08:16:50 2008 @@ -225,7 +225,7 @@ # Now run make. if arch == "amd64": - rc = os.system(r"ml64 -c -Foms\uptable.obj ms\uptable.asm") + rc = os.system("ml64 -c -Foms\\uptable.obj ms\\uptable.asm") if rc: print("ml64 assembler has failed.") sys.exit(rc) Modified: python/branches/py3k/PCbuild/build_ssl.py ============================================================================== --- python/branches/py3k/PCbuild/build_ssl.py (original) +++ python/branches/py3k/PCbuild/build_ssl.py Sat Apr 5 08:16:50 2008 @@ -233,7 +233,7 @@ # Now run make. if arch == "amd64": - rc = os.system(r"ml64 -c -Foms\uptable.obj ms\uptable.asm") + rc = os.system("ml64 -c -Foms\\uptable.obj ms\\uptable.asm") if rc: print("ml64 assembler has failed.") sys.exit(rc) From python-3000-checkins at python.org Sat Apr 5 16:49:54 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Sat, 5 Apr 2008 16:49:54 +0200 (CEST) Subject: [Python-3000-checkins] r62165 - in python/branches/py3k: Lib/test/test_unicode.py Python/ast.c Message-ID: <20080405144954.CD4521E4012@bag.python.org> Author: benjamin.peterson Date: Sat Apr 5 16:49:54 2008 New Revision: 62165 Modified: python/branches/py3k/Lib/test/test_unicode.py python/branches/py3k/Python/ast.c Log: Reverted r62128 on Guido's orders Modified: python/branches/py3k/Lib/test/test_unicode.py ============================================================================== --- python/branches/py3k/Lib/test/test_unicode.py (original) +++ python/branches/py3k/Lib/test/test_unicode.py Sat Apr 5 16:49:54 2008 @@ -68,8 +68,6 @@ self.assertRaises(SyntaxError, eval, '\'\\Ufffffffe\'') self.assertRaises(SyntaxError, eval, '\'\\Uffffffff\'') self.assertRaises(SyntaxError, eval, '\'\\U%08x\'' % 0x110000) - # Test that raw mode does unicode escapes - self.assertEqual(r"\u0020", " ") def test_repr(self): if not sys.platform.startswith('java'): Modified: python/branches/py3k/Python/ast.c ============================================================================== --- python/branches/py3k/Python/ast.c (original) +++ python/branches/py3k/Python/ast.c Sat Apr 5 16:49:54 2008 @@ -3231,7 +3231,7 @@ return NULL; } } - if (!*bytesmode) { + if (!*bytesmode && !rawmode) { return decode_unicode(s, len, rawmode, c->c_encoding); } if (*bytesmode) { From python-3000-checkins at python.org Sat Apr 5 17:09:30 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Sat, 5 Apr 2008 17:09:30 +0200 (CEST) Subject: [Python-3000-checkins] r62166 - python/branches/py3k/Lib/test/test_unicode.py Message-ID: <20080405150930.8B0FA1E4023@bag.python.org> Author: benjamin.peterson Date: Sat Apr 5 17:09:30 2008 New Revision: 62166 Modified: python/branches/py3k/Lib/test/test_unicode.py Log: Added a test to make sure raw strings don't get unicode escapes Modified: python/branches/py3k/Lib/test/test_unicode.py ============================================================================== --- python/branches/py3k/Lib/test/test_unicode.py (original) +++ python/branches/py3k/Lib/test/test_unicode.py Sat Apr 5 17:09:30 2008 @@ -68,6 +68,8 @@ self.assertRaises(SyntaxError, eval, '\'\\Ufffffffe\'') self.assertRaises(SyntaxError, eval, '\'\\Uffffffff\'') self.assertRaises(SyntaxError, eval, '\'\\U%08x\'' % 0x110000) + # raw strings should not have unicode escapes + self.assertNotEquals(r"\u0020", " ") def test_repr(self): if not sys.platform.startswith('java'): From eric+python-dev at trueblade.com Sat Apr 5 17:27:32 2008 From: eric+python-dev at trueblade.com (Eric Smith) Date: Sat, 05 Apr 2008 11:27:32 -0400 Subject: [Python-3000-checkins] r62166 - python/branches/py3k/Lib/test/test_unicode.py In-Reply-To: <20080405150930.8B0FA1E4023@bag.python.org> References: <20080405150930.8B0FA1E4023@bag.python.org> Message-ID: <47F79A64.8060009@trueblade.com> I think a better test here would be what it _should_ equal, namely '\\u0020', or maybe '\\' + 'u0020', if you want to remove '\u' from the test string. As written, any string other than a space would pass, for example if this became '\\\\u0020' through some other error. benjamin.peterson wrote: > Author: benjamin.peterson > Date: Sat Apr 5 17:09:30 2008 > New Revision: 62166 > > Modified: > python/branches/py3k/Lib/test/test_unicode.py > Log: > Added a test to make sure raw strings don't get unicode escapes > > > Modified: python/branches/py3k/Lib/test/test_unicode.py > ============================================================================== > --- python/branches/py3k/Lib/test/test_unicode.py (original) > +++ python/branches/py3k/Lib/test/test_unicode.py Sat Apr 5 17:09:30 2008 > @@ -68,6 +68,8 @@ > self.assertRaises(SyntaxError, eval, '\'\\Ufffffffe\'') > self.assertRaises(SyntaxError, eval, '\'\\Uffffffff\'') > self.assertRaises(SyntaxError, eval, '\'\\U%08x\'' % 0x110000) > + # raw strings should not have unicode escapes > + self.assertNotEquals(r"\u0020", " ") > > def test_repr(self): > if not sys.platform.startswith('java'): > _______________________________________________ > Python-3000-checkins mailing list > Python-3000-checkins at python.org > http://mail.python.org/mailman/listinfo/python-3000-checkins > From python-3000-checkins at python.org Sat Apr 5 19:37:09 2008 From: python-3000-checkins at python.org (georg.brandl) Date: Sat, 5 Apr 2008 19:37:09 +0200 (CEST) Subject: [Python-3000-checkins] r62172 - python/branches/py3k/Doc/library/math.rst Message-ID: <20080405173709.97B811E4002@bag.python.org> Author: georg.brandl Date: Sat Apr 5 19:37:09 2008 New Revision: 62172 Modified: python/branches/py3k/Doc/library/math.rst Log: ceil and floor return ints in 3k. Modified: python/branches/py3k/Doc/library/math.rst ============================================================================== --- python/branches/py3k/Doc/library/math.rst (original) +++ python/branches/py3k/Doc/library/math.rst Sat Apr 5 19:37:09 2008 @@ -26,9 +26,9 @@ .. function:: ceil(x) - Return the ceiling of *x* as a float, the smallest integer value greater than - or equal to *x*. If *x* is not a float, delegates to ``x.__ceil__()``, which - should return an :class:`Integral` value. + Return the ceiling of *x*, the smallest integer greater than or equal to *x*. + If *x* is not a float, delegates to ``x.__ceil__()``, which should return an + :class:`Integral` value. .. function:: copysign(x, y) @@ -44,9 +44,9 @@ .. function:: floor(x) - Return the floor of *x* as a float, the largest integer value less than or - equal to *x*. If *x* is not a float, delegates to ``x.__floor__()``, which - should return an :class:`Integral` value. + Return the floor of *x*, the largest integer less than or equal to *x*. + If *x* is not a float, delegates to ``x.__floor__()``, which should return an + :class:`Integral` value. .. function:: fmod(x, y) @@ -117,7 +117,6 @@ Power and logarithmic functions: - .. function:: exp(x) Return ``e**x``. From nnorwitz at gmail.com Sat Apr 5 19:55:41 2008 From: nnorwitz at gmail.com (Neal Norwitz) Date: Sat, 5 Apr 2008 10:55:41 -0700 Subject: [Python-3000-checkins] r62165 - in python/branches/py3k: Lib/test/test_unicode.py Python/ast.c In-Reply-To: <20080405144954.CD4521E4012@bag.python.org> References: <20080405144954.CD4521E4012@bag.python.org> Message-ID: Can you update Misc/NEWS? Any user visible change like this should always be mentioned there. Thanks, n On Sat, Apr 5, 2008 at 7:49 AM, benjamin.peterson wrote: > Author: benjamin.peterson > Date: Sat Apr 5 16:49:54 2008 > New Revision: 62165 > > Modified: > python/branches/py3k/Lib/test/test_unicode.py > python/branches/py3k/Python/ast.c > Log: > Reverted r62128 on Guido's orders > > > Modified: python/branches/py3k/Lib/test/test_unicode.py > ============================================================================== > --- python/branches/py3k/Lib/test/test_unicode.py (original) > +++ python/branches/py3k/Lib/test/test_unicode.py Sat Apr 5 16:49:54 2008 > @@ -68,8 +68,6 @@ > self.assertRaises(SyntaxError, eval, '\'\\Ufffffffe\'') > self.assertRaises(SyntaxError, eval, '\'\\Uffffffff\'') > self.assertRaises(SyntaxError, eval, '\'\\U%08x\'' % 0x110000) > - # Test that raw mode does unicode escapes > - self.assertEqual(r"\u0020", " ") > > def test_repr(self): > if not sys.platform.startswith('java'): > > Modified: python/branches/py3k/Python/ast.c > ============================================================================== > --- python/branches/py3k/Python/ast.c (original) > +++ python/branches/py3k/Python/ast.c Sat Apr 5 16:49:54 2008 > @@ -3231,7 +3231,7 @@ > return NULL; > } > } > - if (!*bytesmode) { > + if (!*bytesmode && !rawmode) { > return decode_unicode(s, len, rawmode, c->c_encoding); > } > if (*bytesmode) { > _______________________________________________ > Python-3000-checkins mailing list > Python-3000-checkins at python.org > http://mail.python.org/mailman/listinfo/python-3000-checkins > From python-3000-checkins at python.org Sat Apr 5 20:58:10 2008 From: python-3000-checkins at python.org (martin.v.loewis) Date: Sat, 5 Apr 2008 20:58:10 +0200 (CEST) Subject: [Python-3000-checkins] r62175 - in python/branches/py3k: Doc/library/pickle.rst Doc/whatsnew/2.6.rst Tools/msi/merge.py Tools/msi/msi.py Tools/msi/schema.py Message-ID: <20080405185810.2FAAB1E4002@bag.python.org> Author: martin.v.loewis Date: Sat Apr 5 20:58:09 2008 New Revision: 62175 Added: python/branches/py3k/Tools/msi/merge.py - copied unchanged from r62174, python/trunk/Tools/msi/merge.py Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/pickle.rst python/branches/py3k/Doc/whatsnew/2.6.rst python/branches/py3k/Tools/msi/msi.py python/branches/py3k/Tools/msi/schema.py Log: Merged revisions 61440-61441,61443,61445-61448,61451-61452,61455-61457,61459-61464,61466-61467,61469-61470,61476-61477,61479,61481-61482,61485,61487,61490,61493-61494,61497,61499-61502,61505-61506,61508,61511-61514,61519,61521-61522,61530-61531,61533-61537,61541-61555,61557-61558,61561-61562,61566-61569,61572-61574,61578-61579,61583-61584,61588-61589,61592,61594,61598-61601,61603-61604,61607-61612,61617,61619-61620,61624,61626,61628-61630,61635-61638,61640-61643,61645,61648,61653-61655,61659-61662,61664,61666,61668-61671,61673,61675,61679-61680,61682,61685-61686,61689-61695,61697-61699,61701-61703,61706,61710,61713,61717,61723,61726-61730,61736,61738,61740,61742,61745-61752,61754-61760,61762-61764,61768,61770-61772,61774-61775,61784-61787,61789-61792,61794-61795,61797-61806,61808-61809,61811-61812,61814-61819,61824,61826-61833,61835-61840,61843-61845,61848,61850,61854-61862,61865-61866,61868,61872-61873,61876-61877,61883-61888,61890-61891,61893-61899,61901-61903,61905-61912,61914,61917,61920-61921,61927,61930,61932-61934,61939,61941-61942,61944-61951,61955,61960-61963,61980,61982-61983,61991,61994-61996,62001-62003,62008-62010,62016-62017,62022,62024,62027,62031-62034,62041,62045-62046,62055-62058,62060-62066,62068-62074,62076-62079,62081-62083,62086-62089,62092-62094,62098,62101,62104,62106-62109,62115-62122,62124-62125,62128,62130,62132,62134-62135,62137,62139-62140,62144,62146,62151,62155,62157,62162-62174 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62167 | martin.v.loewis | 2008-04-05 17:45:25 +0200 (Sa, 05 Apr 2008) | 1 line Extend sizes of various fields, to support the CRT90 merge module. ........ r62168 | martin.v.loewis | 2008-04-05 17:48:36 +0200 (Sa, 05 Apr 2008) | 1 line Add two features to distinguish between private and SxS CRT. ........ r62169 | martin.v.loewis | 2008-04-05 17:50:58 +0200 (Sa, 05 Apr 2008) | 1 line Add script to merge msvcr90. ........ r62170 | andrew.kuchling | 2008-04-05 17:57:46 +0200 (Sa, 05 Apr 2008) | 1 line Markup fixes; write PEP 3118 section ........ r62173 | georg.brandl | 2008-04-05 19:45:58 +0200 (Sa, 05 Apr 2008) | 2 lines Mention that the tuple returned by __reduce__ is pickled as normal. ........ r62174 | andrew.kuchling | 2008-04-05 20:15:30 +0200 (Sa, 05 Apr 2008) | 1 line Write PEP 3119 section ........ Modified: python/branches/py3k/Doc/library/pickle.rst ============================================================================== --- python/branches/py3k/Doc/library/pickle.rst (original) +++ python/branches/py3k/Doc/library/pickle.rst Sat Apr 5 20:58:09 2008 @@ -468,8 +468,9 @@ namespace to determine the object's module. When a tuple is returned, it must be between two and five elements long. -Optional elements can either be omitted, or ``None`` can be provided as their -value. The semantics of each element are: +Optional elements can either be omitted, or ``None`` can be provided as their +value. The contents of this tuple are pickled as normal and used to +reconstruct the object at unpickling time. The semantics of each element are: * A callable object that will be called to create the initial version of the object. The next element of the tuple will provide arguments for this callable, Modified: python/branches/py3k/Doc/whatsnew/2.6.rst ============================================================================== --- python/branches/py3k/Doc/whatsnew/2.6.rst (original) +++ python/branches/py3k/Doc/whatsnew/2.6.rst Sat Apr 5 20:58:09 2008 @@ -156,15 +156,18 @@ .. seealso:: - http://bugs.python.org: The Python bug tracker. + http://bugs.python.org + The Python bug tracker. - http://bugs.jython.org: The Jython bug tracker. + http://bugs.jython.org: + The Jython bug tracker. - http://roundup.sourceforge.net/: Roundup downloads and documentation. + http://roundup.sourceforge.net/ + Roundup downloads and documentation. -New Documentation Format: ReStructured Text --------------------------------------------------- +New Documentation Format: ReStructured Text Using Sphinx +----------------------------------------------------------- Since the Python project's inception around 1989, the documentation had been written using LaTeX. At that time, most documentation was @@ -191,16 +194,20 @@ a markup commonly used in the Python community that supports custom extensions and directives. Sphinx concentrates on HTML output, producing attractively styled -and modern HTML, but printed output is still supported through -conversion to LaTeX as an output format. +and modern HTML, though printed output is still supported through +conversion to LaTeX. Sphinx is a standalone package that +can be used in documenting other projects. .. seealso:: - `Docutils `__: The fundamental - reStructured Text parser and toolset. + :ref:`documenting-index` + Describes how to write for Python's documentation. + + `Sphinx `__ + Documentation and code for the Sphinx toolchain. - :ref:`documenting-index`: Describes how to write for - Python's documentation. + `Docutils `__ + The underlying reStructured Text parser and toolset. PEP 343: The 'with' statement @@ -487,8 +494,7 @@ .. seealso:: :pep:`370` - XXX - - PEP written by XXX; implemented by Christian Heimes. + PEP written by XXX; implemented by Christian Heimes. .. ====================================================================== @@ -633,9 +639,8 @@ ===================================================== The ``print`` statement becomes the :func:`print` function in Python 3.0. -Making :func:`print` a function makes it easier to replace within a -module by doing 'def print(...)' or importing a new -function from somewhere else. +Making :func:`print` a function makes it easier to change +by doing 'def print(...)' or importing a new function from somewhere else. Python 2.6 has a ``__future__`` import that removes ``print`` as language syntax, letting you use the functional form instead. For example:: @@ -750,13 +755,50 @@ PEP 3118: Revised Buffer Protocol ===================================================== -The buffer protocol is a C-level API that lets Python extensions -XXX +The buffer protocol is a C-level API that lets Python types +exchange pointers into their internal representations. A +memory-mapped file can be viewed as a buffer of characters, for +example, and this lets another module such as :mod:`re` +treat memory-mapped files as a string of characters to be searched. + +The primary users of the buffer protocol are numeric-processing +packages such as NumPy, which can expose the internal representation +of arrays so that callers can write data directly into an array instead +of going through a slower API. This PEP updates the buffer protocol in light of experience +from NumPy development, adding a number of new features +such as indicating the shape of an array, +locking memory . + +The most important new C API function is +``PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)``, which +takes an object and a set of flags, and fills in the +``Py_buffer`` structure with information +about the object's memory representation. Objects +can use this operation to lock memory in place +while an external caller could be modifying the contents, +so there's a corresponding +``PyObject_ReleaseBuffer(PyObject *obj, Py_buffer *view)`` to +indicate that the external caller is done. + +The **flags** argument to :cfunc:`PyObject_GetBuffer` specifies +constraints upon the memory returned. Some examples are: + + * :const:`PyBUF_WRITABLE` indicates that the memory must be writable. + + * :const:`PyBUF_LOCK` requests a read-only or exclusive lock on the memory. + + * :const:`PyBUF_C_CONTIGUOUS` and :const:`PyBUF_F_CONTIGUOUS` + requests a C-contiguous (last dimension varies the fastest) or + Fortran-contiguous (first dimension varies the fastest) layout. + +.. XXX this feature is not in 2.6 docs yet .. seealso:: :pep:`3118` - Revising the buffer protocol - PEP written by Travis Oliphant and Carl Banks. + PEP written by Travis Oliphant and Carl Banks; implemented by + Travis Oliphant. + .. ====================================================================== @@ -765,41 +807,142 @@ PEP 3119: Abstract Base Classes ===================================================== -XXX write this -- this section is currently just brief notes. +Some object-oriented languages such as Java support interfaces: declarations +that a class has a given set of methods or supports a given access protocol. +Abstract Base Classes (or ABCs) are an equivalent feature for Python. The ABC +support consists of an :mod:`abc` module containing a metaclass called +:class:`ABCMeta`, special handling +of this metaclass by the :func:`isinstance` and :func:`issubclass` built-ins, +and a collection of basic ABCs that the Python developers think will be widely +useful. + +Let's say you have a particular class and wish to know whether it supports +dictionary-style access. The phrase "dictionary-style" is vague, however. +It probably means that accessing items with ``obj[1]`` works. +Does it imply that setting items with ``obj[2] = value`` works? +Or that the object will have :meth:`keys`, :meth:`values`, and :meth:`items` +methods? What about the iterative variants such as :meth:`iterkeys`? :meth:`copy` +and :meth:`update`? Iterating over the object with :func:`iter`? + +Python 2.6 includes a number of different ABCs in the :mod:`collections` +module. :class:`Iterable` indicates that a class defines :meth:`__iter__`, +and :class:`Container` means the class supports ``x in y`` expressions +by defining a :meth:`__contains__` method. The basic dictionary interface of +getting items, setting items, and +:meth:`keys`, :meth:`values`, and :meth:`items`, is defined by the +:class:`MutableMapping` ABC. -How to identify a file object? +You can derive your own classes from a particular ABC +to indicate they support that ABC's interface:: + + import collections + + class Storage(collections.MutableMapping): + ... -ABCs are a collection of classes describing various interfaces. -Classes can derive from an ABC to indicate they support that ABC's -interface. Concrete classes should obey the semantics specified by -an ABC, but Python can't check this; it's up to the implementor. -A metaclass lets you declare that an existing class or type -derives from a particular ABC. You can even +Alternatively, you could write the class without deriving from +the desired ABC and instead register the class by +calling the ABC's :meth:`register` method:: + + import collections + + class Storage: + ... + + collections.MutableMapping.register(Storage) + +For classes that you write, deriving from the ABC is probably clearer. +The :meth:`register` method is useful when you've written a new +ABC that can describe an existing type or class, or if you want +to declare that some third-party class implements an ABC. +For example, if you defined a :class:`PrintableType` ABC, +it's legal to do: + + # Register Python's types + PrintableType.register(int) + PrintableType.register(float) + PrintableType.register(str) + +Classes should obey the semantics specified by an ABC, but +Python can't check this; it's up to the class author to +understand the ABC's requirements and to implement the code accordingly. + +To check whether an object supports a particular interface, you can +now write:: + + def func(d): + if not isinstance(d, collections.MutableMapping): + raise ValueError("Mapping object expected, not %r" % d) + +(Don't feel that you must now begin writing lots of checks as in the +above example. Python has a strong tradition of duck-typing, where +explicit type-checking isn't done and code simply calls methods on +an object, trusting that those methods will be there and raising an +exception if they aren't. Be judicious in checking for ABCs +and only do it where it helps.) -class AppendableSequence: - __metaclass__ = ABCMeta +You can write your own ABCs by using ``abc.ABCMeta`` as the +metaclass in a class definition:: -AppendableSequence.register(list) -assert issubclass(list, AppendableSequence) -assert isinstance([], AppendableSequence) + from abc import ABCMeta + + class Drawable(): + __metaclass__ = ABCMeta + + def draw(self, x, y, scale=1.0): + pass - at abstractmethod decorator -- you can't instantiate classes w/ -an abstract method. + def draw_doubled(self, x, y): + self.draw(x, y, scale=2.0) + + + class Square(Drawable): + def draw(self, x, y, scale): + ... + + +In the :class:`Drawable` ABC above, the :meth:`draw_doubled` method +renders the object at twice its size and can be implemented in terms +of other methods described in :class:`Drawable`. Classes implementing +this ABC therefore don't need to provide their own implementation +of :meth:`draw_doubled`, though they can do so. An implementation +of :meth:`draw` is necessary, though; the ABC can't provide +a useful generic implementation. You +can apply the ``@abstractmethod`` decorator to methods such as +:meth:`draw` that must be implemented; Python will +then raise an exception for classes that +don't define the method:: + + class Drawable(): + __metaclass__ = ABCMeta + + @abstractmethod + def draw(self, x, y, scale): + pass + +Note that the exception is only raised when you actually +try to create an instance of a subclass without the method:: + + >>> s=Square() + Traceback (most recent call last): + File "", line 1, in + TypeError: Can't instantiate abstract class Square with abstract methods draw + >>> -:: +Abstract data attributes can be declared using the ``@abstractproperty`` decorator:: - @abstractproperty decorator @abstractproperty def readonly(self): return self._x +Subclasses must then define a :meth:`readonly` property .. seealso:: :pep:`3119` - Introducing Abstract Base Classes PEP written by Guido van Rossum and Talin. - Implemented by XXX. + Implemented by Guido van Rossum. Backported to 2.6 by Benjamin Aranguren, with Alex Martelli. .. ====================================================================== Modified: python/branches/py3k/Tools/msi/msi.py ============================================================================== --- python/branches/py3k/Tools/msi/msi.py (original) +++ python/branches/py3k/Tools/msi/msi.py Sat Apr 5 20:58:09 2008 @@ -799,6 +799,12 @@ default_feature = Feature(db, "DefaultFeature", "Python", "Python Interpreter and Libraries", 1, directory = "TARGETDIR") + shared_crt = Feature(db, "SharedCRT", "MSVCRT", "C Run-Time (system-wide)", 0, + level=0) + private_crt = Feature(db, "PrivateCRT", "MSVCRT", "C Run-Time (private)", 0, + level=0) + add_data(db, "Condition", [("SharedCRT", 1, sys32cond), + ("PrivateCRT", 1, "not "+sys32cond)]) # We don't support advertisement of extensions ext_feature = Feature(db, "Extensions", "Register Extensions", "Make this Python installation the default Python installation", 3, @@ -899,7 +905,7 @@ DLLs = PyDirectory(db, cab, root, srcdir + "/" + PCBUILD, "DLLs", "DLLS|DLLs") # XXX determine dependencies if MSVCR == "90": - root.start_component("msvcr90") + root.start_component("msvcr90", feature=private_crt) for file, kw in extract_msvcr90(): root.add_file(file, **kw) if file.endswith("manifest"): Modified: python/branches/py3k/Tools/msi/schema.py ============================================================================== --- python/branches/py3k/Tools/msi/schema.py (original) +++ python/branches/py3k/Tools/msi/schema.py Sat Apr 5 20:58:09 2008 @@ -18,7 +18,7 @@ ActionText.add_field(3,'Template',7936) AdminExecuteSequence = Table('AdminExecuteSequence') -AdminExecuteSequence.add_field(1,'Action',11592) +AdminExecuteSequence.add_field(1,'Action',0x2DFF) AdminExecuteSequence.add_field(2,'Condition',7679) AdminExecuteSequence.add_field(3,'Sequence',5378) @@ -28,12 +28,12 @@ Condition.add_field(3,'Condition',7679) AdminUISequence = Table('AdminUISequence') -AdminUISequence.add_field(1,'Action',11592) +AdminUISequence.add_field(1,'Action',0x2DFF) AdminUISequence.add_field(2,'Condition',7679) AdminUISequence.add_field(3,'Sequence',5378) AdvtExecuteSequence = Table('AdvtExecuteSequence') -AdvtExecuteSequence.add_field(1,'Action',11592) +AdvtExecuteSequence.add_field(1,'Action',0x2DFF) AdvtExecuteSequence.add_field(2,'Condition',7679) AdvtExecuteSequence.add_field(3,'Sequence',5378) @@ -83,7 +83,7 @@ Feature.add_field(4,'Description',8191) Feature.add_field(5,'Display',5378) Feature.add_field(6,'Level',1282) -Feature.add_field(7,'Directory_',7496) +Feature.add_field(7,'Directory_',0x1DFF) Feature.add_field(8,'Attributes',1282) Binary = Table('Binary') @@ -91,15 +91,15 @@ Binary.add_field(2,'Data',2304) BindImage = Table('BindImage') -BindImage.add_field(1,'File_',11592) +BindImage.add_field(1,'File_',0x2DFF) BindImage.add_field(2,'Path',7679) File = Table('File') -File.add_field(1,'File',11592) -File.add_field(2,'Component_',3400) +File.add_field(1,'File',0x2DFF) +File.add_field(2,'Component_',0xDFF) File.add_field(3,'FileName',4095) File.add_field(4,'FileSize',260) -File.add_field(5,'Version',7496) +File.add_field(5,'Version',0x1DFF) File.add_field(6,'Language',7444) File.add_field(7,'Attributes',5378) File.add_field(8,'Sequence',1282) @@ -114,7 +114,7 @@ Class = Table('Class') Class.add_field(1,'CLSID',11558) Class.add_field(2,'Context',11552) -Class.add_field(3,'Component_',11592) +Class.add_field(3,'Component_',0x2DFF) Class.add_field(4,'ProgId_Default',7679) Class.add_field(5,'Description',8191) Class.add_field(6,'AppId_',7462) @@ -127,12 +127,12 @@ Class.add_field(13,'Attributes',5378) Component = Table('Component') -Component.add_field(1,'Component',11592) +Component.add_field(1,'Component',0x2DFF) Component.add_field(2,'ComponentId',7462) -Component.add_field(3,'Directory_',3400) +Component.add_field(3,'Directory_',0xDFF) Component.add_field(4,'Attributes',1282) Component.add_field(5,'Condition',7679) -Component.add_field(6,'KeyPath',7496) +Component.add_field(6,'KeyPath',0x1DFF) Icon = Table('Icon') Icon.add_field(1,'Name',11592) @@ -158,12 +158,12 @@ CompLocator.add_field(3,'Type',5378) Complus = Table('Complus') -Complus.add_field(1,'Component_',11592) +Complus.add_field(1,'Component_',0x2DFF) Complus.add_field(2,'ExpType',13570) Directory = Table('Directory') -Directory.add_field(1,'Directory',11592) -Directory.add_field(2,'Directory_Parent',7496) +Directory.add_field(1,'Directory',0x2DFF) +Directory.add_field(2,'Directory_Parent',0x1DFF) Directory.add_field(3,'DefaultDir',4095) Control = Table('Control') @@ -207,13 +207,13 @@ ControlEvent.add_field(6,'Ordering',5378) CreateFolder = Table('CreateFolder') -CreateFolder.add_field(1,'Directory_',11592) -CreateFolder.add_field(2,'Component_',11592) +CreateFolder.add_field(1,'Directory_',0x2DFF) +CreateFolder.add_field(2,'Component_',0x2DFF) CustomAction = Table('CustomAction') -CustomAction.add_field(1,'Action',11592) +CustomAction.add_field(1,'Action',0x2DFF) CustomAction.add_field(2,'Type',1282) -CustomAction.add_field(3,'Source',7496) +CustomAction.add_field(3,'Source',0x1DFF) CustomAction.add_field(4,'Target',7679) DrLocator = Table('DrLocator') @@ -224,8 +224,8 @@ DuplicateFile = Table('DuplicateFile') DuplicateFile.add_field(1,'FileKey',11592) -DuplicateFile.add_field(2,'Component_',3400) -DuplicateFile.add_field(3,'File_',3400) +DuplicateFile.add_field(2,'Component_',0xDFF) +DuplicateFile.add_field(3,'File_',0xDFF) DuplicateFile.add_field(4,'DestName',8191) DuplicateFile.add_field(5,'DestFolder',7496) @@ -233,7 +233,7 @@ Environment.add_field(1,'Environment',11592) Environment.add_field(2,'Name',4095) Environment.add_field(3,'Value',8191) -Environment.add_field(4,'Component_',3400) +Environment.add_field(4,'Component_',0xDFF) Error = Table('Error') Error.add_field(1,'Error',9474) @@ -247,7 +247,7 @@ Extension = Table('Extension') Extension.add_field(1,'Extension',11775) -Extension.add_field(2,'Component_',11592) +Extension.add_field(2,'Component_',0x2DFF) Extension.add_field(3,'ProgId_',7679) Extension.add_field(4,'MIME_',7488) Extension.add_field(5,'Feature_',3366) @@ -259,10 +259,10 @@ FeatureComponents = Table('FeatureComponents') FeatureComponents.add_field(1,'Feature_',11558) -FeatureComponents.add_field(2,'Component_',11592) +FeatureComponents.add_field(2,'Component_',0x2DFF) FileSFPCatalog = Table('FileSFPCatalog') -FileSFPCatalog.add_field(1,'File_',11592) +FileSFPCatalog.add_field(1,'File_',0x2DFF) FileSFPCatalog.add_field(2,'SFPCatalog_',11775) SFPCatalog = Table('SFPCatalog') @@ -271,7 +271,7 @@ SFPCatalog.add_field(3,'Dependency',7424) Font = Table('Font') -Font.add_field(1,'File_',11592) +Font.add_field(1,'File_',0x2DFF) Font.add_field(2,'FontTitle',7552) IniFile = Table('IniFile') @@ -282,7 +282,7 @@ IniFile.add_field(5,'Key',3968) IniFile.add_field(6,'Value',4095) IniFile.add_field(7,'Action',1282) -IniFile.add_field(8,'Component_',3400) +IniFile.add_field(8,'Component_',0xDFF) IniLocator = Table('IniLocator') IniLocator.add_field(1,'Signature_',11592) @@ -293,18 +293,18 @@ IniLocator.add_field(6,'Type',5378) InstallExecuteSequence = Table('InstallExecuteSequence') -InstallExecuteSequence.add_field(1,'Action',11592) +InstallExecuteSequence.add_field(1,'Action',0x2DFF) InstallExecuteSequence.add_field(2,'Condition',7679) InstallExecuteSequence.add_field(3,'Sequence',5378) InstallUISequence = Table('InstallUISequence') -InstallUISequence.add_field(1,'Action',11592) +InstallUISequence.add_field(1,'Action',0x2DFF) InstallUISequence.add_field(2,'Condition',7679) InstallUISequence.add_field(3,'Sequence',5378) IsolatedComponent = Table('IsolatedComponent') -IsolatedComponent.add_field(1,'Component_Shared',11592) -IsolatedComponent.add_field(2,'Component_Application',11592) +IsolatedComponent.add_field(1,'Component_Shared',0x2DFF) +IsolatedComponent.add_field(2,'Component_Application',0x2DFF) LaunchCondition = Table('LaunchCondition') LaunchCondition.add_field(1,'Condition',11775) @@ -340,7 +340,7 @@ MoveFile = Table('MoveFile') MoveFile.add_field(1,'FileKey',11592) -MoveFile.add_field(2,'Component_',3400) +MoveFile.add_field(2,'Component_',0xDFF) MoveFile.add_field(3,'SourceName',8191) MoveFile.add_field(4,'DestName',8191) MoveFile.add_field(5,'SourceFolder',7496) @@ -348,14 +348,14 @@ MoveFile.add_field(7,'Options',1282) MsiAssembly = Table('MsiAssembly') -MsiAssembly.add_field(1,'Component_',11592) +MsiAssembly.add_field(1,'Component_',0x2DFF) MsiAssembly.add_field(2,'Feature_',3366) -MsiAssembly.add_field(3,'File_Manifest',7496) -MsiAssembly.add_field(4,'File_Application',7496) +MsiAssembly.add_field(3,'File_Manifest',0x1DFF) +MsiAssembly.add_field(4,'File_Application',0x1DFF) MsiAssembly.add_field(5,'Attributes',5378) MsiAssemblyName = Table('MsiAssemblyName') -MsiAssemblyName.add_field(1,'Component_',11592) +MsiAssemblyName.add_field(1,'Component_',0x2DFF) MsiAssemblyName.add_field(2,'Name',11775) MsiAssemblyName.add_field(3,'Value',3583) @@ -370,7 +370,7 @@ MsiDigitalSignature.add_field(4,'Hash',6400) MsiFileHash = Table('MsiFileHash') -MsiFileHash.add_field(1,'File_',11592) +MsiFileHash.add_field(1,'File_',0x2DFF) MsiFileHash.add_field(2,'Options',1282) MsiFileHash.add_field(3,'HashPart1',260) MsiFileHash.add_field(4,'HashPart2',260) @@ -388,14 +388,14 @@ ODBCDriver = Table('ODBCDriver') ODBCDriver.add_field(1,'Driver',11592) -ODBCDriver.add_field(2,'Component_',3400) +ODBCDriver.add_field(2,'Component_',0xDFF) ODBCDriver.add_field(3,'Description',3583) -ODBCDriver.add_field(4,'File_',3400) -ODBCDriver.add_field(5,'File_Setup',7496) +ODBCDriver.add_field(4,'File_',0xDFF) +ODBCDriver.add_field(5,'File_Setup',0x1DFF) ODBCDataSource = Table('ODBCDataSource') -ODBCDataSource.add_field(1,'DataSource',11592) -ODBCDataSource.add_field(2,'Component_',3400) +ODBCDataSource.add_field(1,'DataSource',0x2DFF) +ODBCDataSource.add_field(2,'Component_',0xDFF) ODBCDataSource.add_field(3,'Description',3583) ODBCDataSource.add_field(4,'DriverDescription',3583) ODBCDataSource.add_field(5,'Registration',1282) @@ -407,10 +407,10 @@ ODBCTranslator = Table('ODBCTranslator') ODBCTranslator.add_field(1,'Translator',11592) -ODBCTranslator.add_field(2,'Component_',3400) +ODBCTranslator.add_field(2,'Component_',0xDFF) ODBCTranslator.add_field(3,'Description',3583) -ODBCTranslator.add_field(4,'File_',3400) -ODBCTranslator.add_field(5,'File_Setup',7496) +ODBCTranslator.add_field(4,'File_',0xDFF) +ODBCTranslator.add_field(5,'File_Setup',0x1DFF) Patch = Table('Patch') Patch.add_field(1,'File_',11592) @@ -427,7 +427,7 @@ PublishComponent = Table('PublishComponent') PublishComponent.add_field(1,'ComponentId',11558) PublishComponent.add_field(2,'Qualifier',11775) -PublishComponent.add_field(3,'Component_',11592) +PublishComponent.add_field(3,'Component_',0x2DFF) PublishComponent.add_field(4,'AppData',8191) PublishComponent.add_field(5,'Feature_',3366) @@ -443,12 +443,12 @@ RadioButton.add_field(9,'Help',7986) Registry = Table('Registry') -Registry.add_field(1,'Registry',11592) +Registry.add_field(1,'Registry',0x2DFF) Registry.add_field(2,'Root',1282) Registry.add_field(3,'Key',4095) Registry.add_field(4,'Name',8191) Registry.add_field(5,'Value',7936) -Registry.add_field(6,'Component_',3400) +Registry.add_field(6,'Component_',0xDFF) RegLocator = Table('RegLocator') RegLocator.add_field(1,'Signature_',11592) @@ -459,7 +459,7 @@ RemoveFile = Table('RemoveFile') RemoveFile.add_field(1,'FileKey',11592) -RemoveFile.add_field(2,'Component_',3400) +RemoveFile.add_field(2,'Component_',0xDFF) RemoveFile.add_field(3,'FileName',8191) RemoveFile.add_field(4,'DirProperty',3400) RemoveFile.add_field(5,'InstallMode',1282) @@ -472,24 +472,24 @@ RemoveIniFile.add_field(5,'Key',3968) RemoveIniFile.add_field(6,'Value',8191) RemoveIniFile.add_field(7,'Action',1282) -RemoveIniFile.add_field(8,'Component_',3400) +RemoveIniFile.add_field(8,'Component_',0xDFF) RemoveRegistry = Table('RemoveRegistry') RemoveRegistry.add_field(1,'RemoveRegistry',11592) RemoveRegistry.add_field(2,'Root',1282) RemoveRegistry.add_field(3,'Key',4095) RemoveRegistry.add_field(4,'Name',8191) -RemoveRegistry.add_field(5,'Component_',3400) +RemoveRegistry.add_field(5,'Component_',0xDFF) ReserveCost = Table('ReserveCost') ReserveCost.add_field(1,'ReserveKey',11592) -ReserveCost.add_field(2,'Component_',3400) +ReserveCost.add_field(2,'Component_',0xDFF) ReserveCost.add_field(3,'ReserveFolder',7496) ReserveCost.add_field(4,'ReserveLocal',260) ReserveCost.add_field(5,'ReserveSource',260) SelfReg = Table('SelfReg') -SelfReg.add_field(1,'File_',11592) +SelfReg.add_field(1,'File_',0x2DFF) SelfReg.add_field(2,'Cost',5378) ServiceControl = Table('ServiceControl') @@ -498,7 +498,7 @@ ServiceControl.add_field(3,'Event',1282) ServiceControl.add_field(4,'Arguments',8191) ServiceControl.add_field(5,'Wait',5378) -ServiceControl.add_field(6,'Component_',3400) +ServiceControl.add_field(6,'Component_',0xDFF) ServiceInstall = Table('ServiceInstall') ServiceInstall.add_field(1,'ServiceInstall',11592) @@ -512,14 +512,14 @@ ServiceInstall.add_field(9,'StartName',7679) ServiceInstall.add_field(10,'Password',7679) ServiceInstall.add_field(11,'Arguments',7679) -ServiceInstall.add_field(12,'Component_',3400) +ServiceInstall.add_field(12,'Component_',0xDFF) ServiceInstall.add_field(13,'Description',8191) Shortcut = Table('Shortcut') Shortcut.add_field(1,'Shortcut',11592) -Shortcut.add_field(2,'Directory_',3400) +Shortcut.add_field(2,'Directory_',0xDFF) Shortcut.add_field(3,'Name',3968) -Shortcut.add_field(4,'Component_',3400) +Shortcut.add_field(4,'Component_',0xDFF) Shortcut.add_field(5,'Target',3400) Shortcut.add_field(6,'Arguments',7679) Shortcut.add_field(7,'Description',8191) @@ -550,10 +550,10 @@ TypeLib = Table('TypeLib') TypeLib.add_field(1,'LibID',11558) TypeLib.add_field(2,'Language',9474) -TypeLib.add_field(3,'Component_',11592) +TypeLib.add_field(3,'Component_',0x2DFF) TypeLib.add_field(4,'Version',4356) TypeLib.add_field(5,'Description',8064) -TypeLib.add_field(6,'Directory_',7496) +TypeLib.add_field(6,'Directory_',0x1DFF) TypeLib.add_field(7,'Feature_',3366) TypeLib.add_field(8,'Cost',4356) From python-3000-checkins at python.org Sat Apr 5 21:47:23 2008 From: python-3000-checkins at python.org (martin.v.loewis) Date: Sat, 5 Apr 2008 21:47:23 +0200 (CEST) Subject: [Python-3000-checkins] r62176 - python/branches/py3k/Modules/_tkinter.c Message-ID: <20080405194723.9CAFB1E4014@bag.python.org> Author: martin.v.loewis Date: Sat Apr 5 21:47:23 2008 New Revision: 62176 Modified: python/branches/py3k/Modules/_tkinter.c Log: Remove baseName argument from Tkapp_New, as it apparently isn't used anymore. Modified: python/branches/py3k/Modules/_tkinter.c ============================================================================== --- python/branches/py3k/Modules/_tkinter.c (original) +++ python/branches/py3k/Modules/_tkinter.c Sat Apr 5 21:47:23 2008 @@ -583,7 +583,7 @@ static void DisableEventHook(void); /* Forward */ static TkappObject * -Tkapp_New(char *screenName, char *baseName, char *className, +Tkapp_New(char *screenName, char *className, int interactive, int wantobjects, int wantTk, int sync, char *use) { TkappObject *v; @@ -2812,7 +2812,8 @@ Tkinter_Create(PyObject *self, PyObject *args) { char *screenName = NULL; - char *baseName = NULL; + char *baseName = NULL; /* XXX this is not used anymore; + try getting rid of it. */ char *className = NULL; int interactive = 0; int wantobjects = 0; @@ -2820,11 +2821,6 @@ int sync = 0; /* pass -sync to wish */ char *use = NULL; /* pass -use to wish */ - baseName = strrchr(Py_GetProgramName(), '/'); - if (baseName != NULL) - baseName++; - else - baseName = Py_GetProgramName(); className = "Tk"; if (!PyArg_ParseTuple(args, "|zssiiiiz:create", @@ -2833,7 +2829,7 @@ &sync, &use)) return NULL; - return (PyObject *) Tkapp_New(screenName, baseName, className, + return (PyObject *) Tkapp_New(screenName, className, interactive, wantobjects, wantTk, sync, use); } From python-3000-checkins at python.org Sat Apr 5 22:41:38 2008 From: python-3000-checkins at python.org (martin.v.loewis) Date: Sat, 5 Apr 2008 22:41:38 +0200 (CEST) Subject: [Python-3000-checkins] r62178 - in python/branches/py3k: Doc/c-api/init.rst Doc/c-api/sys.rst Doc/c-api/unicode.rst Doc/c-api/veryhigh.rst Include/osdefs.h Include/pygetopt.h Include/pythonrun.h Include/sysmodule.h Misc/NEWS Modules/_tkinter.c Modules/getpath.c Modules/main.c Modules/python.c Objects/unicodeobject.c PC/WinMain.c PC/getpathp.c PC/pyconfig.h Python/frozenmain.c Python/getopt.c Python/pythonrun.c Python/sysmodule.c Message-ID: <20080405204138.493D71E4014@bag.python.org> Author: martin.v.loewis Date: Sat Apr 5 22:41:37 2008 New Revision: 62178 Modified: python/branches/py3k/Doc/c-api/init.rst python/branches/py3k/Doc/c-api/sys.rst python/branches/py3k/Doc/c-api/unicode.rst python/branches/py3k/Doc/c-api/veryhigh.rst python/branches/py3k/Include/osdefs.h python/branches/py3k/Include/pygetopt.h python/branches/py3k/Include/pythonrun.h python/branches/py3k/Include/sysmodule.h python/branches/py3k/Misc/NEWS python/branches/py3k/Modules/_tkinter.c python/branches/py3k/Modules/getpath.c python/branches/py3k/Modules/main.c python/branches/py3k/Modules/python.c python/branches/py3k/Objects/unicodeobject.c python/branches/py3k/PC/WinMain.c python/branches/py3k/PC/getpathp.c python/branches/py3k/PC/pyconfig.h python/branches/py3k/Python/frozenmain.c python/branches/py3k/Python/getopt.c python/branches/py3k/Python/pythonrun.c python/branches/py3k/Python/sysmodule.c Log: Change command line processing API to use wchar_t. Fixes #2128. Modified: python/branches/py3k/Doc/c-api/init.rst ============================================================================== --- python/branches/py3k/Doc/c-api/init.rst (original) +++ python/branches/py3k/Doc/c-api/init.rst Sat Apr 5 22:41:37 2008 @@ -161,7 +161,7 @@ haven't been explicitly destroyed at that point. -.. cfunction:: void Py_SetProgramName(char *name) +.. cfunction:: void Py_SetProgramName(wchar_t *name) .. index:: single: Py_Initialize() @@ -170,11 +170,12 @@ This function should be called before :cfunc:`Py_Initialize` is called for the first time, if it is called at all. It tells the interpreter the value - of the ``argv[0]`` argument to the :cfunc:`main` function of the program. + of the ``argv[0]`` argument to the :cfunc:`main` function of the program + (converted to wide characters). This is used by :cfunc:`Py_GetPath` and some other functions below to find the Python run-time libraries relative to the interpreter executable. The default value is ``'python'``. The argument should point to a - zero-terminated character string in static storage whose contents will not + zero-terminated wide character string in static storage whose contents will not change for the duration of the program's execution. No code in the Python interpreter will change the contents of this storage. @@ -188,7 +189,7 @@ value. -.. cfunction:: char* Py_GetPrefix() +.. cfunction:: wchar_t* Py_GetPrefix() Return the *prefix* for installed platform-independent files. This is derived through a number of complicated rules from the program name set with @@ -201,7 +202,7 @@ It is only useful on Unix. See also the next function. -.. cfunction:: char* Py_GetExecPrefix() +.. cfunction:: wchar_t* Py_GetExecPrefix() Return the *exec-prefix* for installed platform-*dependent* files. This is derived through a number of complicated rules from the program name set with @@ -236,7 +237,7 @@ platform. -.. cfunction:: char* Py_GetProgramFullPath() +.. cfunction:: wchar_t* Py_GetProgramFullPath() .. index:: single: Py_SetProgramName() @@ -249,7 +250,7 @@ to Python code as ``sys.executable``. -.. cfunction:: char* Py_GetPath() +.. cfunction:: wchar_t* Py_GetPath() .. index:: triple: module; search; path @@ -342,7 +343,7 @@ ``sys.version``. -.. cfunction:: void PySys_SetArgv(int argc, char **argv) +.. cfunction:: void PySys_SetArgv(int argc, wchar_t **argv) .. index:: single: main() Modified: python/branches/py3k/Doc/c-api/sys.rst ============================================================================== --- python/branches/py3k/Doc/c-api/sys.rst (original) +++ python/branches/py3k/Doc/c-api/sys.rst Sat Apr 5 22:41:37 2008 @@ -84,11 +84,11 @@ Reset :data:`sys.warnoptions` to an empty list. -.. cfunction:: void PySys_AddWarnOption(char *s) +.. cfunction:: void PySys_AddWarnOption(wchar_t *s) Append *s* to :data:`sys.warnoptions`. -.. cfunction:: void PySys_SetPath(char *path) +.. cfunction:: void PySys_SetPath(wchar_t *path) Set :data:`sys.path` to a list object of paths found in *path* which should be a list of paths separated with the platform's search path delimiter Modified: python/branches/py3k/Doc/c-api/unicode.rst ============================================================================== --- python/branches/py3k/Doc/c-api/unicode.rst (original) +++ python/branches/py3k/Doc/c-api/unicode.rst Sat Apr 5 22:41:37 2008 @@ -336,6 +336,8 @@ .. cfunction:: PyObject* PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size) Create a Unicode object from the :ctype:`wchar_t` buffer *w* of the given size. + Passing -1 as the size indicates that the function must itself compute the length, + using wcslen. Return *NULL* on failure. Modified: python/branches/py3k/Doc/c-api/veryhigh.rst ============================================================================== --- python/branches/py3k/Doc/c-api/veryhigh.rst (original) +++ python/branches/py3k/Doc/c-api/veryhigh.rst Sat Apr 5 22:41:37 2008 @@ -25,16 +25,18 @@ the same library that the Python runtime is using. -.. cfunction:: int Py_Main(int argc, char **argv) +.. cfunction:: int Py_Main(int argc, wchar_t **argv) - The main program for the standard interpreter. This is made available for - programs which embed Python. The *argc* and *argv* parameters should be - prepared exactly as those which are passed to a C program's :cfunc:`main` - function. It is important to note that the argument list may be modified (but - the contents of the strings pointed to by the argument list are not). The return - value will be the integer passed to the :func:`sys.exit` function, ``1`` if the - interpreter exits due to an exception, or ``2`` if the parameter list does not - represent a valid Python command line. + The main program for the standard interpreter. This is made + available for programs which embed Python. The *argc* and *argv* + parameters should be prepared exactly as those which are passed to + a C program's :cfunc:`main` function (converted to wchar_t + according to the user's locale). It is important to note that the + argument list may be modified (but the contents of the strings + pointed to by the argument list are not). The return value will be + the integer passed to the :func:`sys.exit` function, ``1`` if the + interpreter exits due to an exception, or ``2`` if the parameter + list does not represent a valid Python command line. .. cfunction:: int PyRun_AnyFile(FILE *fp, const char *filename) Modified: python/branches/py3k/Include/osdefs.h ============================================================================== --- python/branches/py3k/Include/osdefs.h (original) +++ python/branches/py3k/Include/osdefs.h Sat Apr 5 22:41:37 2008 @@ -12,20 +12,20 @@ #if defined(MS_WINDOWS) || defined(__BORLANDC__) || defined(__WATCOMC__) || defined(__DJGPP__) || defined(PYOS_OS2) #if defined(PYOS_OS2) && defined(PYCC_GCC) #define MAXPATHLEN 260 -#define SEP '/' -#define ALTSEP '\\' +#define SEP L'/' +#define ALTSEP L'\\' #else -#define SEP '\\' -#define ALTSEP '/' +#define SEP L'\\' +#define ALTSEP L'/' #define MAXPATHLEN 256 #endif -#define DELIM ';' +#define DELIM L';' #endif #endif /* Filename separator */ #ifndef SEP -#define SEP '/' +#define SEP L'/' #endif /* Max pathname length */ @@ -39,7 +39,7 @@ /* Search path entry delimiter */ #ifndef DELIM -#define DELIM ':' +#define DELIM L':' #endif #ifdef __cplusplus Modified: python/branches/py3k/Include/pygetopt.h ============================================================================== --- python/branches/py3k/Include/pygetopt.h (original) +++ python/branches/py3k/Include/pygetopt.h Sat Apr 5 22:41:37 2008 @@ -7,9 +7,9 @@ PyAPI_DATA(int) _PyOS_opterr; PyAPI_DATA(int) _PyOS_optind; -PyAPI_DATA(char *) _PyOS_optarg; +PyAPI_DATA(wchar_t *) _PyOS_optarg; -PyAPI_FUNC(int) _PyOS_GetOpt(int argc, char **argv, char *optstring); +PyAPI_FUNC(int) _PyOS_GetOpt(int argc, wchar_t **argv, wchar_t *optstring); #ifdef __cplusplus } Modified: python/branches/py3k/Include/pythonrun.h ============================================================================== --- python/branches/py3k/Include/pythonrun.h (original) +++ python/branches/py3k/Include/pythonrun.h Sat Apr 5 22:41:37 2008 @@ -17,11 +17,11 @@ int cf_flags; /* bitmask of CO_xxx flags relevant to future */ } PyCompilerFlags; -PyAPI_FUNC(void) Py_SetProgramName(char *); -PyAPI_FUNC(char *) Py_GetProgramName(void); +PyAPI_FUNC(void) Py_SetProgramName(wchar_t *); +PyAPI_FUNC(wchar_t *) Py_GetProgramName(void); -PyAPI_FUNC(void) Py_SetPythonHome(char *); -PyAPI_FUNC(char *) Py_GetPythonHome(void); +PyAPI_FUNC(void) Py_SetPythonHome(wchar_t *); +PyAPI_FUNC(wchar_t *) Py_GetPythonHome(void); PyAPI_FUNC(void) Py_Initialize(void); PyAPI_FUNC(void) Py_InitializeEx(int); @@ -81,7 +81,7 @@ PyAPI_FUNC(int) Py_FdIsInteractive(FILE *, const char *); /* Bootstrap */ -PyAPI_FUNC(int) Py_Main(int argc, char **argv); +PyAPI_FUNC(int) Py_Main(int argc, wchar_t **argv); /* Use macros for a bunch of old variants */ #define PyRun_String(str, s, g, l) PyRun_StringFlags(str, s, g, l, NULL) @@ -103,10 +103,10 @@ PyRun_FileExFlags(fp, p, s, g, l, 0, flags) /* In getpath.c */ -PyAPI_FUNC(char *) Py_GetProgramFullPath(void); -PyAPI_FUNC(char *) Py_GetPrefix(void); -PyAPI_FUNC(char *) Py_GetExecPrefix(void); -PyAPI_FUNC(char *) Py_GetPath(void); +PyAPI_FUNC(wchar_t *) Py_GetProgramFullPath(void); +PyAPI_FUNC(wchar_t *) Py_GetPrefix(void); +PyAPI_FUNC(wchar_t *) Py_GetExecPrefix(void); +PyAPI_FUNC(wchar_t *) Py_GetPath(void); /* In their own files */ PyAPI_FUNC(const char *) Py_GetVersion(void); Modified: python/branches/py3k/Include/sysmodule.h ============================================================================== --- python/branches/py3k/Include/sysmodule.h (original) +++ python/branches/py3k/Include/sysmodule.h Sat Apr 5 22:41:37 2008 @@ -9,8 +9,8 @@ PyAPI_FUNC(PyObject *) PySys_GetObject(const char *); PyAPI_FUNC(int) PySys_SetObject(const char *, PyObject *); -PyAPI_FUNC(void) PySys_SetArgv(int, char **); -PyAPI_FUNC(void) PySys_SetPath(const char *); +PyAPI_FUNC(void) PySys_SetArgv(int, wchar_t **); +PyAPI_FUNC(void) PySys_SetPath(const wchar_t *); PyAPI_FUNC(void) PySys_WriteStdout(const char *format, ...) Py_GCC_ATTRIBUTE((format(printf, 1, 2))); @@ -21,7 +21,7 @@ PyAPI_DATA(int) _PySys_CheckInterval; PyAPI_FUNC(void) PySys_ResetWarnOptions(void); -PyAPI_FUNC(void) PySys_AddWarnOption(const char *); +PyAPI_FUNC(void) PySys_AddWarnOption(const wchar_t *); #ifdef __cplusplus } Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sat Apr 5 22:41:37 2008 @@ -12,6 +12,10 @@ Core and Builtins ----------------- +- The command line processing was converted to pass Unicode strings + through as unmodified as possible; as a consequence, the C API + related to command line arguments was changed to use wchar_t. + Extension Modules ----------------- Modified: python/branches/py3k/Modules/_tkinter.c ============================================================================== --- python/branches/py3k/Modules/_tkinter.c (original) +++ python/branches/py3k/Modules/_tkinter.c Sat Apr 5 22:41:37 2008 @@ -3012,7 +3012,7 @@ PyMODINIT_FUNC init_tkinter(void) { - PyObject *m, *d; + PyObject *m, *d, *uexe, *cexe; Py_TYPE(&Tkapp_Type) = &PyType_Type; @@ -3065,7 +3065,16 @@ /* This helps the dynamic loader; in Unicode aware Tcl versions it also helps Tcl find its encodings. */ - Tcl_FindExecutable(Py_GetProgramName()); + uexe = PyUnicode_FromWideChar(Py_GetProgramName(), -1); + if (uexe) { + cexe = PyUnicode_AsEncodedString(uexe, + Py_FileSystemDefaultEncoding, + NULL); + if (cexe) + Tcl_FindExecutable(PyString_AsString(cexe)); + Py_XDECREF(cexe); + Py_DECREF(uexe); + } if (PyErr_Occurred()) return; Modified: python/branches/py3k/Modules/getpath.c ============================================================================== --- python/branches/py3k/Modules/getpath.c (original) +++ python/branches/py3k/Modules/getpath.c Sat Apr 5 22:41:37 2008 @@ -122,19 +122,81 @@ #endif #ifndef LANDMARK -#define LANDMARK "os.py" +#define LANDMARK L"os.py" #endif -static char prefix[MAXPATHLEN+1]; -static char exec_prefix[MAXPATHLEN+1]; -static char progpath[MAXPATHLEN+1]; -static char *module_search_path = NULL; -static char lib_python[] = "lib/python" VERSION; +static wchar_t prefix[MAXPATHLEN+1]; +static wchar_t exec_prefix[MAXPATHLEN+1]; +static wchar_t progpath[MAXPATHLEN+1]; +static wchar_t *module_search_path = NULL; +static wchar_t lib_python[] = L"lib/python" VERSION; + +/* In principle, this should use HAVE__WSTAT, and _wstat + should be detected by autoconf. However, no current + POSIX system provides that function, so testing for + it is pointless. */ +#ifndef MS_WINDOWS +static int +_wstat(const wchar_t* path, struct stat *buf) +{ + char fname[PATH_MAX]; + size_t res = wcstombs(fname, path, sizeof(fname)); + if (res == (size_t)-1) { + errno = EINVAL; + return -1; + } + return stat(fname, buf); +} +#endif + +#ifndef MS_WINDOWS +static wchar_t* +_wgetcwd(wchar_t *buf, size_t size) +{ + char fname[PATH_MAX]; + if (getcwd(fname, PATH_MAX) == NULL) + return NULL; + if (mbstowcs(buf, fname, size) >= size) { + errno = ERANGE; + return NULL; + } + return buf; +} +#endif + +#ifdef HAVE_READLINK +int +_Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t bufsiz) +{ + char cbuf[PATH_MAX]; + char cpath[PATH_MAX]; + int res; + size_t r1 = wcstombs(cpath, path, PATH_MAX); + if (r1 == (size_t)-1 || r1 >= PATH_MAX) { + errno = EINVAL; + return -1; + } + res = (int)readlink(cpath, cbuf, PATH_MAX); + if (res == -1) + return -1; + if (res == PATH_MAX) { + errno = EINVAL; + return -1; + } + r1 = mbstowcs(buf, cbuf, bufsiz); + if (r1 == -1) { + errno = EINVAL; + return -1; + } + return (int)r1; + +} +#endif static void -reduce(char *dir) +reduce(wchar_t *dir) { - size_t i = strlen(dir); + size_t i = wcslen(dir); while (i > 0 && dir[i] != SEP) --i; dir[i] = '\0'; @@ -142,10 +204,10 @@ static int -isfile(char *filename) /* Is file, not directory */ +isfile(wchar_t *filename) /* Is file, not directory */ { struct stat buf; - if (stat(filename, &buf) != 0) + if (_wstat(filename, &buf) != 0) return 0; if (!S_ISREG(buf.st_mode)) return 0; @@ -154,14 +216,14 @@ static int -ismodule(char *filename) /* Is module -- check for .pyc/.pyo too */ +ismodule(wchar_t *filename) /* Is module -- check for .pyc/.pyo too */ { if (isfile(filename)) return 1; /* Check for the compiled version of prefix. */ - if (strlen(filename) < MAXPATHLEN) { - strcat(filename, Py_OptimizeFlag ? "o" : "c"); + if (wcslen(filename) < MAXPATHLEN) { + wcscat(filename, Py_OptimizeFlag ? L"o" : L"c"); if (isfile(filename)) return 1; } @@ -170,10 +232,10 @@ static int -isxfile(char *filename) /* Is executable file */ +isxfile(wchar_t *filename) /* Is executable file */ { struct stat buf; - if (stat(filename, &buf) != 0) + if (_wstat(filename, &buf) != 0) return 0; if (!S_ISREG(buf.st_mode)) return 0; @@ -184,10 +246,10 @@ static int -isdir(char *filename) /* Is directory */ +isdir(wchar_t *filename) /* Is directory */ { struct stat buf; - if (stat(filename, &buf) != 0) + if (_wstat(filename, &buf) != 0) return 0; if (!S_ISDIR(buf.st_mode)) return 0; @@ -205,34 +267,34 @@ stuff as fits will be appended. */ static void -joinpath(char *buffer, char *stuff) +joinpath(wchar_t *buffer, wchar_t *stuff) { size_t n, k; if (stuff[0] == SEP) n = 0; else { - n = strlen(buffer); + n = wcslen(buffer); if (n > 0 && buffer[n-1] != SEP && n < MAXPATHLEN) buffer[n++] = SEP; } if (n > MAXPATHLEN) Py_FatalError("buffer overflow in getpath.c's joinpath()"); - k = strlen(stuff); + k = wcslen(stuff); if (n + k > MAXPATHLEN) k = MAXPATHLEN - n; - strncpy(buffer+n, stuff, k); + wcsncpy(buffer+n, stuff, k); buffer[n+k] = '\0'; } /* copy_absolute requires that path be allocated at least MAXPATHLEN + 1 bytes and that p be no more than MAXPATHLEN bytes. */ static void -copy_absolute(char *path, char *p) +copy_absolute(wchar_t *path, wchar_t *p) { if (p[0] == SEP) - strcpy(path, p); + wcscpy(path, p); else { - getcwd(path, MAXPATHLEN); + _wgetcwd(path, MAXPATHLEN); if (p[0] == '.' && p[1] == SEP) p += 2; joinpath(path, p); @@ -241,46 +303,46 @@ /* absolutize() requires that path be allocated at least MAXPATHLEN+1 bytes. */ static void -absolutize(char *path) +absolutize(wchar_t *path) { - char buffer[MAXPATHLEN + 1]; + wchar_t buffer[MAXPATHLEN + 1]; if (path[0] == SEP) return; copy_absolute(buffer, path); - strcpy(path, buffer); + wcscpy(path, buffer); } /* search_for_prefix requires that argv0_path be no more than MAXPATHLEN bytes long. */ static int -search_for_prefix(char *argv0_path, char *home) +search_for_prefix(wchar_t *argv0_path, wchar_t *home) { size_t n; - char *vpath; + wchar_t *vpath; /* If PYTHONHOME is set, we believe it unconditionally */ if (home) { - char *delim; - strncpy(prefix, home, MAXPATHLEN); - delim = strchr(prefix, DELIM); + wchar_t *delim; + wcsncpy(prefix, home, MAXPATHLEN); + delim = wcschr(prefix, DELIM); if (delim) - *delim = '\0'; + *delim = L'\0'; joinpath(prefix, lib_python); joinpath(prefix, LANDMARK); return 1; } /* Check to see if argv[0] is in the build directory */ - strcpy(prefix, argv0_path); - joinpath(prefix, "Modules/Setup"); + wcscpy(prefix, argv0_path); + joinpath(prefix, L"Modules/Setup"); if (isfile(prefix)) { /* Check VPATH to see if argv0_path is in the build directory. */ - vpath = VPATH; - strcpy(prefix, argv0_path); + vpath = L"" VPATH; + wcscpy(prefix, argv0_path); joinpath(prefix, vpath); - joinpath(prefix, "Lib"); + joinpath(prefix, L"Lib"); joinpath(prefix, LANDMARK); if (ismodule(prefix)) return -1; @@ -289,17 +351,17 @@ /* Search from argv0_path, until root is found */ copy_absolute(prefix, argv0_path); do { - n = strlen(prefix); + n = wcslen(prefix); joinpath(prefix, lib_python); joinpath(prefix, LANDMARK); if (ismodule(prefix)) return 1; - prefix[n] = '\0'; + prefix[n] = L'\0'; reduce(prefix); } while (prefix[0]); /* Look at configure's PREFIX */ - strncpy(prefix, PREFIX, MAXPATHLEN); + wcsncpy(prefix, L"" PREFIX, MAXPATHLEN); joinpath(prefix, lib_python); joinpath(prefix, LANDMARK); if (ismodule(prefix)) @@ -314,26 +376,26 @@ MAXPATHLEN bytes long. */ static int -search_for_exec_prefix(char *argv0_path, char *home) +search_for_exec_prefix(wchar_t *argv0_path, wchar_t *home) { size_t n; /* If PYTHONHOME is set, we believe it unconditionally */ if (home) { - char *delim; - delim = strchr(home, DELIM); + wchar_t *delim; + delim = wcschr(home, DELIM); if (delim) - strncpy(exec_prefix, delim+1, MAXPATHLEN); + wcsncpy(exec_prefix, delim+1, MAXPATHLEN); else - strncpy(exec_prefix, home, MAXPATHLEN); + wcsncpy(exec_prefix, home, MAXPATHLEN); joinpath(exec_prefix, lib_python); - joinpath(exec_prefix, "lib-dynload"); + joinpath(exec_prefix, L"lib-dynload"); return 1; } /* Check to see if argv[0] is in the build directory */ - strcpy(exec_prefix, argv0_path); - joinpath(exec_prefix, "Modules/Setup"); + wcscpy(exec_prefix, argv0_path); + joinpath(exec_prefix, L"Modules/Setup"); if (isfile(exec_prefix)) { reduce(exec_prefix); return -1; @@ -342,19 +404,19 @@ /* Search from argv0_path, until root is found */ copy_absolute(exec_prefix, argv0_path); do { - n = strlen(exec_prefix); + n = wcslen(exec_prefix); joinpath(exec_prefix, lib_python); - joinpath(exec_prefix, "lib-dynload"); + joinpath(exec_prefix, L"lib-dynload"); if (isdir(exec_prefix)) return 1; - exec_prefix[n] = '\0'; + exec_prefix[n] = L'\0'; reduce(exec_prefix); } while (exec_prefix[0]); /* Look at configure's EXEC_PREFIX */ - strncpy(exec_prefix, EXEC_PREFIX, MAXPATHLEN); + wcsncpy(exec_prefix, L"" EXEC_PREFIX, MAXPATHLEN); joinpath(exec_prefix, lib_python); - joinpath(exec_prefix, "lib-dynload"); + joinpath(exec_prefix, L"lib-dynload"); if (isdir(exec_prefix)) return 1; @@ -366,22 +428,25 @@ static void calculate_path(void) { - extern char *Py_GetProgramName(void); + extern wchar_t *Py_GetProgramName(void); - static char delimiter[2] = {DELIM, '\0'}; - static char separator[2] = {SEP, '\0'}; - char *pythonpath = PYTHONPATH; - char *rtpypath = Py_GETENV("PYTHONPATH"); - char *home = Py_GetPythonHome(); - char *path = getenv("PATH"); - char *prog = Py_GetProgramName(); - char argv0_path[MAXPATHLEN+1]; - char zip_path[MAXPATHLEN+1]; + static wchar_t delimiter[2] = {DELIM, '\0'}; + static wchar_t separator[2] = {SEP, '\0'}; + wchar_t *pythonpath = L"" PYTHONPATH; + char *_rtpypath = Py_GETENV("PYTHONPATH"); /* XXX use wide version on Windows */ + wchar_t rtpypath[MAXPATHLEN+1]; + wchar_t *home = Py_GetPythonHome(); + char *_path = getenv("PATH"); + wchar_t wpath[MAXPATHLEN+1]; + wchar_t *path = NULL; + wchar_t *prog = Py_GetProgramName(); + wchar_t argv0_path[MAXPATHLEN+1]; + wchar_t zip_path[MAXPATHLEN+1]; int pfound, efound; /* 1 if found; -1 if found build directory */ - char *buf; + wchar_t *buf; size_t bufsz; size_t prefixsz; - char *defpath = pythonpath; + wchar_t *defpath = pythonpath; #ifdef WITH_NEXT_FRAMEWORK NSModule pythonModule; #endif @@ -393,13 +458,22 @@ #endif #endif + if (_path) { + size_t r = mbstowcs(wpath, _path, MAXPATHLEN+1); + path = wpath; + if (r == (size_t)-1 || r > MAXPATHLEN) { + /* Could not convert PATH, or it's too long. */ + path = NULL; + } + } + /* If there is no slash in the argv0 path, then we have to * assume python is on the user's $PATH, since there's no * other way to find a directory to start the search from. If * $PATH isn't exported, you lose. */ - if (strchr(prog, SEP)) - strncpy(progpath, prog, MAXPATHLEN); + if (wcschr(prog, SEP)) + wcsncpy(progpath, prog, MAXPATHLEN); #ifdef __APPLE__ /* On Mac OS X, if a script uses an interpreter of the form * "#!/opt/python2.3/bin/python", the kernel only passes "python" @@ -416,24 +490,24 @@ #endif /* __APPLE__ */ else if (path) { while (1) { - char *delim = strchr(path, DELIM); + wchar_t *delim = wcschr(path, DELIM); if (delim) { size_t len = delim - path; if (len > MAXPATHLEN) len = MAXPATHLEN; - strncpy(progpath, path, len); + wcsncpy(progpath, path, len); *(progpath + len) = '\0'; } else - strncpy(progpath, path, MAXPATHLEN); + wcsncpy(progpath, path, MAXPATHLEN); joinpath(progpath, prog); if (isxfile(progpath)) break; if (!delim) { - progpath[0] = '\0'; + progpath[0] = L'\0'; break; } path = delim + 1; @@ -443,7 +517,7 @@ progpath[0] = '\0'; if (progpath[0] != SEP) absolutize(progpath); - strncpy(argv0_path, progpath, MAXPATHLEN); + wcsncpy(argv0_path, progpath, MAXPATHLEN); argv0_path[MAXPATHLEN] = '\0'; #ifdef WITH_NEXT_FRAMEWORK @@ -454,7 +528,7 @@ */ pythonModule = NSModuleForSymbol(NSLookupAndBindSymbol("_Py_Initialize")); /* Use dylib functions to find out where the framework was loaded from */ - buf = (char *)NSLibraryNameForModule(pythonModule); + buf = (wchar_t *)NSLibraryNameForModule(pythonModule); if (buf != NULL) { /* We're in a framework. */ /* See if we might be in the build directory. The framework in the @@ -464,39 +538,39 @@ ** be running the interpreter in the build directory, so we use the ** build-directory-specific logic to find Lib and such. */ - strncpy(argv0_path, buf, MAXPATHLEN); + wcsncpy(argv0_path, buf, MAXPATHLEN); reduce(argv0_path); joinpath(argv0_path, lib_python); joinpath(argv0_path, LANDMARK); if (!ismodule(argv0_path)) { /* We are in the build directory so use the name of the executable - we know that the absolute path is passed */ - strncpy(argv0_path, prog, MAXPATHLEN); + wcsncpy(argv0_path, prog, MAXPATHLEN); } else { /* Use the location of the library as the progpath */ - strncpy(argv0_path, buf, MAXPATHLEN); + wcsncpy(argv0_path, buf, MAXPATHLEN); } } #endif #if HAVE_READLINK { - char tmpbuffer[MAXPATHLEN+1]; - int linklen = readlink(progpath, tmpbuffer, MAXPATHLEN); + wchar_t tmpbuffer[MAXPATHLEN+1]; + int linklen = _Py_wreadlink(progpath, tmpbuffer, MAXPATHLEN); while (linklen != -1) { /* It's not null terminated! */ tmpbuffer[linklen] = '\0'; if (tmpbuffer[0] == SEP) /* tmpbuffer should never be longer than MAXPATHLEN, but extra check does not hurt */ - strncpy(argv0_path, tmpbuffer, MAXPATHLEN); + wcsncpy(argv0_path, tmpbuffer, MAXPATHLEN); else { /* Interpret relative to progpath */ reduce(argv0_path); joinpath(argv0_path, tmpbuffer); } - linklen = readlink(argv0_path, tmpbuffer, MAXPATHLEN); + linklen = _Py_wreadlink(argv0_path, tmpbuffer, MAXPATHLEN); } } #endif /* HAVE_READLINK */ @@ -510,22 +584,22 @@ if (!Py_FrozenFlag) fprintf(stderr, "Could not find platform independent libraries \n"); - strncpy(prefix, PREFIX, MAXPATHLEN); + wcsncpy(prefix, L"" PREFIX, MAXPATHLEN); joinpath(prefix, lib_python); } else reduce(prefix); - strncpy(zip_path, prefix, MAXPATHLEN); - zip_path[MAXPATHLEN] = '\0'; + wcsncpy(zip_path, prefix, MAXPATHLEN); + zip_path[MAXPATHLEN] = L'\0'; if (pfound > 0) { /* Use the reduced prefix returned by Py_GetPrefix() */ reduce(zip_path); reduce(zip_path); } else - strncpy(zip_path, PREFIX, MAXPATHLEN); - joinpath(zip_path, "lib/python00.zip"); - bufsz = strlen(zip_path); /* Replace "00" with version */ + wcsncpy(zip_path, L"" PREFIX, MAXPATHLEN); + joinpath(zip_path, L"lib/python00.zip"); + bufsz = wcslen(zip_path); /* Replace "00" with version */ zip_path[bufsz - 6] = VERSION[0]; zip_path[bufsz - 5] = VERSION[2]; @@ -533,8 +607,8 @@ if (!Py_FrozenFlag) fprintf(stderr, "Could not find platform dependent libraries \n"); - strncpy(exec_prefix, EXEC_PREFIX, MAXPATHLEN); - joinpath(exec_prefix, "lib/lib-dynload"); + wcsncpy(exec_prefix, L"" EXEC_PREFIX, MAXPATHLEN); + joinpath(exec_prefix, L"lib/lib-dynload"); } /* If we found EXEC_PREFIX do *not* reduce it! (Yet.) */ @@ -546,13 +620,19 @@ */ bufsz = 0; - if (rtpypath) - bufsz += strlen(rtpypath) + 1; + if (_rtpypath) { + size_t s = mbstowcs(rtpypath, _rtpypath, sizeof(rtpypath)/sizeof(wchar_t)); + if (s == (size_t)-1 || s >=sizeof(rtpypath)) + /* XXX deal with errors more gracefully */ + _rtpypath = NULL; + if (_rtpypath) + bufsz += wcslen(rtpypath) + 1; + } - prefixsz = strlen(prefix) + 1; + prefixsz = wcslen(prefix) + 1; while (1) { - char *delim = strchr(defpath, DELIM); + wchar_t *delim = wcschr(defpath, DELIM); if (defpath[0] != SEP) /* Paths are relative to prefix */ @@ -561,65 +641,65 @@ if (delim) bufsz += delim - defpath + 1; else { - bufsz += strlen(defpath) + 1; + bufsz += wcslen(defpath) + 1; break; } defpath = delim + 1; } - bufsz += strlen(zip_path) + 1; - bufsz += strlen(exec_prefix) + 1; + bufsz += wcslen(zip_path) + 1; + bufsz += wcslen(exec_prefix) + 1; /* This is the only malloc call in this file */ - buf = (char *)PyMem_Malloc(bufsz); + buf = (wchar_t *)PyMem_Malloc(bufsz*sizeof(wchar_t)); if (buf == NULL) { /* We can't exit, so print a warning and limp along */ fprintf(stderr, "Not enough memory for dynamic PYTHONPATH.\n"); fprintf(stderr, "Using default static PYTHONPATH.\n"); - module_search_path = PYTHONPATH; + module_search_path = L"" PYTHONPATH; } else { /* Run-time value of $PYTHONPATH goes first */ - if (rtpypath) { - strcpy(buf, rtpypath); - strcat(buf, delimiter); + if (_rtpypath) { + wcscpy(buf, rtpypath); + wcscat(buf, delimiter); } else buf[0] = '\0'; /* Next is the default zip path */ - strcat(buf, zip_path); - strcat(buf, delimiter); + wcscat(buf, zip_path); + wcscat(buf, delimiter); /* Next goes merge of compile-time $PYTHONPATH with * dynamically located prefix. */ defpath = pythonpath; while (1) { - char *delim = strchr(defpath, DELIM); + wchar_t *delim = wcschr(defpath, DELIM); if (defpath[0] != SEP) { - strcat(buf, prefix); - strcat(buf, separator); + wcscat(buf, prefix); + wcscat(buf, separator); } if (delim) { size_t len = delim - defpath + 1; - size_t end = strlen(buf) + len; - strncat(buf, defpath, len); + size_t end = wcslen(buf) + len; + wcsncat(buf, defpath, len); *(buf + end) = '\0'; } else { - strcat(buf, defpath); + wcscat(buf, defpath); break; } defpath = delim + 1; } - strcat(buf, delimiter); + wcscat(buf, delimiter); /* Finally, on goes the directory for dynamic-load modules */ - strcat(buf, exec_prefix); + wcscat(buf, exec_prefix); /* And publish the results */ module_search_path = buf; @@ -636,26 +716,26 @@ /* The prefix is the root directory, but reduce() chopped * off the "/". */ if (!prefix[0]) - strcpy(prefix, separator); + wcscpy(prefix, separator); } else - strncpy(prefix, PREFIX, MAXPATHLEN); + wcsncpy(prefix, L"" PREFIX, MAXPATHLEN); if (efound > 0) { reduce(exec_prefix); reduce(exec_prefix); reduce(exec_prefix); if (!exec_prefix[0]) - strcpy(exec_prefix, separator); + wcscpy(exec_prefix, separator); } else - strncpy(exec_prefix, EXEC_PREFIX, MAXPATHLEN); + wcsncpy(exec_prefix, L"" EXEC_PREFIX, MAXPATHLEN); } /* External interface */ -char * +wchar_t * Py_GetPath(void) { if (!module_search_path) @@ -663,7 +743,7 @@ return module_search_path; } -char * +wchar_t * Py_GetPrefix(void) { if (!module_search_path) @@ -671,7 +751,7 @@ return prefix; } -char * +wchar_t * Py_GetExecPrefix(void) { if (!module_search_path) @@ -679,7 +759,7 @@ return exec_prefix; } -char * +wchar_t * Py_GetProgramFullPath(void) { if (!module_search_path) Modified: python/branches/py3k/Modules/main.c ============================================================================== --- python/branches/py3k/Modules/main.c (original) +++ python/branches/py3k/Modules/main.c Sat Apr 5 22:41:37 2008 @@ -12,6 +12,7 @@ #include #ifdef HAVE_FCNTL_H #include +#define PATH_MAX MAXPATHLEN #endif #endif @@ -40,17 +41,17 @@ #endif /* For Py_GetArgcArgv(); set by main() */ -static char **orig_argv; +static wchar_t **orig_argv; static int orig_argc; /* command line options */ -#define BASE_OPTS "bBc:dEhim:OStuvVW:xX?" +#define BASE_OPTS L"bBc:dEhim:OStuvVW:xX?" #define PROGRAM_OPTS BASE_OPTS /* Short usage message (with %s for argv0) */ static char *usage_line = -"usage: %s [option] ... [-c cmd | -m mod | file | -] [arg] ...\n"; +"usage: %ls [option] ... [-c cmd | -m mod | file | -] [arg] ...\n"; /* Long usage message, split into parts < 512 bytes */ static char *usage_1 = "\ @@ -96,9 +97,30 @@ PYTHONCASEOK : ignore case in 'import' statements (Windows).\n\ "; +#ifndef MS_WINDOWS +static FILE* +_wfopen(const wchar_t *path, const wchar_t *mode) +{ + char cpath[PATH_MAX]; + char cmode[10]; + size_t r; + r = wcstombs(cpath, path, PATH_MAX); + if (r == (size_t)-1 || r >= PATH_MAX) { + errno = EINVAL; + return NULL; + } + r = wcstombs(cmode, mode, 10); + if (r == (size_t)-1 || r >= 10) { + errno = EINVAL; + return NULL; + } + return fopen(cpath, cmode); +} +#endif + static int -usage(int exitcode, char* program) +usage(int exitcode, wchar_t* program) { FILE *f = exitcode ? stderr : stdout; @@ -187,11 +209,11 @@ return 0; } -static int RunMainFromImporter(char *filename) +static int RunMainFromImporter(wchar_t *filename) { PyObject *argv0 = NULL, *importer = NULL; - if ((argv0 = PyUnicode_DecodeFSDefault(filename)) && + if ((argv0 = PyUnicode_FromWideChar(filename,wcslen(filename))) && (importer = PyImport_GetImporter(argv0)) && (importer->ob_type != &PyNullImporter_Type)) { @@ -249,12 +271,12 @@ /* Main program */ int -Py_Main(int argc, char **argv) +Py_Main(int argc, wchar_t **argv) { int c; int sts; char *command = NULL; - char *filename = NULL; + wchar_t *filename = NULL; char *module = NULL; FILE *fp = stdin; char *p; @@ -275,14 +297,19 @@ while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) { if (c == 'c') { + size_t r1 = wcslen(_PyOS_optarg) + 2; + size_t r2; /* -c is the last option; following arguments that look like options are left for the command to interpret. */ - command = (char *)malloc(strlen(_PyOS_optarg) + 2); + command = (char *)malloc(r1); if (command == NULL) Py_FatalError( "not enough memory to copy -c argument"); - strcpy(command, _PyOS_optarg); + r2 = wcstombs(command, _PyOS_optarg, r1); + if (r2 > r1-2) + Py_FatalError( + "not enough memory to copy -c argument"); strcat(command, "\n"); break; } @@ -291,11 +318,16 @@ /* -m is the last option; following arguments that look like options are left for the module to interpret. */ - module = (char *)malloc(strlen(_PyOS_optarg) + 2); + size_t r1 = wcslen(_PyOS_optarg) + 1; + size_t r2; + module = (char *)malloc(r1); if (module == NULL) Py_FatalError( "not enough memory to copy -m argument"); - strcpy(module, _PyOS_optarg); + r2 = wcstombs(module, _PyOS_optarg, r1); + if (r2 >= r1) + Py_FatalError( + "not enough memory to copy -m argument"); break; } @@ -355,7 +387,7 @@ version++; break; - case 'W': + case 'W': PySys_AddWarnOption(_PyOS_optarg); break; @@ -384,7 +416,7 @@ unbuffered = 1; if (command == NULL && module == NULL && _PyOS_optind < argc && - strcmp(argv[_PyOS_optind], "-") != 0) + wcscmp(argv[_PyOS_optind], L"-") != 0) { #ifdef __VMS filename = decc$translate_vms(argv[_PyOS_optind]); @@ -462,14 +494,14 @@ if (command != NULL) { /* Backup _PyOS_optind and force sys.argv[0] = '-c' */ _PyOS_optind--; - argv[_PyOS_optind] = "-c"; + argv[_PyOS_optind] = L"-c"; } if (module != NULL) { /* Backup _PyOS_optind and force sys.argv[0] = '-c' so that PySys_SetArgv correctly sets sys.path[0] to ''*/ _PyOS_optind--; - argv[_PyOS_optind] = "-c"; + argv[_PyOS_optind] = L"-c"; } PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind); @@ -506,8 +538,8 @@ } if (sts==-1 && filename!=NULL) { - if ((fp = fopen(filename, "r")) == NULL) { - fprintf(stderr, "%s: can't open file '%s': [Errno %d] %s\n", + if ((fp = _wfopen(filename, L"r")) == NULL) { + fprintf(stderr, "%s: can't open file '%ls': [Errno %d] %s\n", argv[0], filename, errno, strerror(errno)); return 2; @@ -528,7 +560,7 @@ struct stat sb; if (fstat(fileno(fp), &sb) == 0 && S_ISDIR(sb.st_mode)) { - fprintf(stderr, "%s: '%s' is a directory, cannot continue\n", argv[0], filename); + fprintf(stderr, "%ls: '%ls' is a directory, cannot continue\n", argv[0], filename); fclose(fp); return 1; } @@ -536,9 +568,17 @@ } if (sts==-1) { + char cfilename[PATH_MAX]; + char *p_cfilename = ""; + if (filename) { + size_t r = wcstombs(cfilename, filename, PATH_MAX); + p_cfilename = cfilename; + if (r == (size_t)-1 || r >= PATH_MAX) + p_cfilename = ""; + } sts = PyRun_AnyFileExFlags( fp, - filename == NULL ? "" : filename, + p_cfilename, filename != NULL, &cf) != 0; } @@ -589,7 +629,7 @@ This is rare, but it is needed by the secureware extension. */ void -Py_GetArgcArgv(int *argc, char ***argv) +Py_GetArgcArgv(int *argc, wchar_t ***argv) { *argc = orig_argc; *argv = orig_argv; Modified: python/branches/py3k/Modules/python.c ============================================================================== --- python/branches/py3k/Modules/python.c (original) +++ python/branches/py3k/Modules/python.c Sat Apr 5 22:41:37 2008 @@ -1,14 +1,27 @@ /* Minimal main program -- everything is loaded from the library */ #include "Python.h" +#include #ifdef __FreeBSD__ #include #endif +#ifdef MS_WINDOWS +int +wmain(int argc, wchar_t **argv) +{ + return Py_Main(argc, argv); +} +#else int main(int argc, char **argv) { + wchar_t **argv_copy = PyMem_Malloc(sizeof(wchar_t*)*argc); + /* We need a second copies, as Python might modify the first one. */ + wchar_t **argv_copy2 = PyMem_Malloc(sizeof(wchar_t*)*argc); + int i, res; + char *oldloc; /* 754 requires that FP exceptions run in "no stop" mode by default, * and until C vendors implement C99's ways to control FP exceptions, * Python requires non-stop mode. Alas, some platforms enable FP @@ -20,5 +33,33 @@ m = fpgetmask(); fpsetmask(m & ~FP_X_OFL); #endif - return Py_Main(argc, argv); + if (!argv_copy || !argv_copy2) { + fprintf(stderr, "out of memory"); + return 1; + } + oldloc = setlocale(LC_ALL, NULL); + setlocale(LC_ALL, ""); + for (i = 0; i < argc; i++) { + size_t argsize = mbstowcs(NULL, argv[i], 0); + if (argsize == (size_t)-1) { + fprintf(stderr, "Could not convert argument %d to string", i); + return 1; + } + argv_copy[i] = PyMem_Malloc((argsize+1)*sizeof(wchar_t)); + argv_copy2[i] = argv_copy[i]; + if (!argv_copy[i]) { + fprintf(stderr, "out of memory"); + return 1; + } + mbstowcs(argv_copy[i], argv[i], argsize+1); + } + setlocale(LC_ALL, oldloc); + res = Py_Main(argc, argv_copy); + for (i = 0; i < argc; i++) { + PyMem_Free(argv_copy2[i]); + } + PyMem_Free(argv_copy); + PyMem_Free(argv_copy2); + return res; } +#endif Modified: python/branches/py3k/Objects/unicodeobject.c ============================================================================== --- python/branches/py3k/Objects/unicodeobject.c (original) +++ python/branches/py3k/Objects/unicodeobject.c Sat Apr 5 22:41:37 2008 @@ -553,10 +553,16 @@ PyUnicodeObject *unicode; if (w == NULL) { + if (size == 0) + return PyUnicode_FromStringAndSize(NULL, 0); PyErr_BadInternalCall(); return NULL; } + if (size == -1) { + size = wcslen(w); + } + unicode = _PyUnicode_New(size); if (!unicode) return NULL; Modified: python/branches/py3k/PC/WinMain.c ============================================================================== --- python/branches/py3k/PC/WinMain.c (original) +++ python/branches/py3k/PC/WinMain.c Sat Apr 5 22:41:37 2008 @@ -12,5 +12,5 @@ int nCmdShow /* show state of window */ ) { - return Py_Main(__argc, __argv); + return Py_Main(__argc, __wargv); } Modified: python/branches/py3k/PC/getpathp.c ============================================================================== --- python/branches/py3k/PC/getpathp.c (original) +++ python/branches/py3k/PC/getpathp.c Sat Apr 5 22:41:37 2008 @@ -56,10 +56,10 @@ #include "Python.h" #include "osdefs.h" +#include #ifdef MS_WINDOWS #include -#include #endif #ifdef HAVE_SYS_TYPES_H @@ -82,17 +82,17 @@ */ #ifndef LANDMARK -#define LANDMARK "lib\\os.py" +#define LANDMARK L"lib\\os.py" #endif -static char prefix[MAXPATHLEN+1]; -static char progpath[MAXPATHLEN+1]; -static char dllpath[MAXPATHLEN+1]; -static char *module_search_path = NULL; +static wchar_t prefix[MAXPATHLEN+1]; +static wchar_t progpath[MAXPATHLEN+1]; +static wchar_t dllpath[MAXPATHLEN+1]; +static wchar_t *module_search_path = NULL; static int -is_sep(char ch) /* determine if "ch" is a separator character */ +is_sep(wchar_t ch) /* determine if "ch" is a separator character */ { #ifdef ALTSEP return ch == SEP || ch == ALTSEP; @@ -105,9 +105,9 @@ beyond existing terminator. */ static void -reduce(char *dir) +reduce(wchar_t *dir) { - size_t i = strlen(dir); + size_t i = wcslen(dir); while (i > 0 && !is_sep(dir[i])) --i; dir[i] = '\0'; @@ -115,24 +115,24 @@ static int -exists(char *filename) +exists(wchar_t *filename) { - struct stat buf; - return stat(filename, &buf) == 0; + struct _stat64 buf; + return _wstat64(filename, &buf) == 0; } /* Assumes 'filename' MAXPATHLEN+1 bytes long - may extend 'filename' by one character. */ static int -ismodule(char *filename) /* Is module -- check for .pyc/.pyo too */ +ismodule(wchar_t *filename) /* Is module -- check for .pyc/.pyo too */ { if (exists(filename)) return 1; /* Check for the compiled version of prefix. */ - if (strlen(filename) < MAXPATHLEN) { - strcat(filename, Py_OptimizeFlag ? "o" : "c"); + if (wcslen(filename) < MAXPATHLEN) { + wcscat(filename, Py_OptimizeFlag ? L"o" : L"c"); if (exists(filename)) return 1; } @@ -149,22 +149,22 @@ stuff as fits will be appended. */ static void -join(char *buffer, char *stuff) +join(wchar_t *buffer, wchar_t *stuff) { size_t n, k; if (is_sep(stuff[0])) n = 0; else { - n = strlen(buffer); + n = wcslen(buffer); if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) buffer[n++] = SEP; } if (n > MAXPATHLEN) Py_FatalError("buffer overflow in getpathp.c's joinpath()"); - k = strlen(stuff); + k = wcslen(stuff); if (n + k > MAXPATHLEN) k = MAXPATHLEN - n; - strncpy(buffer+n, stuff, k); + wcsncpy(buffer+n, stuff, k); buffer[n+k] = '\0'; } @@ -173,12 +173,12 @@ 'landmark' can not overflow prefix if too long. */ static int -gotlandmark(char *landmark) +gotlandmark(wchar_t *landmark) { int ok; Py_ssize_t n; - n = strlen(prefix); + n = wcslen(prefix); join(prefix, landmark); ok = ismodule(prefix); prefix[n] = '\0'; @@ -188,10 +188,10 @@ /* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd. assumption provided by only caller, calculate_path() */ static int -search_for_prefix(char *argv0_path, char *landmark) +search_for_prefix(wchar_t *argv0_path, wchar_t *landmark) { /* Search from argv0_path, until landmark is found */ - strcpy(prefix, argv0_path); + wcscpy(prefix, argv0_path); do { if (gotlandmark(landmark)) return 1; @@ -219,39 +219,39 @@ in advance. It could be simplied now Win16/Win32s is dead! */ -static char * +static wchar_t * getpythonregpath(HKEY keyBase, int skipcore) { HKEY newKey = 0; DWORD dataSize = 0; DWORD numKeys = 0; LONG rc; - char *retval = NULL; - TCHAR *dataBuf = NULL; - static const TCHAR keyPrefix[] = _T("Software\\Python\\PythonCore\\"); - static const TCHAR keySuffix[] = _T("\\PythonPath"); + wchar_t *retval = NULL; + WCHAR *dataBuf = NULL; + static const WCHAR keyPrefix[] = L"Software\\Python\\PythonCore\\"; + static const WCHAR keySuffix[] = L"\\PythonPath"; size_t versionLen; DWORD index; - TCHAR *keyBuf = NULL; - TCHAR *keyBufPtr; - TCHAR **ppPaths = NULL; - + WCHAR *keyBuf = NULL; + WCHAR *keyBufPtr; + WCHAR **ppPaths = NULL; + /* Tried to use sysget("winver") but here is too early :-( */ - versionLen = _tcslen(PyWin_DLLVersionString); + versionLen = strlen(PyWin_DLLVersionString); /* Space for all the chars, plus one \0 */ keyBuf = keyBufPtr = malloc(sizeof(keyPrefix) + - sizeof(TCHAR)*(versionLen-1) + + sizeof(WCHAR)*(versionLen-1) + sizeof(keySuffix)); if (keyBuf==NULL) goto done; - memcpy(keyBufPtr, keyPrefix, sizeof(keyPrefix)-sizeof(TCHAR)); - keyBufPtr += sizeof(keyPrefix)/sizeof(TCHAR) - 1; - memcpy(keyBufPtr, PyWin_DLLVersionString, versionLen * sizeof(TCHAR)); + memcpy(keyBufPtr, keyPrefix, sizeof(keyPrefix)-sizeof(WCHAR)); + keyBufPtr += sizeof(keyPrefix)/sizeof(WCHAR) - 1; + mbstowcs(keyBufPtr, PyWin_DLLVersionString, versionLen); keyBufPtr += versionLen; /* NULL comes with this one! */ memcpy(keyBufPtr, keySuffix, sizeof(keySuffix)); /* Open the root Python key */ - rc=RegOpenKeyEx(keyBase, + rc=RegOpenKeyExW(keyBase, keyBuf, /* subkey */ 0, /* reserved */ KEY_READ, @@ -265,31 +265,31 @@ /* Allocate a temp array of char buffers, so we only need to loop reading the registry once */ - ppPaths = malloc( sizeof(TCHAR *) * numKeys ); + ppPaths = malloc( sizeof(WCHAR *) * numKeys ); if (ppPaths==NULL) goto done; - memset(ppPaths, 0, sizeof(TCHAR *) * numKeys); + memset(ppPaths, 0, sizeof(WCHAR *) * numKeys); /* Loop over all subkeys, allocating a temp sub-buffer. */ for(index=0;index 0) { - *(szCur++) = _T(';'); + *(szCur++) = L';'; dataSize--; } if (ppPaths[index]) { - Py_ssize_t len = _tcslen(ppPaths[index]); - _tcsncpy(szCur, ppPaths[index], len); + Py_ssize_t len = wcslen(ppPaths[index]); + wcsncpy(szCur, ppPaths[index], len); szCur += len; assert(dataSize > (DWORD)len); dataSize -= (DWORD)len; @@ -325,30 +325,17 @@ else { /* If we have no values, we dont need a ';' */ if (numKeys) { - *(szCur++) = _T(';'); + *(szCur++) = L';'; dataSize--; } /* Now append the core path entries - this will include the NULL */ - rc = RegQueryValueEx(newKey, NULL, 0, NULL, - (LPBYTE)szCur, &dataSize); + rc = RegQueryValueExW(newKey, NULL, 0, NULL, + (LPBYTE)szCur, &dataSize); } - /* And set the result - caller must free - If MBCS, it is fine as is. If Unicode, allocate new - buffer and convert. - */ -#ifdef UNICODE - retval = (char *)malloc(reqdSize+1); - if (retval) - WideCharToMultiByte(CP_ACP, 0, - dataBuf, -1, /* source */ - retval, reqdSize+1, /* dest */ - NULL, NULL); - free(dataBuf); -#else + /* And set the result - caller must free */ retval = dataBuf; -#endif } done: /* Loop freeing my temp buffers */ @@ -368,45 +355,21 @@ static void get_progpath(void) { - extern char *Py_GetProgramName(void); - char *path = getenv("PATH"); - char *prog = Py_GetProgramName(); + extern wchar_t *Py_GetProgramName(void); + wchar_t *path = _wgetenv(L"PATH"); + wchar_t *prog = Py_GetProgramName(); #ifdef MS_WINDOWS extern HANDLE PyWin_DLLhModule; -#ifdef UNICODE - WCHAR wprogpath[MAXPATHLEN+1]; - /* Windows documents that GetModuleFileName() will "truncate", - but makes no mention of the null terminator. Play it safe. - PLUS Windows itself defines MAX_PATH as the same, but anyway... - */ - wprogpath[MAXPATHLEN]=_T('\0'); - if (PyWin_DLLhModule && - GetModuleFileName(PyWin_DLLhModule, wprogpath, MAXPATHLEN)) { - WideCharToMultiByte(CP_ACP, 0, - wprogpath, -1, - dllpath, MAXPATHLEN+1, - NULL, NULL); - } - wprogpath[MAXPATHLEN]=_T('\0'); - if (GetModuleFileName(NULL, wprogpath, MAXPATHLEN)) { - WideCharToMultiByte(CP_ACP, 0, - wprogpath, -1, - progpath, MAXPATHLEN+1, - NULL, NULL); - return; - } -#else /* static init of progpath ensures final char remains \0 */ if (PyWin_DLLhModule) - if (!GetModuleFileName(PyWin_DLLhModule, dllpath, MAXPATHLEN)) + if (!GetModuleFileNameW(PyWin_DLLhModule, dllpath, MAXPATHLEN)) dllpath[0] = 0; - if (GetModuleFileName(NULL, progpath, MAXPATHLEN)) + if (GetModuleFileNameW(NULL, progpath, MAXPATHLEN)) return; #endif -#endif if (prog == NULL || *prog == '\0') - prog = "python"; + prog = L"python"; /* If there is no slash in the argv0 path, then we have to * assume python is on the user's $PATH, since there's no @@ -414,24 +377,24 @@ * $PATH isn't exported, you lose. */ #ifdef ALTSEP - if (strchr(prog, SEP) || strchr(prog, ALTSEP)) + if (wcschr(prog, SEP) || wcschr(prog, ALTSEP)) #else - if (strchr(prog, SEP)) + if (wcschr(prog, SEP)) #endif - strncpy(progpath, prog, MAXPATHLEN); + wcsncpy(progpath, prog, MAXPATHLEN); else if (path) { while (1) { - char *delim = strchr(path, DELIM); + wchar_t *delim = wcschr(path, DELIM); if (delim) { size_t len = delim - path; /* ensure we can't overwrite buffer */ len = min(MAXPATHLEN,len); - strncpy(progpath, path, len); + wcsncpy(progpath, path, len); *(progpath + len) = '\0'; } else - strncpy(progpath, path, MAXPATHLEN); + wcsncpy(progpath, path, MAXPATHLEN); /* join() is safe for MAXPATHLEN+1 size buffer */ join(progpath, prog); @@ -452,23 +415,31 @@ static void calculate_path(void) { - char argv0_path[MAXPATHLEN+1]; - char *buf; + wchar_t argv0_path[MAXPATHLEN+1]; + wchar_t *buf; size_t bufsz; - char *pythonhome = Py_GetPythonHome(); - char *envpath = Py_GETENV("PYTHONPATH"); + wchar_t *pythonhome = Py_GetPythonHome(); + char *_envpath = Py_GETENV("PYTHONPATH"); + wchar_t wenvpath[MAXPATHLEN+1]; + wchar_t *envpath = NULL; #ifdef MS_WINDOWS int skiphome, skipdefault; - char *machinepath = NULL; - char *userpath = NULL; - char zip_path[MAXPATHLEN+1]; + wchar_t *machinepath = NULL; + wchar_t *userpath = NULL; + wchar_t zip_path[MAXPATHLEN+1]; size_t len; #endif + if (_envpath) { + size_t r = mbstowcs(wenvpath, _envpath, MAXPATHLEN+1); + envpath = wenvpath; + if (r == (size_t)-1 || r >= MAXPATHLEN) + envpath = NULL; + } get_progpath(); /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */ - strcpy(argv0_path, progpath); + wcscpy(argv0_path, progpath); reduce(argv0_path); if (pythonhome == NULL || *pythonhome == '\0') { if (search_for_prefix(argv0_path, LANDMARK)) @@ -477,7 +448,7 @@ pythonhome = NULL; } else - strncpy(prefix, pythonhome, MAXPATHLEN); + wcsncpy(prefix, pythonhome, MAXPATHLEN); if (envpath && *envpath == '\0') envpath = NULL; @@ -486,11 +457,11 @@ #ifdef MS_WINDOWS /* Calculate zip archive path */ if (dllpath[0]) /* use name of python DLL */ - strncpy(zip_path, dllpath, MAXPATHLEN); + wcsncpy(zip_path, dllpath, MAXPATHLEN); else /* use name of executable program */ - strncpy(zip_path, progpath, MAXPATHLEN); + wcsncpy(zip_path, progpath, MAXPATHLEN); zip_path[MAXPATHLEN] = '\0'; - len = strlen(zip_path); + len = wcslen(zip_path); if (len > 4) { zip_path[len-3] = 'z'; /* change ending to "zip" */ zip_path[len-2] = 'i'; @@ -524,29 +495,29 @@ /* Calculate size of return buffer */ if (pythonhome != NULL) { - char *p; + wchar_t *p; bufsz = 1; for (p = PYTHONPATH; *p; p++) { if (*p == DELIM) bufsz++; /* number of DELIM plus one */ } - bufsz *= strlen(pythonhome); + bufsz *= wcslen(pythonhome); } else bufsz = 0; - bufsz += strlen(PYTHONPATH) + 1; - bufsz += strlen(argv0_path) + 1; + bufsz += wcslen(PYTHONPATH) + 1; + bufsz += wcslen(argv0_path) + 1; #ifdef MS_WINDOWS if (userpath) - bufsz += strlen(userpath) + 1; + bufsz += wcslen(userpath) + 1; if (machinepath) - bufsz += strlen(machinepath) + 1; - bufsz += strlen(zip_path) + 1; + bufsz += wcslen(machinepath) + 1; + bufsz += wcslen(zip_path) + 1; #endif if (envpath != NULL) - bufsz += strlen(envpath) + 1; + bufsz += wcslen(envpath) + 1; - module_search_path = buf = malloc(bufsz); + module_search_path = buf = malloc(bufsz*sizeof(wchar_t)); if (buf == NULL) { /* We can't exit, so print a warning and limp along */ fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); @@ -568,57 +539,57 @@ } if (envpath) { - strcpy(buf, envpath); - buf = strchr(buf, '\0'); + wcscpy(buf, envpath); + buf = wcschr(buf, L'\0'); *buf++ = DELIM; } #ifdef MS_WINDOWS if (zip_path[0]) { - strcpy(buf, zip_path); - buf = strchr(buf, '\0'); + wcscpy(buf, zip_path); + buf = wcschr(buf, L'\0'); *buf++ = DELIM; } if (userpath) { - strcpy(buf, userpath); - buf = strchr(buf, '\0'); + wcscpy(buf, userpath); + buf = wcschr(buf, L'\0'); *buf++ = DELIM; free(userpath); } if (machinepath) { - strcpy(buf, machinepath); - buf = strchr(buf, '\0'); + wcscpy(buf, machinepath); + buf = wcschr(buf, L'\0'); *buf++ = DELIM; free(machinepath); } if (pythonhome == NULL) { if (!skipdefault) { - strcpy(buf, PYTHONPATH); - buf = strchr(buf, '\0'); + wcscpy(buf, PYTHONPATH); + buf = wcschr(buf, L'\0'); } } #else if (pythonhome == NULL) { - strcpy(buf, PYTHONPATH); - buf = strchr(buf, '\0'); + wcscpy(buf, PYTHONPATH); + buf = wcschr(buf, L'\0'); } #endif /* MS_WINDOWS */ else { - char *p = PYTHONPATH; - char *q; + wchar_t *p = PYTHONPATH; + wchar_t *q; size_t n; for (;;) { - q = strchr(p, DELIM); + q = wcschr(p, DELIM); if (q == NULL) - n = strlen(p); + n = wcslen(p); else n = q-p; if (p[0] == '.' && is_sep(p[1])) { - strcpy(buf, pythonhome); - buf = strchr(buf, '\0'); + wcscpy(buf, pythonhome); + buf = wcschr(buf, L'\0'); p++; n--; } - strncpy(buf, p, n); + wcsncpy(buf, p, n); buf += n; if (q == NULL) break; @@ -628,10 +599,10 @@ } if (argv0_path) { *buf++ = DELIM; - strcpy(buf, argv0_path); - buf = strchr(buf, '\0'); + wcscpy(buf, argv0_path); + buf = wcschr(buf, L'\0'); } - *buf = '\0'; + *buf = L'\0'; /* Now to pull one last hack/trick. If sys.prefix is empty, then try and find it somewhere on the paths we calculated. We scan backwards, as our general policy @@ -640,12 +611,12 @@ on the path, and that our 'prefix' directory is the parent of that. */ - if (*prefix=='\0') { - char lookBuf[MAXPATHLEN+1]; - char *look = buf - 1; /* 'buf' is at the end of the buffer */ + if (*prefix==L'\0') { + wchar_t lookBuf[MAXPATHLEN+1]; + wchar_t *look = buf - 1; /* 'buf' is at the end of the buffer */ while (1) { Py_ssize_t nchars; - char *lookEnd = look; + wchar_t *lookEnd = look; /* 'look' will end up one character before the start of the path in question - even if this is one character before the start of the buffer @@ -653,8 +624,8 @@ while (look >= module_search_path && *look != DELIM) look--; nchars = lookEnd-look; - strncpy(lookBuf, look+1, nchars); - lookBuf[nchars] = '\0'; + wcsncpy(lookBuf, look+1, nchars); + lookBuf[nchars] = L'\0'; /* Up one level to the parent */ reduce(lookBuf); if (search_for_prefix(lookBuf, LANDMARK)) { @@ -671,7 +642,7 @@ /* External interface */ -char * +wchar_t * Py_GetPath(void) { if (!module_search_path) @@ -679,7 +650,7 @@ return module_search_path; } -char * +wchar_t * Py_GetPrefix(void) { if (!module_search_path) @@ -687,13 +658,13 @@ return prefix; } -char * +wchar_t * Py_GetExecPrefix(void) { return Py_GetPrefix(); } -char * +wchar_t * Py_GetProgramFullPath(void) { if (!module_search_path) Modified: python/branches/py3k/PC/pyconfig.h ============================================================================== --- python/branches/py3k/PC/pyconfig.h (original) +++ python/branches/py3k/PC/pyconfig.h Sat Apr 5 22:41:37 2008 @@ -80,7 +80,7 @@ #define MS_WIN32 /* only support win32 and greater. */ #define MS_WINDOWS #ifndef PYTHONPATH -# define PYTHONPATH ".\\DLLs;.\\lib;.\\lib\\plat-win;.\\lib\\lib-tk" +# define PYTHONPATH L".\\DLLs;.\\lib;.\\lib\\plat-win;.\\lib\\lib-tk" #endif #define NT_THREADS #define WITH_THREAD Modified: python/branches/py3k/Python/frozenmain.c ============================================================================== --- python/branches/py3k/Python/frozenmain.c (original) +++ python/branches/py3k/Python/frozenmain.c Sat Apr 5 22:41:37 2008 @@ -2,6 +2,7 @@ /* Python interpreter main program for frozen scripts */ #include "Python.h" +#include #ifdef MS_WINDOWS extern void PyWinFreeze_ExeInit(void); @@ -15,9 +16,13 @@ Py_FrozenMain(int argc, char **argv) { char *p; - int n, sts; + int i, n, sts; int inspect = 0; int unbuffered = 0; + char *oldloc; + wchar_t **argv_copy = PyMem_Malloc(sizeof(wchar_t*)*argc); + /* We need a second copies, as Python might modify the first one. */ + wchar_t **argv_copy2 = PyMem_Malloc(sizeof(wchar_t*)*argc); Py_FrozenFlag = 1; /* Suppress errors from getpath.c */ @@ -32,10 +37,33 @@ setbuf(stderr, (char *)NULL); } + if (!argv_copy) { + fprintf(stderr, "out of memory"); + return 1; + } + + oldloc = setlocale(LC_ALL, NULL); + setlocale(LC_ALL, ""); + for (i = 0; i < argc; i++) { + size_t argsize = mbstowcs(NULL, argv[i], 0); + if (argsize == (size_t)-1) { + fprintf(stderr, "Could not convert argument %d to string", i); + return 1; + } + argv_copy[i] = PyMem_Malloc((argsize+1)*sizeof(wchar_t)); + argv_copy2[i] = argv_copy[i]; + if (!argv_copy[i]) { + fprintf(stderr, "out of memory"); + return 1; + } + mbstowcs(argv_copy[i], argv[i], argsize+1); + } + setlocale(LC_ALL, oldloc); + #ifdef MS_WINDOWS PyInitFrozenExtensions(); #endif /* MS_WINDOWS */ - Py_SetProgramName(argv[0]); + Py_SetProgramName(argv_copy[0]); Py_Initialize(); #ifdef MS_WINDOWS PyWinFreeze_ExeInit(); @@ -45,7 +73,7 @@ fprintf(stderr, "Python %s\n%s\n", Py_GetVersion(), Py_GetCopyright()); - PySys_SetArgv(argc, argv); + PySys_SetArgv(argc, argv_copy); n = PyImport_ImportFrozenModule("__main__"); if (n == 0) @@ -64,5 +92,10 @@ PyWinFreeze_ExeTerm(); #endif Py_Finalize(); + for (i = 0; i < argc; i++) { + PyMem_Free(argv_copy2[i]); + } + PyMem_Free(argv_copy); + PyMem_Free(argv_copy2); return sts; } Modified: python/branches/py3k/Python/getopt.c ============================================================================== --- python/branches/py3k/Python/getopt.c (original) +++ python/branches/py3k/Python/getopt.c Sat Apr 5 22:41:37 2008 @@ -27,8 +27,11 @@ /* Modified to support --help and --version, as well as /? on Windows * by Georg Brandl. */ +#include #include #include +#include +#include #ifdef __cplusplus extern "C" { @@ -36,40 +39,40 @@ int _PyOS_opterr = 1; /* generate error messages */ int _PyOS_optind = 1; /* index into argv array */ -char *_PyOS_optarg = NULL; /* optional argument */ +wchar_t *_PyOS_optarg = NULL; /* optional argument */ -int _PyOS_GetOpt(int argc, char **argv, char *optstring) +int _PyOS_GetOpt(int argc, wchar_t **argv, wchar_t *optstring) { - static char *opt_ptr = ""; - char *ptr; - int option; + static wchar_t *opt_ptr = L""; + wchar_t *ptr; + wchar_t option; if (*opt_ptr == '\0') { if (_PyOS_optind >= argc) return -1; #ifdef MS_WINDOWS - else if (strcmp(argv[_PyOS_optind], "/?") == 0) { + else if (wcscmp(argv[_PyOS_optind], L"/?") == 0) { ++_PyOS_optind; return 'h'; } #endif - else if (argv[_PyOS_optind][0] != '-' || - argv[_PyOS_optind][1] == '\0' /* lone dash */ ) + else if (argv[_PyOS_optind][0] != L'-' || + argv[_PyOS_optind][1] == L'\0' /* lone dash */ ) return -1; - else if (strcmp(argv[_PyOS_optind], "--") == 0) { + else if (wcscmp(argv[_PyOS_optind], L"--") == 0) { ++_PyOS_optind; return -1; } - else if (strcmp(argv[_PyOS_optind], "--help") == 0) { + else if (wcscmp(argv[_PyOS_optind], L"--help") == 0) { ++_PyOS_optind; return 'h'; } - else if (strcmp(argv[_PyOS_optind], "--version") == 0) { + else if (wcscmp(argv[_PyOS_optind], L"--version") == 0) { ++_PyOS_optind; return 'V'; } @@ -78,27 +81,27 @@ opt_ptr = &argv[_PyOS_optind++][1]; } - if ( (option = *opt_ptr++) == '\0') + if ( (option = *opt_ptr++) == L'\0') return -1; - if ((ptr = strchr(optstring, option)) == NULL) { + if ((ptr = wcschr(optstring, option)) == NULL) { if (_PyOS_opterr) - fprintf(stderr, "Unknown option: -%c\n", option); + fprintf(stderr, "Unknown option: -%c\n", (char)option); return '_'; } - if (*(ptr + 1) == ':') { - if (*opt_ptr != '\0') { + if (*(ptr + 1) == L':') { + if (*opt_ptr != L'\0') { _PyOS_optarg = opt_ptr; - opt_ptr = ""; + opt_ptr = L""; } else { if (_PyOS_optind >= argc) { if (_PyOS_opterr) fprintf(stderr, - "Argument expected for the -%c option\n", option); + "Argument expected for the -%c option\n", (char)option); return '_'; } Modified: python/branches/py3k/Python/pythonrun.c ============================================================================== --- python/branches/py3k/Python/pythonrun.c (original) +++ python/branches/py3k/Python/pythonrun.c Sat Apr 5 22:41:37 2008 @@ -17,6 +17,7 @@ #include "ast.h" #include "eval.h" #include "marshal.h" +#include "osdefs.h" #ifdef HAVE_SIGNAL_H #include @@ -30,6 +31,7 @@ #ifdef MS_WINDOWS #undef BYTE #include "windows.h" +#define PATH_MAX MAXPATHLEN #endif #ifndef Py_REF_DEBUG @@ -44,7 +46,7 @@ extern "C" { #endif -extern char *Py_GetPath(void); +extern wchar_t *Py_GetPath(void); extern grammar _PyParser_Grammar; /* From graminit.c */ @@ -646,35 +648,43 @@ PyInterpreterState_Delete(interp); } -static char *progname = "python"; +static wchar_t *progname = L"python"; void -Py_SetProgramName(char *pn) +Py_SetProgramName(wchar_t *pn) { if (pn && *pn) progname = pn; } -char * +wchar_t * Py_GetProgramName(void) { return progname; } -static char *default_home = NULL; +static wchar_t *default_home = NULL; +static wchar_t env_home[PATH_MAX+1]; void -Py_SetPythonHome(char *home) +Py_SetPythonHome(wchar_t *home) { default_home = home; } -char * +wchar_t * Py_GetPythonHome(void) { - char *home = default_home; - if (home == NULL && !Py_IgnoreEnvironmentFlag) - home = Py_GETENV("PYTHONHOME"); + wchar_t *home = default_home; + if (home == NULL && !Py_IgnoreEnvironmentFlag) { + char* chome = Py_GETENV("PYTHONHOME"); + if (chome) { + size_t r = mbstowcs(env_home, chome, PATH_MAX+1); + if (r != (size_t)-1 && r <= PATH_MAX) + home = env_home; + } + + } return home; } Modified: python/branches/py3k/Python/sysmodule.c ============================================================================== --- python/branches/py3k/Python/sysmodule.c (original) +++ python/branches/py3k/Python/sysmodule.c Sat Apr 5 22:41:37 2008 @@ -882,7 +882,7 @@ } void -PySys_AddWarnOption(const char *s) +PySys_AddWarnOption(const wchar_t *s) { PyObject *str; @@ -892,7 +892,7 @@ if (warnoptions == NULL) return; } - str = PyUnicode_FromString(s); + str = PyUnicode_FromWideChar(s, -1); if (str != NULL) { PyList_Append(warnoptions, str); Py_DECREF(str); @@ -1222,12 +1222,12 @@ SET_SYS_FROM_STRING("platform", PyUnicode_FromString(Py_GetPlatform())); SET_SYS_FROM_STRING("executable", - PyUnicode_DecodeFSDefault( - Py_GetProgramFullPath())); + PyUnicode_FromWideChar( + Py_GetProgramFullPath(), -1)); SET_SYS_FROM_STRING("prefix", - PyUnicode_DecodeFSDefault(Py_GetPrefix())); + PyUnicode_FromWideChar(Py_GetPrefix(), -1)); SET_SYS_FROM_STRING("exec_prefix", - PyUnicode_DecodeFSDefault(Py_GetExecPrefix())); + PyUnicode_FromWideChar(Py_GetExecPrefix(), -1)); SET_SYS_FROM_STRING("maxsize", PyLong_FromSsize_t(PY_SSIZE_T_MAX)); SET_SYS_FROM_STRING("float_info", @@ -1280,15 +1280,15 @@ } static PyObject * -makepathobject(const char *path, int delim) +makepathobject(const wchar_t *path, wchar_t delim) { int i, n; - const char *p; + const wchar_t *p; PyObject *v, *w; n = 1; p = path; - while ((p = strchr(p, delim)) != NULL) { + while ((p = wcschr(p, delim)) != NULL) { n++; p++; } @@ -1296,10 +1296,10 @@ if (v == NULL) return NULL; for (i = 0; ; i++) { - p = strchr(path, delim); + p = wcschr(path, delim); if (p == NULL) - p = strchr(path, '\0'); /* End of string */ - w = PyUnicode_DecodeFSDefaultAndSize(path, (Py_ssize_t) (p - path)); + p = wcschr(path, L'\0'); /* End of string */ + w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path)); if (w == NULL) { Py_DECREF(v); return NULL; @@ -1313,7 +1313,7 @@ } void -PySys_SetPath(const char *path) +PySys_SetPath(const wchar_t *path) { PyObject *v; if ((v = makepathobject(path, DELIM)) == NULL) @@ -1324,12 +1324,12 @@ } static PyObject * -makeargvobject(int argc, char **argv) +makeargvobject(int argc, wchar_t **argv) { PyObject *av; if (argc <= 0 || argv == NULL) { /* Ensure at least one (empty) argument is seen */ - static char *empty_argv[1] = {""}; + static wchar_t *empty_argv[1] = {L""}; argv = empty_argv; argc = 1; } @@ -1351,7 +1351,7 @@ } else v = PyUnicode_FromString(argv[i]); #else - PyObject *v = PyUnicode_FromString(argv[i]); + PyObject *v = PyUnicode_FromWideChar(argv[i], -1); #endif if (v == NULL) { Py_DECREF(av); @@ -1364,13 +1364,38 @@ return av; } +#ifdef HAVE_REALPATH +static wchar_t* +_wrealpath(const wchar_t *path, wchar_t *resolved_path) +{ + char cpath[PATH_MAX]; + char cresolved_path[PATH_MAX]; + char *res; + size_t r; + r = wcstombs(cpath, path, PATH_MAX); + if (r == (size_t)-1 || r >= PATH_MAX) { + errno = EINVAL; + return NULL; + } + res = realpath(cpath, cresolved_path); + if (res == NULL) + return NULL; + r = mbstowcs(resolved_path, cresolved_path, PATH_MAX); + if (r == (size_t)-1 || r >= PATH_MAX) { + errno = EINVAL; + return NULL; + } + return resolved_path; +} +#endif + void -PySys_SetArgv(int argc, char **argv) +PySys_SetArgv(int argc, wchar_t **argv) { #if defined(HAVE_REALPATH) - char fullpath[MAXPATHLEN]; + wchar_t fullpath[MAXPATHLEN]; #elif defined(MS_WINDOWS) - char fullpath[MAX_PATH]; + wchar_t fullpath[MAX_PATH]; #endif PyObject *av = makeargvobject(argc, argv); PyObject *path = PySys_GetObject("path"); @@ -1379,53 +1404,54 @@ if (PySys_SetObject("argv", av) != 0) Py_FatalError("can't assign sys.argv"); if (path != NULL) { - char *argv0 = argv[0]; - char *p = NULL; + wchar_t *argv0 = argv[0]; + wchar_t *p = NULL; Py_ssize_t n = 0; PyObject *a; + extern int _Py_wreadlink(const wchar_t *, wchar_t *, size_t); #ifdef HAVE_READLINK - char link[MAXPATHLEN+1]; - char argv0copy[2*MAXPATHLEN+1]; + wchar_t link[MAXPATHLEN+1]; + wchar_t argv0copy[2*MAXPATHLEN+1]; int nr = 0; - if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) - nr = readlink(argv0, link, MAXPATHLEN); + if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) + nr = _Py_wreadlink(argv0, link, MAXPATHLEN); if (nr > 0) { /* It's a symlink */ link[nr] = '\0'; if (link[0] == SEP) argv0 = link; /* Link to absolute path */ - else if (strchr(link, SEP) == NULL) + else if (wcschr(link, SEP) == NULL) ; /* Link without path */ else { /* Must join(dirname(argv0), link) */ - char *q = strrchr(argv0, SEP); + wchar_t *q = wcsrchr(argv0, SEP); if (q == NULL) argv0 = link; /* argv0 without path */ else { /* Must make a copy */ - strcpy(argv0copy, argv0); - q = strrchr(argv0copy, SEP); - strcpy(q+1, link); + wcscpy(argv0copy, argv0); + q = wcsrchr(argv0copy, SEP); + wcscpy(q+1, link); argv0 = argv0copy; } } } #endif /* HAVE_READLINK */ #if SEP == '\\' /* Special case for MS filename syntax */ - if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) { - char *q; + if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) { + wchar_t *q; #ifdef MS_WINDOWS - char *ptemp; - if (GetFullPathName(argv0, - sizeof(fullpath), + wchar_t *ptemp; + if (GetFullPathNameW(argv0, + sizeof(fullpath)/sizeof(fullpath[0]), fullpath, &ptemp)) { argv0 = fullpath; } #endif - p = strrchr(argv0, SEP); + p = wcsrchr(argv0, SEP); /* Test for alternate separator */ - q = strrchr(p ? p : argv0, '/'); + q = wcsrchr(p ? p : argv0, '/'); if (q != NULL) p = q; if (p != NULL) { @@ -1435,13 +1461,13 @@ } } #else /* All other filename syntaxes */ - if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) { + if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) { #if defined(HAVE_REALPATH) - if (realpath(argv0, fullpath)) { + if (_wrealpath(argv0, fullpath)) { argv0 = fullpath; } #endif - p = strrchr(argv0, SEP); + p = wcsrchr(argv0, SEP); } if (p != NULL) { n = p + 1 - argv0; @@ -1451,7 +1477,7 @@ #endif /* Unix */ } #endif /* All others */ - a = PyUnicode_FromStringAndSize(argv0, n); + a = PyUnicode_FromWideChar(argv0, n); if (a == NULL) Py_FatalError("no mem for sys.path insertion"); if (PyList_Insert(path, 0, a) < 0) From python-3000-checkins at python.org Sun Apr 6 10:39:38 2008 From: python-3000-checkins at python.org (georg.brandl) Date: Sun, 6 Apr 2008 10:39:38 +0200 (CEST) Subject: [Python-3000-checkins] r62181 - python/branches/py3k/Doc/library/pickle.rst Message-ID: <20080406083938.571AD1E4008@bag.python.org> Author: georg.brandl Date: Sun Apr 6 10:39:37 2008 New Revision: 62181 Modified: python/branches/py3k/Doc/library/pickle.rst Log: #2558: document pickle protocol version 3. Thanks to Guilherme Polo. Modified: python/branches/py3k/Doc/library/pickle.rst ============================================================================== --- python/branches/py3k/Doc/library/pickle.rst (original) +++ python/branches/py3k/Doc/library/pickle.rst Sun Apr 6 10:39:37 2008 @@ -110,7 +110,7 @@ :mod:`pickle`'s representation) is that for debugging or recovery purposes it is possible for a human to read the pickled file with a standard text editor. -There are currently 3 different protocols which can be used for pickling. +There are currently 4 different protocols which can be used for pickling. * Protocol version 0 is the original ASCII protocol and is backwards compatible with earlier versions of Python. @@ -121,11 +121,14 @@ * Protocol version 2 was introduced in Python 2.3. It provides much more efficient pickling of :term:`new-style class`\es. +* Protocol version 3 was added in Python 3.0. It has explicit support for + bytes and cannot be unpickled by Python 2.x pickle modules. + Refer to :pep:`307` for more information. -If a *protocol* is not specified, protocol 0 is used. If *protocol* is specified -as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol version -available will be used. +If a *protocol* is not specified, protocol 3 is used. If *protocol* is +specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest +protocol version available will be used. A binary format, which is slightly more efficient, can be chosen by specifying a *protocol* version >= 1. @@ -164,9 +167,9 @@ Write a pickled representation of *obj* to the open file object *file*. This is equivalent to ``Pickler(file, protocol).dump(obj)``. - If the *protocol* parameter is omitted, protocol 0 is used. If *protocol* is - specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol - version will be used. + If the *protocol* parameter is omitted, protocol 3 is used. If *protocol* is + specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest + protocol version will be used. *file* must have a :meth:`write` method that accepts a single string argument. It can thus be a file object opened for writing, a :mod:`StringIO` object, or @@ -194,9 +197,9 @@ Return the pickled representation of the object as a string, instead of writing it to a file. - If the *protocol* parameter is omitted, protocol 0 is used. If *protocol* is - specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol - version will be used. + If the *protocol* parameter is omitted, protocol 3 is used. If *protocol* + is specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest + protocol version will be used. .. function:: loads(string) @@ -234,7 +237,7 @@ This takes a file-like object to which it will write a pickle data stream. - If the *protocol* parameter is omitted, protocol 0 is used. If *protocol* is + If the *protocol* parameter is omitted, protocol 3 is used. If *protocol* is specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol version will be used. @@ -681,8 +684,8 @@ output = open('data.pkl', 'wb') - # Pickle dictionary using protocol 0. - pickle.dump(data1, output) + # Pickle dictionary using protocol 2. + pickle.dump(data1, output, 2) # Pickle the list using the highest protocol available. pickle.dump(selfref_list, output, -1) From python-3000-checkins at python.org Sun Apr 6 18:47:13 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Sun, 6 Apr 2008 18:47:13 +0200 (CEST) Subject: [Python-3000-checkins] r62185 - python/branches/py3k/Lib/io.py Message-ID: <20080406164713.C67201E400C@bag.python.org> Author: benjamin.peterson Date: Sun Apr 6 18:47:13 2008 New Revision: 62185 Modified: python/branches/py3k/Lib/io.py Log: fix typo in doc string Modified: python/branches/py3k/Lib/io.py ============================================================================== --- python/branches/py3k/Lib/io.py (original) +++ python/branches/py3k/Lib/io.py Sun Apr 6 18:47:13 2008 @@ -228,8 +228,8 @@ This does not define read(), readinto() and write(), nor readline() and friends, since their signatures vary per layer. - Not that calling any method (even inquiries) on a closed file is - undefined. Implementations may raise IOError in this case. + Note that calling any method (even inquiries) on a closed file is + undefined. Implementations may raise IOError in this case. """ ### Internal ### From python-3000-checkins at python.org Sun Apr 6 19:57:16 2008 From: python-3000-checkins at python.org (martin.v.loewis) Date: Sun, 6 Apr 2008 19:57:16 +0200 (CEST) Subject: [Python-3000-checkins] r62190 - python/branches/py3k/Modules/main.c Message-ID: <20080406175716.E9C261E400E@bag.python.org> Author: martin.v.loewis Date: Sun Apr 6 19:57:16 2008 New Revision: 62190 Modified: python/branches/py3k/Modules/main.c Log: Convert another %s to %ls. Modified: python/branches/py3k/Modules/main.c ============================================================================== --- python/branches/py3k/Modules/main.c (original) +++ python/branches/py3k/Modules/main.c Sun Apr 6 19:57:16 2008 @@ -539,7 +539,7 @@ if (sts==-1 && filename!=NULL) { if ((fp = _wfopen(filename, L"r")) == NULL) { - fprintf(stderr, "%s: can't open file '%ls': [Errno %d] %s\n", + fprintf(stderr, "%ls: can't open file '%ls': [Errno %d] %s\n", argv[0], filename, errno, strerror(errno)); return 2; From python-3000-checkins at python.org Sun Apr 6 22:27:02 2008 From: python-3000-checkins at python.org (georg.brandl) Date: Sun, 6 Apr 2008 22:27:02 +0200 (CEST) Subject: [Python-3000-checkins] r62192 - python/branches/py3k/Lib/io.py Message-ID: <20080406202702.B88DB1E4028@bag.python.org> Author: georg.brandl Date: Sun Apr 6 22:27:02 2008 New Revision: 62192 Modified: python/branches/py3k/Lib/io.py Log: Docstring fix. Modified: python/branches/py3k/Lib/io.py ============================================================================== --- python/branches/py3k/Lib/io.py (original) +++ python/branches/py3k/Lib/io.py Sun Apr 6 22:27:02 2008 @@ -246,8 +246,8 @@ Seek to byte offset pos relative to position indicated by whence: 0 Start of stream (the default). pos should be >= 0; - 1 Current position - whence may be negative; - 2 End of stream - whence usually negative. + 1 Current position - pos may be negative; + 2 End of stream - pos usually negative. Returns the new absolute position. """ self._unsupported("seek") From python-3000-checkins at python.org Mon Apr 7 02:26:00 2008 From: python-3000-checkins at python.org (thomas.wouters) Date: Mon, 7 Apr 2008 02:26:00 +0200 (CEST) Subject: [Python-3000-checkins] r62196 - in python/branches/py3k: Lib/distutils/tests/test_sysconfig.py setup.py Message-ID: <20080407002600.46DE71E400C@bag.python.org> Author: thomas.wouters Date: Mon Apr 7 02:25:59 2008 New Revision: 62196 Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/distutils/tests/test_sysconfig.py python/branches/py3k/setup.py Log: Merged revisions 62179 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62179 | thomas.wouters | 2008-04-06 01:39:15 +0200 (Sun, 06 Apr 2008) | 10 lines Fix test_distutils to not fail when running 'make test' from a Python build directory that is not the source directory (ie, one created using '/path/to/source/configure'.) Leaves this test very slightly degraded in that particular case, compared to the build-in-sourcedir case, but that case isn't a particularly strong test either: neither test the actual path that will be used after installing. There isn't a particularly good way to test this, and a poor test beats a failing test. ........ Modified: python/branches/py3k/Lib/distutils/tests/test_sysconfig.py ============================================================================== --- python/branches/py3k/Lib/distutils/tests/test_sysconfig.py (original) +++ python/branches/py3k/Lib/distutils/tests/test_sysconfig.py Mon Apr 7 02:25:59 2008 @@ -19,7 +19,27 @@ # test for pythonxx.lib? def test_get_python_inc(self): - inc_dir = sysconfig.get_python_inc() + # The check for srcdir is copied from Python's setup.py, + # and is necessary to make this test pass when building + # Python in a directory other than the source directory. + (srcdir,) = sysconfig.get_config_vars('srcdir') + if not srcdir: + inc_dir = sysconfig.get_python_inc() + else: + # This test is not really a proper test: when building + # Python from source, even in the same directory, + # we won't be testing the same thing as when running + # distutils' tests on an installed Python. Nevertheless, + # let's try to do our best: if we are running Python's + # unittests from a build directory that is not the source + # directory, the normal inc_dir will exist, it will just not + # contain anything of interest. + inc_dir = sysconfig.get_python_inc() + self.assert_(os.path.isdir(inc_dir)) + # Now test the source location, to make sure Python.h does + # exist. + inc_dir = os.path.join(os.getcwd(), srcdir, 'Include') + inc_dir = os.path.normpath(inc_dir) self.assert_(os.path.isdir(inc_dir), inc_dir) python_h = os.path.join(inc_dir, "Python.h") self.assert_(os.path.isfile(python_h), python_h) Modified: python/branches/py3k/setup.py ============================================================================== --- python/branches/py3k/setup.py (original) +++ python/branches/py3k/setup.py Mon Apr 7 02:25:59 2008 @@ -119,6 +119,8 @@ raise ValueError("No source directory; cannot proceed.") # Figure out the location of the source code for extension modules + # (This logic is copied in distutils.test.test_sysconfig, + # so building in a separate directory does not break test_distutils.) moddir = os.path.join(os.getcwd(), srcdir, 'Modules') moddir = os.path.normpath(moddir) srcdir, tail = os.path.split(moddir) From python-3000-checkins at python.org Mon Apr 7 05:17:54 2008 From: python-3000-checkins at python.org (martin.v.loewis) Date: Mon, 7 Apr 2008 05:17:54 +0200 (CEST) Subject: [Python-3000-checkins] r62200 - in python/branches/py3k: Modules/timemodule.c PC/_winreg.c PCbuild/kill_python.vcproj PCbuild/pythoncore.vcproj Tools/buildbot/build-amd64.bat Tools/buildbot/build.bat Message-ID: <20080407031754.D08801E400C@bag.python.org> Author: martin.v.loewis Date: Mon Apr 7 05:17:54 2008 New Revision: 62200 Modified: python/branches/py3k/ (props changed) python/branches/py3k/Modules/timemodule.c python/branches/py3k/PC/_winreg.c python/branches/py3k/PCbuild/kill_python.vcproj python/branches/py3k/PCbuild/pythoncore.vcproj python/branches/py3k/Tools/buildbot/build-amd64.bat python/branches/py3k/Tools/buildbot/build.bat Log: Merged revisions 62177-62178,62180-62193 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62177 | skip.montanaro | 2008-04-05 21:47:47 +0200 (Sa, 05 Apr 2008) | 2 lines Declare inittimezone static. ........ r62180 | mark.hammond | 2008-04-06 03:42:06 +0200 (So, 06 Apr 2008) | 4 lines From issue 1753245 - better _winreg support for x64. Adds _winreg.DisableReflectionKey, EnableReflectionKey, QueryReflectionKey, KEY_WOW64_64KEY and KEY_WOW64_32KEY. ........ r62187 | skip.montanaro | 2008-04-06 19:05:57 +0200 (So, 06 Apr 2008) | 1 line type ........ r62193 | trent.nelson | 2008-04-06 22:51:23 +0200 (So, 06 Apr 2008) | 1 line Don't run kill_python as part of the build process. Change the buildbots so they have to call it explicitly instead. ........ Modified: python/branches/py3k/Modules/timemodule.c ============================================================================== --- python/branches/py3k/Modules/timemodule.c (original) +++ python/branches/py3k/Modules/timemodule.c Mon Apr 7 05:17:54 2008 @@ -661,7 +661,7 @@ #endif /* HAVE_MKTIME */ #ifdef HAVE_WORKING_TZSET -void inittimezone(PyObject *module); +static void inittimezone(PyObject *module); static PyObject * time_tzset(PyObject *self, PyObject *unused) @@ -697,11 +697,12 @@ should not be relied on."); #endif /* HAVE_WORKING_TZSET */ -void inittimezone(PyObject *m) { +static void +inittimezone(PyObject *m) { /* This code moved from inittime wholesale to allow calling it from time_tzset. In the future, some parts of it can be moved back (for platforms that don't HAVE_WORKING_TZSET, when we know what they - are), and the extranious calls to tzset(3) should be removed. + are), and the extraneous calls to tzset(3) should be removed. I haven't done this yet, as I don't want to change this code as little as possible when introducing the time.tzset and time.tzsetwall methods. This should simply be a method of doing the following once, Modified: python/branches/py3k/PC/_winreg.c ============================================================================== --- python/branches/py3k/PC/_winreg.c (original) +++ python/branches/py3k/PC/_winreg.c Mon Apr 7 05:17:54 2008 @@ -289,6 +289,22 @@ "2048 bytes) should be stored as files with the filenames stored in \n" "the configuration registry. This helps the registry perform efficiently."); +PyDoc_STRVAR(DisableReflectionKey_doc, +"Disables registry reflection for 32bit processes running on a 64bit\n" +"Operating System. Will generally raise NotImplemented if executed on\n" +"a 32bit Operating System.\n" +"If the key is not on the reflection list, the function succeeds but has no effect.\n" +"Disabling reflection for a key does not affect reflection of any subkeys."); + +PyDoc_STRVAR(EnableReflectionKey_doc, +"Restores registry reflection for the specified disabled key.\n" +"Will generally raise NotImplemented if executed on a 32bit Operating System.\n" +"Restoring reflection for a key does not affect reflection of any subkeys."); + +PyDoc_STRVAR(QueryReflectionKey_doc, +"bool = QueryReflectionKey(hkey) - Determines the reflection state for the specified key.\n" +"Will generally raise NotImplemented if executed on a 32bit Operating System.\n"); + /* PyHKEY docstrings */ PyDoc_STRVAR(PyHKEY_doc, "PyHKEY Object - A Python object, representing a win32 registry key.\n" @@ -1393,12 +1409,122 @@ return Py_None; } +static PyObject * +PyDisableReflectionKey(PyObject *self, PyObject *args) +{ + HKEY hKey; + PyObject *obKey; + HMODULE hMod; + typedef LONG (WINAPI *RDRKFunc)(HKEY); + RDRKFunc pfn = NULL; + LONG rc; + + if (!PyArg_ParseTuple(args, "O:DisableReflectionKey", &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + // Only available on 64bit platforms, so we must load it + // dynamically. + hMod = GetModuleHandle("advapi32.dll"); + if (hMod) + pfn = (RDRKFunc)GetProcAddress(hMod, + "RegDisableReflectionKey"); + if (!pfn) { + PyErr_SetString(PyExc_NotImplementedError, + "not implemented on this platform"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = (*pfn)(hKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegDisableReflectionKey"); + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject * +PyEnableReflectionKey(PyObject *self, PyObject *args) +{ + HKEY hKey; + PyObject *obKey; + HMODULE hMod; + typedef LONG (WINAPI *RERKFunc)(HKEY); + RERKFunc pfn = NULL; + LONG rc; + + if (!PyArg_ParseTuple(args, "O:EnableReflectionKey", &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + // Only available on 64bit platforms, so we must load it + // dynamically. + hMod = GetModuleHandle("advapi32.dll"); + if (hMod) + pfn = (RERKFunc)GetProcAddress(hMod, + "RegEnableReflectionKey"); + if (!pfn) { + PyErr_SetString(PyExc_NotImplementedError, + "not implemented on this platform"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = (*pfn)(hKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegEnableReflectionKey"); + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject * +PyQueryReflectionKey(PyObject *self, PyObject *args) +{ + HKEY hKey; + PyObject *obKey; + HMODULE hMod; + typedef LONG (WINAPI *RQRKFunc)(HKEY, BOOL *); + RQRKFunc pfn = NULL; + BOOL result; + LONG rc; + + if (!PyArg_ParseTuple(args, "O:QueryReflectionKey", &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + // Only available on 64bit platforms, so we must load it + // dynamically. + hMod = GetModuleHandle("advapi32.dll"); + if (hMod) + pfn = (RQRKFunc)GetProcAddress(hMod, + "RegQueryReflectionKey"); + if (!pfn) { + PyErr_SetString(PyExc_NotImplementedError, + "not implemented on this platform"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = (*pfn)(hKey, &result); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryReflectionKey"); + return PyBool_FromLong(rc); +} + static struct PyMethodDef winreg_methods[] = { {"CloseKey", PyCloseKey, METH_VARARGS, CloseKey_doc}, {"ConnectRegistry", PyConnectRegistry, METH_VARARGS, ConnectRegistry_doc}, {"CreateKey", PyCreateKey, METH_VARARGS, CreateKey_doc}, {"DeleteKey", PyDeleteKey, METH_VARARGS, DeleteKey_doc}, {"DeleteValue", PyDeleteValue, METH_VARARGS, DeleteValue_doc}, + {"DisableReflectionKey", PyDisableReflectionKey, METH_VARARGS, DisableReflectionKey_doc}, + {"EnableReflectionKey", PyEnableReflectionKey, METH_VARARGS, EnableReflectionKey_doc}, {"EnumKey", PyEnumKey, METH_VARARGS, EnumKey_doc}, {"EnumValue", PyEnumValue, METH_VARARGS, EnumValue_doc}, {"ExpandEnvironmentStrings", PyExpandEnvironmentStrings, METH_VARARGS, @@ -1410,6 +1536,7 @@ {"QueryValue", PyQueryValue, METH_VARARGS, QueryValue_doc}, {"QueryValueEx", PyQueryValueEx, METH_VARARGS, QueryValueEx_doc}, {"QueryInfoKey", PyQueryInfoKey, METH_VARARGS, QueryInfoKey_doc}, + {"QueryReflectionKey",PyQueryReflectionKey,METH_VARARGS, QueryReflectionKey_doc}, {"SaveKey", PySaveKey, METH_VARARGS, SaveKey_doc}, {"SetValue", PySetValue, METH_VARARGS, SetValue_doc}, {"SetValueEx", PySetValueEx, METH_VARARGS, SetValueEx_doc}, @@ -1478,6 +1605,12 @@ ADD_INT(KEY_WRITE); ADD_INT(KEY_EXECUTE); ADD_INT(KEY_ALL_ACCESS); +#ifdef KEY_WOW64_64KEY + ADD_INT(KEY_WOW64_64KEY); +#endif +#ifdef KEY_WOW64_32KEY + ADD_INT(KEY_WOW64_32KEY); +#endif ADD_INT(REG_OPTION_RESERVED); ADD_INT(REG_OPTION_NON_VOLATILE); ADD_INT(REG_OPTION_VOLATILE); Modified: python/branches/py3k/PCbuild/kill_python.vcproj ============================================================================== --- python/branches/py3k/PCbuild/kill_python.vcproj (original) +++ python/branches/py3k/PCbuild/kill_python.vcproj Mon Apr 7 05:17:54 2008 @@ -77,8 +77,6 @@ /> Modified: python/branches/py3k/PCbuild/pythoncore.vcproj ============================================================================== --- python/branches/py3k/PCbuild/pythoncore.vcproj (original) +++ python/branches/py3k/PCbuild/pythoncore.vcproj Mon Apr 7 05:17:54 2008 @@ -58,8 +58,8 @@ /> Author: martin.v.loewis Date: Mon Apr 7 05:22:07 2008 New Revision: 62201 Modified: python/branches/py3k/ (props changed) python/branches/py3k/Objects/stringlib/formatter.h python/branches/py3k/Objects/stringlib/string_format.h python/branches/py3k/Objects/unicodeobject.c Log: Merged revisions 62199 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62199 | martin.v.loewis | 2008-04-07 05:08:28 +0200 (Mo, 07 Apr 2008) | 2 lines Bug #2388: Fix gcc warnings when compiling with --enable-unicode=ucs4. ........ Modified: python/branches/py3k/Objects/stringlib/formatter.h ============================================================================== --- python/branches/py3k/Objects/stringlib/formatter.h (original) +++ python/branches/py3k/Objects/stringlib/formatter.h Mon Apr 7 05:22:07 2008 @@ -785,8 +785,19 @@ break; default: /* unknown */ - PyErr_Format(PyExc_ValueError, "Unknown conversion type %c", - format.type); + #if STRINGLIB_IS_UNICODE + /* If STRINGLIB_CHAR is Py_UNICODE, %c might be out-of-range, + hence the two cases. If it is char, gcc complains that the + condition below is always true, hence the ifdef. */ + if (format.type > 32 && format.type <128) + #endif + PyErr_Format(PyExc_ValueError, "Unknown conversion type %c", + (char)format.type); + #if STRINGLIB_IS_UNICODE + else + PyErr_Format(PyExc_ValueError, "Unknown conversion type '\\x%x'", + (unsigned int)format.type); + #endif goto done; } Modified: python/branches/py3k/Objects/stringlib/string_format.h ============================================================================== --- python/branches/py3k/Objects/stringlib/string_format.h (original) +++ python/branches/py3k/Objects/stringlib/string_format.h Mon Apr 7 05:22:07 2008 @@ -740,9 +740,17 @@ case 's': return STRINGLIB_TOSTR(obj); default: - PyErr_Format(PyExc_ValueError, - "Unknown converion specifier %c", - conversion); + if (conversion > 32 && conversion < 127) { + /* It's the ASCII subrange; casting to char is safe + (assuming the execution character set is an ASCII + superset). */ + PyErr_Format(PyExc_ValueError, + "Unknown conversion specifier %c", + (char)conversion); + } else + PyErr_Format(PyExc_ValueError, + "Unknown conversion specifier \\x%x", + (unsigned int)conversion); return NULL; } } Modified: python/branches/py3k/Objects/unicodeobject.c ============================================================================== --- python/branches/py3k/Objects/unicodeobject.c (original) +++ python/branches/py3k/Objects/unicodeobject.c Mon Apr 7 05:22:07 2008 @@ -8895,7 +8895,7 @@ if (!isnumok) { PyErr_Format(PyExc_TypeError, "%%%c format: a number is required, " - "not %.200s", c, Py_TYPE(v)->tp_name); + "not %.200s", (char)c, Py_TYPE(v)->tp_name); goto onError; } if (flags & F_ZERO) From python-3000-checkins at python.org Mon Apr 7 07:43:43 2008 From: python-3000-checkins at python.org (martin.v.loewis) Date: Mon, 7 Apr 2008 07:43:43 +0200 (CEST) Subject: [Python-3000-checkins] r62203 - in python/branches/py3k: Doc/library/stdtypes.rst Doc/tutorial/errors.rst Lib/ctypes/test/test_structures.py Lib/test/test_defaultdict.py Lib/test/test_descrtut.py Lib/test/test_doctest3.txt Lib/test/test_generators.py Lib/test/test_genexps.py Lib/test/test_metaclass.py Lib/test/test_wsgiref.py Lib/test/test_xmlrpc.py Misc/NEWS Objects/typeobject.c Message-ID: <20080407054343.9B50A1E400C@bag.python.org> Author: martin.v.loewis Date: Mon Apr 7 07:43:42 2008 New Revision: 62203 Modified: python/branches/py3k/Doc/library/stdtypes.rst python/branches/py3k/Doc/tutorial/errors.rst python/branches/py3k/Lib/ctypes/test/test_structures.py python/branches/py3k/Lib/test/test_defaultdict.py python/branches/py3k/Lib/test/test_descrtut.py python/branches/py3k/Lib/test/test_doctest3.txt python/branches/py3k/Lib/test/test_generators.py python/branches/py3k/Lib/test/test_genexps.py python/branches/py3k/Lib/test/test_metaclass.py python/branches/py3k/Lib/test/test_wsgiref.py python/branches/py3k/Lib/test/test_xmlrpc.py python/branches/py3k/Misc/NEWS python/branches/py3k/Objects/typeobject.c Log: Bug #2565: The repr() of type objects now calls them 'class', not 'type' - whether they are builtin types or not. Modified: python/branches/py3k/Doc/library/stdtypes.rst ============================================================================== --- python/branches/py3k/Doc/library/stdtypes.rst (original) +++ python/branches/py3k/Doc/library/stdtypes.rst Mon Apr 7 07:43:42 2008 @@ -2345,7 +2345,7 @@ types. The standard module :mod:`types` defines names for all standard built-in types. -Types are written like this: ````. +Types are written like this: ````. .. _bltin-null-object: Modified: python/branches/py3k/Doc/tutorial/errors.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/errors.rst (original) +++ python/branches/py3k/Doc/tutorial/errors.rst Mon Apr 7 07:43:42 2008 @@ -184,7 +184,7 @@ ... print('x =', x) ... print('y =', y) ... - + ('spam', 'eggs') ('spam', 'eggs') x = spam Modified: python/branches/py3k/Lib/ctypes/test/test_structures.py ============================================================================== --- python/branches/py3k/Lib/ctypes/test/test_structures.py (original) +++ python/branches/py3k/Lib/ctypes/test/test_structures.py Mon Apr 7 07:43:42 2008 @@ -307,14 +307,14 @@ cls, msg = self.get_except(Person, "Someone", (1, 2)) self.failUnlessEqual(cls, RuntimeError) self.failUnlessEqual(msg, - "(Phone) : " + "(Phone) : " "expected string, int found") cls, msg = self.get_except(Person, "Someone", ("a", "b", "c")) self.failUnlessEqual(cls, RuntimeError) if issubclass(Exception, object): self.failUnlessEqual(msg, - "(Phone) : too many initializers") + "(Phone) : too many initializers") else: self.failUnlessEqual(msg, "(Phone) TypeError: too many initializers") Modified: python/branches/py3k/Lib/test/test_defaultdict.py ============================================================================== --- python/branches/py3k/Lib/test/test_defaultdict.py (original) +++ python/branches/py3k/Lib/test/test_defaultdict.py Mon Apr 7 07:43:42 2008 @@ -64,7 +64,7 @@ d2 = defaultdict(int) self.assertEqual(d2.default_factory, int) d2[12] = 42 - self.assertEqual(repr(d2), "defaultdict(, {12: 42})") + self.assertEqual(repr(d2), "defaultdict(, {12: 42})") def foo(): return 43 d3 = defaultdict(foo) self.assert_(d3.default_factory is foo) Modified: python/branches/py3k/Lib/test/test_descrtut.py ============================================================================== --- python/branches/py3k/Lib/test/test_descrtut.py (original) +++ python/branches/py3k/Lib/test/test_descrtut.py Mon Apr 7 07:43:42 2008 @@ -39,7 +39,7 @@ >>> print(defaultdict) # show our type >>> print(type(defaultdict)) # its metatype - + >>> a = defaultdict(default=0.0) # create an instance >>> print(a) # show the instance {} @@ -149,11 +149,11 @@ For instance of built-in types, x.__class__ is now the same as type(x): >>> type([]) - + >>> [].__class__ - + >>> list - + >>> isinstance([], list) True >>> isinstance([], dict) @@ -346,7 +346,7 @@ >>> del property # unmask the builtin >>> property - + >>> class C(object): ... def __init__(self): Modified: python/branches/py3k/Lib/test/test_doctest3.txt ============================================================================== --- python/branches/py3k/Lib/test/test_doctest3.txt (original) +++ python/branches/py3k/Lib/test/test_doctest3.txt Mon Apr 7 07:43:42 2008 @@ -2,4 +2,4 @@ Here we check that `__file__` is provided: >>> type(__file__) - + Modified: python/branches/py3k/Lib/test/test_generators.py ============================================================================== --- python/branches/py3k/Lib/test/test_generators.py (original) +++ python/branches/py3k/Lib/test/test_generators.py Mon Apr 7 07:43:42 2008 @@ -377,10 +377,10 @@ ... yield 1 ... >>> type(g) - + >>> i = g() >>> type(i) - + >>> [s for s in dir(i) if not s.startswith('_')] ['close', 'gi_code', 'gi_frame', 'gi_running', 'send', 'throw'] >>> print(i.__next__.__doc__) @@ -396,7 +396,7 @@ >>> i.gi_running 0 >>> type(i.gi_frame) - + >>> i.gi_running = 42 Traceback (most recent call last): ... @@ -794,27 +794,27 @@ >>> def f(): ... yield >>> type(f()) - + >>> def f(): ... if 0: ... yield >>> type(f()) - + >>> def f(): ... if 0: ... yield 1 >>> type(f()) - + >>> def f(): ... if "": ... yield None >>> type(f()) - + >>> def f(): ... return @@ -838,7 +838,7 @@ ... x = 1 ... return >>> type(f()) - + >>> def f(): ... if 0: @@ -846,7 +846,7 @@ ... yield 1 ... >>> type(f()) - + >>> def f(): ... if 0: @@ -856,7 +856,7 @@ ... def f(self): ... yield 2 >>> type(f()) - + >>> def f(): ... if 0: @@ -864,7 +864,7 @@ ... if 0: ... yield 2 >>> type(f()) - + >>> def f(): @@ -1512,7 +1512,7 @@ >>> def f(): list(i for i in [(yield 26)]) >>> type(f()) - + A yield expression with augmented assignment. @@ -1749,25 +1749,25 @@ >>> def f(): x += yield >>> type(f()) - + >>> def f(): x = yield >>> type(f()) - + >>> def f(): lambda x=(yield): 1 >>> type(f()) - + >>> def f(): x=(i for i in (yield) if (yield)) >>> type(f()) - + >>> def f(d): d[(yield "a")] = d[(yield "b")] = 27 >>> data = [1,2] >>> g = f(data) >>> type(g) - + >>> g.send(None) 'a' >>> data Modified: python/branches/py3k/Lib/test/test_genexps.py ============================================================================== --- python/branches/py3k/Lib/test/test_genexps.py (original) +++ python/branches/py3k/Lib/test/test_genexps.py Mon Apr 7 07:43:42 2008 @@ -27,7 +27,7 @@ >>> g = (i*i for i in range(4)) >>> type(g) - + >>> list(g) [0, 1, 4, 9] Modified: python/branches/py3k/Lib/test/test_metaclass.py ============================================================================== --- python/branches/py3k/Lib/test/test_metaclass.py (original) +++ python/branches/py3k/Lib/test/test_metaclass.py Mon Apr 7 07:43:42 2008 @@ -78,7 +78,7 @@ >>> class C(object, metaclass=M, other="haha"): ... pass ... - Prepare called: ('C', (,)) {'other': 'haha'} + Prepare called: ('C', (,)) {'other': 'haha'} New called: {'other': 'haha'} >>> C.__class__ is M True @@ -104,7 +104,7 @@ >>> kwds = {'metaclass': M, 'other': 'haha'} >>> class C(*bases, **kwds): pass ... - Prepare called: ('C', (,)) {'other': 'haha'} + Prepare called: ('C', (,)) {'other': 'haha'} New called: {'other': 'haha'} >>> C.__class__ is M True @@ -114,7 +114,7 @@ >>> kwds = {'other': 'haha'} >>> class C(B, metaclass=M, *bases, **kwds): pass ... - Prepare called: ('C', (, )) {'other': 'haha'} + Prepare called: ('C', (, )) {'other': 'haha'} New called: {'other': 'haha'} >>> C.__class__ is M True Modified: python/branches/py3k/Lib/test/test_wsgiref.py ============================================================================== --- python/branches/py3k/Lib/test/test_wsgiref.py (original) +++ python/branches/py3k/Lib/test/test_wsgiref.py Mon Apr 7 07:43:42 2008 @@ -157,7 +157,7 @@ self.assertEqual( err.splitlines()[-2], "AssertionError: Headers (('Content-Type', 'text/plain')) must" - " be of type list: " + " be of type list: " ) Modified: python/branches/py3k/Lib/test/test_xmlrpc.py ============================================================================== --- python/branches/py3k/Lib/test/test_xmlrpc.py (original) +++ python/branches/py3k/Lib/test/test_xmlrpc.py Mon Apr 7 07:43:42 2008 @@ -416,12 +416,12 @@ result = multicall() # result.results contains; - # [{'faultCode': 1, 'faultString': ':' + # [{'faultCode': 1, 'faultString': ':' # 'method "this_is_not_exists" is not supported'>}] self.assertEqual(result.results[0]['faultCode'], 1) self.assertEqual(result.results[0]['faultString'], - ':method "this_is_not_exists" ' + ':method "this_is_not_exists" ' 'is not supported') except (xmlrpclib.ProtocolError, socket.error) as e: # ignore failures due to non-blocking socket 'unavailable' errors Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Mon Apr 7 07:43:42 2008 @@ -12,6 +12,9 @@ Core and Builtins ----------------- +- Bug #2565: The repr() of type objects now calls them 'class', + not 'type' - whether they are builtin types or not. + - The command line processing was converted to pass Unicode strings through as unmodified as possible; as a consequence, the C API related to command line arguments was changed to use wchar_t. Modified: python/branches/py3k/Objects/typeobject.c ============================================================================== --- python/branches/py3k/Objects/typeobject.c (original) +++ python/branches/py3k/Objects/typeobject.c Mon Apr 7 07:43:42 2008 @@ -600,7 +600,6 @@ type_repr(PyTypeObject *type) { PyObject *mod, *name, *rtn; - char *kind; mod = type_module(type, NULL); if (mod == NULL) @@ -613,15 +612,10 @@ if (name == NULL) return NULL; - if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) - kind = "class"; - else - kind = "type"; - if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins")) - rtn = PyUnicode_FromFormat("<%s '%U.%U'>", kind, mod, name); + rtn = PyUnicode_FromFormat("", mod, name); else - rtn = PyUnicode_FromFormat("<%s '%s'>", kind, type->tp_name); + rtn = PyUnicode_FromFormat("", type->tp_name); Py_XDECREF(mod); Py_DECREF(name); From python-3000-checkins at python.org Mon Apr 7 18:44:14 2008 From: python-3000-checkins at python.org (martin.v.loewis) Date: Mon, 7 Apr 2008 18:44:14 +0200 (CEST) Subject: [Python-3000-checkins] r62211 - python/branches/py3k/Tools/msi/uuids.py Message-ID: <20080407164414.4782F1E4023@bag.python.org> Author: martin.v.loewis Date: Mon Apr 7 18:44:13 2008 New Revision: 62211 Modified: python/branches/py3k/Tools/msi/uuids.py Log: Add uuids for 3.0a4 and 3.0a5. Modified: python/branches/py3k/Tools/msi/uuids.py ============================================================================== --- python/branches/py3k/Tools/msi/uuids.py (original) +++ python/branches/py3k/Tools/msi/uuids.py Mon Apr 7 18:44:13 2008 @@ -44,6 +44,8 @@ '3.0.101': '{8554263a-3242-4857-9359-aa87bc2c58c2}', # 3.0a1 '3.0.102': '{692d6e2c-f0ac-40b8-a133-7191aeeb67f9}', # 3.0a2 '3.0.103': '{49cb2995-751a-4753-be7a-d0b1bb585e06}', # 3.0a3 + '3.0.104': '{87cb019e-19fd-4238-b1c7-85751437d646}', # 3.0a4 + '3.0.105': '{cf2659af-19ec-43d2-8c35-0f6a09439d42}', # 3.0a5 '3.0.111': '{36c26f55-837d-45cf-848c-5f5c0fb47a28}', # 3.0b1 '3.0.112': '{056a0fbc-c8fe-4c61-aade-c4411b70c998}', # 3.0b2 '3.0.121': '{d0979c5e-cd3c-42ec-be4c-e294da793573}', # 3.0c1 From python-3000-checkins at python.org Mon Apr 7 20:37:41 2008 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 7 Apr 2008 20:37:41 +0200 (CEST) Subject: [Python-3000-checkins] r62213 - in python/branches/py3k: Makefile.pre.in Misc/NEWS Message-ID: <20080407183741.C9F8B1E4013@bag.python.org> Author: guido.van.rossum Date: Mon Apr 7 20:37:41 2008 New Revision: 62213 Modified: python/branches/py3k/Makefile.pre.in python/branches/py3k/Misc/NEWS Log: "make install" is now an alias for "make altinstall", to prevent accidentally overwriting a Python 2.x installation. Use "make fullinstall" to force Python 3.0 to be installed as "python". Modified: python/branches/py3k/Makefile.pre.in ============================================================================== --- python/branches/py3k/Makefile.pre.in (original) +++ python/branches/py3k/Makefile.pre.in Mon Apr 7 20:37:41 2008 @@ -687,7 +687,15 @@ $(TESTPYTHON) $(TESTPROG) $(MEMTESTOPTS) # Install everything -install: @FRAMEWORKINSTALLFIRST@ altinstall bininstall maninstall @FRAMEWORKINSTALLLAST@ +fullinstall: @FRAMEWORKINSTALLFIRST@ altinstall bininstall maninstall @FRAMEWORKINSTALLLAST@ + +# "make install" is an alias for "make altinstall" since we never want to +# overwrite Python 2.x. +install: altinstall + echo "* Note: not installed as 'python'." + echo "* Use 'make fullinstall' to install as 'python'." + echo "* However, 'make fulinstall' is discouraged," + echo "* as it will clobber your Python 2.x installation." # Install almost everything without disturbing previous versions altinstall: @FRAMEWORKALTINSTALLFIRST@ altbininstall libinstall inclinstall libainstall \ Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Mon Apr 7 20:37:41 2008 @@ -32,6 +32,11 @@ Build ----- +- "make install" is now an alias for "make altinstall", to prevent + accidentally overwriting a Python 2.x installation. + Use "make fullinstall" to force Python 3.0 to be installed as + "python". + - Issue #2544: On HP-UX systems, use 'gcc -shared' for linking when gcc is used as compiler. From python-3000-checkins at python.org Mon Apr 7 21:17:06 2008 From: python-3000-checkins at python.org (georg.brandl) Date: Mon, 7 Apr 2008 21:17:06 +0200 (CEST) Subject: [Python-3000-checkins] r62216 - in python/branches/py3k/Doc: c-api/typeobj.rst glossary.rst library/copy_reg.rst library/pickle.rst reference/compound_stmts.rst reference/datamodel.rst Message-ID: <20080407191706.99EA91E402C@bag.python.org> Author: georg.brandl Date: Mon Apr 7 21:17:06 2008 New Revision: 62216 Modified: python/branches/py3k/Doc/c-api/typeobj.rst python/branches/py3k/Doc/glossary.rst python/branches/py3k/Doc/library/copy_reg.rst python/branches/py3k/Doc/library/pickle.rst python/branches/py3k/Doc/reference/compound_stmts.rst python/branches/py3k/Doc/reference/datamodel.rst Log: #2567: remove new-style/old-style class docs. Modified: python/branches/py3k/Doc/c-api/typeobj.rst ============================================================================== --- python/branches/py3k/Doc/c-api/typeobj.rst (original) +++ python/branches/py3k/Doc/c-api/typeobj.rst Mon Apr 7 21:17:06 2008 @@ -730,8 +730,7 @@ An optional pointer to a function that returns an iterator for the object. Its presence normally signals that the instances of this type are iterable (although - sequences may be iterable without this function, and classic instances always - have this function, even if they don't define an :meth:`__iter__` method). + sequences may be iterable without this function). This function has the same signature as :cfunc:`PyObject_GetIter`. @@ -742,9 +741,7 @@ An optional pointer to a function that returns the next item in an iterator, or raises :exc:`StopIteration` when the iterator is exhausted. Its presence - normally signals that the instances of this type are iterators (although classic - instances always have this function, even if they don't define a - :meth:`__next__` method). + normally signals that the instances of this type are iterators. Iterator types should also define the :attr:`tp_iter` function, and that function should return the iterator instance itself (not a new iterator Modified: python/branches/py3k/Doc/glossary.rst ============================================================================== --- python/branches/py3k/Doc/glossary.rst (original) +++ python/branches/py3k/Doc/glossary.rst Mon Apr 7 21:17:06 2008 @@ -39,10 +39,6 @@ "intermediate language" is said to run on a "virtual machine" that calls the subroutines corresponding to each bytecode. - classic class - One of the two flavors of classes in earlier Python versions. Since - Python 3.0, there are no classic classes anymore. - complex number An extension of the familiar real number system in which all numbers are expressed as a sum of a real part and an imaginary part. Imaginary @@ -367,8 +363,6 @@ versatile features like :attr:`__slots__`, descriptors, properties, :meth:`__getattribute__`, class methods, and static methods. - More information can be found in :ref:`newstyle`. - positional argument The arguments assigned to local names inside a function or method, determined by the order in which they were given in the call. ``*`` is Modified: python/branches/py3k/Doc/library/copy_reg.rst ============================================================================== --- python/branches/py3k/Doc/library/copy_reg.rst (original) +++ python/branches/py3k/Doc/library/copy_reg.rst Mon Apr 7 21:17:06 2008 @@ -26,11 +26,9 @@ .. function:: pickle(type, function[, constructor]) - Declares that *function* should be used as a "reduction" function for objects of - type *type*; *type* must not be a "classic" class object. (Classic classes are - handled differently; see the documentation for the :mod:`pickle` module for - details.) *function* should return either a string or a tuple containing two or - three elements. + Declares that *function* should be used as a "reduction" function for objects + of type *type*. *function* should return either a string or a tuple + containing two or three elements. The optional *constructor* parameter, if provided, is a callable object which can be used to reconstruct the object when called with the tuple of arguments Modified: python/branches/py3k/Doc/library/pickle.rst ============================================================================== --- python/branches/py3k/Doc/library/pickle.rst (original) +++ python/branches/py3k/Doc/library/pickle.rst Mon Apr 7 21:17:06 2008 @@ -403,6 +403,7 @@ single: __init__() (instance constructor) .. XXX is __getinitargs__ only used with old-style classes? +.. XXX update w.r.t Py3k's classes When a pickled class instance is unpickled, its :meth:`__init__` method is normally *not* invoked. If it is desirable that the :meth:`__init__` method be @@ -447,8 +448,8 @@ .. warning:: - For :term:`new-style class`\es, if :meth:`__getstate__` returns a false - value, the :meth:`__setstate__` method will not be called. + If :meth:`__getstate__` returns a false value, the :meth:`__setstate__` + method will not be called. Pickling and unpickling extension types Modified: python/branches/py3k/Doc/reference/compound_stmts.rst ============================================================================== --- python/branches/py3k/Doc/reference/compound_stmts.rst (original) +++ python/branches/py3k/Doc/reference/compound_stmts.rst Mon Apr 7 21:17:06 2008 @@ -577,9 +577,8 @@ variables are accessible through the notation "``self.name``", and an instance variable hides a class variable with the same name when accessed in this way. Class variables can be used as defaults for instance variables, but using -mutable values there can lead to unexpected results. For :term:`new-style -class`\es, descriptors can be used to create instance variables with different -implementation details. +mutable values there can lead to unexpected results. Descriptors can be used +to create instance variables with different implementation details. .. XXX add link to descriptor docs above Modified: python/branches/py3k/Doc/reference/datamodel.rst ============================================================================== --- python/branches/py3k/Doc/reference/datamodel.rst (original) +++ python/branches/py3k/Doc/reference/datamodel.rst Mon Apr 7 21:17:06 2008 @@ -980,45 +980,6 @@ by the built-in :func:`classmethod` constructor. -.. _newstyle: - -New-style and classic classes -============================= - -Classes and instances come in two flavors: old-style or classic, and new-style. - -Up to Python 2.1, old-style classes were the only flavour available to the user. -The concept of (old-style) class is unrelated to the concept of type: if *x* is -an instance of an old-style class, then ``x.__class__`` designates the class of -*x*, but ``type(x)`` is always ````. This reflects the fact -that all old-style instances, independently of their class, are implemented with -a single built-in type, called ``instance``. - -New-style classes were introduced in Python 2.2 to unify classes and types. A -new-style class is neither more nor less than a user-defined type. If *x* is an -instance of a new-style class, then ``type(x)`` is the same as ``x.__class__``. - -The major motivation for introducing new-style classes is to provide a unified -object model with a full meta-model. It also has a number of immediate -benefits, like the ability to subclass most built-in types, or the introduction -of "descriptors", which enable computed properties. - -For compatibility reasons, classes are still old-style by default. New-style -classes are created by specifying another new-style class (i.e. a type) as a -parent class, or the "top-level type" :class:`object` if no other parent is -needed. The behaviour of new-style classes differs from that of old-style -classes in a number of important details in addition to what :func:`type` -returns. Some of these changes are fundamental to the new object model, like -the way special methods are invoked. Others are "fixes" that could not be -implemented before for compatibility concerns, like the method resolution order -in case of multiple inheritance. - -This manual is not up-to-date with respect to new-style classes. For now, -please see http://www.python.org/doc/newstyle/ for more information. - -.. XXX remove old style classes from docs - - .. _specialnames: Special method names @@ -1418,9 +1379,7 @@ However, if the looked-up value is an object defining one of the descriptor methods, then Python may override the default behavior and invoke the descriptor method instead. Where this occurs in the precedence chain depends on which -descriptor methods were defined and how they were called. Note that descriptors -are only invoked for new style objects or classes (ones that subclass -:class:`object()` or :class:`type()`). +descriptor methods were defined and how they were called. The starting point for descriptor invocation is a binding, ``a.x``. How the arguments are assembled depends on ``a``: @@ -1477,7 +1436,7 @@ .. data:: object.__slots__ This class variable can be assigned a string, iterable, or sequence of - strings with variable names used by instances. If defined in a new-style + strings with variable names used by instances. If defined in a class, *__slots__* reserves space for the declared variables and prevents the automatic creation of *__dict__* and *__weakref__* for each instance. @@ -1801,7 +1760,7 @@ ``-``, ``*``, ``/``, ``%``, :func:`divmod`, :func:`pow`, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``) with reflected (swapped) operands. These functions are only called if the left operand does not support the corresponding operation and - the operands are of different types. [#]_ For instance, to evaluate the + the operands are of different types. [#]_ For instance, to evaluate the expression *x*``-``*y*, where *y* is an instance of a class that has an :meth:`__rsub__` method, ``y.__rsub__(x)`` is called if ``x.__sub__(y)`` returns *NotImplemented*. @@ -1927,18 +1886,6 @@ .. rubric:: Footnotes -.. [#] Since Python 2.2, a gradual merging of types and classes has been started that - makes this and a few other assertions made in this manual not 100% accurate and - complete: for example, it *is* now possible in some cases to change an object's - type, under certain controlled conditions. Until this manual undergoes - extensive revision, it must now be taken as authoritative only regarding - "classic classes", that are still the default, for compatibility purposes, in - Python 2.2 and 2.3. For more information, see - http://www.python.org/doc/newstyle/. - -.. [#] This, and other statements, are only roughly true for instances of new-style - classes. - .. [#] A descriptor can define any combination of :meth:`__get__`, :meth:`__set__` and :meth:`__delete__`. If it does not define :meth:`__get__`, then accessing the attribute even on an instance will return the descriptor @@ -1949,4 +1896,3 @@ .. [#] For operands of the same type, it is assumed that if the non-reflected method (such as :meth:`__add__`) fails the operation is not supported, which is why the reflected method is not called. - From python-3000-checkins at python.org Mon Apr 7 23:14:19 2008 From: python-3000-checkins at python.org (martin.v.loewis) Date: Mon, 7 Apr 2008 23:14:19 +0200 (CEST) Subject: [Python-3000-checkins] r62217 - in python/branches/py3k: Tools/msi/merge.py Tools/msi/msi.py Message-ID: <20080407211419.D45A21E4019@bag.python.org> Author: martin.v.loewis Date: Mon Apr 7 23:14:19 2008 New Revision: 62217 Modified: python/branches/py3k/ (props changed) python/branches/py3k/Tools/msi/merge.py python/branches/py3k/Tools/msi/msi.py Log: Merged revisions 62207-62210 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62207 | martin.v.loewis | 2008-04-07 16:53:34 +0200 (Mo, 07 Apr 2008) | 1 line Delete ALLUSERS property merged from CRT merge module, so that per-user installations become possible again. ........ r62208 | martin.v.loewis | 2008-04-07 16:54:16 +0200 (Mo, 07 Apr 2008) | 1 line Make private_crt feature object a global variable. ........ r62209 | martin.v.loewis | 2008-04-07 16:55:53 +0200 (Mo, 07 Apr 2008) | 1 line Drop support for 7.1 CRT. ........ r62210 | martin.v.loewis | 2008-04-07 18:34:04 +0200 (Mo, 07 Apr 2008) | 2 lines Make the "private CRT" case work, by editing the manifest in DLLs to refer to the root copy of the CRT. ........ Modified: python/branches/py3k/Tools/msi/merge.py ============================================================================== --- python/branches/py3k/Tools/msi/merge.py (original) +++ python/branches/py3k/Tools/msi/merge.py Mon Apr 7 23:14:19 2008 @@ -65,6 +65,11 @@ msilib.add_stream(db, stream, cabname) os.unlink(cabname) maxmedia += count + # The merge module sets ALLUSERS to 1 in the property table. + # This is undesired; delete that + v = db.OpenView("DELETE FROM Property WHERE Property='ALLUSERS'") + v.Execute(None) + v.Close() db.Commit() merge(msi, "SharedCRT", "TARGETDIR", modules) Modified: python/branches/py3k/Tools/msi/msi.py ============================================================================== --- python/branches/py3k/Tools/msi/msi.py (original) +++ python/branches/py3k/Tools/msi/msi.py Mon Apr 7 23:14:19 2008 @@ -29,7 +29,6 @@ # path to PCbuild directory PCBUILD="PCbuild" # msvcrt version -#MSVCR = "71" MSVCR = "90" try: @@ -106,8 +105,6 @@ # Using the same UUID is fine since these files are versioned, # so Installer will always keep the newest version. # NOTE: All uuids are self generated. -msvcr71_uuid = "{8666C8DD-D0B4-4B42-928E-A69E32FA5D4D}" -msvcr90_uuid = "{9C28CD84-397C-4045-855C-28B02291A272}" pythondll_uuid = { "24":"{9B81E618-2301-4035-AC77-75D9ABEB7301}", "25":"{2e41b118-38bd-4c1b-a840-6977efd1b911}", @@ -795,7 +792,7 @@ # (i.e. additional Python libraries) need to follow the parent feature. # Features that have no advertisement trigger (e.g. the test suite) # must not support advertisement - global default_feature, tcltk, htmlfiles, tools, testsuite, ext_feature + global default_feature, tcltk, htmlfiles, tools, testsuite, ext_feature, private_crt default_feature = Feature(db, "DefaultFeature", "Python", "Python Interpreter and Libraries", 1, directory = "TARGETDIR") @@ -821,27 +818,6 @@ "Python test suite (Lib/test/)", 11, parent = default_feature, attributes=2|8) -def extract_msvcr71(): - import _winreg - # Find the location of the merge modules - k = _winreg.OpenKey( - _winreg.HKEY_LOCAL_MACHINE, - r"Software\Microsoft\VisualStudio\7.1\Setup\VS") - dir = _winreg.QueryValueEx(k, "MSMDir")[0] - _winreg.CloseKey(k) - files = glob.glob1(dir, "*CRT71*") - assert len(files) == 1, (dir, files) - file = os.path.join(dir, files[0]) - # Extract msvcr71.dll - m = msilib.MakeMerge2() - m.OpenModule(file, 0) - m.ExtractFiles(".") - m.CloseModule() - # Find the version/language of msvcr71.dll - installer = msilib.MakeInstaller() - return installer.FileVersion("msvcr71.dll", 0), \ - installer.FileVersion("msvcr71.dll", 1) - def extract_msvcr90(): # Find the redistributable files dir = os.path.join(os.environ['VS90COMNTOOLS'], r"..\..\VC\redist\x86\Microsoft.VC90.CRT") @@ -903,21 +879,24 @@ version=pyversion, language=installer.FileVersion(pydllsrc, 1)) DLLs = PyDirectory(db, cab, root, srcdir + "/" + PCBUILD, "DLLs", "DLLS|DLLs") - # XXX determine dependencies - if MSVCR == "90": - root.start_component("msvcr90", feature=private_crt) - for file, kw in extract_msvcr90(): - root.add_file(file, **kw) - if file.endswith("manifest"): - DLLs.add_file(file, **kw) - else: - version, lang = extract_msvcr71() - dlldir.start_component("msvcr71", flags=8, keyfile="msvcr71.dll", - uuid=msvcr71_uuid) - dlldir.add_file("msvcr71.dll", src=os.path.abspath("msvcr71.dll"), - version=version, language=lang) - tmpfiles.append("msvcr71.dll") + # msvcr90.dll: Need to place the DLL and the manifest into the root directory, + # plus another copy of the manifest in the DLLs directory, with the manifest + # pointing to the root directory + root.start_component("msvcr90", feature=private_crt) + # Results are ID,keyword pairs + manifest, crtdll = extract_msvcr90() + root.add_file(manifest[0], **manifest[1]) + root.add_file(crtdll[0], **crtdll[1]) + # Copy the manifest + manifest_dlls = manifest[0]+".root" + open(manifest_dlls, "w").write(open(manifest[1]['src']).read().replace("msvcr","../msvcr")) + DLLs.start_component("msvcr90_dlls", feature=private_crt) + DLLs.add_file(manifest[0], src=os.path.abspath(manifest_dlls)) + + # Now start the main component for the DLLs directory; + # no regular files have been added to the directory yet. + DLLs.start_component() # Check if _ctypes.pyd exists have_ctypes = os.path.exists(srcdir+"/%s/_ctypes.pyd" % PCBUILD) From python-3000-checkins at python.org Tue Apr 8 00:27:41 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Tue, 8 Apr 2008 00:27:41 +0200 (CEST) Subject: [Python-3000-checkins] r62218 - python/branches/py3k/Lib/io.py Message-ID: <20080407222741.DB95B1E4013@bag.python.org> Author: benjamin.peterson Date: Tue Apr 8 00:27:34 2008 New Revision: 62218 Modified: python/branches/py3k/Lib/io.py Log: fixed outdated annotation of readinto in io Modified: python/branches/py3k/Lib/io.py ============================================================================== --- python/branches/py3k/Lib/io.py (original) +++ python/branches/py3k/Lib/io.py Tue Apr 8 00:27:34 2008 @@ -487,8 +487,8 @@ res += data return bytes(res) - def readinto(self, b: bytes) -> int: - """readinto(b: bytes) -> int. Read up to len(b) bytes into b. + def readinto(self, b: bytearray) -> int: + """readinto(b: bytearray) -> int. Read up to len(b) bytes into b. Returns number of bytes read (0 for EOF), or None if the object is set not to block as has no data to read. @@ -563,8 +563,8 @@ """ self._unsupported("read") - def readinto(self, b: bytes) -> int: - """readinto(b: bytes) -> int. Read up to len(b) bytes into b. + def readinto(self, b: bytearray) -> int: + """readinto(b: bytearray) -> int. Read up to len(b) bytes into b. Like read(), this may issue multiple reads to the underlying raw stream, unless the latter is 'interactive' (XXX or a From python-3000-checkins at python.org Tue Apr 8 11:44:14 2008 From: python-3000-checkins at python.org (christian.heimes) Date: Tue, 8 Apr 2008 11:44:14 +0200 (CEST) Subject: [Python-3000-checkins] r62222 - python/branches/py3k Message-ID: <20080408094414.F1D981E4013@bag.python.org> Author: christian.heimes Date: Tue Apr 8 11:44:14 2008 New Revision: 62222 Modified: python/branches/py3k/ (props changed) Log: Blocked revisions 62195 via svnmerge ........ r62195 | gregory.p.smith | 2008-04-07 01:11:17 +0200 (Mon, 07 Apr 2008) | 10 lines Make file objects as thread safe as the underlying libc FILE* implementation. close() will now raise an IOError if any operations on the file object are currently in progress in other threads. Most code was written by Antoine Pitrou (pitrou). Additional testing, documentation and test suite cleanup done by me (gregory.p.smith). Fixes issue 815646 and 595601 (as well as many other bugs and references to this problem dating back to the dawn of Python). ........ From python-3000-checkins at python.org Tue Apr 8 18:53:25 2008 From: python-3000-checkins at python.org (martin.v.loewis) Date: Tue, 8 Apr 2008 18:53:25 +0200 (CEST) Subject: [Python-3000-checkins] r62224 - python/branches/py3k Message-ID: <20080408165325.E1F881E4018@bag.python.org> Author: martin.v.loewis Date: Tue Apr 8 18:53:25 2008 New Revision: 62224 Modified: python/branches/py3k/ (props changed) Log: Tentatively Blocked revisions 62223 via svnmerge, as compilation of py3_ should work in py3k. ........ r62223 | martin.v.loewis | 2008-04-08 18:48:35 +0200 (Di, 08 Apr 2008) | 1 line Suppress compilation of py3_ files upon installation. ........ From python-3000-checkins at python.org Tue Apr 8 19:17:47 2008 From: python-3000-checkins at python.org (martin.v.loewis) Date: Tue, 8 Apr 2008 19:17:47 +0200 (CEST) Subject: [Python-3000-checkins] r62225 - python/branches/py3k/Tools/msi/msi.py Message-ID: <20080408171747.1B2611E4019@bag.python.org> Author: martin.v.loewis Date: Tue Apr 8 19:17:46 2008 New Revision: 62225 Modified: python/branches/py3k/Tools/msi/msi.py Log: Suppress compilation of py2_ test files. Modified: python/branches/py3k/Tools/msi/msi.py ============================================================================== --- python/branches/py3k/Tools/msi/msi.py (original) +++ python/branches/py3k/Tools/msi/msi.py Tue Apr 8 19:17:46 2008 @@ -376,7 +376,7 @@ ("VerdanaRed9", "Verdana", 9, 255, 0), ]) - compileargs = r'-Wi "[TARGETDIR]Lib\compileall.py" -f -x bad_coding|badsyntax|site-packages "[TARGETDIR]Lib"' + compileargs = r'-Wi "[TARGETDIR]Lib\compileall.py" -f -x bad_coding|badsyntax|site-packages|py2_ "[TARGETDIR]Lib"' # See "CustomAction Table" add_data(db, "CustomAction", [ # msidbCustomActionTypeFirstSequence + msidbCustomActionTypeTextData + msidbCustomActionTypeProperty From python-3000-checkins at python.org Wed Apr 9 09:32:07 2008 From: python-3000-checkins at python.org (georg.brandl) Date: Wed, 9 Apr 2008 09:32:07 +0200 (CEST) Subject: [Python-3000-checkins] r62240 - python/branches/py3k/Doc/whatsnew/3.0.rst Message-ID: <20080409073207.A1EDC1E4003@bag.python.org> Author: georg.brandl Date: Wed Apr 9 09:32:07 2008 New Revision: 62240 Modified: python/branches/py3k/Doc/whatsnew/3.0.rst Log: Clarify xrange() entry. Modified: python/branches/py3k/Doc/whatsnew/3.0.rst ============================================================================== --- python/branches/py3k/Doc/whatsnew/3.0.rst (original) +++ python/branches/py3k/Doc/whatsnew/3.0.rst Wed Apr 9 09:32:07 2008 @@ -301,7 +301,8 @@ terminated prematurely. To get the old behavior of :func:`input`, use ``eval(input())``. -* :func:`xrange` renamed to :func:`range`. +* :func:`xrange` renamed to :func:`range`, so :func:`range` will no longer + produce a list but an iterable yielding integers when iterated over. * PEP 3113: Tuple parameter unpacking removed. You can no longer write ``def foo(a, (b, c)): ...``. Use ``def foo(a, b_c): b, c = b_c`` instead. From python-3000-checkins at python.org Wed Apr 9 09:33:01 2008 From: python-3000-checkins at python.org (georg.brandl) Date: Wed, 9 Apr 2008 09:33:01 +0200 (CEST) Subject: [Python-3000-checkins] r62241 - python/branches/py3k/Lib/io.py Message-ID: <20080409073301.57BE91E4003@bag.python.org> Author: georg.brandl Date: Wed Apr 9 09:33:01 2008 New Revision: 62241 Modified: python/branches/py3k/Lib/io.py Log: More docstring fixes, and an XXX. Modified: python/branches/py3k/Lib/io.py ============================================================================== --- python/branches/py3k/Lib/io.py (original) +++ python/branches/py3k/Lib/io.py Wed Apr 9 09:33:01 2008 @@ -257,9 +257,9 @@ return self.seek(0, 1) def truncate(self, pos: int = None) -> int: - """truncate(size: int = None) -> int. Truncate file to size bytes. + """truncate(pos: int = None) -> int. Truncate file to pos bytes. - Size defaults to the current IO position as reported by tell(). + Pos defaults to the current IO position as reported by tell(). Returns the new size. """ self._unsupported("truncate") @@ -465,7 +465,7 @@ def read(self, n: int = -1) -> bytes: """read(n: int) -> bytes. Read and return up to n bytes. - Returns an empty bytes array on EOF, or None if the object is + Returns an empty bytes object on EOF, or None if the object is set not to block and has no data to read. """ if n is None: @@ -478,7 +478,7 @@ return bytes(b) def readall(self): - """readall() -> bytes. Read until EOF, using multiple read() call.""" + """readall() -> bytes. Read until EOF, using multiple read() calls.""" res = bytearray() while True: data = self.read(DEFAULT_BUFFER_SIZE) @@ -521,6 +521,7 @@ def name(self): return self._name + # XXX(gb): _FileIO already has a mode property @property def mode(self): return self._mode From python-3000-checkins at python.org Wed Apr 9 10:37:06 2008 From: python-3000-checkins at python.org (christian.heimes) Date: Wed, 9 Apr 2008 10:37:06 +0200 (CEST) Subject: [Python-3000-checkins] r62242 - in python/branches/py3k: Doc/distutils/builtdist.rst Doc/includes/tzinfo-examples.py Doc/library/index.rst Doc/library/select.rst Doc/library/types.rst Doc/whatsnew/2.6.rst Lib/distutils/command/bdist.py Lib/distutils/command/bdist_msi.py Lib/distutils/command/bdist_wininst.py Lib/distutils/command/build.py Lib/distutils/command/build_ext.py Lib/distutils/command/install.py Lib/distutils/command/wininst-9.0-amd64.exe Lib/distutils/msvc9compiler.py Lib/distutils/msvccompiler.py Lib/distutils/util.py Lib/inspect.py Lib/sre_compile.py Lib/test/test_asynchat.py Lib/test/test_asyncore.py Lib/test/test_capi.py Lib/test/test_ftplib.py Lib/test/test_httplib.py Lib/test/test_poplib.py Lib/test/test_signal.py Lib/test/test_smtplib.py Lib/test/test_socket.py Lib/test/test_socketserver.py Lib/test/test_ssl.py Lib/test/test_sundry.py Lib/test/test_support.py Lib/test/test_telnetlib.py Lib/test/test_zlib.py Lib/types.py Makefile.pre.in Modules/_typesmodule.c Modules/config.c.in Modules/zlibmodule.c PC/VC6/pythoncore.dsp PC/VS7.1/pythoncore.vcproj PC/VS8.0/pythoncore.vcproj PC/_winreg.c PC/config.c PC/example_nt/readme.txt PC/example_nt/setup.py PCbuild/bdist_wininst.vcproj PCbuild/pcbuild.sln PCbuild/pythoncore.vcproj Message-ID: <20080409083706.71BA11E4003@bag.python.org> Author: christian.heimes Date: Wed Apr 9 10:37:03 2008 New Revision: 62242 Added: python/branches/py3k/Lib/distutils/command/wininst-9.0-amd64.exe - copied unchanged from r62198, python/trunk/Lib/distutils/command/wininst-9.0-amd64.exe python/branches/py3k/PC/example_nt/setup.py - copied unchanged from r62198, python/trunk/PC/example_nt/setup.py Removed: python/branches/py3k/Modules/_typesmodule.c Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/distutils/builtdist.rst python/branches/py3k/Doc/includes/tzinfo-examples.py python/branches/py3k/Doc/library/index.rst python/branches/py3k/Doc/library/select.rst python/branches/py3k/Doc/library/types.rst python/branches/py3k/Doc/whatsnew/2.6.rst python/branches/py3k/Lib/distutils/command/bdist.py python/branches/py3k/Lib/distutils/command/bdist_msi.py python/branches/py3k/Lib/distutils/command/bdist_wininst.py python/branches/py3k/Lib/distutils/command/build.py python/branches/py3k/Lib/distutils/command/build_ext.py python/branches/py3k/Lib/distutils/command/install.py python/branches/py3k/Lib/distutils/msvc9compiler.py python/branches/py3k/Lib/distutils/msvccompiler.py python/branches/py3k/Lib/distutils/util.py python/branches/py3k/Lib/inspect.py python/branches/py3k/Lib/sre_compile.py python/branches/py3k/Lib/test/test_asynchat.py python/branches/py3k/Lib/test/test_asyncore.py python/branches/py3k/Lib/test/test_capi.py python/branches/py3k/Lib/test/test_ftplib.py python/branches/py3k/Lib/test/test_httplib.py python/branches/py3k/Lib/test/test_poplib.py python/branches/py3k/Lib/test/test_signal.py python/branches/py3k/Lib/test/test_smtplib.py python/branches/py3k/Lib/test/test_socket.py python/branches/py3k/Lib/test/test_socketserver.py python/branches/py3k/Lib/test/test_ssl.py python/branches/py3k/Lib/test/test_sundry.py python/branches/py3k/Lib/test/test_support.py python/branches/py3k/Lib/test/test_telnetlib.py python/branches/py3k/Lib/test/test_zlib.py python/branches/py3k/Lib/types.py python/branches/py3k/Makefile.pre.in python/branches/py3k/Modules/config.c.in python/branches/py3k/Modules/zlibmodule.c python/branches/py3k/PC/VC6/pythoncore.dsp python/branches/py3k/PC/VS7.1/pythoncore.vcproj python/branches/py3k/PC/VS8.0/pythoncore.vcproj python/branches/py3k/PC/_winreg.c python/branches/py3k/PC/config.c python/branches/py3k/PC/example_nt/readme.txt python/branches/py3k/PCbuild/bdist_wininst.vcproj python/branches/py3k/PCbuild/pcbuild.sln python/branches/py3k/PCbuild/pythoncore.vcproj Log: Merged revisions 62194,62197-62198,62204-62205,62214,62219-62221,62227,62229-62231,62233-62235,62237-62239 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62194 | jeffrey.yasskin | 2008-04-07 01:04:28 +0200 (Mon, 07 Apr 2008) | 7 lines Add enough debugging information to diagnose failures where the HandlerBException is ignored, and fix one such problem, where it was thrown during the __del__ method of the previous Popen object. We may want to find a better way of printing verbose information so it's not spammy when the test passes. ........ r62197 | mark.hammond | 2008-04-07 03:53:39 +0200 (Mon, 07 Apr 2008) | 2 lines Issue #2513: enable 64bit cross compilation on windows. ........ r62198 | mark.hammond | 2008-04-07 03:59:40 +0200 (Mon, 07 Apr 2008) | 2 lines correct heading underline for new "Cross-compiling on Windows" section ........ r62204 | gregory.p.smith | 2008-04-07 08:33:21 +0200 (Mon, 07 Apr 2008) | 4 lines Use the new PyFile_IncUseCount & PyFile_DecUseCount calls appropriatly within the standard library. These modules use PyFile_AsFile and later release the GIL while operating on the previously returned FILE*. ........ r62205 | mark.summerfield | 2008-04-07 09:39:23 +0200 (Mon, 07 Apr 2008) | 4 lines changed "2500 components" to "several thousand" since the number keeps growning:-) ........ r62214 | georg.brandl | 2008-04-07 20:51:59 +0200 (Mon, 07 Apr 2008) | 2 lines #2525: update timezone info examples in the docs. ........ r62219 | andrew.kuchling | 2008-04-08 01:57:07 +0200 (Tue, 08 Apr 2008) | 1 line Write PEP 3127 section; add items ........ r62220 | andrew.kuchling | 2008-04-08 01:57:21 +0200 (Tue, 08 Apr 2008) | 1 line Typo fix ........ r62221 | andrew.kuchling | 2008-04-08 03:33:10 +0200 (Tue, 08 Apr 2008) | 1 line Typographical fix: 32bit -> 32-bit, 64bit -> 64-bit ........ r62227 | andrew.kuchling | 2008-04-08 23:22:53 +0200 (Tue, 08 Apr 2008) | 1 line Add items ........ r62229 | amaury.forgeotdarc | 2008-04-08 23:27:42 +0200 (Tue, 08 Apr 2008) | 7 lines Issue2564: Prevent a hang in "import test.autotest", which runs the entire test suite as a side-effect of importing the module. - in test_capi, a thread tried to import other modules - re.compile() imported sre_parse again on every call. ........ r62230 | amaury.forgeotdarc | 2008-04-08 23:51:57 +0200 (Tue, 08 Apr 2008) | 2 lines Prevent an error when inspect.isabstract() is called with something else than a new-style class. ........ r62231 | amaury.forgeotdarc | 2008-04-09 00:07:05 +0200 (Wed, 09 Apr 2008) | 8 lines Issue 2408: remove the _types module It was only used as a helper in types.py to access types (GetSetDescriptorType and MemberDescriptorType), when they can easily be obtained with python code. These expressions even work with Jython. I don't know what the future of the types module is; (cf. discussion in http://bugs.python.org/issue1605 ) at least this change makes it simpler. ........ r62233 | amaury.forgeotdarc | 2008-04-09 01:10:07 +0200 (Wed, 09 Apr 2008) | 2 lines Add a NEWS entry for previous checkin ........ r62234 | trent.nelson | 2008-04-09 01:47:30 +0200 (Wed, 09 Apr 2008) | 37 lines - Issue #2550: The approach used by client/server code for obtaining ports to listen on in network-oriented tests has been refined in an effort to facilitate running multiple instances of the entire regression test suite in parallel without issue. test_support.bind_port() has been fixed such that it will always return a unique port -- which wasn't always the case with the previous implementation, especially if socket options had been set that affected address reuse (i.e. SO_REUSEADDR, SO_REUSEPORT). The new implementation of bind_port() will actually raise an exception if it is passed an AF_INET/SOCK_STREAM socket with either the SO_REUSEADDR or SO_REUSEPORT socket option set. Furthermore, if available, bind_port() will set the SO_EXCLUSIVEADDRUSE option on the socket it's been passed. This currently only applies to Windows. This option prevents any other sockets from binding to the host/port we've bound to, thus removing the possibility of the 'non-deterministic' behaviour, as Microsoft puts it, that occurs when a second SOCK_STREAM socket binds and accepts to a host/port that's already been bound by another socket. The optional preferred port parameter to bind_port() has been removed. Under no circumstances should tests be hard coding ports! test_support.find_unused_port() has also been introduced, which will pass a temporary socket object to bind_port() in order to obtain an unused port. The temporary socket object is then closed and deleted, and the port is returned. This method should only be used for obtaining an unused port in order to pass to an external program (i.e. the -accept [port] argument to openssl's s_server mode) or as a parameter to a server-oriented class that doesn't give you direct access to the underlying socket used. Finally, test_support.HOST has been introduced, which should be used for the host argument of any relevant socket calls (i.e. bind and connect). The following tests were updated to following the new conventions: test_socket, test_smtplib, test_asyncore, test_ssl, test_httplib, test_poplib, test_ftplib, test_telnetlib, test_socketserver, test_asynchat and test_socket_ssl. It is now possible for multiple instances of the regression test suite to run in parallel without issue. ........ r62235 | gregory.p.smith | 2008-04-09 02:25:17 +0200 (Wed, 09 Apr 2008) | 3 lines Fix zlib crash from zlib.decompressobj().flush(val) when val was not positive. It tried to allocate negative or zero memory. That fails. ........ r62237 | trent.nelson | 2008-04-09 02:34:53 +0200 (Wed, 09 Apr 2008) | 1 line Fix typo with regards to self.PORT shadowing class variables with the same name. ........ r62238 | andrew.kuchling | 2008-04-09 03:08:32 +0200 (Wed, 09 Apr 2008) | 1 line Add items ........ r62239 | jerry.seutter | 2008-04-09 07:07:58 +0200 (Wed, 09 Apr 2008) | 1 line Changed test so it no longer runs as a side effect of importing. ........ Modified: python/branches/py3k/Doc/distutils/builtdist.rst ============================================================================== --- python/branches/py3k/Doc/distutils/builtdist.rst (original) +++ python/branches/py3k/Doc/distutils/builtdist.rst Wed Apr 9 10:37:03 2008 @@ -329,6 +329,42 @@ The installer file will be written to the "distribution directory" --- normally :file:`dist/`, but customizable with the :option:`--dist-dir` option. +.. _cross-compile-windows: + +Cross-compiling on Windows +========================== + +Starting with Python 2.6, distutils is capable of cross-compiling between +Windows platforms. In practice, this means that with the correct tools +installed, you can use a 32bit version of Windows to create 64bit extensions +and vice-versa. + +To build for an alternate platform, specify the :option:`--plat-name` option +to the build command. Valid values are currently 'win32', 'win-amd64' and +'win-ia64'. For example, on a 32bit version of Windows, you could execute:: + + python setup.py build --plat-name=win-amd64 + +to build a 64bit version of your extension. The Windows Installers also +support this option, so the command:: + + python setup.py build --plat-name=win-amd64 bdist_wininst + +would create a 64bit installation executable on your 32bit version of Windows. + +To cross-compile, you must download the Python source code and cross-compile +Python itself for the platform you are targetting - it is not possible from a +binary installtion of Python (as the .lib etc file for other platforms are +not included.) In practice, this means the user of a 32 bit operating +system will need to use Visual Studio 2008 to open the +:file:`PCBuild/PCbuild.sln` solution in the Python source tree and build the +"x64" configuration of the 'pythoncore' project before cross-compiling +extensions is possible. + +Note that by default, Visual Studio 2008 does not install 64bit compilers or +tools. You may need to reexecute the Visual Studio setup process and select +these tools (using Control Panel->[Add/Remove] Programs is a convenient way to +check or modify your existing install.) .. _postinstallation-script: Modified: python/branches/py3k/Doc/includes/tzinfo-examples.py ============================================================================== --- python/branches/py3k/Doc/includes/tzinfo-examples.py (original) +++ python/branches/py3k/Doc/includes/tzinfo-examples.py Wed Apr 9 10:37:03 2008 @@ -87,11 +87,31 @@ dt += timedelta(days_to_go) return dt -# In the US, DST starts at 2am (standard time) on the first Sunday in April. -DSTSTART = datetime(1, 4, 1, 2) -# and ends at 2am (DST time; 1am standard time) on the last Sunday of Oct. -# which is the first Sunday on or after Oct 25. -DSTEND = datetime(1, 10, 25, 1) + +# US DST Rules +# +# This is a simplified (i.e., wrong for a few cases) set of rules for US +# DST start and end times. For a complete and up-to-date set of DST rules +# and timezone definitions, visit the Olson Database (or try pytz): +# http://www.twinsun.com/tz/tz-link.htm +# http://sourceforge.net/projects/pytz/ (might not be up-to-date) +# +# In the US, since 2007, DST starts at 2am (standard time) on the second +# Sunday in March, which is the first Sunday on or after Mar 8. +DSTSTART_2007 = datetime(1, 3, 8, 2) +# and ends at 2am (DST time; 1am standard time) on the first Sunday of Nov. +DSTEND_2007 = datetime(1, 11, 1, 1) +# From 1987 to 2006, DST used to start at 2am (standard time) on the first +# Sunday in April and to end at 2am (DST time; 1am standard time) on the last +# Sunday of October, which is the first Sunday on or after Oct 25. +DSTSTART_1987_2006 = datetime(1, 4, 1, 2) +DSTEND_1987_2006 = datetime(1, 10, 25, 1) +# From 1967 to 1986, DST used to start at 2am (standard time) on the last +# Sunday in April (the one on or after April 24) and to end at 2am (DST time; +# 1am standard time) on the last Sunday of October, which is the first Sunday +# on or after Oct 25. +DSTSTART_1967_1986 = datetime(1, 4, 24, 2) +DSTEND_1967_1986 = DSTEND_1987_2006 class USTimeZone(tzinfo): @@ -122,9 +142,19 @@ return ZERO assert dt.tzinfo is self - # Find first Sunday in April & the last in October. - start = first_sunday_on_or_after(DSTSTART.replace(year=dt.year)) - end = first_sunday_on_or_after(DSTEND.replace(year=dt.year)) + # Find start and end times for US DST. For years before 1967, return + # ZERO for no DST. + if 2006 < dt.year: + dststart, dstend = DSTSTART_2007, DSTEND_2007 + elif 1986 < dt.year < 2007: + dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006 + elif 1966 < dt.year < 1987: + dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986 + else: + return ZERO + + start = first_sunday_on_or_after(dststart.replace(year=dt.year)) + end = first_sunday_on_or_after(dstend.replace(year=dt.year)) # Can't compare naive to aware objects, so strip the timezone from # dt first. Modified: python/branches/py3k/Doc/library/index.rst ============================================================================== --- python/branches/py3k/Doc/library/index.rst (original) +++ python/branches/py3k/Doc/library/index.rst Wed Apr 9 10:37:03 2008 @@ -31,8 +31,9 @@ optional components. In addition to the standard library, there is a growing collection of -over 2500 additional components available from the `Python Package Index -`_. +several thousand components (from individual programs and modules to +packages and entire application development frameworks), available from +the `Python Package Index `_. .. toctree:: Modified: python/branches/py3k/Doc/library/select.rst ============================================================================== --- python/branches/py3k/Doc/library/select.rst (original) +++ python/branches/py3k/Doc/library/select.rst Wed Apr 9 10:37:03 2008 @@ -113,9 +113,9 @@ +-----------------------+-----------------------------------------------+ | :const:`EPOLLPRI` | Urgent data for read | +-----------------------+-----------------------------------------------+ - | :const:`EPOLLERR` | Error condition happend on the assoc. fd | + | :const:`EPOLLERR` | Error condition happened on the assoc. fd | +-----------------------+-----------------------------------------------+ - | :const:`EPOLLHUP` | Hang up happend on the assoc. fd | + | :const:`EPOLLHUP` | Hang up happened on the assoc. fd | +-----------------------+-----------------------------------------------+ | :const:`EPOLLET` | Set Edge Trigger behavior, the default is | | | Level Trigger behavior | Modified: python/branches/py3k/Doc/library/types.rst ============================================================================== --- python/branches/py3k/Doc/library/types.rst (original) +++ python/branches/py3k/Doc/library/types.rst Wed Apr 9 10:37:03 2008 @@ -86,15 +86,17 @@ .. data:: GetSetDescriptorType - The type of objects defined in extension modules with ``PyGetSetDef``, such as - ``FrameType.f_locals`` or ``array.array.typecode``. This constant is not - defined in implementations of Python that do not have such extension types, so - for portable code use ``hasattr(types, 'GetSetDescriptorType')``. + The type of objects defined in extension modules with ``PyGetSetDef``, such + as ``FrameType.f_locals`` or ``array.array.typecode``. This type is used as + descriptor for object attributes; it has the same purpose as the + :class:`property` type, but for classes defined in extension modules. .. data:: MemberDescriptorType - The type of objects defined in extension modules with ``PyMemberDef``, such as - ``datetime.timedelta.days``. This constant is not defined in implementations of - Python that do not have such extension types, so for portable code use - ``hasattr(types, 'MemberDescriptorType')``. + The type of objects defined in extension modules with ``PyMemberDef``, such + as ``datetime.timedelta.days``. This type is used as descriptor for simple C + data members which use standard conversion functions; it has the same purpose + as the :class:`property` type, but for classes defined in extension modules. + In other implementations of Python, this type may be identical to + ``GetSetDescriptorType``. Modified: python/branches/py3k/Doc/whatsnew/2.6.rst ============================================================================== --- python/branches/py3k/Doc/whatsnew/2.6.rst (original) +++ python/branches/py3k/Doc/whatsnew/2.6.rst Wed Apr 9 10:37:03 2008 @@ -728,6 +728,12 @@ Python 2.6 adds :class:`bytes` as a synonym for the :class:`str` type, and it also supports the ``b''`` notation. +There's also a ``__future__`` import that causes all string literals +to become Unicode strings. This means that ``\u`` escape sequences +can be used to include Unicode characters. + +XXX give example + .. seealso:: :pep:`3112` - Bytes literals in Python 3000 @@ -740,7 +746,70 @@ PEP 3116: New I/O Library ===================================================== -XXX write this. +Python's built-in file objects support a number of methods, but +file-like objects don't necessarily support all of them. Objects that +imitate files usually support :meth:`read` and :meth:`write`, but they +may not support :meth:`readline`. Python 3.0 introduces a layered I/O +library in the :mod:`io` module that separates buffering and +text-handling features from the fundamental read and write operations. + +There are three levels of abstract base classes provided by +the :mod:`io` module: + +* :class:`RawIOBase`: defines raw I/O operations: :meth:`read`, + :meth:`readinto`, + :meth:`write`, :meth:`seek`, :meth:`tell`, :meth:`truncate`, + and :meth:`close`. + Most of the methods of this class will often map to a single system call. + There are also :meth:`readable`, :meth:`writable`, and :meth:`seekable` + methods for determining what operations a given object will allow. + + Python 3.0 has concrete implementations of this class for files and + sockets, but Python 2.6 hasn't restructured its file and socket objects + in this way. + + .. XXX should 2.6 register them in io.py? + +* :class:`BufferedIOBase`: is an abstract base class that + buffers data in memory to reduce the number of + system calls used, making I/O processing more efficient. + It supports all of the methods of :class:`RawIOBase`, + and adds a :attr:`raw` attribute holding the underlying raw object. + + There are four concrete classes implementing this ABC: + :class:`BufferedWriter` and + :class:`BufferedReader` for objects that only support + writing or reading and don't support random access, + :class:`BufferedRandom` for objects that support the :meth:`seek` method + for random access, + and :class:`BufferedRWPair` for objects such as TTYs that have + both read and write operations that act upon unconnected streams of data. + +* :class:`TextIOBase`: Provides functions for reading and writing + strings (remember, strings will be Unicode in Python 3.0), + and supporting universal newlines. :class:`TextIOBase` defines + the :meth:`readline` method and supports iteration upon + objects. + + There are two concrete implementations. :class:`TextIOWrapper` + wraps a buffered I/O object, supporting all of the methods for + text I/O and adding a :attr:`buffer` attribute for access + to the underlying object. :class:`StringIO` simply buffers + everything in memory without ever writing anything to disk. + + (In current 2.6 alpha releases, :class:`io.StringIO` is implemented in + pure Python, so it's pretty slow. You should therefore stick with the + existing :mod:`StringIO` module or :mod:`cStringIO` for now. At some + point Python 3.0's :mod:`io` module will be rewritten into C for speed, + and perhaps the C implementation will be backported to the 2.x releases.) + + .. XXX check before final release: is io.py still written in Python? + +In Python 2.6, the underlying implementations haven't been +restructured to build on top of the :mod:`io` module's classes. The +module is being provided to make it easier to write code that's +forward-compatible with 3.0, and to save developers the effort of writing +their own implementations of buffering and text I/O. .. seealso:: @@ -952,22 +1021,48 @@ PEP 3127: Integer Literal Support and Syntax ===================================================== -XXX write this -- this section is currently just brief notes. - -Python 3.0 changes the syntax for octal integer literals, and -adds supports for binary integers: 0o instad of 0, -and 0b for binary. Python 2.6 doesn't support this, but a bin() -builtin was added. - -XXX changes to the hex/oct builtins - +Python 3.0 changes the syntax for octal (base-8) integer literals, +which are now prefixed by "0o" or "0O" instead of a leading zero, and +adds support for binary (base-2) integer literals, signalled by a "0b" +or "0B" prefix. + +Python 2.6 doesn't drop support for a leading 0 signalling +an octal number, but it does add support for "0o" and "0b":: + + >>> 0o21, 2*8 + 1 + (17, 17) + >>> 0b101111 + 47 + +The :func:`oct` built-in still returns numbers +prefixed with a leading zero, and a new :func:`bin` +built-in returns the binary representation for a number:: + + >>> oct(42) + '052' + >>> bin(173) + '0b10101101' + +The :func:`int` and :func:`long` built-ins will now accept the "0o" +and "0b" prefixes when base-8 or base-2 are requested, or when the +**base** argument is zero (meaning the base used is determined from +the string): + + >>> int ('0o52', 0) + 42 + >>> int('1101', 2) + 13 + >>> int('0b1101', 2) + 13 + >>> int('0b1101', 0) + 13 -New bin() built-in returns the binary form of a number. .. seealso:: :pep:`3127` - Integer Literal Support and Syntax - PEP written by Patrick Maupin. + PEP written by Patrick Maupin; backported to 2.6 by + Eric Smith. .. ====================================================================== @@ -1124,6 +1219,13 @@ .. Patch 1686487 +* Tuples now have an :meth:`index` method matching the list type's + :meth:`index` method:: + + >>> t = (0,1,2,3,4) + >>> t.index(3) + 3 + * The built-in types now have improved support for extended slicing syntax, where various combinations of ``(start, stop, step)`` are supplied. Previously, the support was partial and certain corner cases wouldn't work. @@ -1532,7 +1634,7 @@ (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)] - ``itertools.chain(*iterables)` is an existing function in + ``itertools.chain(*iterables)`` is an existing function in :mod:`itertools` that gained a new constructor in Python 2.6. ``itertools.chain.from_iterable(iterable)`` takes a single iterable that should return other iterables. :func:`chain` will @@ -1642,6 +1744,12 @@ .. Patch #1393667 + The :func:`post_mortem` function, used to enter debugging of a + traceback, will now use the traceback returned by :func:`sys.exc_info` + if no traceback is supplied. (Contributed by Facundo Batista.) + + .. Patch #1106316 + * The :mod:`pickletools` module now has an :func:`optimize` function that takes a string containing a pickle and removes some unused opcodes, returning a shorter pickle that contains the same data structure. @@ -1720,6 +1828,8 @@ .. Patch 1657 + .. XXX + * The :mod:`sets` module has been deprecated; it's better to use the built-in :class:`set` and :class:`frozenset` types. @@ -1791,9 +1901,12 @@ * The base classes in the :mod:`SocketServer` module now support calling a :meth:`handle_timeout` method after a span of inactivity specified by the server's :attr:`timeout` attribute. (Contributed - by Michael Pomraning.) + by Michael Pomraning.) The :meth:`serve_forever` method + now takes an optional poll interval measured in seconds, + controlling how often the server will check for a shutdown request. + (Contributed by Pedro Werneck and Jeffrey Yasskin.) - .. Patch #742598 + .. Patch #742598, #1193577 * The :mod:`struct` module now supports the C99 :ctype:`_Bool` type, using the format character ``'?'``. @@ -2069,6 +2182,19 @@ .. Patch 1551895 +* Python's use of the C stdio library is now thread-safe, or at least + as thread-safe as the underlying library is. A long-standing potential + bug occurred if one thread closed a file object while another thread + was reading from or writing to the object. In 2.6 file objects + have a reference count, manipulated by the + :cfunc:`PyFile_IncUseCount` and :cfunc:`PyFile_DecUseCount` + functions. File objects can't be closed unless the reference count + is zero. :cfunc:`PyFile_IncUseCount` should be called while the GIL + is still held, before carrying out an I/O operation using the + ``FILE *`` pointer, and :cfunc:`PyFile_DecUseCount` should be called + immediately after the GIL is re-acquired. + (Contributed by Antoine Pitrou and Gregory P. Smith.) + * Several functions return information about the platform's floating-point support. :cfunc:`PyFloat_GetMax` returns the maximum representable floating point value, @@ -2089,6 +2215,13 @@ .. Issue 1635 +* Many C extensions define their own little macro for adding + integers and strings to the module's dictionary in the + ``init*`` function. Python 2.6 finally defines standard macros + for adding values to a module, :cmacro:`PyModule_AddStringMacro` + and :cmacro:`PyModule_AddIntMacro()`. (Contributed by + Christian Heimes.) + * Some macros were renamed in both 3.0 and 2.6 to make it clearer that they are macros, not functions. :cmacro:`Py_Size()` became :cmacro:`Py_SIZE()`, @@ -2112,6 +2245,13 @@ ``numfree``, and a macro :cmacro:`Py_MAXFREELIST` is always defined. +* A new Makefile target, "make check", prepares the Python source tree + for making a patch: it fixes trailing whitespace in all modified + ``.py`` files, checks whether the documentation has been changed, + and reports whether the :file:`Misc/ACKS` and :file:`Misc/NEWS` files + have been updated. + (Contributed by Brett Cannon.) + .. ====================================================================== @@ -2140,6 +2280,13 @@ module now support the context protocol, so they can be used in :keyword:`with` statements. (Contributed by Christian Heimes.) + :mod:`_winreg` also has better support for x64 systems, + exposing the :func:`DisableReflectionKey`, :func:`EnableReflectionKey`, + and :func:`QueryReflectionKey` functions, which enable and disable + registry reflection for 32-bit processes running on 64-bit systems. + + .. Patch 1753245 + * The new default compiler on Windows is Visual Studio 2008 (VS 9.0). The build directories for Visual Studio 2003 (VS7.1) and 2005 (VS8.0) were moved into the PC/ directory. The new PCbuild directory supports @@ -2237,5 +2384,5 @@ ================ The author would like to thank the following people for offering suggestions, -corrections and assistance with various drafts of this article: . +corrections and assistance with various drafts of this article: Jim Jewett. Modified: python/branches/py3k/Lib/distutils/command/bdist.py ============================================================================== --- python/branches/py3k/Lib/distutils/command/bdist.py (original) +++ python/branches/py3k/Lib/distutils/command/bdist.py Wed Apr 9 10:37:03 2008 @@ -91,7 +91,10 @@ def finalize_options(self): # have to finalize 'plat_name' before 'bdist_base' if self.plat_name is None: - self.plat_name = get_platform() + if self.skip_build: + self.plat_name = get_platform() + else: + self.plat_name = self.get_finalized_command('build').plat_name # 'bdist_base' -- parent of per-built-distribution-format # temporary directories (eg. we'll probably have Modified: python/branches/py3k/Lib/distutils/command/bdist_msi.py ============================================================================== --- python/branches/py3k/Lib/distutils/command/bdist_msi.py (original) +++ python/branches/py3k/Lib/distutils/command/bdist_msi.py Wed Apr 9 10:37:03 2008 @@ -9,11 +9,11 @@ import sys, os from distutils.core import Command -from distutils.util import get_platform from distutils.dir_util import remove_tree from distutils.sysconfig import get_python_version from distutils.version import StrictVersion from distutils.errors import DistutilsOptionError +from distutils.util import get_platform from distutils import log import msilib from msilib import schema, sequence, text @@ -87,6 +87,9 @@ user_options = [('bdist-dir=', None, "temporary directory for creating the distribution"), + ('plat-name=', 'p', + "platform name to embed in generated filenames " + "(default: %s)" % get_platform()), ('keep-temp', 'k', "keep the pseudo-installation tree around after " + "creating the distribution archive"), @@ -116,6 +119,7 @@ def initialize_options(self): self.bdist_dir = None + self.plat_name = None self.keep_temp = 0 self.no_target_compile = 0 self.no_target_optimize = 0 @@ -139,7 +143,10 @@ else: self.target_version = short_version - self.set_undefined_options('bdist', ('dist_dir', 'dist_dir')) + self.set_undefined_options('bdist', + ('dist_dir', 'dist_dir'), + ('plat_name', 'plat_name'), + ) if self.pre_install_script: raise DistutilsOptionError( @@ -180,7 +187,7 @@ if not target_version: assert self.skip_build, "Should have already checked this" target_version = sys.version[0:3] - plat_specifier = ".%s-%s" % (get_platform(), target_version) + plat_specifier = ".%s-%s" % (self.plat_name, target_version) build = self.get_finalized_command('build') build.build_lib = os.path.join(build.build_base, 'lib' + plat_specifier) @@ -633,8 +640,7 @@ def get_installer_filename(self, fullname): # Factored out to allow overriding in subclasses - plat = get_platform() - installer_name = os.path.join(self.dist_dir, - "%s.%s-py%s.msi" % - (fullname, plat, self.target_version)) + base_name = "%s.%s-py%s.msi" % (fullname, self.plat_name, + self.target_version) + installer_name = os.path.join(self.dist_dir, base_name) return installer_name Modified: python/branches/py3k/Lib/distutils/command/bdist_wininst.py ============================================================================== --- python/branches/py3k/Lib/distutils/command/bdist_wininst.py (original) +++ python/branches/py3k/Lib/distutils/command/bdist_wininst.py Wed Apr 9 10:37:03 2008 @@ -19,6 +19,9 @@ user_options = [('bdist-dir=', None, "temporary directory for creating the distribution"), + ('plat-name=', 'p', + "platform name to embed in generated filenames " + "(default: %s)" % get_platform()), ('keep-temp', 'k', "keep the pseudo-installation tree around after " + "creating the distribution archive"), @@ -52,6 +55,7 @@ def initialize_options(self): self.bdist_dir = None + self.plat_name = None self.keep_temp = 0 self.no_target_compile = 0 self.no_target_optimize = 0 @@ -78,7 +82,10 @@ " option must be specified" % (short_version,)) self.target_version = short_version - self.set_undefined_options('bdist', ('dist_dir', 'dist_dir')) + self.set_undefined_options('bdist', + ('dist_dir', 'dist_dir'), + ('plat_name', 'plat_name'), + ) if self.install_script: for script in self.distribution.scripts: @@ -104,6 +111,7 @@ install.root = self.bdist_dir install.skip_build = self.skip_build install.warn_dir = 0 + install.plat_name = self.plat_name install_lib = self.reinitialize_command('install_lib') # we do not want to include pyc or pyo files @@ -121,7 +129,7 @@ if not target_version: assert self.skip_build, "Should have already checked this" target_version = sys.version[0:3] - plat_specifier = ".%s-%s" % (get_platform(), target_version) + plat_specifier = ".%s-%s" % (self.plat_name, target_version) build = self.get_finalized_command('build') build.build_lib = os.path.join(build.build_base, 'lib' + plat_specifier) @@ -267,11 +275,11 @@ # if we create an installer for a specific python version, # it's better to include this in the name installer_name = os.path.join(self.dist_dir, - "%s.win32-py%s.exe" % - (fullname, self.target_version)) + "%s.%s-py%s.exe" % + (fullname, self.plat_name, self.target_version)) else: installer_name = os.path.join(self.dist_dir, - "%s.win32.exe" % fullname) + "%s.%s.exe" % (fullname, self.plat_name)) return installer_name def get_exe_bytes(self): @@ -293,9 +301,9 @@ bv = get_build_version() else: if self.target_version < "2.4": - bv = "6" + bv = 6.0 else: - bv = "7.1" + bv = 7.1 else: # for current version - use authoritative check. bv = get_build_version() @@ -304,5 +312,9 @@ directory = os.path.dirname(__file__) # we must use a wininst-x.y.exe built with the same C compiler # used for python. XXX What about mingw, borland, and so on? - filename = os.path.join(directory, "wininst-%.1f.exe" % bv) + if self.plat_name == 'win32': + sfix = '' + else: + sfix = self.plat_name[3:] # strip 'win' - leaves eg '-amd64' + filename = os.path.join(directory, "wininst-%.1f%s.exe" % (bv, sfix)) return open(filename, "rb").read() Modified: python/branches/py3k/Lib/distutils/command/build.py ============================================================================== --- python/branches/py3k/Lib/distutils/command/build.py (original) +++ python/branches/py3k/Lib/distutils/command/build.py Wed Apr 9 10:37:03 2008 @@ -6,6 +6,7 @@ import sys, os from distutils.core import Command +from distutils.errors import DistutilsOptionError from distutils.util import get_platform @@ -32,6 +33,9 @@ "build directory for scripts"), ('build-temp=', 't', "temporary build directory"), + ('plat-name=', 'p', + "platform name to build for, if supported " + "(default: %s)" % get_platform()), ('compiler=', 'c', "specify the compiler type"), ('debug', 'g', @@ -59,12 +63,24 @@ self.build_temp = None self.build_scripts = None self.compiler = None + self.plat_name = None self.debug = None self.force = 0 self.executable = None def finalize_options(self): - plat_specifier = ".%s-%s" % (get_platform(), sys.version[0:3]) + if self.plat_name is None: + self.plat_name = get_platform() + else: + # plat-name only supported for windows (other platforms are + # supported via ./configure flags, if at all). Avoid misleading + # other platforms. + if os.name != 'nt': + raise DistutilsOptionError( + "--plat-name only supported on Windows (try " + "using './configure --help' on your platform)") + + plat_specifier = ".%s-%s" % (self.plat_name, sys.version[0:3]) # Make it so Python 2.x and Python 2.x with --with-pydebug don't # share the same build directories. Doing so confuses the build Modified: python/branches/py3k/Lib/distutils/command/build_ext.py ============================================================================== --- python/branches/py3k/Lib/distutils/command/build_ext.py (original) +++ python/branches/py3k/Lib/distutils/command/build_ext.py Wed Apr 9 10:37:03 2008 @@ -12,6 +12,7 @@ from distutils.sysconfig import customize_compiler, get_python_version from distutils.dep_util import newer_group from distutils.extension import Extension +from distutils.util import get_platform from distutils import log if os.name == 'nt': @@ -57,6 +58,9 @@ "directory for compiled extension modules"), ('build-temp=', 't', "directory for temporary files (build by-products)"), + ('plat-name=', 'p', + "platform name to cross-compile for, if supported " + "(default: %s)" % get_platform()), ('inplace', 'i', "ignore build-lib and put compiled extensions into the source " + "directory alongside your pure Python modules"), @@ -98,6 +102,7 @@ def initialize_options(self): self.extensions = None self.build_lib = None + self.plat_name = None self.build_temp = None self.inplace = 0 self.package = None @@ -124,7 +129,9 @@ ('build_temp', 'build_temp'), ('compiler', 'compiler'), ('debug', 'debug'), - ('force', 'force')) + ('force', 'force'), + ('plat_name', 'plat_name'), + ) if self.package is None: self.package = self.distribution.ext_package @@ -167,6 +174,9 @@ # for Release and Debug builds. # also Python's library directory must be appended to library_dirs if os.name == 'nt': + # the 'libs' directory is for binary installs - we assume that + # must be the *native* platform. But we don't really support + # cross-compiling via a binary install anyway, so we let it go. self.library_dirs.append(os.path.join(sys.exec_prefix, 'libs')) if self.debug: self.build_temp = os.path.join(self.build_temp, "Debug") @@ -177,8 +187,17 @@ # this allows distutils on windows to work in the source tree self.include_dirs.append(os.path.join(sys.exec_prefix, 'PC')) if MSVC_VERSION == 9: - self.library_dirs.append(os.path.join(sys.exec_prefix, - 'PCbuild')) + # Use the .lib files for the correct architecture + if self.plat_name == 'win32': + suffix = '' + else: + # win-amd64 or win-ia64 + suffix = self.plat_name[4:] + new_lib = os.path.join(sys.exec_prefix, 'PCbuild') + if suffix: + new_lib = os.path.join(new_lib, suffix) + self.library_dirs.append(new_lib) + elif MSVC_VERSION == 8: self.library_dirs.append(os.path.join(sys.exec_prefix, 'PC', 'VS8.0', 'win32release')) @@ -267,6 +286,11 @@ dry_run=self.dry_run, force=self.force) customize_compiler(self.compiler) + # If we are cross-compiling, init the compiler now (if we are not + # cross-compiling, init would not hurt, but people may rely on + # late initialization of compiler even if they shouldn't...) + if os.name == 'nt' and self.plat_name != get_platform(): + self.compiler.initialize(self.plat_name) # And make sure that any compile/link-related options (which might # come from the command-line or from the setup script) are set in Modified: python/branches/py3k/Lib/distutils/command/install.py ============================================================================== --- python/branches/py3k/Lib/distutils/command/install.py (original) +++ python/branches/py3k/Lib/distutils/command/install.py Wed Apr 9 10:37:03 2008 @@ -13,6 +13,7 @@ from distutils.errors import DistutilsPlatformError from distutils.file_util import write_file from distutils.util import convert_path, subst_vars, change_root +from distutils.util import get_platform from distutils.errors import DistutilsOptionError if sys.version < "2.2": @@ -485,6 +486,14 @@ # Obviously have to build before we can install if not self.skip_build: self.run_command('build') + # If we built for any other platform, we can't install. + build_plat = self.distribution.get_command_obj('build').plat_name + # check warn_dir - it is a clue that the 'install' is happening + # internally, and not to sys.path, so we don't check the platform + # matches what we are running. + if self.warn_dir and build_plat != get_platform(): + raise DistutilsPlatformError("Can't install when " + "cross-compiling") # Run all sub-commands (at least those that need to be run) for cmd_name in self.get_sub_commands(): Modified: python/branches/py3k/Lib/distutils/msvc9compiler.py ============================================================================== --- python/branches/py3k/Lib/distutils/msvc9compiler.py (original) +++ python/branches/py3k/Lib/distutils/msvc9compiler.py Wed Apr 9 10:37:03 2008 @@ -22,6 +22,7 @@ from distutils.ccompiler import (CCompiler, gen_preprocess_options, gen_lib_options) from distutils import log +from distutils.util import get_platform import _winreg @@ -38,13 +39,15 @@ VS_BASE = r"Software\Microsoft\VisualStudio\%0.1f" WINSDK_BASE = r"Software\Microsoft\Microsoft SDKs\Windows" NET_BASE = r"Software\Microsoft\.NETFramework" -ARCHS = {'DEFAULT' : 'x86', - 'intel' : 'x86', 'x86' : 'x86', - 'amd64' : 'x64', 'x64' : 'x64', - 'itanium' : 'ia64', 'ia64' : 'ia64', - } -# The globals VERSION, ARCH, MACROS and VC_ENV are defined later +# A map keyed by get_platform() return values to values accepted by +# 'vcvarsall.bat'. Note a cross-compile may combine these (eg, 'x86_amd64' is +# the param to cross-compile on x86 targetting amd64.) +PLAT_TO_VCVARS = { + 'win32' : 'x86', + 'win-amd64' : 'amd64', + 'win-ia64' : 'ia64', +} class Reg: """Helper class to read values from the registry @@ -176,23 +179,6 @@ # else we don't know what version of the compiler this is return None -def get_build_architecture(): - """Return the processor architecture. - - Possible results are "x86" or "amd64". - """ - prefix = " bit (" - i = sys.version.find(prefix) - if i == -1: - return "x86" - j = sys.version.find(")", i) - sysarch = sys.version[i+len(prefix):j].lower() - arch = ARCHS.get(sysarch, None) - if arch is None: - return ARCHS['DEFAULT'] - else: - return arch - def normalize_and_reduce_paths(paths): """Return a list of normalized paths with duplicates removed. @@ -251,6 +237,7 @@ if vcvarsall is None: raise IOError("Unable to find vcvarsall.bat") + log.debug("Calling 'vcvarsall.bat %s' (version=%s)", arch, version) popen = subprocess.Popen('"%s" %s & set' % (vcvarsall, arch), stdout=subprocess.PIPE, stderr=subprocess.PIPE) @@ -281,9 +268,7 @@ VERSION = get_build_version() if VERSION < 8.0: raise DistutilsPlatformError("VC %0.1f is not supported by this module" % VERSION) -ARCH = get_build_architecture() # MACROS = MacroExpander(VERSION) -VC_ENV = query_vcvarsall(VERSION, ARCH) class MSVCCompiler(CCompiler) : """Concrete class that implements an interface to Microsoft Visual C++, @@ -318,13 +303,25 @@ def __init__(self, verbose=0, dry_run=0, force=0): CCompiler.__init__ (self, verbose, dry_run, force) self.__version = VERSION - self.__arch = ARCH self.__root = r"Software\Microsoft\VisualStudio" # self.__macros = MACROS self.__path = [] + # target platform (.plat_name is consistent with 'bdist') + self.plat_name = None + self.__arch = None # deprecated name self.initialized = False - def initialize(self): + def initialize(self, plat_name=None): + # multi-init means we would need to check platform same each time... + assert not self.initialized, "don't init multiple times" + if plat_name is None: + plat_name = get_platform() + # sanity check for platforms to prevent obscure errors later. + ok_plats = 'win32', 'win-amd64', 'win-ia64' + if plat_name not in ok_plats: + raise DistutilsPlatformError("--plat-name must be one of %s" % + (ok_plats,)) + if "DISTUTILS_USE_SDK" in os.environ and "MSSdk" in os.environ and self.find_exe("cl.exe"): # Assume that the SDK set up everything alright; don't try to be # smarter @@ -334,9 +331,24 @@ self.rc = "rc.exe" self.mc = "mc.exe" else: - self.__paths = VC_ENV['path'].split(os.pathsep) - os.environ['lib'] = VC_ENV['lib'] - os.environ['include'] = VC_ENV['include'] + # On x86, 'vcvars32.bat amd64' creates an env that doesn't work; + # to cross compile, you use 'x86_amd64'. + # On AMD64, 'vcvars32.bat amd64' is a native build env; to cross + # compile use 'x86' (ie, it runs the x86 compiler directly) + # No idea how itanium handles this, if at all. + if plat_name == get_platform() or plat_name == 'win32': + # native build or cross-compile to win32 + plat_spec = PLAT_TO_VCVARS[plat_name] + else: + # cross compile from win32 -> some 64bit + plat_spec = PLAT_TO_VCVARS[get_platform()] + '_' + \ + PLAT_TO_VCVARS[plat_name] + + vc_env = query_vcvarsall(VERSION, plat_spec) + + self.__paths = vc_env['path'].split(os.pathsep) + os.environ['lib'] = vc_env['lib'] + os.environ['include'] = vc_env['include'] if len(self.__paths) == 0: raise DistutilsPlatformError("Python was built with %s, " Modified: python/branches/py3k/Lib/distutils/msvccompiler.py ============================================================================== --- python/branches/py3k/Lib/distutils/msvccompiler.py (original) +++ python/branches/py3k/Lib/distutils/msvccompiler.py Wed Apr 9 10:37:03 2008 @@ -638,5 +638,5 @@ log.debug("Importing new compiler from distutils.msvc9compiler") OldMSVCCompiler = MSVCCompiler from distutils.msvc9compiler import MSVCCompiler - from distutils.msvc9compiler import get_build_architecture + # get_build_architecture not really relevant now we support cross-compile from distutils.msvc9compiler import MacroExpander Modified: python/branches/py3k/Lib/distutils/util.py ============================================================================== --- python/branches/py3k/Lib/distutils/util.py (original) +++ python/branches/py3k/Lib/distutils/util.py Wed Apr 9 10:37:03 2008 @@ -30,7 +30,7 @@ irix64-6.2 Windows will return one of: - win-x86_64 (64bit Windows on x86_64 (AMD64)) + win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc) win-ia64 (64bit Windows on Itanium) win32 (all others - specifically, sys.platform is returned) @@ -45,7 +45,7 @@ j = sys.version.find(")", i) look = sys.version[i+len(prefix):j].lower() if look == 'amd64': - return 'win-x86_64' + return 'win-amd64' if look == 'itanium': return 'win-ia64' return sys.platform Modified: python/branches/py3k/Lib/inspect.py ============================================================================== --- python/branches/py3k/Lib/inspect.py (original) +++ python/branches/py3k/Lib/inspect.py Wed Apr 9 10:37:03 2008 @@ -247,7 +247,7 @@ def isabstract(object): """Return true if the object is an abstract base class (ABC).""" - return object.__flags__ & TPFLAGS_IS_ABSTRACT + return isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT def getmembers(object, predicate=None): """Return all members of an object as (name, value) pairs sorted by name. Modified: python/branches/py3k/Lib/sre_compile.py ============================================================================== --- python/branches/py3k/Lib/sre_compile.py (original) +++ python/branches/py3k/Lib/sre_compile.py Wed Apr 9 10:37:03 2008 @@ -11,7 +11,7 @@ """Internal support module for sre""" import _sre, sys - +import sre_parse from sre_constants import * assert _sre.MAGIC == MAGIC, "SRE module mismatch" @@ -493,7 +493,6 @@ # internal: convert pattern list to internal format if isstring(p): - import sre_parse pattern = p p = sre_parse.parse(p, flags) else: Modified: python/branches/py3k/Lib/test/test_asynchat.py ============================================================================== --- python/branches/py3k/Lib/test/test_asynchat.py (original) +++ python/branches/py3k/Lib/test/test_asynchat.py Wed Apr 9 10:37:03 2008 @@ -6,8 +6,7 @@ import sys from test import test_support -HOST = "127.0.0.1" -PORT = 54322 +HOST = test_support.HOST SERVER_QUIT = b'QUIT\n' class echo_server(threading.Thread): @@ -18,15 +17,13 @@ def __init__(self, event): threading.Thread.__init__(self) self.event = event + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.port = test_support.bind_port(self.sock) def run(self): - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - global PORT - PORT = test_support.bind_port(sock, HOST, PORT) - sock.listen(1) + self.sock.listen(1) self.event.set() - conn, client = sock.accept() + conn, client = self.sock.accept() self.buffer = b"" # collect data until quit message is seen while SERVER_QUIT not in self.buffer: @@ -50,15 +47,15 @@ pass conn.close() - sock.close() + self.sock.close() class echo_client(asynchat.async_chat): - def __init__(self, terminator): + def __init__(self, terminator, server_port): asynchat.async_chat.__init__(self) self.contents = [] self.create_socket(socket.AF_INET, socket.SOCK_STREAM) - self.connect((HOST, PORT)) + self.connect((HOST, server_port)) self.set_terminator(terminator) self.buffer = b"" @@ -106,7 +103,7 @@ event.wait() event.clear() time.sleep(0.01) # Give server time to start accepting. - c = echo_client(term) + c = echo_client(term, s.port) c.push(b"hello ") c.push(bytes("world%s" % term, "ascii")) c.push(bytes("I'm not dead yet!%s" % term, "ascii")) @@ -138,7 +135,7 @@ def numeric_terminator_check(self, termlen): # Try reading a fixed number of bytes s, event = start_echo_server() - c = echo_client(termlen) + c = echo_client(termlen, s.port) data = b"hello world, I'm not dead yet!\n" c.push(data) c.push(SERVER_QUIT) @@ -158,7 +155,7 @@ def test_none_terminator(self): # Try reading a fixed number of bytes s, event = start_echo_server() - c = echo_client(None) + c = echo_client(None, s.port) data = b"hello world, I'm not dead yet!\n" c.push(data) c.push(SERVER_QUIT) @@ -170,7 +167,7 @@ def test_simple_producer(self): s, event = start_echo_server() - c = echo_client(b'\n') + c = echo_client(b'\n', s.port) data = b"hello world\nI'm not dead yet!\n" p = asynchat.simple_producer(data+SERVER_QUIT, buffer_size=8) c.push_with_producer(p) @@ -181,7 +178,7 @@ def test_string_producer(self): s, event = start_echo_server() - c = echo_client(b'\n') + c = echo_client(b'\n', s.port) data = b"hello world\nI'm not dead yet!\n" c.push_with_producer(data+SERVER_QUIT) asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01) @@ -192,8 +189,8 @@ def test_empty_line(self): # checks that empty lines are handled correctly s, event = start_echo_server() - c = echo_client(b'\n') - c.push(b"hello world\n\nI'm not dead yet!\n") + c = echo_client(b'\n', s.port) + c.push("hello world\n\nI'm not dead yet!\n") c.push(SERVER_QUIT) asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01) s.join() @@ -203,8 +200,8 @@ def test_close_when_done(self): s, event = start_echo_server() - c = echo_client(b'\n') - c.push(b"hello world\nI'm not dead yet!\n") + c = echo_client(b'\n', s.port) + c.push("hello world\nI'm not dead yet!\n") c.push(SERVER_QUIT) c.close_when_done() asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01) Modified: python/branches/py3k/Lib/test/test_asyncore.py ============================================================================== --- python/branches/py3k/Lib/test/test_asyncore.py (original) +++ python/branches/py3k/Lib/test/test_asyncore.py Wed Apr 9 10:37:03 2008 @@ -9,10 +9,10 @@ from test import test_support from test.test_support import TESTFN, run_unittest, unlink -from io import StringIO, BytesIO +from io import BytesIO +from io import StringIO -HOST = "127.0.0.1" -PORT = None +HOST = test_support.HOST class dummysocket: def __init__(self): @@ -52,14 +52,8 @@ self.error_handled = True # used when testing senders; just collects what it gets until newline is sent -def capture_server(evt, buf): +def capture_server(evt, buf, serv): try: - serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - serv.settimeout(3) - serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - serv.bind(("", 0)) - global PORT - PORT = serv.getsockname()[1] serv.listen(5) conn, addr = serv.accept() except socket.timeout: @@ -80,7 +74,6 @@ conn.close() finally: serv.close() - PORT = None evt.set() @@ -339,14 +332,13 @@ def test_send(self): self.evt = threading.Event() - cap = BytesIO() - threading.Thread(target=capture_server, args=(self.evt, cap)).start() + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.sock.settimeout(3) + self.port = test_support.bind_port(self.sock) - # wait until server thread has assigned a port number - n = 1000 - while PORT is None and n > 0: - time.sleep(0.01) - n -= 1 + cap = BytesIO() + args = (self.evt, cap, self.sock) + threading.Thread(target=capture_server, args=args).start() # wait a little longer for the server to initialize (it sometimes # refuses connections on slow machines without this wait) @@ -355,7 +347,7 @@ data = b"Suppose there isn't a 16-ton weight?" d = dispatcherwithsend_noread() d.create_socket(socket.AF_INET, socket.SOCK_STREAM) - d.connect((HOST, PORT)) + d.connect((HOST, self.port)) # give time for socket to connect time.sleep(0.1) Modified: python/branches/py3k/Lib/test/test_capi.py ============================================================================== --- python/branches/py3k/Lib/test/test_capi.py (original) +++ python/branches/py3k/Lib/test/test_capi.py Wed Apr 9 10:37:03 2008 @@ -16,9 +16,6 @@ # some extra thread-state tests driven via _testcapi def TestThreadState(): - import thread - import time - if test_support.verbose: print("auto-thread-state") @@ -42,6 +39,8 @@ have_thread_state = False if have_thread_state: + import thread + import time TestThreadState() import threading t=threading.Thread(target=TestThreadState) Modified: python/branches/py3k/Lib/test/test_ftplib.py ============================================================================== --- python/branches/py3k/Lib/test/test_ftplib.py (original) +++ python/branches/py3k/Lib/test/test_ftplib.py Wed Apr 9 10:37:03 2008 @@ -6,18 +6,13 @@ from unittest import TestCase from test import test_support -server_port = None +HOST = test_support.HOST # This function sets the evt 3 times: # 1) when the connection is ready to be accepted. # 2) when it is safe for the caller to close the connection # 3) when we have closed the socket -def server(evt): - global server_port - serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - serv.settimeout(3) - serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - server_port = test_support.bind_port(serv, "", 9091) +def server(evt, serv): serv.listen(5) # (1) Signal the caller that we are ready to accept the connection. @@ -40,14 +35,16 @@ def setUp(self): self.evt = threading.Event() - threading.Thread(target=server, args=(self.evt,)).start() + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.sock.settimeout(3) + self.port = test_support.bind_port(self.sock) + threading.Thread(target=server, args=(self.evt,self.sock)).start() # Wait for the server to be ready. self.evt.wait() self.evt.clear() - ftplib.FTP.port = server_port + ftplib.FTP.port = self.port def tearDown(self): - # Wait on the closing of the socket (this shouldn't be necessary). self.evt.wait() def testBasic(self): @@ -55,34 +52,34 @@ ftplib.FTP() # connects - ftp = ftplib.FTP("localhost") + ftp = ftplib.FTP(HOST) self.evt.wait() ftp.sock.close() def testTimeoutDefault(self): # default - ftp = ftplib.FTP("localhost") + ftp = ftplib.FTP(HOST) self.assertTrue(ftp.sock.gettimeout() is None) self.evt.wait() ftp.sock.close() def testTimeoutValue(self): # a value - ftp = ftplib.FTP("localhost", timeout=30) + ftp = ftplib.FTP(HOST, timeout=30) self.assertEqual(ftp.sock.gettimeout(), 30) self.evt.wait() ftp.sock.close() def testTimeoutConnect(self): ftp = ftplib.FTP() - ftp.connect("localhost", timeout=30) + ftp.connect(HOST, timeout=30) self.assertEqual(ftp.sock.gettimeout(), 30) self.evt.wait() ftp.sock.close() def testTimeoutDifferentOrder(self): ftp = ftplib.FTP(timeout=30) - ftp.connect("localhost") + ftp.connect(HOST) self.assertEqual(ftp.sock.gettimeout(), 30) self.evt.wait() ftp.sock.close() @@ -90,7 +87,7 @@ def testTimeoutDirectAccess(self): ftp = ftplib.FTP() ftp.timeout = 30 - ftp.connect("localhost") + ftp.connect(HOST) self.assertEqual(ftp.sock.gettimeout(), 30) self.evt.wait() ftp.sock.close() @@ -100,7 +97,7 @@ previous = socket.getdefaulttimeout() socket.setdefaulttimeout(30) try: - ftp = ftplib.FTP("localhost", timeout=None) + ftp = ftplib.FTP(HOST, timeout=None) finally: socket.setdefaulttimeout(previous) self.assertEqual(ftp.sock.gettimeout(), 30) Modified: python/branches/py3k/Lib/test/test_httplib.py ============================================================================== --- python/branches/py3k/Lib/test/test_httplib.py (original) +++ python/branches/py3k/Lib/test/test_httplib.py Wed Apr 9 10:37:03 2008 @@ -6,6 +6,8 @@ from test import test_support +HOST = test_support.HOST + class FakeSocket: def __init__(self, text, fileclass=io.BytesIO): if isinstance(text, str): @@ -199,16 +201,12 @@ def test_responses(self): self.assertEquals(httplib.responses[httplib.NOT_FOUND], "Not Found") -PORT = 50003 -HOST = "localhost" - class TimeoutTest(TestCase): + PORT = None def setUp(self): self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - global PORT - PORT = test_support.bind_port(self.serv, HOST, PORT) + TimeoutTest.PORT = test_support.bind_port(self.serv) self.serv.listen(5) def tearDown(self): @@ -220,13 +218,13 @@ # and into the socket. # default - httpConn = httplib.HTTPConnection(HOST, PORT) + httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT) httpConn.connect() self.assertTrue(httpConn.sock.gettimeout() is None) httpConn.close() # a value - httpConn = httplib.HTTPConnection(HOST, PORT, timeout=30) + httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30) httpConn.connect() self.assertEqual(httpConn.sock.gettimeout(), 30) httpConn.close() @@ -235,7 +233,8 @@ previous = socket.getdefaulttimeout() socket.setdefaulttimeout(30) try: - httpConn = httplib.HTTPConnection(HOST, PORT, timeout=None) + httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT, + timeout=None) httpConn.connect() finally: socket.setdefaulttimeout(previous) @@ -249,11 +248,12 @@ def test_attributes(self): # simple test to check it's storing it if hasattr(httplib, 'HTTPSConnection'): - h = httplib.HTTPSConnection(HOST, PORT, timeout=30) + h = httplib.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30) self.assertEqual(h.timeout, 30) def test_main(verbose=None): - test_support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest, HTTPSTimeoutTest) + test_support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest, + HTTPSTimeoutTest) if __name__ == '__main__': test_main() Modified: python/branches/py3k/Lib/test/test_poplib.py ============================================================================== --- python/branches/py3k/Lib/test/test_poplib.py (original) +++ python/branches/py3k/Lib/test/test_poplib.py Wed Apr 9 10:37:03 2008 @@ -6,14 +6,10 @@ from unittest import TestCase from test import test_support +HOST = test_support.HOST -def server(ready, evt): - serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - serv.settimeout(3) - serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - serv.bind(("", 9091)) +def server(evt, serv): serv.listen(5) - ready.set() try: conn, addr = serv.accept() except socket.timeout: @@ -29,27 +25,29 @@ def setUp(self): self.evt = threading.Event() - self.ready = threading.Event() - threading.Thread(target=server, args=(self.ready, self.evt,)).start() - self.ready.wait() + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.sock.settimeout(3) + self.port = test_support.bind_port(self.sock) + threading.Thread(target=server, args=(self.evt,self.sock)).start() + time.sleep(.1) def tearDown(self): self.evt.wait() def testBasic(self): # connects - pop = poplib.POP3("localhost", 9091) + pop = poplib.POP3(HOST, self.port) pop.sock.close() def testTimeoutDefault(self): # default - pop = poplib.POP3("localhost", 9091) + pop = poplib.POP3(HOST, self.port) self.assertTrue(pop.sock.gettimeout() is None) pop.sock.close() def testTimeoutValue(self): # a value - pop = poplib.POP3("localhost", 9091, timeout=30) + pop = poplib.POP3(HOST, self.port, timeout=30) self.assertEqual(pop.sock.gettimeout(), 30) pop.sock.close() @@ -58,7 +56,7 @@ previous = socket.getdefaulttimeout() socket.setdefaulttimeout(30) try: - pop = poplib.POP3("localhost", 9091, timeout=None) + pop = poplib.POP3(HOST, self.port, timeout=None) finally: socket.setdefaulttimeout(previous) self.assertEqual(pop.sock.gettimeout(), 30) Modified: python/branches/py3k/Lib/test/test_signal.py ============================================================================== --- python/branches/py3k/Lib/test/test_signal.py (original) +++ python/branches/py3k/Lib/test/test_signal.py Wed Apr 9 10:37:03 2008 @@ -48,16 +48,21 @@ if self.using_gc: gc.enable() - def handlerA(self, *args): + def format_frame(self, frame, limit=None): + return ''.join(traceback.format_stack(frame, limit=limit)) + + def handlerA(self, signum, frame): self.a_called = True if test_support.verbose: - print("handlerA invoked", args) + print("handlerA invoked from signal %s at:\n%s" % ( + signum, self.format_frame(frame, limit=1))) - def handlerB(self, *args): + def handlerB(self, signum, frame): self.b_called = True if test_support.verbose: - print("handlerB invoked", args) - raise HandlerBCalled(*args) + print ("handlerB invoked from signal %s at:\n%s" % ( + signum, self.format_frame(frame, limit=1))) + raise HandlerBCalled(signum, self.format_frame(frame)) def wait(self, child): """Wait for child to finish, ignoring EINTR.""" @@ -95,6 +100,10 @@ self.assertFalse(self.b_called) self.a_called = False + # Make sure the signal isn't delivered while the previous + # Popen object is being destroyed, because __del__ swallows + # exceptions. + del child try: child = subprocess.Popen(['kill', '-USR1', str(pid)]) # This wait should be interrupted by the signal's exception. Modified: python/branches/py3k/Lib/test/test_smtplib.py ============================================================================== --- python/branches/py3k/Lib/test/test_smtplib.py (original) +++ python/branches/py3k/Lib/test/test_smtplib.py Wed Apr 9 10:37:03 2008 @@ -12,18 +12,9 @@ from unittest import TestCase from test import test_support -# PORT is used to communicate the port number assigned to the server -# to the test client -HOST = "localhost" -PORT = None - -def server(evt, buf): - serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - serv.settimeout(15) - serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - serv.bind(("", 0)) - global PORT - PORT = serv.getsockname()[1] +HOST = test_support.HOST + +def server(evt, buf, serv): serv.listen(5) evt.set() try: @@ -43,14 +34,16 @@ conn.close() finally: serv.close() - PORT = None evt.set() class GeneralTests(TestCase): def setUp(self): self.evt = threading.Event() - servargs = (self.evt, b"220 Hola mundo\n") + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.sock.settimeout(15) + self.port = test_support.bind_port(self.sock) + servargs = (self.evt, b"220 Hola mundo\n", self.sock) threading.Thread(target=server, args=servargs).start() self.evt.wait() self.evt.clear() @@ -60,29 +53,29 @@ def testBasic1(self): # connects - smtp = smtplib.SMTP(HOST, PORT) + smtp = smtplib.SMTP(HOST, self.port) smtp.sock.close() def testBasic2(self): # connects, include port in host name - smtp = smtplib.SMTP("%s:%s" % (HOST, PORT)) + smtp = smtplib.SMTP("%s:%s" % (HOST, self.port)) smtp.sock.close() def testLocalHostName(self): # check that supplied local_hostname is used - smtp = smtplib.SMTP(HOST, PORT, local_hostname="testhost") + smtp = smtplib.SMTP(HOST, self.port, local_hostname="testhost") self.assertEqual(smtp.local_hostname, "testhost") smtp.sock.close() def testTimeoutDefault(self): # default - smtp = smtplib.SMTP(HOST, PORT) + smtp = smtplib.SMTP(HOST, self.port) self.assertTrue(smtp.sock.gettimeout() is None) smtp.sock.close() def testTimeoutValue(self): # a value - smtp = smtplib.SMTP(HOST, PORT, timeout=30) + smtp = smtplib.SMTP(HOST, self.port, timeout=30) self.assertEqual(smtp.sock.gettimeout(), 30) smtp.sock.close() @@ -91,7 +84,7 @@ previous = socket.getdefaulttimeout() socket.setdefaulttimeout(30) try: - smtp = smtplib.SMTP(HOST, PORT, timeout=None) + smtp = smtplib.SMTP(HOST, self.port, timeout=None) finally: socket.setdefaulttimeout(previous) self.assertEqual(smtp.sock.gettimeout(), 30) @@ -99,10 +92,7 @@ # Test server thread using the specified SMTP server class -def debugging_server(server_class, serv_evt, client_evt): - serv = server_class(("", 0), ('nowhere', -1)) - global PORT - PORT = serv.getsockname()[1] +def debugging_server(serv, serv_evt, client_evt): serv_evt.set() try: @@ -131,7 +121,6 @@ time.sleep(0.5) serv.close() asyncore.close_all() - PORT = None serv_evt.set() MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n' @@ -153,7 +142,9 @@ self.serv_evt = threading.Event() self.client_evt = threading.Event() - serv_args = (smtpd.DebuggingServer, self.serv_evt, self.client_evt) + self.port = test_support.find_unused_port() + self.serv = smtpd.DebuggingServer((HOST, self.port), ('nowhere', -1)) + serv_args = (self.serv, self.serv_evt, self.client_evt) threading.Thread(target=debugging_server, args=serv_args).start() # wait until server thread has assigned a port number @@ -170,31 +161,31 @@ def testBasic(self): # connect - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) smtp.quit() def testNOOP(self): - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) expected = (250, b'Ok') self.assertEqual(smtp.noop(), expected) smtp.quit() def testRSET(self): - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) expected = (250, b'Ok') self.assertEqual(smtp.rset(), expected) smtp.quit() def testNotImplemented(self): # EHLO isn't implemented in DebuggingServer - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) expected = (502, b'Error: command "EHLO" not implemented') self.assertEqual(smtp.ehlo(), expected) smtp.quit() def testVRFY(self): # VRFY isn't implemented in DebuggingServer - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) expected = (502, b'Error: command "VRFY" not implemented') self.assertEqual(smtp.vrfy('nobody at nowhere.com'), expected) self.assertEqual(smtp.verify('nobody at nowhere.com'), expected) @@ -203,21 +194,21 @@ def testSecondHELO(self): # check that a second HELO returns a message that it's a duplicate # (this behavior is specific to smtpd.SMTPChannel) - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) smtp.helo() expected = (503, b'Duplicate HELO/EHLO') self.assertEqual(smtp.helo(), expected) smtp.quit() def testHELP(self): - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) self.assertEqual(smtp.help(), b'Error: command "HELP" not implemented') smtp.quit() def testSend(self): # connect and send mail m = 'A test message' - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) smtp.sendmail('John', 'Sally', m) smtp.quit() @@ -257,7 +248,10 @@ sys.stdout = self.output self.evt = threading.Event() - servargs = (self.evt, b"199 no hello for you!\n") + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.sock.settimeout(15) + self.port = test_support.bind_port(self.sock) + servargs = (self.evt, b"199 no hello for you!\n", self.sock) threading.Thread(target=server, args=servargs).start() self.evt.wait() self.evt.clear() @@ -268,7 +262,7 @@ def testFailingHELO(self): self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP, - HOST, PORT, 'localhost', 3) + HOST, self.port, 'localhost', 3) sim_users = {'Mr.A at somewhere.com':'John A', @@ -333,7 +327,9 @@ def setUp(self): self.serv_evt = threading.Event() self.client_evt = threading.Event() - serv_args = (SimSMTPServer, self.serv_evt, self.client_evt) + self.port = test_support.find_unused_port() + self.serv = SimSMTPServer((HOST, self.port), ('nowhere', -1)) + serv_args = (self.serv, self.serv_evt, self.client_evt) threading.Thread(target=debugging_server, args=serv_args).start() # wait until server thread has assigned a port number @@ -348,11 +344,11 @@ def testBasic(self): # smoke test - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=15) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15) smtp.quit() def testEHLO(self): - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=15) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15) # no features should be present before the EHLO self.assertEqual(smtp.esmtp_features, {}) @@ -373,7 +369,7 @@ smtp.quit() def testVRFY(self): - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=15) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15) for email, name in sim_users.items(): expected_known = (250, bytes('%s %s' % @@ -388,7 +384,7 @@ smtp.quit() def testEXPN(self): - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=15) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15) for listname, members in sim_lists.items(): users = [] Modified: python/branches/py3k/Lib/test/test_socket.py ============================================================================== --- python/branches/py3k/Lib/test/test_socket.py (original) +++ python/branches/py3k/Lib/test/test_socket.py Wed Apr 9 10:37:03 2008 @@ -3,6 +3,7 @@ import unittest from test import test_support +import errno import socket import select import thread, threading @@ -15,17 +16,14 @@ from weakref import proxy import signal -PORT = 50007 -HOST = 'localhost' +HOST = test_support.HOST MSG = b'Michael Gilfix was here\n' class SocketTCPTest(unittest.TestCase): def setUp(self): self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - global PORT - PORT = test_support.bind_port(self.serv, HOST, PORT) + self.port = test_support.bind_port(self.serv) self.serv.listen(1) def tearDown(self): @@ -36,9 +34,7 @@ def setUp(self): self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - global PORT - PORT = test_support.bind_port(self.serv, HOST, PORT) + self.port = test_support.bind_port(self.serv) def tearDown(self): self.serv.close() @@ -190,7 +186,7 @@ def clientSetUp(self): ThreadedTCPSocketTest.clientSetUp(self) - self.cli.connect((HOST, PORT)) + self.cli.connect((HOST, self.port)) self.serv_conn = self.cli def clientTearDown(self): @@ -470,16 +466,23 @@ # XXX The following don't test module-level functionality... def testSockName(self): - # Testing getsockname() + # Testing getsockname(). Use a temporary socket to elicit an unused + # ephemeral port that we can use later in the test. + tempsock = socket.socket() + tempsock.bind(("0.0.0.0", 0)) + (host, port) = tempsock.getsockname() + tempsock.close() + del tempsock + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.bind(("0.0.0.0", PORT+1)) + sock.bind(("0.0.0.0", port)) name = sock.getsockname() # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate # it reasonable to get the host's addr in addition to 0.0.0.0. # At least for eCos. This is required for the S/390 to pass. my_ip_addr = socket.gethostbyname(socket.gethostname()) self.assert_(name[0] in ("0.0.0.0", my_ip_addr), '%s invalid' % name[0]) - self.assertEqual(name[1], PORT+1) + self.assertEqual(name[1], port) def testGetSockOpt(self): # Testing getsockopt() @@ -615,7 +618,7 @@ self.assertEqual(msg, MSG) def _testSendtoAndRecv(self): - self.cli.sendto(MSG, 0, (HOST, PORT)) + self.cli.sendto(MSG, 0, (HOST, self.port)) def testRecvFrom(self): # Testing recvfrom() over UDP @@ -623,14 +626,14 @@ self.assertEqual(msg, MSG) def _testRecvFrom(self): - self.cli.sendto(MSG, 0, (HOST, PORT)) + self.cli.sendto(MSG, 0, (HOST, self.port)) def testRecvFromNegative(self): # Negative lengths passed to recvfrom should give ValueError. self.assertRaises(ValueError, self.serv.recvfrom, -1) def _testRecvFromNegative(self): - self.cli.sendto(MSG, 0, (HOST, PORT)) + self.cli.sendto(MSG, 0, (HOST, self.port)) class TCPCloserTest(ThreadedTCPSocketTest): @@ -648,7 +651,7 @@ conn.close() def _testClose(self): - self.cli.connect((HOST, PORT)) + self.cli.connect((HOST, self.port)) time.sleep(1.0) class BasicSocketPairTest(SocketPairTest): @@ -706,7 +709,7 @@ def _testAccept(self): time.sleep(0.1) - self.cli.connect((HOST, PORT)) + self.cli.connect((HOST, self.port)) def testConnect(self): # Testing non-blocking connect @@ -714,7 +717,7 @@ def _testConnect(self): self.cli.settimeout(10) - self.cli.connect((HOST, PORT)) + self.cli.connect((HOST, self.port)) def testRecv(self): # Testing non-blocking recv @@ -734,7 +737,7 @@ self.fail("Error during select call to non-blocking socket.") def _testRecv(self): - self.cli.connect((HOST, PORT)) + self.cli.connect((HOST, self.port)) time.sleep(0.1) self.cli.send(MSG) @@ -883,7 +886,9 @@ """Prove network connection.""" def clientSetUp(self): - self.cli = socket.create_connection((HOST, PORT)) + # We're inherited below by BasicTCPTest2, which also inherits + # BasicTCPTest, which defines self.port referenced below. + self.cli = socket.create_connection((HOST, self.port)) self.serv_conn = self.cli class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest): @@ -893,7 +898,11 @@ class NetworkConnectionNoServer(unittest.TestCase): def testWithoutServer(self): - self.failUnlessRaises(socket.error, lambda: socket.create_connection((HOST, PORT))) + port = test_support.find_unused_port() + self.failUnlessRaises( + socket.error, + lambda: socket.create_connection((HOST, port)) + ) class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest): @@ -914,22 +923,22 @@ testFamily = _justAccept def _testFamily(self): - self.cli = socket.create_connection((HOST, PORT), timeout=30) + self.cli = socket.create_connection((HOST, self.port), timeout=30) self.assertEqual(self.cli.family, 2) testTimeoutDefault = _justAccept def _testTimeoutDefault(self): - self.cli = socket.create_connection((HOST, PORT)) + self.cli = socket.create_connection((HOST, self.port)) self.assertTrue(self.cli.gettimeout() is None) testTimeoutValueNamed = _justAccept def _testTimeoutValueNamed(self): - self.cli = socket.create_connection((HOST, PORT), timeout=30) + self.cli = socket.create_connection((HOST, self.port), timeout=30) self.assertEqual(self.cli.gettimeout(), 30) testTimeoutValueNonamed = _justAccept def _testTimeoutValueNonamed(self): - self.cli = socket.create_connection((HOST, PORT), 30) + self.cli = socket.create_connection((HOST, self.port), 30) self.assertEqual(self.cli.gettimeout(), 30) testTimeoutNone = _justAccept @@ -937,7 +946,7 @@ previous = socket.getdefaulttimeout() socket.setdefaulttimeout(30) try: - self.cli = socket.create_connection((HOST, PORT), timeout=None) + self.cli = socket.create_connection((HOST, self.port), timeout=None) finally: socket.setdefaulttimeout(previous) self.assertEqual(self.cli.gettimeout(), 30) @@ -964,12 +973,12 @@ testOutsideTimeout = testInsideTimeout def _testInsideTimeout(self): - self.cli = sock = socket.create_connection((HOST, PORT)) + self.cli = sock = socket.create_connection((HOST, self.port)) data = sock.recv(5) self.assertEqual(data, b"done!") def _testOutsideTimeout(self): - self.cli = sock = socket.create_connection((HOST, PORT), timeout=1) + self.cli = sock = socket.create_connection((HOST, self.port), timeout=1) self.failUnlessRaises(socket.timeout, lambda: sock.recv(5)) Modified: python/branches/py3k/Lib/test/test_socketserver.py ============================================================================== --- python/branches/py3k/Lib/test/test_socketserver.py (original) +++ python/branches/py3k/Lib/test/test_socketserver.py Wed Apr 9 10:37:03 2008 @@ -22,7 +22,7 @@ test.test_support.requires("network") TEST_STR = b"hello world\n" -HOST = "localhost" +HOST = test.test_support.HOST HAVE_UNIX_SOCKETS = hasattr(socket, "AF_UNIX") HAVE_FORKING = hasattr(os, "fork") and os.name != "os2" Modified: python/branches/py3k/Lib/test/test_ssl.py ============================================================================== --- python/branches/py3k/Lib/test/test_ssl.py (original) +++ python/branches/py3k/Lib/test/test_ssl.py Wed Apr 9 10:37:03 2008 @@ -25,11 +25,10 @@ except ImportError: skip_expected = True +HOST = test_support.HOST CERTFILE = None SVN_PYTHON_ORG_ROOT_CERT = None -TESTPORT = 10025 - def handle_error(prefix): exc_format = ' '.join(traceback.format_exception(*sys.exc_info())) if test_support.verbose: @@ -299,7 +298,7 @@ except: handle_error('') - def __init__(self, port, certificate, ssl_version=None, + def __init__(self, certificate, ssl_version=None, certreqs=None, cacerts=None, expect_bad_connects=False, chatty=True, connectionchatty=False, starttls_server=False): if ssl_version is None: @@ -315,12 +314,8 @@ self.connectionchatty = connectionchatty self.starttls_server = starttls_server self.sock = socket.socket() + self.port = test_support.bind_port(self.sock) self.flag = None - if hasattr(socket, 'SO_REUSEADDR'): - self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - if hasattr(socket, 'SO_REUSEPORT'): - self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) - self.sock.bind(('127.0.0.1', port)) self.active = False threading.Thread.__init__(self) self.setDaemon(False) @@ -471,12 +466,13 @@ format%args)) - def __init__(self, port, certfile): + def __init__(self, certfile): self.flag = None self.active = False self.RootedHTTPRequestHandler.root = os.path.split(CERTFILE)[0] + self.port = test_support.find_unused_port() self.server = self.HTTPSServer( - ('', port), self.RootedHTTPRequestHandler, certfile) + (HOST, self.port), self.RootedHTTPRequestHandler, certfile) threading.Thread.__init__(self) self.setDaemon(True) @@ -586,7 +582,7 @@ self.server.close() def badCertTest (certfile): - server = ThreadedEchoServer(TESTPORT, CERTFILE, + server = ThreadedEchoServer(CERTFILE, certreqs=ssl.CERT_REQUIRED, cacerts=CERTFILE, chatty=False, connectionchatty=False) @@ -600,7 +596,7 @@ s = ssl.wrap_socket(socket.socket(), certfile=certfile, ssl_version=ssl.PROTOCOL_TLSv1) - s.connect(('127.0.0.1', TESTPORT)) + s.connect((HOST, server.port)) except ssl.SSLError as x: if test_support.verbose: sys.stdout.write("\nSSLError is %s\n" % x) @@ -616,7 +612,7 @@ indata="FOO\n", chatty=False, connectionchatty=False): - server = ThreadedEchoServer(TESTPORT, certfile, + server = ThreadedEchoServer(certfile, certreqs=certreqs, ssl_version=protocol, cacerts=cacertsfile, @@ -631,12 +627,11 @@ client_protocol = protocol try: s = ssl.wrap_socket(socket.socket(), - server_side=False, certfile=client_certfile, ca_certs=cacertsfile, cert_reqs=certreqs, ssl_version=client_protocol) - s.connect(('127.0.0.1', TESTPORT)) + s.connect((HOST, server.port)) except ssl.SSLError as x: raise test_support.TestFailed("Unexpected SSL error: " + str(x)) except Exception as x: @@ -646,18 +641,17 @@ if test_support.verbose: sys.stdout.write( " client: sending %s...\n" % (repr(indata))) - s.write(indata.encode('ASCII', 'strict')) + s.write(indata) outdata = s.read() if connectionchatty: if test_support.verbose: sys.stdout.write(" client: read %s\n" % repr(outdata)) - outdata = str(outdata, 'ASCII', 'strict') if outdata != indata.lower(): raise test_support.TestFailed( "bad data <<%s>> (%d) received; expected <<%s>> (%d)\n" - % (repr(outdata[:min(len(outdata),20)]), len(outdata), - repr(indata[:min(len(indata),20)].lower()), len(indata))) - s.write("over\n".encode("ASCII", "strict")) + % (outdata[:min(len(outdata),20)], len(outdata), + indata[:min(len(indata),20)].lower(), len(indata))) + s.write("over\n") if connectionchatty: if test_support.verbose: sys.stdout.write(" client: closing connection.\n") @@ -703,7 +697,44 @@ class ThreadedTests(unittest.TestCase): - def testEcho (self): + def testRudeShutdown(self): + + listener_ready = threading.Event() + listener_gone = threading.Event() + port = test_support.find_unused_port() + + # `listener` runs in a thread. It opens a socket listening on + # PORT, and sits in an accept() until the main thread connects. + # Then it rudely closes the socket, and sets Event `listener_gone` + # to let the main thread know the socket is gone. + def listener(): + s = socket.socket() + s.bind((HOST, port)) + s.listen(5) + listener_ready.set() + s.accept() + s = None # reclaim the socket object, which also closes it + listener_gone.set() + + def connector(): + listener_ready.wait() + s = socket.socket() + s.connect((HOST, port)) + listener_gone.wait() + try: + ssl_sock = ssl.wrap_socket(s) + except IOError: + pass + else: + raise test_support.TestFailed( + 'connecting to closed SSL socket should have failed') + + t = threading.Thread(target=listener) + t.start() + connector() + t.join() + + def testEcho(self): if test_support.verbose: sys.stdout.write("\n") @@ -716,7 +747,7 @@ if test_support.verbose: sys.stdout.write("\n") s2 = socket.socket() - server = ThreadedEchoServer(TESTPORT, CERTFILE, + server = ThreadedEchoServer(CERTFILE, certreqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_SSLv23, cacerts=CERTFILE, @@ -733,7 +764,7 @@ ca_certs=CERTFILE, cert_reqs=ssl.CERT_REQUIRED, ssl_version=ssl.PROTOCOL_SSLv23) - s.connect(('127.0.0.1', TESTPORT)) + s.connect((HOST, server.port)) except ssl.SSLError as x: raise test_support.TestFailed( "Unexpected SSL error: " + str(x)) @@ -776,46 +807,6 @@ badCertTest(os.path.join(os.path.dirname(__file__) or os.curdir, "badkey.pem")) - def testRudeShutdown(self): - - listener_ready = threading.Event() - listener_gone = threading.Event() - - # `listener` runs in a thread. It opens a socket listening on - # PORT, and sits in an accept() until the main thread connects. - # Then it rudely closes the socket, and sets Event `listener_gone` - # to let the main thread know the socket is gone. - def listener(): - s = socket.socket() - if hasattr(socket, 'SO_REUSEADDR'): - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - if hasattr(socket, 'SO_REUSEPORT'): - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) - s.bind(('127.0.0.1', TESTPORT)) - s.listen(5) - listener_ready.set() - s.accept() - s = None # reclaim the socket object, which also closes it - listener_gone.set() - - def connector(): - listener_ready.wait() - s = socket.socket() - s.connect(('127.0.0.1', TESTPORT)) - listener_gone.wait() - try: - ssl_sock = ssl.wrap_socket(s) - except IOError: - pass - else: - raise test_support.TestFailed( - 'connecting to closed SSL socket should have failed') - - t = threading.Thread(target=listener) - t.start() - connector() - t.join() - def testProtocolSSL2(self): if test_support.verbose: sys.stdout.write("\n") @@ -873,7 +864,7 @@ msgs = ("msg 1", "MSG 2", "STARTTLS", "MSG 3", "msg 4") - server = ThreadedEchoServer(TESTPORT, CERTFILE, + server = ThreadedEchoServer(CERTFILE, ssl_version=ssl.PROTOCOL_TLSv1, starttls_server=True, chatty=True, @@ -888,7 +879,7 @@ try: s = socket.socket() s.setblocking(1) - s.connect(('127.0.0.1', TESTPORT)) + s.connect((HOST, server.port)) except Exception as x: raise test_support.TestFailed("Unexpected exception: " + str(x)) else: @@ -936,7 +927,8 @@ def testSocketServer(self): - server = OurHTTPSServer(TESTPORT, CERTFILE) + + server = AsyncoreHTTPSServer(CERTFILE) flag = threading.Event() server.start(flag) # wait for it to start @@ -948,8 +940,8 @@ d1 = open(CERTFILE, 'rb').read() d2 = '' # now fetch the same data from the HTTPS server - url = 'https://127.0.0.1:%d/%s' % ( - TESTPORT, os.path.split(CERTFILE)[1]) + url = 'https://%s:%d/%s' % ( + HOST, server.port, os.path.split(CERTFILE)[1]) f = urllib.urlopen(url) dlen = f.info().getheader("content-length") if dlen and (int(dlen) > 0): @@ -978,71 +970,11 @@ sys.stdout.write('joining thread\n') server.join() - def testAsyncoreServer(self): - - if test_support.verbose: - sys.stdout.write("\n") - - indata="FOO\n" - server = AsyncoreEchoServer(TESTPORT, CERTFILE) - flag = threading.Event() - server.start(flag) - # wait for it to start - flag.wait() - # try to connect - try: - s = ssl.wrap_socket(socket.socket()) - s.connect(('127.0.0.1', TESTPORT)) - except ssl.SSLError as x: - raise test_support.TestFailed("Unexpected SSL error: " + str(x)) - except Exception as x: - raise test_support.TestFailed("Unexpected exception: " + str(x)) - else: - if test_support.verbose: - sys.stdout.write( - " client: sending %s...\n" % (repr(indata))) - s.sendall(indata.encode('ASCII', 'strict')) - outdata = s.recv() - if test_support.verbose: - sys.stdout.write(" client: read %s\n" % repr(outdata)) - outdata = str(outdata, 'ASCII', 'strict') - if outdata != indata.lower(): - raise test_support.TestFailed( - "bad data <<%s>> (%d) received; expected <<%s>> (%d)\n" - % (repr(outdata[:min(len(outdata),20)]), len(outdata), - repr(indata[:min(len(indata),20)].lower()), len(indata))) - s.write("over\n".encode("ASCII", "strict")) - if test_support.verbose: - sys.stdout.write(" client: closing connection.\n") - s.close() - finally: - server.stop() - server.join() - - -def findtestsocket(start, end): - def testbind(i): - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - try: - s.bind(("127.0.0.1", i)) - except: - return 0 - else: - return 1 - finally: - s.close() - - for i in range(start, end): - if testbind(i) and testbind(i+1): - return i - return 0 - - def test_main(verbose=False): if skip_expected: raise test_support.TestSkipped("No SSL support") - global CERTFILE, TESTPORT, SVN_PYTHON_ORG_ROOT_CERT + global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir, "keycert.pem") SVN_PYTHON_ORG_ROOT_CERT = os.path.join( @@ -1053,10 +985,6 @@ not os.path.exists(SVN_PYTHON_ORG_ROOT_CERT)): raise test_support.TestFailed("Can't read certificate files!") - TESTPORT = findtestsocket(10025, 12000) - if not TESTPORT: - raise test_support.TestFailed("Can't find open port to test servers on!") - tests = [BasicTests] if test_support.is_resource_enabled('network'): Modified: python/branches/py3k/Lib/test/test_sundry.py ============================================================================== --- python/branches/py3k/Lib/test/test_sundry.py (original) +++ python/branches/py3k/Lib/test/test_sundry.py Wed Apr 9 10:37:03 2008 @@ -1,111 +1,119 @@ """Do a minimal test of all the modules that aren't otherwise tested.""" -from test.test_support import catch_warning +from test import test_support import sys +import unittest import warnings -with catch_warning(): - from test.test_support import verbose +class TestUntestedModules(unittest.TestCase): + def test_at_least_import_untested_modules(self): + with test_support.catch_warning(): + import BaseHTTPServer + import DocXMLRPCServer + import CGIHTTPServer + import SimpleHTTPServer + import SimpleXMLRPCServer + import aifc + import bdb + import cgitb + import cmd + import code + import compileall + + import distutils.archive_util + import distutils.bcppcompiler + import distutils.ccompiler + import distutils.cmd + import distutils.core + import distutils.cygwinccompiler + import distutils.dep_util + import distutils.dir_util + import distutils.emxccompiler + import distutils.errors + import distutils.extension + import distutils.file_util + import distutils.filelist + import distutils.log + if sys.platform.startswith('win'): + import distutils.msvccompiler + import distutils.mwerkscompiler + import distutils.sysconfig + import distutils.text_file + import distutils.unixccompiler + import distutils.util + import distutils.version + + import distutils.command.bdist_dumb + if sys.platform.startswith('win'): + import distutils.command.bdist_msi + import distutils.command.bdist + import distutils.command.bdist_rpm + import distutils.command.bdist_wininst + import distutils.command.build_clib + import distutils.command.build_ext + import distutils.command.build + import distutils.command.build_py + import distutils.command.build_scripts + import distutils.command.clean + import distutils.command.config + import distutils.command.install_data + import distutils.command.install_egg_info + import distutils.command.install_headers + import distutils.command.install_lib + import distutils.command.install + import distutils.command.install_scripts + import distutils.command.register + import distutils.command.sdist + import distutils.command.upload + + import encodings + import formatter + import ftplib + import getpass + import htmlentitydefs + import ihooks + import imghdr + import imputil + import keyword + import linecache + import macurl2path + import mailcap + import mutex + import nntplib + import nturl2path + import opcode + import os2emxpath + import pdb + import pstats + import py_compile + import pydoc + import rlcompleter + import sched + import smtplib + import sndhdr + import statvfs + import sunau + import sunaudio + import symbol + import tabnanny + import telnetlib + import timeit + import token + try: + import tty # not available on Windows + except ImportError: + if test_support.verbose: + print("skipping tty") + + # Can't test the "user" module -- if the user has a ~/.pythonrc.py, it + # can screw up all sorts of things (esp. if it prints!). + #import user + import webbrowser + import xml - import BaseHTTPServer - import DocXMLRPCServer - import CGIHTTPServer - import SimpleHTTPServer - import SimpleXMLRPCServer - import aifc - import bdb - import cgitb - import cmd - import code - import compileall - - import distutils.archive_util - import distutils.bcppcompiler - import distutils.ccompiler - import distutils.cmd - import distutils.core - import distutils.cygwinccompiler - import distutils.dep_util - import distutils.dir_util - import distutils.emxccompiler - import distutils.errors - import distutils.extension - import distutils.file_util - import distutils.filelist - import distutils.log - if sys.platform.startswith('win'): - import distutils.msvccompiler - import distutils.mwerkscompiler - import distutils.sysconfig - import distutils.text_file - import distutils.unixccompiler - import distutils.util - import distutils.version - - import distutils.command.bdist_dumb - if sys.platform.startswith('win'): - import distutils.command.bdist_msi - import distutils.command.bdist - import distutils.command.bdist_rpm - import distutils.command.bdist_wininst - import distutils.command.build_clib - import distutils.command.build_ext - import distutils.command.build - import distutils.command.build_py - import distutils.command.build_scripts - import distutils.command.clean - import distutils.command.config - import distutils.command.install_data - import distutils.command.install_egg_info - import distutils.command.install_headers - import distutils.command.install_lib - import distutils.command.install - import distutils.command.install_scripts - import distutils.command.register - import distutils.command.sdist - import distutils.command.upload - - import encodings - import formatter - import ftplib - import getpass - import htmlentitydefs - import ihooks - import imghdr - import imputil - import keyword - import linecache - import macurl2path - import mailcap - import mutex - import nntplib - import nturl2path - import opcode - import os2emxpath - import pdb - import pstats - import py_compile - import pydoc - import rlcompleter - import sched - import smtplib - import sndhdr - import statvfs - import sunau - import sunaudio - import symbol - import tabnanny - import telnetlib - import timeit - import token - try: - import tty # not available on Windows - except ImportError: - if verbose: - print("skipping tty") - - # Can't test the "user" module -- if the user has a ~/.pythonrc.py, it - # can screw up all sorts of things (esp. if it prints!). - #import user - import webbrowser - import xml + +def test_main(): + test_support.run_unittest(TestUntestedModules) + +if __name__ == "__main__": + test_main() Modified: python/branches/py3k/Lib/test/test_support.py ============================================================================== --- python/branches/py3k/Lib/test/test_support.py (original) +++ python/branches/py3k/Lib/test/test_support.py Wed Apr 9 10:37:03 2008 @@ -103,32 +103,100 @@ msg = "Use of the `%s' resource not enabled" % resource raise ResourceDenied(msg) -def bind_port(sock, host='', preferred_port=54321): - """Try to bind the sock to a port. If we are running multiple - tests and we don't try multiple ports, the test can fail. This - makes the test more robust.""" - - # Find some random ports that hopefully no one is listening on. - # Ideally each test would clean up after itself and not continue listening - # on any ports. However, this isn't the case. The last port (0) is - # a stop-gap that asks the O/S to assign a port. Whenever the warning - # message below is printed, the test that is listening on the port should - # be fixed to close the socket at the end of the test. - # Another reason why we can't use a port is another process (possibly - # another instance of the test suite) is using the same port. - for port in [preferred_port, 9907, 10243, 32999, 0]: - try: - sock.bind((host, port)) - if port == 0: - port = sock.getsockname()[1] - return port - except socket.error as e: - (err, msg) = e.args - if err != errno.EADDRINUSE: - raise - print(' WARNING: failed to listen on port %d, ' % port + - 'trying another', file=sys.__stderr__) - raise TestFailed('unable to find port to listen on') +HOST = 'localhost' + +def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM): + """Returns an unused port that should be suitable for binding. This is + achieved by creating a temporary socket with the same family and type as + the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to + the specified host address (defaults to 0.0.0.0) with the port set to 0, + eliciting an unused ephemeral port from the OS. The temporary socket is + then closed and deleted, and the ephemeral port is returned. + + Either this method or bind_port() should be used for any tests where a + server socket needs to be bound to a particular port for the duration of + the test. Which one to use depends on whether the calling code is creating + a python socket, or if an unused port needs to be provided in a constructor + or passed to an external program (i.e. the -accept argument to openssl's + s_server mode). Always prefer bind_port() over find_unused_port() where + possible. Hard coded ports should *NEVER* be used. As soon as a server + socket is bound to a hard coded port, the ability to run multiple instances + of the test simultaneously on the same host is compromised, which makes the + test a ticking time bomb in a buildbot environment. On Unix buildbots, this + may simply manifest as a failed test, which can be recovered from without + intervention in most cases, but on Windows, the entire python process can + completely and utterly wedge, requiring someone to log in to the buildbot + and manually kill the affected process. + + (This is easy to reproduce on Windows, unfortunately, and can be traced to + the SO_REUSEADDR socket option having different semantics on Windows versus + Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind, + listen and then accept connections on identical host/ports. An EADDRINUSE + socket.error will be raised at some point (depending on the platform and + the order bind and listen were called on each socket). + + However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE + will ever be raised when attempting to bind two identical host/ports. When + accept() is called on each socket, the second caller's process will steal + the port from the first caller, leaving them both in an awkwardly wedged + state where they'll no longer respond to any signals or graceful kills, and + must be forcibly killed via OpenProcess()/TerminateProcess(). + + The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option + instead of SO_REUSEADDR, which effectively affords the same semantics as + SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open + Source world compared to Windows ones, this is a common mistake. A quick + look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when + openssl.exe is called with the 's_server' option, for example. See + http://bugs.python.org/issue2550 for more info. The following site also + has a very thorough description about the implications of both REUSEADDR + and EXCLUSIVEADDRUSE on Windows: + http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx) + + XXX: although this approach is a vast improvement on previous attempts to + elicit unused ports, it rests heavily on the assumption that the ephemeral + port returned to us by the OS won't immediately be dished back out to some + other process when we close and delete our temporary socket but before our + calling code has a chance to bind the returned port. We can deal with this + issue if/when we come across it. + """ + + tempsock = socket.socket(family, socktype) + port = bind_port(tempsock) + tempsock.close() + del tempsock + return port + +def bind_port(sock, host=HOST): + """Bind the socket to a free port and return the port number. Relies on + ephemeral ports in order to ensure we are using an unbound port. This is + important as many tests may be running simultaneously, especially in a + buildbot environment. This method raises an exception if the sock.family + is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR + or SO_REUSEPORT set on it. Tests should *never* set these socket options + for TCP/IP sockets. The only case for setting these options is testing + multicasting via multiple UDP sockets. + + Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e. + on Windows), it will be set on the socket. This will prevent anyone else + from bind()'ing to our host/port for the duration of the test. + """ + + if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM: + if hasattr(socket, 'SO_REUSEADDR'): + if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1: + raise TestFailed("tests should never set the SO_REUSEADDR " \ + "socket option on TCP/IP sockets!") + if hasattr(socket, 'SO_REUSEPORT'): + if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1: + raise TestFailed("tests should never set the SO_REUSEPORT " \ + "socket option on TCP/IP sockets!") + if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'): + sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) + + sock.bind((host, 0)) + port = sock.getsockname()[1] + return port FUZZ = 1e-6 Modified: python/branches/py3k/Lib/test/test_telnetlib.py ============================================================================== --- python/branches/py3k/Lib/test/test_telnetlib.py (original) +++ python/branches/py3k/Lib/test/test_telnetlib.py Wed Apr 9 10:37:03 2008 @@ -6,14 +6,9 @@ from unittest import TestCase from test import test_support -PORT = 9091 +HOST = test_support.HOST -def server(evt): - serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - serv.settimeout(3) - serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - global PORT - PORT = test_support.bind_port(serv, "", PORT) +def server(evt, serv): serv.listen(5) evt.set() try: @@ -28,7 +23,10 @@ def setUp(self): self.evt = threading.Event() - threading.Thread(target=server, args=(self.evt,)).start() + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.sock.settimeout(3) + self.port = test_support.bind_port(self.sock) + threading.Thread(target=server, args=(self.evt,self.sock)).start() self.evt.wait() self.evt.clear() time.sleep(.1) @@ -38,24 +36,24 @@ def testBasic(self): # connects - telnet = telnetlib.Telnet("localhost", PORT) + telnet = telnetlib.Telnet(HOST, self.port) telnet.sock.close() def testTimeoutDefault(self): # default - telnet = telnetlib.Telnet("localhost", PORT) + telnet = telnetlib.Telnet(HOST, self.port) self.assertTrue(telnet.sock.gettimeout() is None) telnet.sock.close() def testTimeoutValue(self): # a value - telnet = telnetlib.Telnet("localhost", PORT, timeout=30) + telnet = telnetlib.Telnet(HOST, self.port, timeout=30) self.assertEqual(telnet.sock.gettimeout(), 30) telnet.sock.close() def testTimeoutDifferentOrder(self): telnet = telnetlib.Telnet(timeout=30) - telnet.open("localhost", PORT) + telnet.open(HOST, self.port) self.assertEqual(telnet.sock.gettimeout(), 30) telnet.sock.close() @@ -64,7 +62,7 @@ previous = socket.getdefaulttimeout() socket.setdefaulttimeout(30) try: - telnet = telnetlib.Telnet("localhost", PORT, timeout=None) + telnet = telnetlib.Telnet(HOST, self.port, timeout=None) finally: socket.setdefaulttimeout(previous) self.assertEqual(telnet.sock.gettimeout(), 30) Modified: python/branches/py3k/Lib/test/test_zlib.py ============================================================================== --- python/branches/py3k/Lib/test/test_zlib.py (original) +++ python/branches/py3k/Lib/test/test_zlib.py Wed Apr 9 10:37:03 2008 @@ -75,6 +75,11 @@ # verify failure on building decompress object with bad params self.assertRaises(ValueError, zlib.decompressobj, 0) + def test_decompressobj_badflush(self): + # verify failure on calling decompressobj.flush with bad params + self.assertRaises(ValueError, zlib.decompressobj().flush, 0) + self.assertRaises(ValueError, zlib.decompressobj().flush, -1) + class CompressTestCase(unittest.TestCase): Modified: python/branches/py3k/Lib/types.py ============================================================================== --- python/branches/py3k/Lib/types.py (original) +++ python/branches/py3k/Lib/types.py Wed Apr 9 10:37:03 2008 @@ -34,16 +34,8 @@ FrameType = type(tb.tb_frame) tb = None; del tb -# Extension types defined in a C helper module. XXX There may be no -# equivalent in implementations other than CPython, so it seems better to -# leave them undefined then to set them to e.g. None. -try: - import _types -except ImportError: - pass -else: - GetSetDescriptorType = type(_types.Helper.getter) - MemberDescriptorType = type(_types.Helper.member) - del _types +# For Jython, the following two types are identical +GetSetDescriptorType = type(FunctionType.__code__) +MemberDescriptorType = type(FunctionType.__globals__) del sys, _f, _g, _C, # Not for export Modified: python/branches/py3k/Makefile.pre.in ============================================================================== --- python/branches/py3k/Makefile.pre.in (original) +++ python/branches/py3k/Makefile.pre.in Wed Apr 9 10:37:03 2008 @@ -331,7 +331,6 @@ ########################################################################## # objects that get linked into the Python library LIBRARY_OBJS= \ - Modules/_typesmodule.o \ Modules/getbuildinfo.o \ $(PARSER_OBJS) \ $(OBJECT_OBJS) \ @@ -369,7 +368,6 @@ $(LIBRARY): $(LIBRARY_OBJS) -rm -f $@ $(AR) cr $@ Modules/getbuildinfo.o - $(AR) cr $@ Modules/_typesmodule.o $(AR) cr $@ $(PARSER_OBJS) $(AR) cr $@ $(OBJECT_OBJS) $(AR) cr $@ $(PYTHON_OBJS) Deleted: /python/branches/py3k/Modules/_typesmodule.c ============================================================================== --- /python/branches/py3k/Modules/_typesmodule.c Wed Apr 9 10:37:03 2008 +++ (empty file) @@ -1,93 +0,0 @@ -/* This extension module exposes some types that are only available at the - * C level. It should not be used directly, but instead through the Python - * level types modules, which imports this. - */ - -#include "Python.h" -#include "structmember.h" - -typedef struct -{ - PyObject_HEAD - int member; -} Helper; - -static PyMemberDef helper_members[] = { - { "member", T_INT, offsetof(Helper, member), READONLY, - PyDoc_STR("A member descriptor") - }, - { NULL } -}; - -static PyObject * -helper_getter(Helper *self, void *unused) -{ - Py_RETURN_NONE; -} - -static PyGetSetDef helper_getset[] = { - { "getter", (getter)helper_getter, NULL, - PyDoc_STR("A getset descriptor"), - }, - { NULL } -}; - -static PyTypeObject HelperType = { - PyVarObject_HEAD_INIT(NULL, 0) - "_types.Helper", /* tp_name */ - sizeof(Helper), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - helper_members, /* tp_members */ - helper_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ -}; - -PyMODINIT_FUNC -init_types(void) -{ - PyObject *m; - - m = Py_InitModule3("_types", NULL, "A types module helper"); - if (!m) - return; - - if (PyType_Ready(&HelperType) < 0) - return; - - Py_INCREF(&HelperType); - PyModule_AddObject(m, "Helper", (PyObject *)&HelperType); -} - - Modified: python/branches/py3k/Modules/config.c.in ============================================================================== --- python/branches/py3k/Modules/config.c.in (original) +++ python/branches/py3k/Modules/config.c.in Wed Apr 9 10:37:03 2008 @@ -28,7 +28,6 @@ extern void initimp(void); extern void initgc(void); extern void init_ast(void); -extern void init_types(void); struct _inittab _PyImport_Inittab[] = { @@ -43,9 +42,6 @@ /* This lives in Python/Python-ast.c */ {"_ast", init_ast}, - /* This lives in Modules/_typesmodule.c */ - {"_types", init_types}, - /* These entries are here for sys.builtin_module_names */ {"__main__", NULL}, {"builtins", NULL}, Modified: python/branches/py3k/Modules/zlibmodule.c ============================================================================== --- python/branches/py3k/Modules/zlibmodule.c (original) +++ python/branches/py3k/Modules/zlibmodule.c Wed Apr 9 10:37:03 2008 @@ -794,6 +794,10 @@ if (!PyArg_ParseTuple(args, "|i:flush", &length)) return NULL; + if (length <= 0) { + PyErr_SetString(PyExc_ValueError, "length must be greater than zero"); + return NULL; + } if (!(retval = PyBytes_FromStringAndSize(NULL, length))) return NULL; Modified: python/branches/py3k/PC/VC6/pythoncore.dsp ============================================================================== --- python/branches/py3k/PC/VC6/pythoncore.dsp (original) +++ python/branches/py3k/PC/VC6/pythoncore.dsp Wed Apr 9 10:37:03 2008 @@ -169,10 +169,6 @@ # End Source File # Begin Source File -SOURCE=..\..\Modules\_typesmodule.c -# End Source File -# Begin Source File - SOURCE=..\..\Modules\_weakref.c # End Source File # Begin Source File Modified: python/branches/py3k/PC/VS7.1/pythoncore.vcproj ============================================================================== --- python/branches/py3k/PC/VS7.1/pythoncore.vcproj (original) +++ python/branches/py3k/PC/VS7.1/pythoncore.vcproj Wed Apr 9 10:37:03 2008 @@ -395,9 +395,6 @@ RelativePath="..\..\Pc\_subprocess.c"> - - - - Modified: python/branches/py3k/PC/_winreg.c ============================================================================== --- python/branches/py3k/PC/_winreg.c (original) +++ python/branches/py3k/PC/_winreg.c Wed Apr 9 10:37:03 2008 @@ -290,20 +290,20 @@ "the configuration registry. This helps the registry perform efficiently."); PyDoc_STRVAR(DisableReflectionKey_doc, -"Disables registry reflection for 32bit processes running on a 64bit\n" +"Disables registry reflection for 32-bit processes running on a 64-bit\n" "Operating System. Will generally raise NotImplemented if executed on\n" -"a 32bit Operating System.\n" +"a 32-bit Operating System.\n" "If the key is not on the reflection list, the function succeeds but has no effect.\n" "Disabling reflection for a key does not affect reflection of any subkeys."); PyDoc_STRVAR(EnableReflectionKey_doc, "Restores registry reflection for the specified disabled key.\n" -"Will generally raise NotImplemented if executed on a 32bit Operating System.\n" +"Will generally raise NotImplemented if executed on a 32-bit Operating System.\n" "Restoring reflection for a key does not affect reflection of any subkeys."); PyDoc_STRVAR(QueryReflectionKey_doc, "bool = QueryReflectionKey(hkey) - Determines the reflection state for the specified key.\n" -"Will generally raise NotImplemented if executed on a 32bit Operating System.\n"); +"Will generally raise NotImplemented if executed on a 32-bit Operating System.\n"); /* PyHKEY docstrings */ PyDoc_STRVAR(PyHKEY_doc, Modified: python/branches/py3k/PC/config.c ============================================================================== --- python/branches/py3k/PC/config.c (original) +++ python/branches/py3k/PC/config.c Wed Apr 9 10:37:03 2008 @@ -58,7 +58,6 @@ extern void init_subprocess(void); extern void init_lsprof(void); extern void init_ast(void); -extern void init_types(void); extern void init_fileio(void); extern void initatexit(void); @@ -146,7 +145,6 @@ {"builtins", NULL}, {"sys", NULL}, - {"_types", init_types}, {"_fileio", init_fileio}, {"atexit", initatexit}, Modified: python/branches/py3k/PC/example_nt/readme.txt ============================================================================== --- python/branches/py3k/PC/example_nt/readme.txt (original) +++ python/branches/py3k/PC/example_nt/readme.txt Wed Apr 9 10:37:03 2008 @@ -2,12 +2,34 @@ ======================================= This directory contains everything needed (except for the Python -distribution!) to build a Python extension module using Microsoft VC++ -("Developer Studio") version 7.1. It has been tested with VC++ 7.1 on -Python 2.4. You can also use earlier versions of VC to build Python -extensions, but the sample VC project file (example.dsw in this directory) -is in VC 7.1 format. Notice that you need to use the same compiler version -that was used to build Python itself. +distribution!) to build a Python extension module using Microsoft VC++. +Notice that you need to use the same compiler version that was used to build +Python itself. + +The simplest way to build this example is to use the distutils script +'setup.py'. To do this, simply execute: + + % python setup.py install + +after everything builds and installs, you can test it: + + % python -c "import example; example.foo()" + Hello, world + +See setup.py for more details. alternatively, see below for instructions on +how to build inside the Visual Studio environment. + +Visual Studio Build Instructions +================================ + +These are instructions how to build an extension using Visual C++. The +instructions and project files have not been updated to the latest VC +version. In general, it is recommended you use the 'setup.py' instructions +above. + +It has been tested with VC++ 7.1 on Python 2.4. You can also use earlier +versions of VC to build Python extensions, but the sample VC project file +(example.dsw in this directory) is in VC 7.1 format. COPY THIS DIRECTORY! -------------------- Modified: python/branches/py3k/PCbuild/bdist_wininst.vcproj ============================================================================== --- python/branches/py3k/PCbuild/bdist_wininst.vcproj (original) +++ python/branches/py3k/PCbuild/bdist_wininst.vcproj Wed Apr 9 10:37:03 2008 @@ -1,7 +1,7 @@ + @@ -104,6 +107,96 @@ Name="VCPostBuildEventTool" /> + + + + + + + + + + + + + + + + + + + Modified: python/branches/py3k/PCbuild/pcbuild.sln ============================================================================== --- python/branches/py3k/PCbuild/pcbuild.sln (original) +++ python/branches/py3k/PCbuild/pcbuild.sln Wed Apr 9 10:37:03 2008 @@ -482,13 +482,13 @@ {D06B6426-4762-44CC-8BAD-D79052507F2F}.Release|x64.ActiveCfg = Release|x64 {D06B6426-4762-44CC-8BAD-D79052507F2F}.Release|x64.Build.0 = Release|x64 {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.Debug|Win32.ActiveCfg = Release|Win32 - {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.Debug|x64.ActiveCfg = Release|Win32 + {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.Debug|x64.ActiveCfg = Release|x64 {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.PGInstrument|Win32.ActiveCfg = Release|Win32 - {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.PGInstrument|x64.ActiveCfg = Release|Win32 + {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.PGInstrument|x64.ActiveCfg = Release|x64 {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.PGUpdate|Win32.ActiveCfg = Release|Win32 - {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.PGUpdate|x64.ActiveCfg = Release|Win32 + {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.PGUpdate|x64.ActiveCfg = Release|x64 {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.Release|Win32.ActiveCfg = Release|Win32 - {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.Release|x64.ActiveCfg = Release|Win32 + {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.Release|x64.ActiveCfg = Release|x64 {447F05A8-F581-4CAC-A466-5AC7936E207E}.Debug|Win32.ActiveCfg = Debug|Win32 {447F05A8-F581-4CAC-A466-5AC7936E207E}.Debug|Win32.Build.0 = Debug|Win32 {447F05A8-F581-4CAC-A466-5AC7936E207E}.Debug|x64.ActiveCfg = Debug|x64 Modified: python/branches/py3k/PCbuild/pythoncore.vcproj ============================================================================== --- python/branches/py3k/PCbuild/pythoncore.vcproj (original) +++ python/branches/py3k/PCbuild/pythoncore.vcproj Wed Apr 9 10:37:03 2008 @@ -1019,10 +1019,6 @@ > - - From python-3000-checkins at python.org Wed Apr 9 20:40:09 2008 From: python-3000-checkins at python.org (georg.brandl) Date: Wed, 9 Apr 2008 20:40:09 +0200 (CEST) Subject: [Python-3000-checkins] r62251 - python/branches/py3k/Lib/io.py Message-ID: <20080409184009.CC2441E401F@bag.python.org> Author: georg.brandl Date: Wed Apr 9 20:40:09 2008 New Revision: 62251 Modified: python/branches/py3k/Lib/io.py Log: Remove __repr__ that doesn't have any advantage compared to the standard one. Modified: python/branches/py3k/Lib/io.py ============================================================================== --- python/branches/py3k/Lib/io.py (original) +++ python/branches/py3k/Lib/io.py Wed Apr 9 20:40:09 2008 @@ -1194,9 +1194,6 @@ # - "bytes_..." for integer variables that count input bytes # - "chars_..." for integer variables that count decoded characters - def __repr__(self): - return '' % id(self) - @property def encoding(self): return self._encoding From python-3000-checkins at python.org Wed Apr 9 20:40:52 2008 From: python-3000-checkins at python.org (georg.brandl) Date: Wed, 9 Apr 2008 20:40:52 +0200 (CEST) Subject: [Python-3000-checkins] r62252 - python/branches/py3k/Doc/library/allos.rst python/branches/py3k/Doc/library/io.rst Message-ID: <20080409184052.645F01E401F@bag.python.org> Author: georg.brandl Date: Wed Apr 9 20:40:51 2008 New Revision: 62252 Added: python/branches/py3k/Doc/library/io.rst Modified: python/branches/py3k/Doc/library/allos.rst Log: #2530: io module documentation. Modified: python/branches/py3k/Doc/library/allos.rst ============================================================================== --- python/branches/py3k/Doc/library/allos.rst (original) +++ python/branches/py3k/Doc/library/allos.rst Wed Apr 9 20:40:51 2008 @@ -14,6 +14,7 @@ .. toctree:: os.rst + io.rst time.rst optparse.rst getopt.rst Added: python/branches/py3k/Doc/library/io.rst ============================================================================== --- (empty file) +++ python/branches/py3k/Doc/library/io.rst Wed Apr 9 20:40:51 2008 @@ -0,0 +1,603 @@ +:mod:`io` --- Core tools for working with streams +================================================= + +.. module:: io + :synopsis: Core tools for working with streams. +.. moduleauthor:: Guido van Rossum +.. moduleauthor:: Mike Verdone +.. moduleauthor:: Mark Russell +.. sectionauthor:: Benjamin Peterson + +The :mod:`io` module provides the Python interfaces to stream handling. The +builtin :func:`open` function is defined in this module. + +At the top of the I/O hierarchy is the abstract base class :class:`IOBase`. It +defines the basic interface to a stream. Note, however, that there is no +seperation between reading and writing to streams; implementations are allowed +to throw an :exc:`IOError` if they do not support a given operation. + +Extending :class:`IOBase` is :class:`RawIOBase` which deals simply with the +reading and writing of raw bytes to a stream. :class:`FileIO` subclasses +:class:`RawIOBase` to provide an interface to OS files. + +:class:`BufferedIOBase` deals with buffering on a raw byte stream +(:class:`RawIOBase`). Its subclasses, :class:`BufferedWriter`, +:class:`BufferedReader`, and :class:`BufferedRWPair` buffer streams that are +readable, writable, and both respectively. :class:`BufferedRandom` provides a +buffered interface to random access streams. :class:`BytesIO` is a simple +stream of in-memory bytes. + +Another :class:`IOBase` subclass, :class:`TextIOBase` deals with the encoding +and decoding of streams into text. :class:`TextIOWrapper`, which extends it, is +a buffered text interface to a buffered raw stream (:class:`BufferedIOBase`). +Finally, :class:`StringIO` is a in-memory stream for text. + + +Module Interface +---------------- + +.. data:: DEFAULT_BUFFER_SIZE + + An int containing the default buffer size used by the module's buffered I/O + classes. :func:`open` uses the file's blksize (as obtained by os.stat) if + possible. + +.. function:: open(file[, mode[, buffering[, encoding[, errors[, newline[, closefd=True]]]]]]) + + Open *file* and return a stream. + + *file* is a string giving the name of the file, or an integer file descriptor + of the file to be wrapped. + + The optional *mode* string determines how the file is opened and consists of + a combination of the following characters: + + ========= =============================================================== + Character Meaning + --------- --------------------------------------------------------------- + ``'r'`` open for reading (default) + ``'w'`` open for writing, truncating the file first + ``'a'`` open for writing, appending to the end of the file if it exists + ``'b'`` binary mode + ``'t'`` text mode (default) + ``'+'`` open a disk file for updating (reading and writing) + ``'U'`` universal newline mode (for backwards compatibility; unneeded + for new code) + ========= =============================================================== + + The default mode is ``'rt'`` (open for reading text). For binary random + access, the mode ``'w+b'`` opens and truncates the file to 0 bytes, while + ``'r+b'`` opens the file without truncation. + + *buffering* is an optional argument controling the buffering of the returned + stream. A value of ``0`` means no buffering, ``1`` means line buffered, and + a greater value means full buffering with the given buffer size. Buffering + cannot be disabled in text mode. + + *encoding* is the name of the encoding used to decode or encode the file. + This may only be used in text mode. Any encoding available in the + :mod:`codecs` module registry can be used. + + *errors* specifies how the encoding should treat errors. "strict", the + default raises a :exc:`ValueError` on problems. See the *errors* argument + of :func:`codecs.open` for more information. XXX + + *newline* controls how universal newlines works (it only applies to text + mode). It can be ``None``, ``''``, ``'\n'``, ``'\r'``, and ``'\r\n'``. It + works as follows: + + * On input, if *newline* is ``None``, universal newlines mode is enabled. + Lines in the input can end in ``'\n'``, ``'\r'``, or ``'\r\n'``, and these + are translated into ``'\n'`` before being returned to the caller. If it is + ``''``, universal newline mode is enabled, but line endings are returned to + the caller untranslated. If it has any of the other legal values, input + lines are only terminated by the given string, and the line ending is + returned to the caller untranslated. + + * On output, if *newline* is ``None``, any ``'\n'`` characters written are + translated to the system default line separator, :data:`os.linesep`. If + *newline* is ``''``, no translation takes place. If *newline* is any of + the other legal values, any ``'\n'`` characters written are translated to + the given string. + + If *closefd* is :keyword:`False`, the underlying file descriptor will be kept + open when the file is closed. This does not work when a file name is given. + + The :func:`open` function returns a file object whose type depends on the + mode, and through which the standard file operations such as reading and + writing are performed. When :func:`open` is used to open a file in a text + mode (``'w'``, ``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a + :class:`TextIOWrapper`. When used to open a file in a binary mode, the + returned class varies: in read binary mode, it returns a + :class:`BufferedReader`; in write binary and append binary modes, it returns + a :class:`BufferedWriter`, and in read/write mode, it returns a + :class:`BufferedRandom`. + + It is also possible to use a string or bytearray as a file for both reading + and writing. For strings :class:`io.StringIO` can be used like a file opened + in a text mode, and for bytes a :class:`io.BytesIO` can be used like a file + opened in a binary mode. + + +.. exception:: BlockingIOError + + Error raised when blocking would occur on a non-blocking stream. It inherits + :exc:`IOError`. + + In addition to those of :exc:`IOError`, :exc:`BlockingIOError` has one + attribute: + + .. attribute:: characters_written + + An integer containing the number of characters written to the stream + before it blocked. + + +.. exception:: UnsupportedOperation + + An exception inheriting :exc:`IOError` and :exc:`ValueError` that is raised + when an unsupported operation is called on a stream. + + +I/O Base Classes +---------------- + +.. class:: IOBase + + The abstract base class for all I/O classes, acting on streams of bytes. + There is no public constructor. + + This class provides dummy implementations for many methods that derived + classes can override selectively; the default implementations represent a + file that cannot be read, written or seeked. + + Even though :class:`IOBase` does not declare :meth:`read`, :meth:`readinto`, + :meth:`seek`, or :meth:`write` because their signatures will vary, + implementations and clients should consider those methods part of the + interface. Also, implementations may raise a :exc:`IOError` when operations + they do not support are called. + + The basic type used for binary data read from or written to a file is + :class:`bytes`. :class:`bytearray`\s are accepted too, and in some cases + (such as :class:`readinto`) needed. Text I/O classes work with :class:`str` + data. + + Note that calling any method (even inquiries) on a closed file is undefined. + Implementations may raise :exc:`IOError` in this case. + + IOBase (and its subclasses) support the iterator protocol, meaning that an + :class:`IOBase` object can be iterated over yielding the lines in a stream. + + IOBase also supports the :keyword:`with` statement. In this example, *fp* is + closed after the suite of the with statment is complete:: + + with open('spam.txt', 'r') as fp: + fp.write('Spam and eggs!') + + :class:`IOBase` provides these methods: + + .. method:: close() + + Flush and close this stream. This method has no effect if the file is + already closed. + + .. attribute:: closed + + True if the stream is closed. + + .. method:: fileno() + + Return the underlying file descriptor (an integer) of the stream, if it + exists. Raises :exc:`IOError` if the IO object does not use a file + descriptor. + + .. method:: flush() + + Flush the write buffers of the stream if applicable. This is a no-op for + read-only and non-blocking streams. + + .. method:: isatty() + + Tell if a stream is interactive (connected to a terminal/tty device). + + .. method:: readable() + + Tell if a stream can be read from. If False, :meth:`read` will raise + :exc:`IOError`. + + .. method:: readline([limit]) + + Read and return a line from the stream. If *limit* is specified, at most + *limit* bytes will be read. + + The line terminator is always ``b'\n'`` for binary files; for text files + the *newlines* argument to :func:`.open` can be used to select the line + terminator(s) recognized. + + .. method:: readlines([hint]) + + Return a list of lines from the stream. *hint* can be specified to + control the number of lines read: no more lines will be read if the total + size (in bytes/characters) of all lines so far exceeds *hint*. + + .. method:: seekable() + + Tell if a stream supports random IO access. If ``False``, :meth:`seek`, + :meth:`tell` and :meth:`truncate` will raise :exc:`IOError`. + + .. method:: tell() + + Return an integer indicating the current stream position. + + .. method:: writable() + + Tell if a stream supports writing. If ``False``, :meth:`write` and + :meth:`truncate` will raise :exc:`IOError`. + + .. method:: writelines(lines) + + Write a list of lines to the stream. The lines will not be altered; they + must contain line separators. + + +.. class:: RawIOBase + + Base class for raw binary I/O. It inherits :class:`IOBase`. There is no + public constructor. + + RawIOBase provides or overrides these methods in addition to those from + :class:`IOBase`: + + .. method:: RawIOBase.read([n]) + + Read and return all bytes from the stream until EOF, or if *n* is + specified, up to *n* bytes. An empty bytes object is returned on EOF; + ``None`` is returned if the object is set not to block and has no data to + read. + + .. method:: RawIOBase.readall() + + Read and return all bytes from the stream until EOF. + + +Raw File I/O +------------ + +.. class:: FileIO(name[, mode]) + + :class:`FileIO` represents an OS file containing bytes data. It implements + the :class:`RawIOBase` interface (and therefore the :class:`IOBase` + interface, too). + + The *mode* can be ``'r'``, ``'w'`` or ``'a'`` for reading (default), writing, + or appending. The file will be created if it doesn't exist when opened for + writing or appending; it will be truncated when opened for writing. Add a + ``'+'`` to the mode to allow simultaneous reading and writing. + + :class:`FileIO` provides or overrides these methods in addition to those from + :class:`RawIOBase` and :class:`IOBase`: + + .. attribute:: mode + + The mode as given in the constructor. + + .. attribute:: name + + The file name. + + .. method:: read([n]) + + Read and return bytes at most *n* bytes. Only one system call is made, so + less data than requested may be returned. In non-blocking mode, ``None`` + is returned when no data is available. + + .. method:: readall() + + Read and return as bytes all the data from the file. As much as + immediately available is returned in non-blocking mode. If the EOF has + been reached, ``b''`` is returned. + + .. method:: readinto(bytearray) + + This method should not be used on :class:`FileIO` objects. + + .. method:: seek(offset, [whence]) + + Change the stream position to byte offset *pos*. *pos* is interpreted + relative to the position indicated by *whence*. Values for *whence* are: + + * ``0`` -- start of stream (the default); *pos* should be zero or positive + * ``1`` -- current stream position; *pos* may be negative + * ``2`` -- end of stream; *pos* is usually negative + + Return the new absolute position. + + .. method:: truncate([pos]) + + Truncate the file to at most *pos* bytes. *pos* defaults to the current + file position, as returned by :meth:`tell`. + + .. method:: write(b) + + Write the bytes *b* to the file, and return the number actually written. + Only one system call is made, so not all of the data may be written. + + +Buffered Streams +---------------- + +.. class:: BufferedIOBase + + Base class for streams that support buffering. It inherits :class:`IOBase`. + There is no public constructor. + + The main difference with :class:`RawIOBase` is that the :meth:`read` method + supports omitting the *size* argument, and does not have a default + implementation that defers to :meth:`readinto`. + + In addition, :meth:`read`, :meth:`readinto`, and :meth:`write` may raise + :exc:`BlockingIOError` if the underlying raw stream is in non-blocking mode + and not ready; unlike their raw counterparts, they will never return + ``None``. + + A typical implementation should not inherit from a :class:`RawIOBase` + implementation, but wrap one like :class:`BufferedWriter` and + :class:`BufferedReader`. + + :class:`BufferedIOBase` provides or overrides these methods in addition to + those from :class:`IOBase`: + + .. method:: read([n]) + + Read and return up to *n* bytes. If the argument is omitted, ``None``, or + negative, data is read and returned until EOF is reached. An empty bytes + object is returned if the stream is already at EOF. + + If the argument is positive, and the underlying raw stream is not + interactive, multiple raw reads may be issued to satisfy the byte count + (unless EOF is reached first). But for interactive raw streams, at most + one raw read will be issued, and a short result does not imply that EOF is + imminent. + + A :exc:`BlockingIOError` is raised if the underlying raw stream has no + data at the moment. + + .. method:: readinto(b) + + Read up to len(b) bytes into bytearray *b* and return the number of bytes + read. + + Like :meth:`read`, multiple reads may be issued to the underlying raw + stream, unless the latter is 'interactive.' + + A :exc:`BlockingIOError` is raised if the underlying raw stream has no + data at the moment. + + .. method:: seek(pos[, whence]) + + Change the stream position to byte offset *pos*. *pos* is interpreted + relative to the position indicated by *whence*. Values for *whence* are: + + * ``0`` -- start of stream (the default); *pos* should be zero or positive + * ``1`` -- current stream position; *pos* may be negative + * ``2`` -- end of stream; *pos* is usually negative + + Return the new absolute position. + + .. method:: write(b) + + Write the given bytes to the underlying raw stream and return the number + of bytes written (never less than ``len(b)``). + + A :exc:`BlockingIOError` is raised if the buffer is full, and the + underlying raw stream cannot accept more data at the moment. + + +.. class:: BytesIO([initial_bytes]) + + A stream implementation using an in-memory bytes buffer. It inherits + :class:`BufferedIOBase`. + + The argument *initial_bytes* is an optional initial bytearray. + + :class:`BytesIO` provides or overrides these methods in addition to those + from :class:`BufferedIOBase` and :class:`IOBase`: + + .. method:: getvalue() + + Return the bytes value of the buffer. + + .. method:: read1() + + In :class:`BytesIO`, this is the same as :meth:`read`. + + .. method:: truncate([pos]) + + Truncate the file to at most *pos* bytes. *pos* defaults to the current + stream position, as returned by :meth:`tell`. + + +.. class:: BufferedReader(raw, [buffer_size]) + + A buffer for a readable sequential RawIO object. It inherits + :class:`BufferedIOBase`. + + The constructor creates a :class:`BufferedReader` for the given readable + *raw* stream and *buffer_size*. If *buffer_size* is omitted, + :data:`DEFAULT_BUFFER_SIZE` is used. + + :class:`BufferedReader` provides or overrides these methods in addition to + those from :class:`BufferedIOBase` and :class:`IOBase`: + + .. method:: peek([n]) + + Return bytes from a buffer without advancing the position. The argument + indicates a desired minimal number of bytes; only one read on the raw + stream is done to satisfy it. More than the buffer's size is never + returned. + + .. method:: read([n]) + + Read and return *n* bytes, or if *n* is not given or negative, until EOF + or if the read call would block in non-blocking mode. + + .. method:: read1(n) + + Read and return up to *n* bytes with only one call on the raw stream. If + at least one byte is buffered, only buffered bytes are returned. + Otherwise, one raw stream read call is made. + + +.. class:: BufferedWriter(raw, [buffer_size, [max_buffer_size]]) + + A buffer for a writeable sequential RawIO object. It inherits + :class:`BufferedIOBase`. + + The constructor creates a :class:`BufferedWriter` for the given writeable + *raw* stream. If the *buffer_size* is not given, it defaults to + :data:`DEAFULT_BUFFER_SIZE`. If *max_buffer_size* is omitted, it defaults to + twice the buffer size. + + :class:`BufferedWriter` provides or overrides these methods in addition to + those from :class:`BufferedIOBase` and :class:`IOBase`: + + .. method:: flush() + + Force bytes held in the buffer into the raw stream. A + :exc:`BlockingIOError` is be raised if the raw stream blocks. + + .. method:: write(b) + + Write bytes *b* onto the raw stream and return the number written. A + :exc:`BlockingIOError` is raised when the raw stream blocks. + + +.. class:: BufferedRWPair(reader, writer, [buffer_size, [max_buffer_size]]) + + A buffered writer and reader object together for a raw stream that can be + written and read from. It has and supports both :meth:`read`, :meth:`write`, + and their variants. This is useful for such applications such as sockets and + two-way pipes. It inherits :class:`BufferedIOBase`. + + *reader* and *writer* are :class:`RawIOBase` objects that are readable and + writeable respectively. If the *buffer_size* is omitted it defaults to + :data:`DEFAULT_BUFFER_SIZE`. The *max_buffer_size* (for the buffered writer) + defaults to twice the buffer size. + + :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods. + + +.. class:: BufferedRandom(raw, [buffer_size, [max_buffer_size]]) + + A buffered interface to random access streams. It inherits + :class:`BufferedReader` and :class:`BufferedWriter`. + + The constructor creates a reader and writer for a seekable *raw* stream given + in the first argument. If the *buffer_size* is omitted it defaults to + :data:`DEFAULT_BUFFER_SIZE`. The *max_buffer_size* (for the buffered writer) + defaults to twice the buffer size. + + :class:`BufferedRandom` is capable of anything :class:`BufferedReader` or + :class:`BufferedWriter` can do. + + +Text I/O +-------- + +.. class:: TextIOBase + + Base class for text streams. This class provides a character and line based + interface to stream I/O. There is no :meth:`readinto` method because + Python's character strings are immutable. It inherits :class:`IOBase`. + There is no public constructor. + + :class:`TextIOBase` provides or overrides these methods in addition to those + from :class:`IOBase`: + + .. attribute:: encoding + + Return the name of the encoding used to decode the stream's bytes into + strings, and to encode strings into bytes. + + .. attribute:: newlines + + Return a string, tuple of strings, or ``None`` indicating the newlines + translated so far. + + .. method:: read(n) + + Read and return at most *n* characters from the stream. If *n* is + negative or ``None``, read to EOF. + + .. method:: readline() + + Read until newline or EOF and return. If the stream is already at EOF, an + empty stream is returned. + + .. method:: truncate([pos]) + + Truncate size to *pos*. If *pos* is not specified, it is assumed to be the + current position, as returned by :meth:`tell`. + + .. method:: write(s) + + Write string *s* to the stream and return the number of characters + written. + + +.. class:: TextIOWrapper(buffer[, encoding[, errors[, newline[, line_buffering]]]]) + + A buffered text stream over a :class:`BufferedIOBase` raw stream, *buffer*. + It inherits :class:`TextIOBase`. + + *encoding* gives the name of the encoding that the stream will be decoded or + encoded with. It defaults to :func:`locale.getpreferredencoding`. + + *errors* determines the strictness of encoding and decoding (see the errors + argument of :func:`codecs.open`) and defaults to "strict". + + *newline* can be ``None``, ``''``, ``'\n'``, ``'\r'``, or ``'\r\n'``. It + controls the handling of line endings. If it is ``None``, universal newlines + is enabled. With this enabled, on input, the lines endings ``'\n'``, + ``'\r'``, or ``'\r\n'`` are translated to ``'\n'`` before being returned to + the caller. Conversely, on output, ``'\n'`` is translated to the system + default line seperator, :data:`os.linesep`. If *newline* is any other of its + legal values, that newline becomes the newline when the file is read and it + is returned untranslated. On output, ``'\n'`` is converted to the *newline*. + + If *line_buffering* is ``True``, :meth:`flush` is implied when a call to + write contains a newline character. + + :class:`TextIOWrapper` provides these methods in addition to those of + :class:`TextIOBase` and its parents: + + .. attribute:: errors + + The encoding and decoding error setting. + + .. attribute:: line_buffering + + Whether line buffering is enabled. + + +.. class:: StringIO([initial_value, [encoding, [errors, [newline]]]]) + + An in-memory stream for text. It in inherits :class:`TextIOWrapper`. + + Create a new StringIO stream with an inital value, encoding, error handling, + and newline setting. See :class:`TextIOWrapper`'s constructor for more + information. + + :class:`StringIO` provides these methods in addition to those from + :class:`TextIOWrapper` and its parents: + + .. method:: getvalue() + + Return a str representation of the contents of the internal buffer. + + +.. class:: IncrementalNewlineDecoder + + A helper codec that decodes newlines. It inherits + :class:`codecs.IncrementalDecoder`. + From python-3000-checkins at python.org Wed Apr 9 20:45:15 2008 From: python-3000-checkins at python.org (georg.brandl) Date: Wed, 9 Apr 2008 20:45:15 +0200 (CEST) Subject: [Python-3000-checkins] r62253 - python/branches/py3k/Doc/library/functions.rst Message-ID: <20080409184515.1906B1E400D@bag.python.org> Author: georg.brandl Date: Wed Apr 9 20:45:14 2008 New Revision: 62253 Modified: python/branches/py3k/Doc/library/functions.rst Log: #2580: int() docs revision. Modified: python/branches/py3k/Doc/library/functions.rst ============================================================================== --- python/branches/py3k/Doc/library/functions.rst (original) +++ python/branches/py3k/Doc/library/functions.rst Wed Apr 9 20:45:14 2008 @@ -556,18 +556,20 @@ to provide elaborate line editing and history features. -.. function:: int([x[, radix]]) +.. function:: int([number | string[, radix]]) - Convert a string or number to an integer. If the argument is a string, it - must contain a possibly signed number of arbitrary size, possibly embedded in - whitespace. The *radix* parameter gives the base for the conversion (which - is 10 by default) and may be any integer in the range [2, 36], or zero. If - *radix* is zero, the interpretation is the same as for integer literals. If - *radix* is specified and *x* is not a string, :exc:`TypeError` is raised. - Otherwise, the argument may be another integer, a floating point number or - any other object that has an :meth:`__int__` method. Conversion of floating - point numbers to integers truncates (towards zero). If no arguments are - given, returns ``0``. + Convert a number or string to an integer. If no arguments are given, return + ``0``. If a number is given, return ``number.__int__()``. Conversion of + floating point numbers to integers truncates towards zero. A string must be + a base-radix integer literal optionally preceded by '+' or '-' (with no space + in between) and optionally surrounded by whitespace. A base-n literal + consists of the digits 0 to n-1, with 'a' to 'z' (or 'A' to 'Z') having + values 10 to 35. The default radix is 10. The allowed values are 0 and 2-36. + Base-2, -8, and -16 literals can be optionally prefixed with ``0b``/``0B``, + ``0o``/``0O``, or ``0x``/``0X``, as with integer literals in code. Radix 0 + means to interpret exactly as a code literal, so that the actual radix is 2, + 8, 10, or 16, and so that ``int('010', 0)`` is not legal, while + ``int('010')`` is, as well as ``int('010', 8)``. The integer type is described in :ref:`typesnumeric`. From python-3000-checkins at python.org Wed Apr 9 20:46:46 2008 From: python-3000-checkins at python.org (georg.brandl) Date: Wed, 9 Apr 2008 20:46:46 +0200 (CEST) Subject: [Python-3000-checkins] r62254 - python/branches/py3k/Doc/reference/lexical_analysis.rst Message-ID: <20080409184646.785BE1E400D@bag.python.org> Author: georg.brandl Date: Wed Apr 9 20:46:46 2008 New Revision: 62254 Modified: python/branches/py3k/Doc/reference/lexical_analysis.rst Log: #2575: bininteger missing in production list. Modified: python/branches/py3k/Doc/reference/lexical_analysis.rst ============================================================================== --- python/branches/py3k/Doc/reference/lexical_analysis.rst (original) +++ python/branches/py3k/Doc/reference/lexical_analysis.rst Wed Apr 9 20:46:46 2008 @@ -587,7 +587,7 @@ Integer literals are described by the following lexical definitions: .. productionlist:: - integer: `decimalinteger` | `octinteger` | `hexinteger` + integer: `decimalinteger` | `octinteger` | `hexinteger` | `bininteger` decimalinteger: `nonzerodigit` `digit`* | "0"+ nonzerodigit: "1"..."9" digit: "0"..."9" From python-3000-checkins at python.org Wed Apr 9 23:38:38 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Wed, 9 Apr 2008 23:38:38 +0200 (CEST) Subject: [Python-3000-checkins] r62258 - python/branches/py3k/Doc/library/io.rst Message-ID: <20080409213838.AF13C1E4022@bag.python.org> Author: benjamin.peterson Date: Wed Apr 9 23:38:38 2008 New Revision: 62258 Modified: python/branches/py3k/Doc/library/io.rst Log: zap the last of the class.method typos in io docs Modified: python/branches/py3k/Doc/library/io.rst ============================================================================== --- python/branches/py3k/Doc/library/io.rst (original) +++ python/branches/py3k/Doc/library/io.rst Wed Apr 9 23:38:38 2008 @@ -248,14 +248,14 @@ RawIOBase provides or overrides these methods in addition to those from :class:`IOBase`: - .. method:: RawIOBase.read([n]) + .. method:: read([n]) Read and return all bytes from the stream until EOF, or if *n* is specified, up to *n* bytes. An empty bytes object is returned on EOF; ``None`` is returned if the object is set not to block and has no data to read. - .. method:: RawIOBase.readall() + .. method:: readall() Read and return all bytes from the stream until EOF. From python-3000-checkins at python.org Thu Apr 10 04:50:50 2008 From: python-3000-checkins at python.org (martin.v.loewis) Date: Thu, 10 Apr 2008 04:50:50 +0200 (CEST) Subject: [Python-3000-checkins] r62264 - in python/branches/py3k: Lib/lib2to3 Lib/lib2to3/fixes/fix_dict.py Lib/lib2to3/fixes/fix_xrange.py Lib/lib2to3/fixes/util.py Lib/lib2to3/pytree.py Lib/lib2to3/tests/test_fixers.py Lib/lib2to3/tests/test_pytree.py Message-ID: <20080410025050.729801E400D@bag.python.org> Author: martin.v.loewis Date: Thu Apr 10 04:50:50 2008 New Revision: 62264 Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/lib2to3/ (props changed) python/branches/py3k/Lib/lib2to3/fixes/fix_dict.py python/branches/py3k/Lib/lib2to3/fixes/fix_xrange.py python/branches/py3k/Lib/lib2to3/fixes/util.py python/branches/py3k/Lib/lib2to3/pytree.py python/branches/py3k/Lib/lib2to3/tests/test_fixers.py python/branches/py3k/Lib/lib2to3/tests/test_pytree.py Log: Merged revisions 62263 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ................ r62263 | martin.v.loewis | 2008-04-10 04:48:01 +0200 (Do, 10 Apr 2008) | 19 lines Merged revisions 62080-62262 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r62092 | collin.winter | 2008-04-01 18:27:10 +0200 (Di, 01 Apr 2008) | 1 line Add get_prev_sibling() to complement pytree's get_next_sibling(). ........ r62226 | collin.winter | 2008-04-08 21:07:56 +0200 (Di, 08 Apr 2008) | 1 line Add min() and max() to the list of special contexts that don't require adding list() calls around dict methods. ........ r62232 | collin.winter | 2008-04-09 00:12:38 +0200 (Mi, 09 Apr 2008) | 4 lines Fix for http://bugs.python.org/issue2596 This extends fix_xrange to know about the (mostly) same special contexts as fix_dict (where a special context is something that is guaranteed to fully consume the iterable), adding list() calls where appropriate. It also special-cases "x in range(y)". ........ ................ Modified: python/branches/py3k/Lib/lib2to3/fixes/fix_dict.py ============================================================================== --- python/branches/py3k/Lib/lib2to3/fixes/fix_dict.py (original) +++ python/branches/py3k/Lib/lib2to3/fixes/fix_dict.py Thu Apr 10 04:50:50 2008 @@ -29,10 +29,10 @@ from ..pgen2 import token from . import basefix from .util import Name, Call, LParen, RParen, ArgList, Dot, set +from . import util -exempt = set(["sorted", "list", "set", "any", "all", "tuple", "sum"]) -iter_exempt = exempt | set(["iter"]) +iter_exempt = util.consuming_calls | set(["iter"]) class FixDict(basefix.BaseFix): @@ -92,7 +92,7 @@ return results["func"].value in iter_exempt else: # list(d.keys()) -> list(d.keys()), etc. - return results["func"].value in exempt + return results["func"].value in util.consuming_calls if not isiter: return False # for ... in d.iterkeys() -> for ... in d.keys(), etc. Modified: python/branches/py3k/Lib/lib2to3/fixes/fix_xrange.py ============================================================================== --- python/branches/py3k/Lib/lib2to3/fixes/fix_xrange.py (original) +++ python/branches/py3k/Lib/lib2to3/fixes/fix_xrange.py Thu Apr 10 04:50:50 2008 @@ -5,14 +5,55 @@ # Local imports from .import basefix -from .util import Name +from .util import Name, Call, consuming_calls +from .. import patcomp + class FixXrange(basefix.BaseFix): PATTERN = """ - power< name='xrange' trailer< '(' [any] ')' > > + power< (name='range'|name='xrange') trailer< '(' [any] ')' > any* > """ def transform(self, node, results): name = results["name"] + if name.value == "xrange": + return self.transform_xrange(node, results) + elif name.value == "range": + return self.transform_range(node, results) + else: + raise ValueError(repr(name)) + + def transform_xrange(self, node, results): + name = results["name"] name.replace(Name("range", prefix=name.get_prefix())) + + def transform_range(self, node, results): + if not self.in_special_context(node): + arg = node.clone() + arg.set_prefix("") + call = Call(Name("list"), [arg]) + call.set_prefix(node.get_prefix()) + return call + return node + + P1 = "power< func=NAME trailer< '(' node=any ')' > any* >" + p1 = patcomp.compile_pattern(P1) + + P2 = """for_stmt< 'for' any 'in' node=any ':' any* > + | comp_for< 'for' any 'in' node=any any* > + | comparison< any 'in' node=any any*> + """ + p2 = patcomp.compile_pattern(P2) + + def in_special_context(self, node): + if node.parent is None: + return False + results = {} + if (node.parent.parent is not None and + self.p1.match(node.parent.parent, results) and + results["node"] is node): + # list(d.keys()) -> list(d.keys()), etc. + return results["func"].value in consuming_calls + # for ... in d.iterkeys() -> for ... in d.keys(), etc. + return self.p2.match(node.parent, results) and results["node"] is node Modified: python/branches/py3k/Lib/lib2to3/fixes/util.py ============================================================================== --- python/branches/py3k/Lib/lib2to3/fixes/util.py (original) +++ python/branches/py3k/Lib/lib2to3/fixes/util.py Thu Apr 10 04:50:50 2008 @@ -182,6 +182,10 @@ ### Misc ########################################################### + +consuming_calls = set(["sorted", "list", "set", "any", "all", "tuple", "sum", + "min", "max"]) + def attr_chain(obj, attr): """Follow an attribute chain. Modified: python/branches/py3k/Lib/lib2to3/pytree.py ============================================================================== --- python/branches/py3k/Lib/lib2to3/pytree.py (original) +++ python/branches/py3k/Lib/lib2to3/pytree.py Thu Apr 10 04:50:50 2008 @@ -167,13 +167,27 @@ return None # Can't use index(); we need to test by identity - for i, sibling in enumerate(self.parent.children): - if sibling is self: + for i, child in enumerate(self.parent.children): + if child is self: try: return self.parent.children[i+1] except IndexError: return None + def get_prev_sibling(self): + """Return the node immediately preceding the invocant in their + parent's children list. If the invocant does not have a previous + sibling, return None.""" + if self.parent is None: + return None + + # Can't use index(); we need to test by identity + for i, child in enumerate(self.parent.children): + if child is self: + if i == 0: + return None + return self.parent.children[i-1] + def get_suffix(self): """Return the string immediately following the invocant node. This is effectively equivalent to node.get_next_sibling().get_prefix()""" Modified: python/branches/py3k/Lib/lib2to3/tests/test_fixers.py ============================================================================== --- python/branches/py3k/Lib/lib2to3/tests/test_fixers.py (original) +++ python/branches/py3k/Lib/lib2to3/tests/test_fixers.py Thu Apr 10 04:50:50 2008 @@ -16,6 +16,8 @@ from .. import pygram from .. import pytree from .. import refactor +from ..fixes import util + class Options: def __init__(self, **kwargs): @@ -1105,8 +1107,7 @@ self.check(b, a) def test_unchanged(self): - wrappers = ["set", "sorted", "any", "all", "tuple", "sum"] - for wrapper in wrappers: + for wrapper in util.consuming_calls: s = "s = %s(d.keys())" % wrapper self.unchanged(s) @@ -1254,26 +1255,54 @@ a = """x = range( 0 , 10 , 2 )""" self.check(b, a) - def test_1(self): + def test_single_arg(self): b = """x = xrange(10)""" a = """x = range(10)""" self.check(b, a) - def test_2(self): + def test_two_args(self): b = """x = xrange(1, 10)""" a = """x = range(1, 10)""" self.check(b, a) - def test_3(self): + def test_three_args(self): b = """x = xrange(0, 10, 2)""" a = """x = range(0, 10, 2)""" self.check(b, a) - def test_4(self): + def test_wrap_in_list(self): + b = """x = range(10, 3, 9)""" + a = """x = list(range(10, 3, 9))""" + self.check(b, a) + + b = """x = foo(range(10, 3, 9))""" + a = """x = foo(list(range(10, 3, 9)))""" + self.check(b, a) + + b = """x = range(10, 3, 9) + [4]""" + a = """x = list(range(10, 3, 9)) + [4]""" + self.check(b, a) + + def test_xrange_in_for(self): b = """for i in xrange(10):\n j=i""" a = """for i in range(10):\n j=i""" self.check(b, a) + b = """[i for i in xrange(10)]""" + a = """[i for i in range(10)]""" + self.check(b, a) + + def test_range_in_for(self): + self.unchanged("for i in range(10): pass") + self.unchanged("[i for i in range(10)]") + + def test_in_contains_test(self): + self.unchanged("x in range(10, 3, 9)") + + def test_in_consuming_context(self): + for call in util.consuming_calls: + self.unchanged("a = %s(range(10))" % call) + class Test_raw_input(FixerTestCase): fixer = "raw_input" Modified: python/branches/py3k/Lib/lib2to3/tests/test_pytree.py ============================================================================== --- python/branches/py3k/Lib/lib2to3/tests/test_pytree.py (original) +++ python/branches/py3k/Lib/lib2to3/tests/test_pytree.py Thu Apr 10 04:50:50 2008 @@ -319,6 +319,24 @@ self.assertEqual(l2.get_next_sibling(), None) self.assertEqual(p1.get_next_sibling(), None) + def testNodePrevSibling(self): + n1 = pytree.Node(1000, []) + n2 = pytree.Node(1000, []) + p1 = pytree.Node(1000, [n1, n2]) + + self.failUnless(n2.get_prev_sibling() is n1) + self.assertEqual(n1.get_prev_sibling(), None) + self.assertEqual(p1.get_prev_sibling(), None) + + def testLeafPrevSibling(self): + l1 = pytree.Leaf(100, "a") + l2 = pytree.Leaf(100, "b") + p1 = pytree.Node(1000, [l1, l2]) + + self.failUnless(l2.get_prev_sibling() is l1) + self.assertEqual(l1.get_prev_sibling(), None) + self.assertEqual(p1.get_prev_sibling(), None) + class TestPatterns(support.TestCase): From python-3000-checkins at python.org Thu Apr 10 05:06:53 2008 From: python-3000-checkins at python.org (martin.v.loewis) Date: Thu, 10 Apr 2008 05:06:53 +0200 (CEST) Subject: [Python-3000-checkins] r62265 - in python/branches/py3k: Doc/conf.py Doc/tools/sphinxext/pyspecific.py Doc/whatsnew/2.6.rst Lib/urllib2.py Tools/msi/msi.py Message-ID: <20080410030653.B743B1E400D@bag.python.org> Author: martin.v.loewis Date: Thu Apr 10 05:06:53 2008 New Revision: 62265 Added: python/branches/py3k/Doc/tools/sphinxext/pyspecific.py - copied unchanged from r62259, python/trunk/Doc/tools/sphinxext/pyspecific.py Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/conf.py python/branches/py3k/Doc/whatsnew/2.6.rst python/branches/py3k/Lib/urllib2.py python/branches/py3k/Tools/msi/msi.py Log: Merged revisions 62246-62259 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62246 | georg.brandl | 2008-04-09 19:57:38 +0200 (Mi, 09 Apr 2008) | 2 lines #2585: initialize code attribute of HTTPError. ........ r62247 | georg.brandl | 2008-04-09 19:58:56 +0200 (Mi, 09 Apr 2008) | 2 lines Add :issue: directive for easy linking to bugs.python.org. ........ r62249 | gregory.p.smith | 2008-04-09 20:18:43 +0200 (Mi, 09 Apr 2008) | 2 lines Add a note about the zlib.decompressobj().flush() fix. ........ r62255 | martin.v.loewis | 2008-04-09 20:56:20 +0200 (Mi, 09 Apr 2008) | 2 lines Package wininst*.exe from distutils/command. ........ r62259 | andrew.kuchling | 2008-04-10 00:28:43 +0200 (Do, 10 Apr 2008) | 1 line Try out the new issue role. Thanks, Georg! ........ Modified: python/branches/py3k/Doc/conf.py ============================================================================== --- python/branches/py3k/Doc/conf.py (original) +++ python/branches/py3k/Doc/conf.py Thu Apr 10 05:06:53 2008 @@ -14,7 +14,7 @@ # --------------------- extensions = ['sphinx.ext.refcounting', 'sphinx.ext.coverage', - 'sphinx.ext.doctest'] + 'sphinx.ext.doctest', 'pyspecific'] templates_path = ['tools/sphinxext'] # General substitutions. Modified: python/branches/py3k/Doc/whatsnew/2.6.rst ============================================================================== --- python/branches/py3k/Doc/whatsnew/2.6.rst (original) +++ python/branches/py3k/Doc/whatsnew/2.6.rst Thu Apr 10 05:06:53 2008 @@ -1217,7 +1217,7 @@ >>> f(**ud) ['a', 'b'] - .. Patch 1686487 + (Contributed by Alexander Belopolsky; :issue:`1686487`.) * Tuples now have an :meth:`index` method matching the list type's :meth:`index` method:: Modified: python/branches/py3k/Lib/urllib2.py ============================================================================== --- python/branches/py3k/Lib/urllib2.py (original) +++ python/branches/py3k/Lib/urllib2.py Thu Apr 10 05:06:53 2008 @@ -157,7 +157,7 @@ # file object. If this happens, the simplest workaround is to # not initialize the base classes. if fp is not None: - self.__super_init(fp, hdrs, url) + self.__super_init(fp, hdrs, url, code) def __str__(self): return 'HTTP Error %s: %s' % (self.code, self.msg) Modified: python/branches/py3k/Tools/msi/msi.py ============================================================================== --- python/branches/py3k/Tools/msi/msi.py (original) +++ python/branches/py3k/Tools/msi/msi.py Thu Apr 10 05:06:53 2008 @@ -969,10 +969,7 @@ lib.glob("*.gif") lib.add_file("idle.icns") if dir=="command" and parent.physical=="distutils": - lib.add_file("wininst-6.0.exe") - lib.add_file("wininst-7.1.exe") - lib.add_file("wininst-8.0.exe") - lib.add_file("wininst-9.0.exe") + lib.glob("wininst*.exe") if dir=="setuptools": lib.add_file("cli.exe") lib.add_file("gui.exe") From python-3000-checkins at python.org Thu Apr 10 18:25:37 2008 From: python-3000-checkins at python.org (trent.nelson) Date: Thu, 10 Apr 2008 18:25:37 +0200 (CEST) Subject: [Python-3000-checkins] r62269 - in python/branches/py3k: Lib/test/test_getargs2.py Objects/abstract.c Python/getargs.c Message-ID: <20080410162537.B4C061E4010@bag.python.org> Author: trent.nelson Date: Thu Apr 10 18:25:37 2008 New Revision: 62269 Modified: python/branches/py3k/Lib/test/test_getargs2.py python/branches/py3k/Objects/abstract.c python/branches/py3k/Python/getargs.c Log: Issue 2440: fix the handling of %n in Python/getargs.c's convertsimple(), extend Objects/abstract.c's PyNumber_Index() to accept PyObjects that have nb_int slots, and update test_getargs2 to test that an exception is thrown when __int__() returns a non-int object. Modified: python/branches/py3k/Lib/test/test_getargs2.py ============================================================================== --- python/branches/py3k/Lib/test/test_getargs2.py (original) +++ python/branches/py3k/Lib/test/test_getargs2.py Thu Apr 10 18:25:37 2008 @@ -63,6 +63,10 @@ def __int__(self): return 99 +class InvalidLongAsString: + def __int__(self): + return 'foobar' + class Unsigned_TestCase(unittest.TestCase): def test_b(self): from _testcapi import getargs_b @@ -199,6 +203,7 @@ self.failUnlessEqual(42, getargs_n(42)) self.assertRaises(OverflowError, getargs_n, VERY_LARGE) + self.assertRaises(TypeError, getargs_n, InvalidLongAsString()) class LongLong_TestCase(unittest.TestCase): def test_L(self): Modified: python/branches/py3k/Objects/abstract.c ============================================================================== --- python/branches/py3k/Objects/abstract.c (original) +++ python/branches/py3k/Objects/abstract.c Thu Apr 10 18:25:37 2008 @@ -1220,6 +1220,7 @@ PyObject * PyNumber_Index(PyObject *item) { + PyNumberMethods *m; PyObject *result = NULL; if (item == NULL) return null_error(); @@ -1227,8 +1228,9 @@ Py_INCREF(item); return item; } + m = item->ob_type->tp_as_number; if (PyIndex_Check(item)) { - result = item->ob_type->tp_as_number->nb_index(item); + result = m->nb_index(item); if (result && !PyLong_Check(result)) { PyErr_Format(PyExc_TypeError, "__index__ returned non-int " @@ -1238,7 +1240,17 @@ return NULL; } } - else { + else if (m && m->nb_int != NULL) { + result = m->nb_int(item); + if (result && !PyLong_Check(result)) { + PyErr_Format(PyExc_TypeError, + "__int__ returned non-int " + "(type %.200s)", + result->ob_type->tp_name); + Py_DECREF(result); + return NULL; + } + } else { PyErr_Format(PyExc_TypeError, "'%.200s' object cannot be interpreted " "as an integer", item->ob_type->tp_name); Modified: python/branches/py3k/Python/getargs.c ============================================================================== --- python/branches/py3k/Python/getargs.c (original) +++ python/branches/py3k/Python/getargs.c Thu Apr 10 18:25:37 2008 @@ -663,7 +663,6 @@ } case 'n': /* Py_ssize_t */ -#if SIZEOF_SIZE_T != SIZEOF_LONG { PyObject *iobj; Py_ssize_t *p = va_arg(*p_va, Py_ssize_t *); @@ -672,14 +671,13 @@ return converterr("integer", arg, msgbuf, bufsize); iobj = PyNumber_Index(arg); if (iobj != NULL) - ival = PyLong_AsSsize_t(arg); + ival = PyLong_AsSsize_t(iobj); if (ival == -1 && PyErr_Occurred()) return converterr("integer", arg, msgbuf, bufsize); *p = ival; break; } -#endif - /* Fall through from 'n' to 'l' if Py_ssize_t is int */ + case 'l': {/* long int */ long *p = va_arg(*p_va, long *); long ival; From amauryfa at gmail.com Thu Apr 10 19:42:53 2008 From: amauryfa at gmail.com (Amaury Forgeot d'Arc) Date: Thu, 10 Apr 2008 19:42:53 +0200 Subject: [Python-3000-checkins] r62269 - in python/branches/py3k: Lib/test/test_getargs2.py Objects/abstract.c Python/getargs.c Message-ID: Hello, > Log: > Issue 2440: fix the handling of %n in Python/getargs.c's convertsimple(), > extend Objects/abstract.c's PyNumber_Index() to accept PyObjects that have nb_int slots, > and update test_getargs2 to test that an exception is thrown when __int__() returns a non-int object. Does this mean that floats can now be used as list indexes? Preventing this was the motivation for introducing the nb_index slot. from http://www.python.org/dev/peps/pep-0357 :: The biggest example of why using nb_int would be a bad thing is that float objects already define the nb_int method, but float objects *should not* be used as indexes in a sequence. -- Amaury Forgeot d'Arc From python-3000-checkins at python.org Thu Apr 10 21:02:25 2008 From: python-3000-checkins at python.org (martin.v.loewis) Date: Thu, 10 Apr 2008 21:02:25 +0200 (CEST) Subject: [Python-3000-checkins] r62270 - in python/branches/py3k: Lib/trace.py Misc/NEWS Message-ID: <20080410190225.ECB5A1E402F@bag.python.org> Author: martin.v.loewis Date: Thu Apr 10 21:02:25 2008 New Revision: 62270 Modified: python/branches/py3k/Lib/trace.py python/branches/py3k/Misc/NEWS Log: Bug #2606: Avoid calling .sort() on a dict_keys object. Modified: python/branches/py3k/Lib/trace.py ============================================================================== --- python/branches/py3k/Lib/trace.py (original) +++ python/branches/py3k/Lib/trace.py Thu Apr 10 21:02:25 2008 @@ -249,19 +249,15 @@ if self.calledfuncs: print() print("functions called:") - calls = self.calledfuncs.keys() - calls.sort() - for filename, modulename, funcname in calls: + for filename, modulename, funcname in sorted(calls.keys()): print(("filename: %s, modulename: %s, funcname: %s" % (filename, modulename, funcname))) if self.callers: print() print("calling relationships:") - calls = self.callers.keys() - calls.sort() lastfile = lastcfile = "" - for ((pfile, pmod, pfunc), (cfile, cmod, cfunc)) in calls: + for ((pfile, pmod, pfunc), (cfile, cmod, cfunc)) in sorted(self.callers.keys()): if pfile != lastfile: print() print("***", pfile, "***") @@ -318,10 +314,8 @@ sums[modulename] = n_lines, percent, modulename, filename if summary and sums: - mods = sums.keys() - mods.sort() print("lines cov% module (path)") - for m in mods: + for m in sorted(sums.keys()): n_lines, percent, modulename, filename = sums[m] print("%5d %3d%% %s (%s)" % sums[m]) Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Thu Apr 10 21:02:25 2008 @@ -25,6 +25,8 @@ Library ------- +- Bug #2606: Avoid calling .sort() on a dict_keys object. + - The bundled libffi copy is now in sync with the recently released libffi3.0.5 version, apart from some small changes to Modules/_ctypes/libffi/configure.ac. From python-3000-checkins at python.org Thu Apr 10 22:12:06 2008 From: python-3000-checkins at python.org (trent.nelson) Date: Thu, 10 Apr 2008 22:12:06 +0200 (CEST) Subject: [Python-3000-checkins] r62273 - python/branches/py3k/Lib/test/test_ssl.py Message-ID: <20080410201206.E5E201E4029@bag.python.org> Author: trent.nelson Date: Thu Apr 10 22:12:06 2008 New Revision: 62273 Modified: python/branches/py3k/Lib/test/test_ssl.py Log: Revert r62242: trunk's test_ssl.py isn't as up-to-date as py3k's, and should't have been brought over in the merge. Modified: python/branches/py3k/Lib/test/test_ssl.py ============================================================================== --- python/branches/py3k/Lib/test/test_ssl.py (original) +++ python/branches/py3k/Lib/test/test_ssl.py Thu Apr 10 22:12:06 2008 @@ -25,10 +25,11 @@ except ImportError: skip_expected = True -HOST = test_support.HOST CERTFILE = None SVN_PYTHON_ORG_ROOT_CERT = None +TESTPORT = 10025 + def handle_error(prefix): exc_format = ' '.join(traceback.format_exception(*sys.exc_info())) if test_support.verbose: @@ -298,7 +299,7 @@ except: handle_error('') - def __init__(self, certificate, ssl_version=None, + def __init__(self, port, certificate, ssl_version=None, certreqs=None, cacerts=None, expect_bad_connects=False, chatty=True, connectionchatty=False, starttls_server=False): if ssl_version is None: @@ -314,8 +315,12 @@ self.connectionchatty = connectionchatty self.starttls_server = starttls_server self.sock = socket.socket() - self.port = test_support.bind_port(self.sock) self.flag = None + if hasattr(socket, 'SO_REUSEADDR'): + self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + if hasattr(socket, 'SO_REUSEPORT'): + self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + self.sock.bind(('127.0.0.1', port)) self.active = False threading.Thread.__init__(self) self.setDaemon(False) @@ -466,13 +471,12 @@ format%args)) - def __init__(self, certfile): + def __init__(self, port, certfile): self.flag = None self.active = False self.RootedHTTPRequestHandler.root = os.path.split(CERTFILE)[0] - self.port = test_support.find_unused_port() self.server = self.HTTPSServer( - (HOST, self.port), self.RootedHTTPRequestHandler, certfile) + ('', port), self.RootedHTTPRequestHandler, certfile) threading.Thread.__init__(self) self.setDaemon(True) @@ -582,7 +586,7 @@ self.server.close() def badCertTest (certfile): - server = ThreadedEchoServer(CERTFILE, + server = ThreadedEchoServer(TESTPORT, CERTFILE, certreqs=ssl.CERT_REQUIRED, cacerts=CERTFILE, chatty=False, connectionchatty=False) @@ -596,7 +600,7 @@ s = ssl.wrap_socket(socket.socket(), certfile=certfile, ssl_version=ssl.PROTOCOL_TLSv1) - s.connect((HOST, server.port)) + s.connect(('127.0.0.1', TESTPORT)) except ssl.SSLError as x: if test_support.verbose: sys.stdout.write("\nSSLError is %s\n" % x) @@ -612,7 +616,7 @@ indata="FOO\n", chatty=False, connectionchatty=False): - server = ThreadedEchoServer(certfile, + server = ThreadedEchoServer(TESTPORT, certfile, certreqs=certreqs, ssl_version=protocol, cacerts=cacertsfile, @@ -627,11 +631,12 @@ client_protocol = protocol try: s = ssl.wrap_socket(socket.socket(), + server_side=False, certfile=client_certfile, ca_certs=cacertsfile, cert_reqs=certreqs, ssl_version=client_protocol) - s.connect((HOST, server.port)) + s.connect(('127.0.0.1', TESTPORT)) except ssl.SSLError as x: raise test_support.TestFailed("Unexpected SSL error: " + str(x)) except Exception as x: @@ -641,17 +646,18 @@ if test_support.verbose: sys.stdout.write( " client: sending %s...\n" % (repr(indata))) - s.write(indata) + s.write(indata.encode('ASCII', 'strict')) outdata = s.read() if connectionchatty: if test_support.verbose: sys.stdout.write(" client: read %s\n" % repr(outdata)) + outdata = str(outdata, 'ASCII', 'strict') if outdata != indata.lower(): raise test_support.TestFailed( "bad data <<%s>> (%d) received; expected <<%s>> (%d)\n" - % (outdata[:min(len(outdata),20)], len(outdata), - indata[:min(len(indata),20)].lower(), len(indata))) - s.write("over\n") + % (repr(outdata[:min(len(outdata),20)]), len(outdata), + repr(indata[:min(len(indata),20)].lower()), len(indata))) + s.write("over\n".encode("ASCII", "strict")) if connectionchatty: if test_support.verbose: sys.stdout.write(" client: closing connection.\n") @@ -697,44 +703,7 @@ class ThreadedTests(unittest.TestCase): - def testRudeShutdown(self): - - listener_ready = threading.Event() - listener_gone = threading.Event() - port = test_support.find_unused_port() - - # `listener` runs in a thread. It opens a socket listening on - # PORT, and sits in an accept() until the main thread connects. - # Then it rudely closes the socket, and sets Event `listener_gone` - # to let the main thread know the socket is gone. - def listener(): - s = socket.socket() - s.bind((HOST, port)) - s.listen(5) - listener_ready.set() - s.accept() - s = None # reclaim the socket object, which also closes it - listener_gone.set() - - def connector(): - listener_ready.wait() - s = socket.socket() - s.connect((HOST, port)) - listener_gone.wait() - try: - ssl_sock = ssl.wrap_socket(s) - except IOError: - pass - else: - raise test_support.TestFailed( - 'connecting to closed SSL socket should have failed') - - t = threading.Thread(target=listener) - t.start() - connector() - t.join() - - def testEcho(self): + def testEcho (self): if test_support.verbose: sys.stdout.write("\n") @@ -747,7 +716,7 @@ if test_support.verbose: sys.stdout.write("\n") s2 = socket.socket() - server = ThreadedEchoServer(CERTFILE, + server = ThreadedEchoServer(TESTPORT, CERTFILE, certreqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_SSLv23, cacerts=CERTFILE, @@ -764,7 +733,7 @@ ca_certs=CERTFILE, cert_reqs=ssl.CERT_REQUIRED, ssl_version=ssl.PROTOCOL_SSLv23) - s.connect((HOST, server.port)) + s.connect(('127.0.0.1', TESTPORT)) except ssl.SSLError as x: raise test_support.TestFailed( "Unexpected SSL error: " + str(x)) @@ -807,6 +776,46 @@ badCertTest(os.path.join(os.path.dirname(__file__) or os.curdir, "badkey.pem")) + def testRudeShutdown(self): + + listener_ready = threading.Event() + listener_gone = threading.Event() + + # `listener` runs in a thread. It opens a socket listening on + # PORT, and sits in an accept() until the main thread connects. + # Then it rudely closes the socket, and sets Event `listener_gone` + # to let the main thread know the socket is gone. + def listener(): + s = socket.socket() + if hasattr(socket, 'SO_REUSEADDR'): + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + if hasattr(socket, 'SO_REUSEPORT'): + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + s.bind(('127.0.0.1', TESTPORT)) + s.listen(5) + listener_ready.set() + s.accept() + s = None # reclaim the socket object, which also closes it + listener_gone.set() + + def connector(): + listener_ready.wait() + s = socket.socket() + s.connect(('127.0.0.1', TESTPORT)) + listener_gone.wait() + try: + ssl_sock = ssl.wrap_socket(s) + except IOError: + pass + else: + raise test_support.TestFailed( + 'connecting to closed SSL socket should have failed') + + t = threading.Thread(target=listener) + t.start() + connector() + t.join() + def testProtocolSSL2(self): if test_support.verbose: sys.stdout.write("\n") @@ -864,7 +873,7 @@ msgs = ("msg 1", "MSG 2", "STARTTLS", "MSG 3", "msg 4") - server = ThreadedEchoServer(CERTFILE, + server = ThreadedEchoServer(TESTPORT, CERTFILE, ssl_version=ssl.PROTOCOL_TLSv1, starttls_server=True, chatty=True, @@ -879,7 +888,7 @@ try: s = socket.socket() s.setblocking(1) - s.connect((HOST, server.port)) + s.connect(('127.0.0.1', TESTPORT)) except Exception as x: raise test_support.TestFailed("Unexpected exception: " + str(x)) else: @@ -927,8 +936,7 @@ def testSocketServer(self): - - server = AsyncoreHTTPSServer(CERTFILE) + server = OurHTTPSServer(TESTPORT, CERTFILE) flag = threading.Event() server.start(flag) # wait for it to start @@ -940,8 +948,8 @@ d1 = open(CERTFILE, 'rb').read() d2 = '' # now fetch the same data from the HTTPS server - url = 'https://%s:%d/%s' % ( - HOST, server.port, os.path.split(CERTFILE)[1]) + url = 'https://127.0.0.1:%d/%s' % ( + TESTPORT, os.path.split(CERTFILE)[1]) f = urllib.urlopen(url) dlen = f.info().getheader("content-length") if dlen and (int(dlen) > 0): @@ -970,11 +978,71 @@ sys.stdout.write('joining thread\n') server.join() + def testAsyncoreServer(self): + + if test_support.verbose: + sys.stdout.write("\n") + + indata="FOO\n" + server = AsyncoreEchoServer(TESTPORT, CERTFILE) + flag = threading.Event() + server.start(flag) + # wait for it to start + flag.wait() + # try to connect + try: + s = ssl.wrap_socket(socket.socket()) + s.connect(('127.0.0.1', TESTPORT)) + except ssl.SSLError as x: + raise test_support.TestFailed("Unexpected SSL error: " + str(x)) + except Exception as x: + raise test_support.TestFailed("Unexpected exception: " + str(x)) + else: + if test_support.verbose: + sys.stdout.write( + " client: sending %s...\n" % (repr(indata))) + s.sendall(indata.encode('ASCII', 'strict')) + outdata = s.recv() + if test_support.verbose: + sys.stdout.write(" client: read %s\n" % repr(outdata)) + outdata = str(outdata, 'ASCII', 'strict') + if outdata != indata.lower(): + raise test_support.TestFailed( + "bad data <<%s>> (%d) received; expected <<%s>> (%d)\n" + % (repr(outdata[:min(len(outdata),20)]), len(outdata), + repr(indata[:min(len(indata),20)].lower()), len(indata))) + s.write("over\n".encode("ASCII", "strict")) + if test_support.verbose: + sys.stdout.write(" client: closing connection.\n") + s.close() + finally: + server.stop() + server.join() + + +def findtestsocket(start, end): + def testbind(i): + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + s.bind(("127.0.0.1", i)) + except: + return 0 + else: + return 1 + finally: + s.close() + + for i in range(start, end): + if testbind(i) and testbind(i+1): + return i + return 0 + + def test_main(verbose=False): if skip_expected: raise test_support.TestSkipped("No SSL support") - global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT + global CERTFILE, TESTPORT, SVN_PYTHON_ORG_ROOT_CERT CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir, "keycert.pem") SVN_PYTHON_ORG_ROOT_CERT = os.path.join( @@ -985,6 +1053,10 @@ not os.path.exists(SVN_PYTHON_ORG_ROOT_CERT)): raise test_support.TestFailed("Can't read certificate files!") + TESTPORT = findtestsocket(10025, 12000) + if not TESTPORT: + raise test_support.TestFailed("Can't find open port to test servers on!") + tests = [BasicTests] if test_support.is_resource_enabled('network'): From python-3000-checkins at python.org Thu Apr 10 22:54:36 2008 From: python-3000-checkins at python.org (trent.nelson) Date: Thu, 10 Apr 2008 22:54:36 +0200 (CEST) Subject: [Python-3000-checkins] r62275 - python/branches/py3k/Lib/test/test_ssl.py Message-ID: <20080410205436.569BB1E4010@bag.python.org> Author: trent.nelson Date: Thu Apr 10 22:54:35 2008 New Revision: 62275 Modified: python/branches/py3k/Lib/test/test_ssl.py Log: Update test_ssl.py to reflect the new approach for writing network-oriented tests in such a way that contention for ports is eliminated, thus allowing multiple instances of the same test to be run in parallel without issue (import for buildbots to run smoothly). This change is in line with the changes made to network-oriented tests in trunk in r62234. test_ssl.py is an odd case because the py3k version was newer than trunk. When the most recent svnmerge was run from trunk to py3k in r62242, the older trunk version was brought over on top of the newer py3k version. So, the plan was/is: revert the recent svnmerged version (done), manually make the changes to improve running in parallel (done with this commit), copy this version back to trunk and manually 3to2 it (to do next), check that in, then svnmerge block it. Then when future changes need to be made to test_ssl.py, we can make them against trunk, and hopefully the merge to py3k should be a lot less painful. Modified: python/branches/py3k/Lib/test/test_ssl.py ============================================================================== --- python/branches/py3k/Lib/test/test_ssl.py (original) +++ python/branches/py3k/Lib/test/test_ssl.py Thu Apr 10 22:54:35 2008 @@ -25,11 +25,10 @@ except ImportError: skip_expected = True +HOST = test_support.HOST CERTFILE = None SVN_PYTHON_ORG_ROOT_CERT = None -TESTPORT = 10025 - def handle_error(prefix): exc_format = ' '.join(traceback.format_exception(*sys.exc_info())) if test_support.verbose: @@ -299,7 +298,7 @@ except: handle_error('') - def __init__(self, port, certificate, ssl_version=None, + def __init__(self, certificate, ssl_version=None, certreqs=None, cacerts=None, expect_bad_connects=False, chatty=True, connectionchatty=False, starttls_server=False): if ssl_version is None: @@ -315,12 +314,8 @@ self.connectionchatty = connectionchatty self.starttls_server = starttls_server self.sock = socket.socket() + self.port = test_support.bind_port(self.sock) self.flag = None - if hasattr(socket, 'SO_REUSEADDR'): - self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - if hasattr(socket, 'SO_REUSEPORT'): - self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) - self.sock.bind(('127.0.0.1', port)) self.active = False threading.Thread.__init__(self) self.setDaemon(False) @@ -471,12 +466,13 @@ format%args)) - def __init__(self, port, certfile): + def __init__(self, certfile): self.flag = None self.active = False self.RootedHTTPRequestHandler.root = os.path.split(CERTFILE)[0] + self.port = test_support.find_unused_port() self.server = self.HTTPSServer( - ('', port), self.RootedHTTPRequestHandler, certfile) + (HOST, self.port), self.RootedHTTPRequestHandler, certfile) threading.Thread.__init__(self) self.setDaemon(True) @@ -557,10 +553,11 @@ def handle_error(self): raise - def __init__(self, port, certfile): + def __init__(self, certfile): self.flag = None self.active = False - self.server = self.EchoServer(port, certfile) + self.port = test_support.find_unused_port() + self.server = self.EchoServer(self.port, certfile) threading.Thread.__init__(self) self.setDaemon(True) @@ -586,7 +583,7 @@ self.server.close() def badCertTest (certfile): - server = ThreadedEchoServer(TESTPORT, CERTFILE, + server = ThreadedEchoServer(CERTFILE, certreqs=ssl.CERT_REQUIRED, cacerts=CERTFILE, chatty=False, connectionchatty=False) @@ -600,7 +597,7 @@ s = ssl.wrap_socket(socket.socket(), certfile=certfile, ssl_version=ssl.PROTOCOL_TLSv1) - s.connect(('127.0.0.1', TESTPORT)) + s.connect((HOST, server.port)) except ssl.SSLError as x: if test_support.verbose: sys.stdout.write("\nSSLError is %s\n" % x) @@ -616,7 +613,7 @@ indata="FOO\n", chatty=False, connectionchatty=False): - server = ThreadedEchoServer(TESTPORT, certfile, + server = ThreadedEchoServer(certfile, certreqs=certreqs, ssl_version=protocol, cacerts=cacertsfile, @@ -636,7 +633,7 @@ ca_certs=cacertsfile, cert_reqs=certreqs, ssl_version=client_protocol) - s.connect(('127.0.0.1', TESTPORT)) + s.connect((HOST, server.port)) except ssl.SSLError as x: raise test_support.TestFailed("Unexpected SSL error: " + str(x)) except Exception as x: @@ -716,7 +713,7 @@ if test_support.verbose: sys.stdout.write("\n") s2 = socket.socket() - server = ThreadedEchoServer(TESTPORT, CERTFILE, + server = ThreadedEchoServer(CERTFILE, certreqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_SSLv23, cacerts=CERTFILE, @@ -733,7 +730,7 @@ ca_certs=CERTFILE, cert_reqs=ssl.CERT_REQUIRED, ssl_version=ssl.PROTOCOL_SSLv23) - s.connect(('127.0.0.1', TESTPORT)) + s.connect((HOST, server.port)) except ssl.SSLError as x: raise test_support.TestFailed( "Unexpected SSL error: " + str(x)) @@ -780,6 +777,7 @@ listener_ready = threading.Event() listener_gone = threading.Event() + port = test_support.find_unused_port() # `listener` runs in a thread. It opens a socket listening on # PORT, and sits in an accept() until the main thread connects. @@ -787,11 +785,7 @@ # to let the main thread know the socket is gone. def listener(): s = socket.socket() - if hasattr(socket, 'SO_REUSEADDR'): - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - if hasattr(socket, 'SO_REUSEPORT'): - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) - s.bind(('127.0.0.1', TESTPORT)) + s.bind((HOST, port)) s.listen(5) listener_ready.set() s.accept() @@ -801,7 +795,7 @@ def connector(): listener_ready.wait() s = socket.socket() - s.connect(('127.0.0.1', TESTPORT)) + s.connect((HOST, port)) listener_gone.wait() try: ssl_sock = ssl.wrap_socket(s) @@ -873,7 +867,7 @@ msgs = ("msg 1", "MSG 2", "STARTTLS", "MSG 3", "msg 4") - server = ThreadedEchoServer(TESTPORT, CERTFILE, + server = ThreadedEchoServer(CERTFILE, ssl_version=ssl.PROTOCOL_TLSv1, starttls_server=True, chatty=True, @@ -888,7 +882,7 @@ try: s = socket.socket() s.setblocking(1) - s.connect(('127.0.0.1', TESTPORT)) + s.connect((HOST, server.port)) except Exception as x: raise test_support.TestFailed("Unexpected exception: " + str(x)) else: @@ -936,7 +930,7 @@ def testSocketServer(self): - server = OurHTTPSServer(TESTPORT, CERTFILE) + server = OurHTTPSServer(CERTFILE) flag = threading.Event() server.start(flag) # wait for it to start @@ -948,8 +942,8 @@ d1 = open(CERTFILE, 'rb').read() d2 = '' # now fetch the same data from the HTTPS server - url = 'https://127.0.0.1:%d/%s' % ( - TESTPORT, os.path.split(CERTFILE)[1]) + url = 'https://%s:%d/%s' % ( + HOST, server.port, os.path.split(CERTFILE)[1]) f = urllib.urlopen(url) dlen = f.info().getheader("content-length") if dlen and (int(dlen) > 0): @@ -984,7 +978,7 @@ sys.stdout.write("\n") indata="FOO\n" - server = AsyncoreEchoServer(TESTPORT, CERTFILE) + server = AsyncoreEchoServer(CERTFILE) flag = threading.Event() server.start(flag) # wait for it to start @@ -992,7 +986,7 @@ # try to connect try: s = ssl.wrap_socket(socket.socket()) - s.connect(('127.0.0.1', TESTPORT)) + s.connect((HOST, server.port)) except ssl.SSLError as x: raise test_support.TestFailed("Unexpected SSL error: " + str(x)) except Exception as x: @@ -1019,30 +1013,11 @@ server.stop() server.join() - -def findtestsocket(start, end): - def testbind(i): - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - try: - s.bind(("127.0.0.1", i)) - except: - return 0 - else: - return 1 - finally: - s.close() - - for i in range(start, end): - if testbind(i) and testbind(i+1): - return i - return 0 - - def test_main(verbose=False): if skip_expected: raise test_support.TestSkipped("No SSL support") - global CERTFILE, TESTPORT, SVN_PYTHON_ORG_ROOT_CERT + global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir, "keycert.pem") SVN_PYTHON_ORG_ROOT_CERT = os.path.join( @@ -1053,10 +1028,6 @@ not os.path.exists(SVN_PYTHON_ORG_ROOT_CERT)): raise test_support.TestFailed("Can't read certificate files!") - TESTPORT = findtestsocket(10025, 12000) - if not TESTPORT: - raise test_support.TestFailed("Can't find open port to test servers on!") - tests = [BasicTests] if test_support.is_resource_enabled('network'): From python-3000-checkins at python.org Thu Apr 10 23:03:09 2008 From: python-3000-checkins at python.org (amaury.forgeotdarc) Date: Thu, 10 Apr 2008 23:03:09 +0200 (CEST) Subject: [Python-3000-checkins] r62276 - in python/branches/py3k: Misc/NEWS Python/pythonrun.c Message-ID: <20080410210309.776031E4002@bag.python.org> Author: amaury.forgeotdarc Date: Thu Apr 10 23:03:09 2008 New Revision: 62276 Modified: python/branches/py3k/Misc/NEWS python/branches/py3k/Python/pythonrun.c Log: Add a NEWS entry for issue2221. Also don't flush stdout on each call to exec() or eval(). Only interactive input really needs it. Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Thu Apr 10 23:03:09 2008 @@ -12,6 +12,10 @@ Core and Builtins ----------------- +- Issue #2221: Corrected a SystemError "error return without exception set", + when the code executed by exec() raises an exception, and sys.stdout.flush() + also raises an error. + - Bug #2565: The repr() of type objects now calls them 'class', not 'type' - whether they are builtin types or not. Modified: python/branches/py3k/Python/pythonrun.c ============================================================================== --- python/branches/py3k/Python/pythonrun.c (original) +++ python/branches/py3k/Python/pythonrun.c Thu Apr 10 23:03:09 2008 @@ -54,6 +54,7 @@ static void initmain(void); static void initsite(void); static int initstdio(void); +static void flush_io(void); static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *, PyCompilerFlags *, PyArena *); static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *, @@ -992,6 +993,7 @@ d = PyModule_GetDict(m); v = run_mod(mod, filename, d, d, flags, arena); PyArena_Free(arena); + flush_io(); if (v == NULL) { PyErr_Print(); return -1; @@ -1082,6 +1084,7 @@ v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d, closeit, flags); } + flush_io(); if (v == NULL) { PyErr_Print(); ret = -1; @@ -1513,7 +1516,6 @@ return NULL; v = PyEval_EvalCode(co, globals, locals); Py_DECREF(co); - flush_io(); return v; } @@ -1546,7 +1548,6 @@ if (v && flags) flags->cf_flags |= (co->co_flags & PyCF_MASK); Py_DECREF(co); - flush_io(); return v; } From python-3000-checkins at python.org Fri Apr 11 00:21:24 2008 From: python-3000-checkins at python.org (trent.nelson) Date: Fri, 11 Apr 2008 00:21:24 +0200 (CEST) Subject: [Python-3000-checkins] r62280 - python/branches/py3k/Objects/abstract.c Message-ID: <20080410222124.06BC41E4002@bag.python.org> Author: trent.nelson Date: Fri Apr 11 00:21:23 2008 New Revision: 62280 Modified: python/branches/py3k/Objects/abstract.c Log: Fix change to PyNumber_Index() made in r62269, which incorrectly allowed floats to be interpreted as longs. Thanks to Benjamin Peterson for picking this up. Modified: python/branches/py3k/Objects/abstract.c ============================================================================== --- python/branches/py3k/Objects/abstract.c (original) +++ python/branches/py3k/Objects/abstract.c Fri Apr 11 00:21:23 2008 @@ -1240,7 +1240,7 @@ return NULL; } } - else if (m && m->nb_int != NULL) { + else if (m && m->nb_int != NULL && m->nb_float == NULL) { result = m->nb_int(item); if (result && !PyLong_Check(result)) { PyErr_Format(PyExc_TypeError, From tnelson at onresolve.com Fri Apr 11 02:24:19 2008 From: tnelson at onresolve.com (Trent Nelson) Date: Thu, 10 Apr 2008 17:24:19 -0700 Subject: [Python-3000-checkins] [Python-3000] r62269 - in python/branches/py3k: Lib/test/test_getargs2.py Objects/abstract.c Python/getargs.c In-Reply-To: References: Message-ID: <87D3F9C72FBF214DB39FA4E3FE618CDC6E22D1F94D@EXMBX04.exchhosting.com> > > Issue 2440: fix the handling of %n in Python/getargs.c's > convertsimple(), > > extend Objects/abstract.c's PyNumber_Index() to accept PyObjects that > have nb_int slots, > > and update test_getargs2 to test that an exception is thrown when > __int__() returns a non-int object. > > Does this mean that floats can now be used as list indexes? > Preventing this was the motivation for introducing the nb_index slot. It sure did! At least, between r62269 and r62279 ;-) Ben pointed out my error, which I fixed in r62280. Trent. From tnelson at onresolve.com Fri Apr 11 02:53:03 2008 From: tnelson at onresolve.com (Trent Nelson) Date: Thu, 10 Apr 2008 17:53:03 -0700 Subject: [Python-3000-checkins] [Python-3000] r62269 - in python/branches/py3k: Lib/test/test_getargs2.py Objects/abstract.c Python/getargs.c In-Reply-To: <87D3F9C72FBF214DB39FA4E3FE618CDC6E22D1F94D@EXMBX04.exchhosting.com> References: <87D3F9C72FBF214DB39FA4E3FE618CDC6E22D1F94D@EXMBX04.exchhosting.com> Message-ID: <87D3F9C72FBF214DB39FA4E3FE618CDC6E22D1F951@EXMBX04.exchhosting.com> > > Does this mean that floats can now be used as list indexes? > > Preventing this was the motivation for introducing the nb_index slot. > > > from http://www.python.org/dev/peps/pep-0357 :: > > > > The biggest example of why using nb_int would be a bad > > thing is that float objects already define the nb_int method, but > > float objects *should not* be used as indexes in a sequence. > It sure did! At least, between r62269 and r62279 ;-) Ben pointed out > my error, which I fixed in r62280. > > Trent. Hrrm. I just re-read that PEP. This stuck out: It is not possible to use the nb_int (and __int__ special method) for this purpose because that method is used to *coerce* objects to integers. It would be inappropriate to allow every object that can be coerced to an integer to be used as an integer everywhere Python expects a true integer. For example, if __int__ were used to convert an object to an integer in slicing, then float objects would be allowed in slicing and x[3.2:5.8] would not raise an error as it should. I think I've pretty much violated the first few sentences with my change to PyNumber_Index(). Even with the change in r62280 which checks that we're not dealing with a float, it's still permitting anything else with an __int__ representation to pass through just fine. Note that all of this originated from the following in test_args2: class Long: def __int__(self): return 99 class Signed_TestCase(unittest.TestCase): ... def test_n(self): ... self.failUnlessEqual(99, getargs_n(Long())) Before the change, %n was passing through to %l unless sizeof(long) != sizeof(size_t) (in convertsimple() -- Python/getargs.c). Windows x64 is the only platform where this assertion holds true, which drew my attention to the problem. The PEP's take on the situation would be that sequence[Long()] should fail (which isn't currently the case with my latest PyNumber_Index() changes). If we want to adhere to the behaviour prescribed in the PEP, then it seems like PyNumber_Index() should be reverted back to its original state, and the handling of %n in convertsimple() should be be done without calling PyNumber_Index(). (I assume we *do* want to support `'%n' % Long()` though right, or should the test be done away with?) Note that there's all sorts of problems with PyLong_AsSize_t() on Windows x64 when it comes to handling numbers close, equal or surpassing negative maximums. (See first posting to issue 2440 for examples.) Trent. From guido at python.org Fri Apr 11 19:42:37 2008 From: guido at python.org (Guido van Rossum) Date: Fri, 11 Apr 2008 10:42:37 -0700 Subject: [Python-3000-checkins] [Python-3000] r62269 - in python/branches/py3k: Lib/test/test_getargs2.py Objects/abstract.c Python/getargs.c In-Reply-To: <87D3F9C72FBF214DB39FA4E3FE618CDC6E22D1F951@EXMBX04.exchhosting.com> References: <87D3F9C72FBF214DB39FA4E3FE618CDC6E22D1F94D@EXMBX04.exchhosting.com> <87D3F9C72FBF214DB39FA4E3FE618CDC6E22D1F951@EXMBX04.exchhosting.com> Message-ID: I think you're right, the whole thing ought to be rolled back. The whole point of __index__ was that __int__ cannot be trusted not to truncate floats or float-like types. (Or do other conversions e.g. from string.) On Thu, Apr 10, 2008 at 5:53 PM, Trent Nelson wrote: > > > Does this mean that floats can now be used as list indexes? > > > Preventing this was the motivation for introducing the nb_index slot. > > > > > > from http://www.python.org/dev/peps/pep-0357 :: > > > > > > The biggest example of why using nb_int would be a bad > > > thing is that float objects already define the nb_int method, but > > > float objects *should not* be used as indexes in a sequence. > > > > It sure did! At least, between r62269 and r62279 ;-) Ben pointed out > > my error, which I fixed in r62280. > > > > Trent. > > Hrrm. I just re-read that PEP. This stuck out: > > It is not possible to use the nb_int (and __int__ special method) > for this purpose because that method is used to *coerce* objects > to integers. It would be inappropriate to allow every object that > can be coerced to an integer to be used as an integer everywhere > Python expects a true integer. For example, if __int__ were used > to convert an object to an integer in slicing, then float objects > would be allowed in slicing and x[3.2:5.8] would not raise an error > as it should. > > I think I've pretty much violated the first few sentences with my change to PyNumber_Index(). Even with the change in r62280 which checks that we're not dealing with a float, it's still permitting anything else with an __int__ representation to pass through just fine. > > Note that all of this originated from the following in test_args2: > > class Long: > > def __int__(self): > return 99 > > class Signed_TestCase(unittest.TestCase): > ... > def test_n(self): > ... > self.failUnlessEqual(99, getargs_n(Long())) > > Before the change, %n was passing through to %l unless sizeof(long) != sizeof(size_t) (in convertsimple() -- Python/getargs.c). Windows x64 is the only platform where this assertion holds true, which drew my attention to the problem. > > The PEP's take on the situation would be that sequence[Long()] should fail (which isn't currently the case with my latest PyNumber_Index() changes). If we want to adhere to the behaviour prescribed in the PEP, then it seems like PyNumber_Index() should be reverted back to its original state, and the handling of %n in convertsimple() should be be done without calling PyNumber_Index(). > > (I assume we *do* want to support `'%n' % Long()` though right, or should the test be done away with?) > > Note that there's all sorts of problems with PyLong_AsSize_t() on Windows x64 when it comes to handling numbers close, equal or surpassing negative maximums. (See first posting to issue 2440 for examples.) > > > > > Trent. > _______________________________________________ > Python-3000-checkins mailing list > Python-3000-checkins at python.org > http://mail.python.org/mailman/listinfo/python-3000-checkins > -- --Guido van Rossum (home page: http://www.python.org/~guido/) From thomas at python.org Fri Apr 11 22:49:03 2008 From: thomas at python.org (Thomas Wouters) Date: Fri, 11 Apr 2008 22:49:03 +0200 Subject: [Python-3000-checkins] [Python-3000] r62269 - in python/branches/py3k: Lib/test/test_getargs2.py Objects/abstract.c Python/getargs.c In-Reply-To: <87D3F9C72FBF214DB39FA4E3FE618CDC6E22D1F951@EXMBX04.exchhosting.com> References: <87D3F9C72FBF214DB39FA4E3FE618CDC6E22D1F94D@EXMBX04.exchhosting.com> <87D3F9C72FBF214DB39FA4E3FE618CDC6E22D1F951@EXMBX04.exchhosting.com> Message-ID: <9e804ac0804111349i1aa1870bk960495622bdb1743@mail.gmail.com> On Fri, Apr 11, 2008 at 2:53 AM, Trent Nelson wrote: > > > Does this mean that floats can now be used as list indexes? > > > Preventing this was the motivation for introducing the nb_index slot. > > > > > from http://www.python.org/dev/peps/pep-0357 :: > > > > > > The biggest example of why using nb_int would be a bad > > > thing is that float objects already define the nb_int method, but > > > float objects *should not* be used as indexes in a sequence. > > > It sure did! At least, between r62269 and r62279 ;-) Ben pointed out > > my error, which I fixed in r62280. > > > > Trent. > > Hrrm. I just re-read that PEP. This stuck out: > > It is not possible to use the nb_int (and __int__ special method) > for this purpose because that method is used to *coerce* objects > to integers. It would be inappropriate to allow every object that > can be coerced to an integer to be used as an integer everywhere > Python expects a true integer. For example, if __int__ were used > to convert an object to an integer in slicing, then float objects > would be allowed in slicing and x[3.2:5.8] would not raise an error > as it should. > > I think I've pretty much violated the first few sentences with my change > to PyNumber_Index(). Even with the change in r62280 which checks that we're > not dealing with a float, it's still permitting anything else with an > __int__ representation to pass through just fine. > > Note that all of this originated from the following in test_args2: > > class Long: > def __int__(self): > return 99 > > class Signed_TestCase(unittest.TestCase): > ... > def test_n(self): > ... > self.failUnlessEqual(99, getargs_n(Long())) > > Before the change, %n was passing through to %l unless sizeof(long) != > sizeof(size_t) (in convertsimple() -- Python/getargs.c). Windows x64 is the > only platform where this assertion holds true, which drew my attention to > the problem. > > The PEP's take on the situation would be that sequence[Long()] should fail > (which isn't currently the case with my latest PyNumber_Index() changes). > If we want to adhere to the behaviour prescribed in the PEP, then it seems > like PyNumber_Index() should be reverted back to its original state, and the > handling of %n in convertsimple() should be be done without calling > PyNumber_Index(). > > (I assume we *do* want to support `'%n' % Long()` though right, or should > the test be done away with?) You keep talking about '%n', but the code is used for Py_BuildValue and PyArg_Parse* and such, not for string formatting (unless you are working to change that for some reason?) The 'n' argument to PyArg_Parse* is meant to be used for indices (like most uses of Py_ssize_t), so the change to PyNumber_Index makes no sense, and the test above is actually broken (IMHO.) -- Thomas Wouters Hi! I'm a .signature virus! copy me into your .signature file to help me spread! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-3000-checkins/attachments/20080411/ebb7278c/attachment.htm From python-3000-checkins at python.org Fri Apr 11 23:17:32 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Fri, 11 Apr 2008 23:17:32 +0200 (CEST) Subject: [Python-3000-checkins] r62291 - python/branches/py3k/Doc/library/functions.rst python/branches/py3k/Doc/library/io.rst Message-ID: <20080411211732.879751E4008@bag.python.org> Author: benjamin.peterson Date: Fri Apr 11 23:17:32 2008 New Revision: 62291 Modified: python/branches/py3k/Doc/library/functions.rst python/branches/py3k/Doc/library/io.rst Log: Synced builtin open and io.open documentation, taking the best of each Modified: python/branches/py3k/Doc/library/functions.rst ============================================================================== --- python/branches/py3k/Doc/library/functions.rst (original) +++ python/branches/py3k/Doc/library/functions.rst Fri Apr 11 23:17:32 2008 @@ -698,94 +698,89 @@ :meth:`__index__` method that returns an integer. -.. function:: open(filename[, mode='r'[, buffering=None[, encoding=None[, errors=None[, newline=None[, closefd=True]]]]]]) +.. function:: open(file[, mode='r'[, buffering=None[, encoding=None[, errors=None[, newline=None[, closefd=True]]]]]]) - Open a file, returning an object of the :class:`file` type described in - section :ref:`bltin-file-objects`. If the file cannot be opened, - :exc:`IOError` is raised. When opening a file, it's preferable to use - :func:`open` instead of invoking the :class:`file` constructor directly. + Open a file. If the file cannot be opened, :exc:`IOError` is raised. - *filename* is either a string giving the name (and the path if the - file isn't in the current working directory) of the file to be - opened; or an integer file descriptor of the file to be wrapped. (If - a file descriptor is given, it is closed when the returned I/O object - is closed, unless *closefd* is set to ``False``.) + *file* is either a string giving the name (and the path if the file isn't in + the current working directory) of the file to be opened or an integer file + descriptor of the file to be wrapped. (If a file descriptor is given, it is + closed when the returned I/O object is closed, unless *closefd* is set to + ``False``.) *mode* is an optional string that specifies the mode in which the file is - opened. It defaults to ``'r'`` which means open for reading in text mode. - Other common values are ``'w'`` for writing (truncating the file if - it already exists), and ``'a'`` for appending (which on *some* Unix - systems means that *all* writes append to the end of the file - regardless of the current seek position). In text mode, if *encoding* - is not specified the encoding used is platform dependent. (For reading - and writing raw bytes use binary mode and leave *encoding* - unspecified.) The available modes are: - - * 'r' open for reading (default) - * 'w' open for writing, truncating the file first - * 'a' open for writing, appending to the end if the file exists - * 'b' binary mode - * 't' text mode (default) - * '+' open the file for updating (implies both reading and writing) - * 'U' universal newline mode (for backwards compatibility; - unnecessary in new code) - - The most commonly-used values of *mode* are ``'r'`` for reading, ``'w'`` for - writing (truncating the file if it already exists), and ``'a'`` for appending - (which on *some* Unix systems means that *all* writes append to the end of the - file regardless of the current seek position). If *mode* is omitted, it - defaults to ``'r'``. The default is to use text mode, which may convert - ``'\n'`` characters to a platform-specific representation on writing and back - on reading. Thus, when opening a binary file, you should append ``'b'`` to - the *mode* value to open the file in binary mode, which will improve - portability. (Appending ``'b'`` is useful even on systems that don't treat - binary and text files differently, where it serves as documentation.) See below - for more possible values of *mode*. + opened. It defaults to ``'r'`` which means open for reading in text mode. + Other common values are ``'w'`` for writing (truncating the file if it + already exists), and ``'a'`` for appending (which on *some* Unix systems, + means that *all* writes append to the end of the file regardless of the + current seek position). In text mode, if *encoding* is not specified the + encoding used is platform dependent. (For reading and writing raw bytes use + binary mode and leave *encoding* unspecified.) The available modes are: + + ========= =============================================================== + Character Meaning + --------- --------------------------------------------------------------- + ``'r'`` open for reading (default) + ``'w'`` open for writing, truncating the file first + ``'a'`` open for writing, appending to the end of the file if it exists + ``'b'`` binary mode + ``'t'`` text mode (default) + ``'+'`` open a disk file for updating (reading and writing) + ``'U'`` universal newline mode (for backwards compatibility; unneeded + for new code) + ========= =============================================================== + + The default mode is ``'rt'`` (open for reading text). For binary random + access, the mode ``'w+b'`` opens and truncates the file to 0 bytes, while + ``'r+b'`` opens the file without truncation. Python distinguishes between files opened in binary and text modes, even when the underlying operating system doesn't. Files opened in binary mode (appending ``'b'`` to the *mode* argument) return contents as - ``bytes`` objects without any decoding. In text mode (the default, - or when ``'t'`` is appended to the *mode* argument) the contents of + ``bytes`` objects without any decoding. In text mode (the default, or when + ``'t'`` is appended to the *mode* argument) the contents of the file are returned as strings, the bytes having been first decoded using a platform-dependent encoding or using the specified *encoding* if given. - *buffering* is an optional integer used to set the buffering policy. By - default full buffering is on. Pass 0 to switch buffering off (only - allowed in binary mode), 1 to set line buffering, and an integer > 1 - for full buffering. + *buffering* is an optional integer used to set the buffering policy. By + default full buffering is on. Pass 0 to switch buffering off (only allowed in + binary mode), 1 to set line buffering, and an integer > 1 for full buffering. - *encoding* is an optional string that specifies the file's encoding when - reading or writing in text mode---this argument should not be used in - binary mode. The default encoding is platform dependent, but any encoding - supported by Python can be used. (See the :mod:`codecs` module for - the list of supported encodings.) + *encoding* is the name of the encoding used to decode or encode the file. + This should only be used in text mode. The default encoding is platform + dependent, but any encoding supported by Python can be passed. See the + :mod:`codecs` module for the list of supported encodings. *errors* is an optional string that specifies how encoding errors are to be - handled---this argument should not be used in binary mode. Pass - ``'strict'`` to raise a :exc:`ValueError` exception if there is an encoding - error (the default of ``None`` has the same effect), or pass ``'ignore'`` - to ignore errors. (Note that ignoring encoding errors can lead to - data loss.) See the documentation for :func:`codecs.register` for a - list of the permitted encoding error strings. - - *newline* is an optional string that specifies the newline character(s). - When reading, if *newline* is ``None``, universal newlines mode is enabled. - Lines read in univeral newlines mode can end in ``'\n'``, ``'\r'``, - or ``'\r\n'``, and these are translated into ``'\n'``. If *newline* - is ``''``, universal newline mode is enabled, but line endings are - not translated. If any other string is given, lines are assumed to be - terminated by that string, and no translating is done. When writing, - if *newline* is ``None``, any ``'\n'`` characters written are - translated to the system default line separator, :attr:`os.linesep`. - If *newline* is ``''``, no translation takes place. If *newline* is - any of the other standard values, any ``'\n'`` characters written are - translated to the given string. - - *closefd* is an optional Boolean which specifies whether to keep the - underlying file descriptor open. It must be ``True`` (the default) if - a filename is given. + handled---this argument should not be used in binary mode. Pass ``'strict'`` + to raise a :exc:`ValueError` exception if there is an encoding error (the + default of ``None`` has the same effect), or pass ``'ignore'`` to ignore + errors. (Note that ignoring encoding errors can lead to data loss.) See the + documentation for :func:`codecs.register` for a list of the permitted + encoding error strings. + + *newline* controls how universal newlines works (it only applies to text + mode). It can be ``None``, ``''``, ``'\n'``, ``'\r'``, and ``'\r\n'``. It + works as follows: + + * On input, if *newline* is ``None``, universal newlines mode is enabled. + Lines in the input can end in ``'\n'``, ``'\r'``, or ``'\r\n'``, and these + are translated into ``'\n'`` before being returned to the caller. If it is + ``''``, universal newline mode is enabled, but line endings are returned to + the caller untranslated. If it has any of the other legal values, input + lines are only terminated by the given string, and the line ending is + returned to the caller untranslated. + + * On output, if *newline* is ``None``, any ``'\n'`` characters written are + translated to the system default line separator, :data:`os.linesep`. If + *newline* is ``''``, no translation takes place. If *newline* is any of + the other legal values, any ``'\n'`` characters written are translated to + the given string. + + If *closefd* is ``False``, the underlying file descriptor will be kept open + when the file is closed. This does not work when a file name is given and + must be ``True`` in that case. .. index:: single: line-buffered I/O @@ -796,9 +791,9 @@ single: text mode module: sys - See also the file handling modules, such as, - :mod:`fileinput`, :mod:`os`, :mod:`os.path`, :mod:`tempfile`, and - :mod:`shutil`. + See also the file handling modules, such as, :mod:`fileinput`, :mod:`io` + (where :func:`open()` is declared), :mod:`os`, :mod:`os.path`, + :mod:`tempfile`, and :mod:`shutil`. .. XXX works for bytes too, but should it? Modified: python/branches/py3k/Doc/library/io.rst ============================================================================== --- python/branches/py3k/Doc/library/io.rst (original) +++ python/branches/py3k/Doc/library/io.rst Fri Apr 11 23:17:32 2008 @@ -44,13 +44,23 @@ .. function:: open(file[, mode[, buffering[, encoding[, errors[, newline[, closefd=True]]]]]]) - Open *file* and return a stream. + Open *file* and return a stream. If the file cannot be opened, an + :exc:`IOError` is raised. - *file* is a string giving the name of the file, or an integer file descriptor - of the file to be wrapped. - - The optional *mode* string determines how the file is opened and consists of - a combination of the following characters: + *file* is either a string giving the name (and the path if the file isn't in + the current working directory) of the file to be opened or an integer file + descriptor of the file to be wrapped. (If a file descriptor is given, it is + closed when the returned I/O object is closed, unless *closefd* is set to + ``False``.) + + *mode* is an optional string that specifies the mode in which the file is + opened. It defaults to ``'r'`` which means open for reading in text mode. + Other common values are ``'w'`` for writing (truncating the file if it + already exists), and ``'a'`` for appending (which on *some* Unix systems, + means that *all* writes append to the end of the file regardless of the + current seek position). In text mode, if *encoding* is not specified the + encoding used is platform dependent. (For reading and writing raw bytes use + binary mode and leave *encoding* unspecified.) The available modes are: ========= =============================================================== Character Meaning @@ -69,18 +79,31 @@ access, the mode ``'w+b'`` opens and truncates the file to 0 bytes, while ``'r+b'`` opens the file without truncation. - *buffering* is an optional argument controling the buffering of the returned - stream. A value of ``0`` means no buffering, ``1`` means line buffered, and - a greater value means full buffering with the given buffer size. Buffering - cannot be disabled in text mode. + Python distinguishes between files opened in binary and text modes, even + when the underlying operating system doesn't. Files opened in binary + mode (appending ``'b'`` to the *mode* argument) return contents as + ``bytes`` objects without any decoding. In text mode (the default, or when + ``'t'`` is appended to the *mode* argument) the contents of + the file are returned as strings, the bytes having been first decoded + using a platform-dependent encoding or using the specified *encoding* + if given. + + *buffering* is an optional integer used to set the buffering policy. By + default full buffering is on. Pass 0 to switch buffering off (only allowed in + binary mode), 1 to set line buffering, and an integer > 1 for full buffering. *encoding* is the name of the encoding used to decode or encode the file. - This may only be used in text mode. Any encoding available in the - :mod:`codecs` module registry can be used. - - *errors* specifies how the encoding should treat errors. "strict", the - default raises a :exc:`ValueError` on problems. See the *errors* argument - of :func:`codecs.open` for more information. XXX + This should only be used in text mode. The default encoding is platform + dependent, but any encoding supported by Python can be passed. See the + :mod:`codecs` module for the list of supported encodings. + + *errors* is an optional string that specifies how encoding errors are to be + handled---this argument should not be used in binary mode. Pass ``'strict'`` + to raise a :exc:`ValueError` exception if there is an encoding error (the + default of ``None`` has the same effect), or pass ``'ignore'`` to ignore + errors. (Note that ignoring encoding errors can lead to data loss.) See the + documentation for :func:`codecs.register` for a list of the permitted + encoding error strings. *newline* controls how universal newlines works (it only applies to text mode). It can be ``None``, ``''``, ``'\n'``, ``'\r'``, and ``'\r\n'``. It @@ -100,13 +123,14 @@ the other legal values, any ``'\n'`` characters written are translated to the given string. - If *closefd* is :keyword:`False`, the underlying file descriptor will be kept - open when the file is closed. This does not work when a file name is given. - - The :func:`open` function returns a file object whose type depends on the - mode, and through which the standard file operations such as reading and - writing are performed. When :func:`open` is used to open a file in a text - mode (``'w'``, ``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a + If *closefd* is ``False``, the underlying file descriptor will be kept open + when the file is closed. This does not work when a file name is given and + must be ``True`` in that case. + + :func:`open()` returns a file object whose type depends on the mode, and + through which the standard file operations such as reading and writing are + performed. When :func:`open()` is used to open a file in a text mode + (``'w'``, ``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a :class:`TextIOWrapper`. When used to open a file in a binary mode, the returned class varies: in read binary mode, it returns a :class:`BufferedReader`; in write binary and append binary modes, it returns @@ -114,9 +138,9 @@ :class:`BufferedRandom`. It is also possible to use a string or bytearray as a file for both reading - and writing. For strings :class:`io.StringIO` can be used like a file opened - in a text mode, and for bytes a :class:`io.BytesIO` can be used like a file - opened in a binary mode. + and writing. For strings :class:`StringIO` can be used like a file opened in + a text mode, and for bytes a :class:`BytesIO` can be used like a file opened + in a binary mode. .. exception:: BlockingIOError From python-3000-checkins at python.org Sat Apr 12 01:02:38 2008 From: python-3000-checkins at python.org (trent.nelson) Date: Sat, 12 Apr 2008 01:02:38 +0200 (CEST) Subject: [Python-3000-checkins] r62292 - in python/branches/py3k: Lib/test/test_getargs2.py Objects/abstract.c Python/getargs.c Message-ID: <20080411230238.3F20E1E4024@bag.python.org> Author: trent.nelson Date: Sat Apr 12 01:02:37 2008 New Revision: 62292 Modified: python/branches/py3k/Lib/test/test_getargs2.py python/branches/py3k/Objects/abstract.c python/branches/py3k/Python/getargs.c Log: Issue 2440: revert r62269 and r62279. These changes were made in an effort to fix test_args2.Signed_TestCase.test_n(), which was failing on Windows x64 on the following line: 'self.failUnlessEqual(99, getargs_n(Long()))'. Although the two commits *did* fix the test on Windows x64, it's become clear that it's the test that's incorrect, and the changes to PyNumber_Index() in particular were not warranted (and actually violate PEP 357). This commit will get us back to where we were at r62268, before I started butchering things. Modified: python/branches/py3k/Lib/test/test_getargs2.py ============================================================================== --- python/branches/py3k/Lib/test/test_getargs2.py (original) +++ python/branches/py3k/Lib/test/test_getargs2.py Sat Apr 12 01:02:37 2008 @@ -63,10 +63,6 @@ def __int__(self): return 99 -class InvalidLongAsString: - def __int__(self): - return 'foobar' - class Unsigned_TestCase(unittest.TestCase): def test_b(self): from _testcapi import getargs_b @@ -203,7 +199,6 @@ self.failUnlessEqual(42, getargs_n(42)) self.assertRaises(OverflowError, getargs_n, VERY_LARGE) - self.assertRaises(TypeError, getargs_n, InvalidLongAsString()) class LongLong_TestCase(unittest.TestCase): def test_L(self): Modified: python/branches/py3k/Objects/abstract.c ============================================================================== --- python/branches/py3k/Objects/abstract.c (original) +++ python/branches/py3k/Objects/abstract.c Sat Apr 12 01:02:37 2008 @@ -1220,7 +1220,6 @@ PyObject * PyNumber_Index(PyObject *item) { - PyNumberMethods *m; PyObject *result = NULL; if (item == NULL) return null_error(); @@ -1228,9 +1227,8 @@ Py_INCREF(item); return item; } - m = item->ob_type->tp_as_number; if (PyIndex_Check(item)) { - result = m->nb_index(item); + result = item->ob_type->tp_as_number->nb_index(item); if (result && !PyLong_Check(result)) { PyErr_Format(PyExc_TypeError, "__index__ returned non-int " @@ -1240,17 +1238,7 @@ return NULL; } } - else if (m && m->nb_int != NULL && m->nb_float == NULL) { - result = m->nb_int(item); - if (result && !PyLong_Check(result)) { - PyErr_Format(PyExc_TypeError, - "__int__ returned non-int " - "(type %.200s)", - result->ob_type->tp_name); - Py_DECREF(result); - return NULL; - } - } else { + else { PyErr_Format(PyExc_TypeError, "'%.200s' object cannot be interpreted " "as an integer", item->ob_type->tp_name); Modified: python/branches/py3k/Python/getargs.c ============================================================================== --- python/branches/py3k/Python/getargs.c (original) +++ python/branches/py3k/Python/getargs.c Sat Apr 12 01:02:37 2008 @@ -663,6 +663,7 @@ } case 'n': /* Py_ssize_t */ +#if SIZEOF_SIZE_T != SIZEOF_LONG { PyObject *iobj; Py_ssize_t *p = va_arg(*p_va, Py_ssize_t *); @@ -671,13 +672,14 @@ return converterr("integer", arg, msgbuf, bufsize); iobj = PyNumber_Index(arg); if (iobj != NULL) - ival = PyLong_AsSsize_t(iobj); + ival = PyLong_AsSsize_t(arg); if (ival == -1 && PyErr_Occurred()) return converterr("integer", arg, msgbuf, bufsize); *p = ival; break; } - +#endif + /* Fall through from 'n' to 'l' if Py_ssize_t is int */ case 'l': {/* long int */ long *p = va_arg(*p_va, long *); long ival; From python-3000-checkins at python.org Sat Apr 12 23:40:56 2008 From: python-3000-checkins at python.org (alexandre.vassalotti) Date: Sat, 12 Apr 2008 23:40:56 +0200 (CEST) Subject: [Python-3000-checkins] r62301 - python/branches/py3k/Modules/posixmodule.c Message-ID: <20080412214056.E63191E400E@bag.python.org> Author: alexandre.vassalotti Date: Sat Apr 12 23:40:56 2008 New Revision: 62301 Log: Removed unused variable. Modified: python/branches/py3k/Modules/posixmodule.c Modified: python/branches/py3k/Modules/posixmodule.c ============================================================================== --- python/branches/py3k/Modules/posixmodule.c (original) +++ python/branches/py3k/Modules/posixmodule.c Sat Apr 12 23:40:56 2008 @@ -5539,7 +5539,6 @@ size_t hi = tablesize; int cmp; const char *confname; - Py_ssize_t namelen; if (!PyUnicode_Check(arg)) { PyErr_SetString(PyExc_TypeError, "configuration names must be strings or integers"); @@ -5548,7 +5547,6 @@ confname = PyUnicode_AsString(arg); if (confname == NULL) return 0; - namelen = strlen(confname); while (lo < hi) { mid = (lo + hi) / 2; cmp = strcmp(confname, table[mid].name); From python-3000-checkins at python.org Sun Apr 13 02:27:46 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Sun, 13 Apr 2008 02:27:46 +0200 (CEST) Subject: [Python-3000-checkins] r62307 - in python/branches/py3k: Doc/library/io.rst Lib/io.py Message-ID: <20080413002746.BD5831E400A@bag.python.org> Author: benjamin.peterson Date: Sun Apr 13 02:27:46 2008 New Revision: 62307 Log: Fleshed out docstrings in the io module, improving the reST one as I went. Modified: python/branches/py3k/Doc/library/io.rst python/branches/py3k/Lib/io.py Modified: python/branches/py3k/Doc/library/io.rst ============================================================================== --- python/branches/py3k/Doc/library/io.rst (original) +++ python/branches/py3k/Doc/library/io.rst Sun Apr 13 02:27:46 2008 @@ -27,11 +27,14 @@ buffered interface to random access streams. :class:`BytesIO` is a simple stream of in-memory bytes. -Another :class:`IOBase` subclass, :class:`TextIOBase` deals with the encoding +Another :class:`IOBase` subclass, :class:`TextIOBase`, deals with the encoding and decoding of streams into text. :class:`TextIOWrapper`, which extends it, is a buffered text interface to a buffered raw stream (:class:`BufferedIOBase`). Finally, :class:`StringIO` is a in-memory stream for text. +Argument names are not part of the specification, and only the arguments of +:func:`open()` are intended to be used as keyword arguments. + Module Interface ---------------- @@ -39,8 +42,8 @@ .. data:: DEFAULT_BUFFER_SIZE An int containing the default buffer size used by the module's buffered I/O - classes. :func:`open` uses the file's blksize (as obtained by os.stat) if - possible. + classes. :func:`open()` uses the file's blksize (as obtained by + :func:`os.stat`) if possible. .. function:: open(file[, mode[, buffering[, encoding[, errors[, newline[, closefd=True]]]]]]) @@ -79,18 +82,18 @@ access, the mode ``'w+b'`` opens and truncates the file to 0 bytes, while ``'r+b'`` opens the file without truncation. - Python distinguishes between files opened in binary and text modes, even - when the underlying operating system doesn't. Files opened in binary - mode (appending ``'b'`` to the *mode* argument) return contents as - ``bytes`` objects without any decoding. In text mode (the default, or when - ``'t'`` is appended to the *mode* argument) the contents of - the file are returned as strings, the bytes having been first decoded - using a platform-dependent encoding or using the specified *encoding* - if given. + Python distinguishes between files opened in binary and text modes, even when + the underlying operating system doesn't. Files opened in binary mode + (appending ``'b'`` to the *mode* argument) return contents as ``bytes`` + objects without any decoding. In text mode (the default, or when ``'t'`` is + appended to the *mode* argument), the contents of the file are returned as + strings, the bytes having been first decoded using a platform-dependent + encoding or using the specified *encoding* if given. *buffering* is an optional integer used to set the buffering policy. By - default full buffering is on. Pass 0 to switch buffering off (only allowed in - binary mode), 1 to set line buffering, and an integer > 1 for full buffering. + default full buffering is on. Pass 0 to switch buffering off (only allowed + in binary mode), 1 to set line buffering, and an integer > 1 for full + buffering. *encoding* is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform @@ -176,18 +179,18 @@ file that cannot be read, written or seeked. Even though :class:`IOBase` does not declare :meth:`read`, :meth:`readinto`, - :meth:`seek`, or :meth:`write` because their signatures will vary, - implementations and clients should consider those methods part of the - interface. Also, implementations may raise a :exc:`IOError` when operations - they do not support are called. + or :meth:`write` because their signatures will vary, implementations and + clients should consider those methods part of the interface. Also, + implementations may raise a :exc:`IOError` when operations they do not + support are called. The basic type used for binary data read from or written to a file is :class:`bytes`. :class:`bytearray`\s are accepted too, and in some cases (such as :class:`readinto`) needed. Text I/O classes work with :class:`str` data. - Note that calling any method (even inquiries) on a closed file is undefined. - Implementations may raise :exc:`IOError` in this case. + Note that calling any method (even inquiries) on a closed stream is + undefined. Implementations may raise :exc:`IOError` in this case. IOBase (and its subclasses) support the iterator protocol, meaning that an :class:`IOBase` object can be iterated over yielding the lines in a stream. @@ -212,13 +215,13 @@ .. method:: fileno() Return the underlying file descriptor (an integer) of the stream, if it - exists. Raises :exc:`IOError` if the IO object does not use a file + exists. An :exc:`IOError` is raised if the IO object does not use a file descriptor. .. method:: flush() - Flush the write buffers of the stream if applicable. This is a no-op for - read-only and non-blocking streams. + Flush the write buffers of the stream if applicable. This is not + implemented for read-only and non-blocking streams. .. method:: isatty() @@ -234,8 +237,8 @@ Read and return a line from the stream. If *limit* is specified, at most *limit* bytes will be read. - The line terminator is always ``b'\n'`` for binary files; for text files - the *newlines* argument to :func:`.open` can be used to select the line + The line terminator is always ``b'\n'`` for binary files; for text files, + the *newlines* argument to :func:`.open()` can be used to select the line terminator(s) recognized. .. method:: readlines([hint]) @@ -244,6 +247,18 @@ control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds *hint*. + .. method:: seek(offset[, whence]) + + Change the stream position to byte offset *offset*. *offset* is + interpreted relative to the position indicated by *whence*. Values for + *whence* are: + + * ``0`` -- start of stream (the default); *pos* should be zero or positive + * ``1`` -- current stream position; *pos* may be negative + * ``2`` -- end of stream; *pos* is usually negative + + Return the new absolute position. + .. method:: seekable() Tell if a stream supports random IO access. If ``False``, :meth:`seek`, @@ -253,6 +268,11 @@ Return an integer indicating the current stream position. + .. method:: truncate([pos]) + + Truncate the file to at most *pos* bytes. *pos* defaults to the current + file position, as returned by :meth:`tell`. + .. method:: writable() Tell if a stream supports writing. If ``False``, :meth:`write` and @@ -281,7 +301,18 @@ .. method:: readall() - Read and return all bytes from the stream until EOF. + Read and return all bytes from the stream until EOF, using multiple calls + to the stream. + + .. method:: readinto(b) + + Read up to len(b) bytes into bytearray *b* and return the number of bytes + read. + + .. method:: write(b) + + Write the given bytes, *b*, to the underlying raw stream and return the + number of bytes written (never less than ``len(b)``). Raw File I/O @@ -325,22 +356,6 @@ This method should not be used on :class:`FileIO` objects. - .. method:: seek(offset, [whence]) - - Change the stream position to byte offset *pos*. *pos* is interpreted - relative to the position indicated by *whence*. Values for *whence* are: - - * ``0`` -- start of stream (the default); *pos* should be zero or positive - * ``1`` -- current stream position; *pos* may be negative - * ``2`` -- end of stream; *pos* is usually negative - - Return the new absolute position. - - .. method:: truncate([pos]) - - Truncate the file to at most *pos* bytes. *pos* defaults to the current - file position, as returned by :meth:`tell`. - .. method:: write(b) Write the bytes *b* to the file, and return the number actually written. @@ -397,21 +412,10 @@ A :exc:`BlockingIOError` is raised if the underlying raw stream has no data at the moment. - .. method:: seek(pos[, whence]) - - Change the stream position to byte offset *pos*. *pos* is interpreted - relative to the position indicated by *whence*. Values for *whence* are: - - * ``0`` -- start of stream (the default); *pos* should be zero or positive - * ``1`` -- current stream position; *pos* may be negative - * ``2`` -- end of stream; *pos* is usually negative - - Return the new absolute position. - .. method:: write(b) - Write the given bytes to the underlying raw stream and return the number - of bytes written (never less than ``len(b)``). + Write the given bytes, *b*, to the underlying raw stream and return the + number of bytes written (never less than ``len(b)``). A :exc:`BlockingIOError` is raised if the buffer is full, and the underlying raw stream cannot accept more data at the moment. @@ -433,17 +437,17 @@ .. method:: read1() - In :class:`BytesIO`, this is the same as :meth:`read`. + In :class:`BytesIO`, this is the same as :meth:`read()`. .. method:: truncate([pos]) Truncate the file to at most *pos* bytes. *pos* defaults to the current - stream position, as returned by :meth:`tell`. + stream position, as returned by :meth:`tell()`. -.. class:: BufferedReader(raw, [buffer_size]) +.. class:: BufferedReader(raw[, buffer_size]) - A buffer for a readable sequential RawIO object. It inherits + A buffer for a readable, sequential :class:`BaseRawIO` object. It inherits :class:`BufferedIOBase`. The constructor creates a :class:`BufferedReader` for the given readable @@ -472,7 +476,7 @@ Otherwise, one raw stream read call is made. -.. class:: BufferedWriter(raw, [buffer_size, [max_buffer_size]]) +.. class:: BufferedWriter(raw[, buffer_size[, max_buffer_size]]) A buffer for a writeable sequential RawIO object. It inherits :class:`BufferedIOBase`. @@ -496,7 +500,7 @@ :exc:`BlockingIOError` is raised when the raw stream blocks. -.. class:: BufferedRWPair(reader, writer, [buffer_size, [max_buffer_size]]) +.. class:: BufferedRWPair(reader, writer[, buffer_size[, max_buffer_size]]) A buffered writer and reader object together for a raw stream that can be written and read from. It has and supports both :meth:`read`, :meth:`write`, @@ -511,12 +515,12 @@ :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods. -.. class:: BufferedRandom(raw, [buffer_size, [max_buffer_size]]) +.. class:: BufferedRandom(raw[, buffer_size[, max_buffer_size]]) A buffered interface to random access streams. It inherits :class:`BufferedReader` and :class:`BufferedWriter`. - The constructor creates a reader and writer for a seekable *raw* stream given + The constructor creates a reader and writer for a seekable raw stream, given in the first argument. If the *buffer_size* is omitted it defaults to :data:`DEFAULT_BUFFER_SIZE`. The *max_buffer_size* (for the buffered writer) defaults to twice the buffer size. @@ -558,11 +562,6 @@ Read until newline or EOF and return. If the stream is already at EOF, an empty stream is returned. - .. method:: truncate([pos]) - - Truncate size to *pos*. If *pos* is not specified, it is assumed to be the - current position, as returned by :meth:`tell`. - .. method:: write(s) Write string *s* to the stream and return the number of characters @@ -578,7 +577,7 @@ encoded with. It defaults to :func:`locale.getpreferredencoding`. *errors* determines the strictness of encoding and decoding (see the errors - argument of :func:`codecs.open`) and defaults to "strict". + argument of :func:`codecs.register`) and defaults to ``'strict'``. *newline* can be ``None``, ``''``, ``'\n'``, ``'\r'``, or ``'\r\n'``. It controls the handling of line endings. If it is ``None``, universal newlines @@ -604,12 +603,12 @@ Whether line buffering is enabled. -.. class:: StringIO([initial_value, [encoding, [errors, [newline]]]]) +.. class:: StringIO([initial_value[, encoding[, errors[, newline]]]]) An in-memory stream for text. It in inherits :class:`TextIOWrapper`. Create a new StringIO stream with an inital value, encoding, error handling, - and newline setting. See :class:`TextIOWrapper`'s constructor for more + and newline setting. See :class:`TextIOWrapper`\'s constructor for more information. :class:`StringIO` provides these methods in addition to those from @@ -622,6 +621,6 @@ .. class:: IncrementalNewlineDecoder - A helper codec that decodes newlines. It inherits - :class:`codecs.IncrementalDecoder`. + A helper codec that decodes newlines for universal newlines mode. It + inherits :class:`codecs.IncrementalDecoder`. Modified: python/branches/py3k/Lib/io.py ============================================================================== --- python/branches/py3k/Lib/io.py (original) +++ python/branches/py3k/Lib/io.py Sun Apr 13 02:27:46 2008 @@ -1,24 +1,51 @@ -"""New I/O library conforming to PEP 3116. - -This is a prototype; hopefully eventually some of this will be -reimplemented in C. +""" +The io module provides the Python interfaces to stream handling. The +builtin open function is defined in this module. -Conformance of alternative implementations: all arguments are intended -to be positional-only except the arguments of the open() function. -Argument names except those of the open() function are not part of the -specification. Instance variables and methods whose name starts with -a leading underscore are not part of the specification (except "magic" -names like __iter__). Only the top-level names listed in the __all__ -variable are part of the specification. - -XXX edge cases when switching between reading/writing -XXX need to support 1 meaning line-buffered -XXX whenever an argument is None, use the default value -XXX read/write ops should check readable/writable -XXX buffered readinto should work with arbitrary buffer objects -XXX use incremental encoder for text output, at least for UTF-16 and UTF-8-SIG -XXX check writable, readable and seekable in appropriate places +At the top of the I/O hierarchy is the abstract base class IOBase. It +defines the basic interface to a stream. Note, however, that there is no +seperation between reading and writing to streams; implementations are +allowed to throw an IOError if they do not support a given operation. + +Extending IOBase is RawIOBase which deals simply with the reading and +writing of raw bytes to a stream. FileIO subclasses RawIOBase to provide +an interface to OS files. + +BufferedIOBase deals with buffering on a raw byte stream (RawIOBase). Its +subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer +streams that are readable, writable, and both respectively. +BufferedRandom provides a buffered interface to random access +streams. BytesIO is a simple stream of in-memory bytes. + +Another IOBase subclass, TextIOBase, deals with the encoding and decoding +of streams into text. TextIOWrapper, which extends it, is a buffered text +interface to a buffered raw stream (`BufferedIOBase`). Finally, StringIO +is a in-memory stream for text. + +Argument names are not part of the specification, and only the arguments +of open() are intended to be used as keyword arguments. + +data: + +DEFAULT_BUFFER_SIZE + + An int containing the default buffer size used by the module's buffered + I/O classes. open() uses the file's blksize (as obtained by os.stat) if + possible. """ +# New I/O library conforming to PEP 3116. + +# This is a prototype; hopefully eventually some of this will be +# reimplemented in C. + +# XXX edge cases when switching between reading/writing +# XXX need to support 1 meaning line-buffered +# XXX whenever an argument is None, use the default value +# XXX read/write ops should check readable/writable +# XXX buffered readinto should work with arbitrary buffer objects +# XXX use incremental encoder for text output, at least for UTF-16 and UTF-8-SIG +# XXX check writable, readable and seekable in appropriate places + __author__ = ("Guido van Rossum , " "Mike Verdone , " @@ -51,62 +78,104 @@ def open(file, mode="r", buffering=None, encoding=None, errors=None, newline=None, closefd=True): - r"""Replacement for the built-in open function. - - Args: - file: string giving the name of the file to be opened; - or integer file descriptor of the file to be wrapped (*). - mode: optional mode string; see below. - buffering: optional int >= 0 giving the buffer size; values - can be: 0 = unbuffered, 1 = line buffered, - larger = fully buffered. - encoding: optional string giving the text encoding. - errors: optional string giving the encoding error handling. - newline: optional newlines specifier; must be None, '', '\n', '\r' - or '\r\n'; all other values are illegal. It controls the - handling of line endings. It works as follows: - - * On input, if `newline` is `None`, universal newlines - mode is enabled. Lines in the input can end in `'\n'`, - `'\r'`, or `'\r\n'`, and these are translated into - `'\n'` before being returned to the caller. If it is - `''`, universal newline mode is enabled, but line endings - are returned to the caller untranslated. If it has any of - the other legal values, input lines are only terminated by - the given string, and the line ending is returned to the - caller untranslated. - - * On output, if `newline` is `None`, any `'\n'` - characters written are translated to the system default - line separator, `os.linesep`. If `newline` is `''`, - no translation takes place. If `newline` is any of the - other legal values, any `'\n'` characters written are - translated to the given string. - - closefd: optional argument to keep the underlying file descriptor - open when the file is closed. It must not be false when - a filename is given. - - (*) If a file descriptor is given, it is closed when the returned - I/O object is closed, unless closefd=False is given. - - Mode strings characters: - 'r': open for reading (default) - 'w': open for writing, truncating the file first - 'a': open for writing, appending to the end if the file exists - 'b': binary mode - 't': text mode (default) - '+': open a disk file for updating (implies reading and writing) - 'U': universal newline mode (for backwards compatibility) - - Constraints: - - encoding or errors must not be given when a binary mode is given - - buffering must not be zero when a text mode is given - - Returns: - Depending on the mode and buffering arguments, either a raw - binary stream, a buffered binary stream, or a buffered text - stream, open for reading and/or writing. + r""" + Open file and return a stream. If the file cannot be opened, an + IOError is raised. + + file is either a string giving the name (and the path if the file + isn't in the current working directory) of the file to be opened or an + integer file descriptor of the file to be wrapped. (If a file + descriptor is given, it is closed when the returned I/O object is + closed, unless closefd is set to False.) + + mode is an optional string that specifies the mode in which the file + is opened. It defaults to 'r' which means open for reading in text + mode. Other common values are 'w' for writing (truncating the file if + it already exists), and 'a' for appending (which on some Unix systems, + means that all writes append to the end of the file regardless of the + current seek position). In text mode, if encoding is not specified the + encoding used is platform dependent. (For reading and writing raw + bytes use binary mode and leave encoding unspecified.) The available + modes are: + + ========= =============================================================== + Character Meaning + --------- --------------------------------------------------------------- + 'r' open for reading (default) + 'w' open for writing, truncating the file first + 'a' open for writing, appending to the end of the file if it exists + 'b' binary mode + 't' text mode (default) + '+' open a disk file for updating (reading and writing) + 'U' universal newline mode (for backwards compatibility; unneeded + for new code) + ========= =============================================================== + + The default mode is 'rt' (open for reading text). For binary random + access, the mode 'w+b' opens and truncates the file to 0 bytes, while + 'r+b' opens the file without truncation. + + Python distinguishes between files opened in binary and text modes, + even when the underlying operating system doesn't. Files opened in + binary mode (appending 'b' to the mode argument) return contents as + bytes objects without any decoding. In text mode (the default, or when + 't' is appended to the mode argument), the contents of the file are + returned as strings, the bytes having been first decoded using a + platform-dependent encoding or using the specified encoding if given. + + buffering is an optional integer used to set the buffering policy. By + default full buffering is on. Pass 0 to switch buffering off (only + allowed in binary mode), 1 to set line buffering, and an integer > 1 + for full buffering. + + encoding is the name of the encoding used to decode or encode the + file. This should only be used in text mode. The default encoding is + platform dependent, but any encoding supported by Python can be + passed. See the codecs module for the list of supported encodings. + + errors is an optional string that specifies how encoding errors are to + be handled---this argument should not be used in binary mode. Pass + 'strict' to raise a ValueError exception if there is an encoding error + (the default of None has the same effect), or pass 'ignore' to ignore + errors. (Note that ignoring encoding errors can lead to data loss.) + See the documentation for codecs.register for a list of the permitted + encoding error strings. + + newline controls how universal newlines works (it only applies to text + mode). It can be None, '', '\n', '\r', and '\r\n'. It works as + follows: + + * On input, if newline is None, universal newlines mode is + enabled. Lines in the input can end in '\n', '\r', or '\r\n', and + these are translated into '\n' before being returned to the + caller. If it is '', universal newline mode is enabled, but line + endings are returned to the caller untranslated. If it has any of + the other legal values, input lines are only terminated by the given + string, and the line ending is returned to the caller untranslated. + + * On output, if newline is None, any '\n' characters written are + translated to the system default line separator, os.linesep. If + newline is '', no translation takes place. If newline is any of the + other legal values, any '\n' characters written are translated to + the given string. + + If closefd is False, the underlying file descriptor will be kept open + when the file is closed. This does not work when a file name is given + and must be True in that case. + + open() returns a file object whose type depends on the mode, and + through which the standard file operations such as reading and writing + are performed. When open() is used to open a file in a text mode ('w', + 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open + a file in a binary mode, the returned class varies: in read binary + mode, it returns a BufferedReader; in write binary and append binary + modes, it returns a BufferedWriter, and in read/write mode, it returns + a BufferedRandom. + + It is also possible to use a string or bytearray as a file for both + reading and writing. For strings StringIO can be used like a file + opened in a text mode, and for bytes a BytesIO can be used like a file + opened in a binary mode. """ if not isinstance(file, (str, int)): raise TypeError("invalid file: %r" % file) @@ -218,18 +287,35 @@ class IOBase(metaclass=abc.ABCMeta): - """Base class for all I/O classes. + """ + The abstract base class for all I/O classes, acting on streams of + bytes. There is no public constructor. This class provides dummy implementations for many methods that - derived classes can override selectively; the default - implementations represent a file that cannot be read, written or - seeked. + derived classes can override selectively; the default implementations + represent a file that cannot be read, written or seeked. - This does not define read(), readinto() and write(), nor - readline() and friends, since their signatures vary per layer. + Even though IOBase does not declare read, readinto, or write because + their signatures will vary, implementations and clients should + consider those methods part of the interface. Also, implementations + may raise a IOError when operations they do not support are called. + + The basic type used for binary data read from or written to a file is + bytes. bytearrays are accepted too, and in some cases (such as + readinto) needed. Text I/O classes work with str data. - Note that calling any method (even inquiries) on a closed file is + Note that calling any method (even inquiries) on a closed stream is undefined. Implementations may raise IOError in this case. + + IOBase (and its subclasses) support the iterator protocol, meaning + that an IOBase object can be iterated over yielding the lines in a + stream. + + IOBase also supports the :keyword:`with` statement. In this example, + fp is closed after the suite of the with statment is complete: + + with open('spam.txt', 'r') as fp: + fp.write('Spam and eggs!') """ ### Internal ### @@ -244,11 +330,15 @@ def seek(self, pos: int, whence: int = 0) -> int: """seek(pos: int, whence: int = 0) -> int. Change stream position. - Seek to byte offset pos relative to position indicated by whence: - 0 Start of stream (the default). pos should be >= 0; - 1 Current position - pos may be negative; - 2 End of stream - pos usually negative. - Returns the new absolute position. + Change the stream position to byte offset offset. offset is + interpreted relative to the position indicated by whence. Values + for whence are: + + * 0 -- start of stream (the default); offset should be zero or positive + * 1 -- current stream position; offset may be negative + * 2 -- end of stream; offset is usually negative + + Return the new absolute position. """ self._unsupported("seek") @@ -269,7 +359,7 @@ def flush(self) -> None: """flush() -> None. Flushes write buffers, if applicable. - This is a no-op for read-only and non-blocking streams. + This is not implemented for read-only and non-blocking streams. """ # XXX Should this return the number of bytes written??? @@ -278,8 +368,7 @@ def close(self) -> None: """close() -> None. Flushes and closes the IO object. - This must be idempotent. It should also set a flag for the - 'closed' property (see below) to test. + This method has no effect if the file is already closed. """ if not self.__closed: try: @@ -385,8 +474,6 @@ def isatty(self) -> bool: """isatty() -> int. Returns whether this is an 'interactive' stream. - - Returns False if we don't know. """ self._checkClosed() return False @@ -394,7 +481,16 @@ ### Readline[s] and writelines ### def readline(self, limit: int = -1) -> bytes: - """For backwards compatibility, a (slowish) readline().""" + r"""readline(limit: int = -1) -> bytes Read and return a line from the + stream. + + If limit is specified, at most limit bytes will be read. + + The line terminator is always b'\n' for binary files; for text + files, the newlines argument to open can be used to select the line + terminator(s) recognized. + """ + # For backwards compatibility, a (slowish) readline(). if hasattr(self, "peek"): def nreadahead(): readahead = self.peek(1) @@ -430,6 +526,12 @@ return line def readlines(self, hint=None): + """readlines(hint=None) -> list Return a list of lines from the stream. + + hint can be specified to control the number of lines read: no more + lines will be read if the total size (in bytes/characters) of all + lines so far exceeds hint. + """ if hint is None: return list(self) n = 0 @@ -449,18 +551,17 @@ class RawIOBase(IOBase): - """Base class for raw binary I/O. + """Base class for raw binary I/O.""" - The read() method is implemented by calling readinto(); derived - classes that want to support read() only need to implement - readinto() as a primitive operation. In general, readinto() - can be more efficient than read(). - - (It would be tempting to also provide an implementation of - readinto() in terms of read(), in case the latter is a more - suitable primitive operation, but that would lead to nasty - recursion in case a subclass doesn't implement either.) - """ + # The read() method is implemented by calling readinto(); derived + # classes that want to support read() only need to implement + # readinto() as a primitive operation. In general, readinto() can be + # more efficient than read(). + + # (It would be tempting to also provide an implementation of + # readinto() in terms of read(), in case the latter is a more suitable + # primitive operation, but that would lead to nasty recursion in case + # a subclass doesn't implement either.) def read(self, n: int = -1) -> bytes: """read(n: int) -> bytes. Read and return up to n bytes. @@ -505,13 +606,12 @@ class FileIO(_fileio._FileIO, RawIOBase): - """Raw I/O implementation for OS files. + """Raw I/O implementation for OS files.""" - This multiply inherits from _FileIO and RawIOBase to make - isinstance(io.FileIO(), io.RawIOBase) return True without - requiring that _fileio._FileIO inherits from io.RawIOBase (which - would be hard to do since _fileio.c is written in C). - """ + # This multiply inherits from _FileIO and RawIOBase to make + # isinstance(io.FileIO(), io.RawIOBase) return True without requiring + # that _fileio._FileIO inherits from io.RawIOBase (which would be hard + # to do since _fileio.c is written in C). def close(self): _fileio._FileIO.close(self) @@ -567,9 +667,8 @@ def readinto(self, b: bytearray) -> int: """readinto(b: bytearray) -> int. Read up to len(b) bytes into b. - Like read(), this may issue multiple reads to the underlying - raw stream, unless the latter is 'interactive' (XXX or a - pipe?). + Like read(), this may issue multiple reads to the underlying raw + stream, unless the latter is 'interactive'. Returns the number of bytes read (0 for EOF). @@ -671,8 +770,6 @@ """Buffered I/O implementation using an in-memory bytes buffer.""" - # XXX More docs - def __init__(self, initial_bytes=None): buf = bytearray() if initial_bytes is not None: @@ -681,6 +778,8 @@ self._pos = 0 def getvalue(self): + """getvalue() -> bytes Return the bytes value (contents) of the buffer + """ return bytes(self._buffer) def read(self, n=None): @@ -694,6 +793,8 @@ return bytes(b) def read1(self, n): + """In BytesIO, this is the same as read. + """ return self.read(n) def write(self, b): @@ -748,7 +849,14 @@ class BufferedReader(_BufferedIOMixin): - """Buffer for a readable sequential RawIO object.""" + """BufferedReader(raw[, buffer_size]) + + A buffer for a readable, sequential BaseRawIO object. + + The constructor creates a BufferedReader for the given readable raw + stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE + is used. + """ def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE): """Create a new buffered reader using the given readable raw IO object. @@ -803,11 +911,9 @@ return self._read_buf def read1(self, n): - """Reads up to n bytes, with at most one read() system call. - - Returns up to n bytes. If at least one byte is buffered, we - only return buffered bytes. Otherwise, we do one raw read. - """ + """Reads up to n bytes, with at most one read() system call.""" + # Returns up to n bytes. If at least one byte is buffered, we + # only return buffered bytes. Otherwise, we do one raw read. if n <= 0: return b"" self.peek(1) @@ -826,7 +932,15 @@ class BufferedWriter(_BufferedIOMixin): - # XXX docstring + """BufferedWriter(raw[, buffer_size[, max_buffer_size]]) + + A buffer for a writeable sequential RawIO object. + + The constructor creates a BufferedWriter for the given writeable raw + stream. If the buffer_size is not given, it defaults to + DEAFULT_BUFFER_SIZE. If max_buffer_size is omitted, it defaults to + twice the buffer size. + """ def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None): @@ -894,15 +1008,19 @@ """A buffered reader and writer object together. - A buffered reader object and buffered writer object put together - to form a sequential IO object that can read and write. - - This is typically used with a socket or two-way pipe. - - XXX The usefulness of this (compared to having two separate IO - objects) is questionable. + A buffered reader object and buffered writer object put together to + form a sequential IO object that can read and write. This is typically + used with a socket or two-way pipe. + + reader and writer are RawIOBase objects that are readable and + writeable respectively. If the buffer_size is omitted it defaults to + DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered writer) + defaults to twice the buffer size. """ + # XXX The usefulness of this (compared to having two separate IO + # objects) is questionable. + def __init__(self, reader, writer, buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None): """Constructor. @@ -954,7 +1072,15 @@ class BufferedRandom(BufferedWriter, BufferedReader): - # XXX docstring + """BufferedRandom(raw[, buffer_size[, max_buffer_size]]) + + A buffered interface to random access streams. + + The constructor creates a reader and writer for a seekable stream, + raw, given in the first argument. If the buffer_size is omitted it + defaults to DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered + writer) defaults to twice the buffer size. + """ def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None): @@ -1005,9 +1131,9 @@ """Base class for text I/O. - This class provides a character and line based interface to stream I/O. - - There is no readinto() method, as character strings are immutable. + This class provides a character and line based interface to stream + I/O. There is no readinto method because Python's character strings + are immutable. There is no public constructor. """ def read(self, n: int = -1) -> str: @@ -1055,11 +1181,11 @@ class IncrementalNewlineDecoder(codecs.IncrementalDecoder): - """Codec used when reading a file in universal newlines mode. - It wraps another incremental decoder, translating \\r\\n and \\r into \\n. - It also records the types of newlines encountered. - When used with translate=False, it ensures that the newline sequence is - returned in one piece. + r"""Codec used when reading a file in universal newlines mode. It wraps + another incremental decoder, translating \r\n and \r into \n. It also + records the types of newlines encountered. When used with + translate=False, it ensures that the newline sequence is returned in + one piece. """ def __init__(self, decoder, translate, errors='strict'): codecs.IncrementalDecoder.__init__(self, errors=errors) @@ -1135,9 +1261,28 @@ class TextIOWrapper(TextIOBase): - """Buffered text stream. + r"""TextIOWrapper(buffer[, encoding[, errors[, newline[, line_buffering]]]]) + + Character and line based layer over a BufferedIOBase object, buffer. + + encoding gives the name of the encoding that the stream will be + decoded or encoded with. It defaults to locale.getpreferredencoding. - Character and line based layer over a BufferedIOBase object. + errors determines the strictness of encoding and decoding (see the + codecs.register) and defaults to "strict". + + newline can be None, '', '\n', '\r', or '\r\n'. It controls the + handling of line endings. If it is None, universal newlines is + enabled. With this enabled, on input, the lines endings '\n', '\r', + or '\r\n' are translated to '\n' before being returned to the + caller. Conversely, on output, '\n' is translated to the system + default line seperator, os.linesep. If newline is any other of its + legal values, that newline becomes the newline when the file is read + and it is returned untranslated. On output, '\n' is converted to the + newline. + + If line_buffering is True, a call to flush is implied when a call to + write contains a newline character. """ _CHUNK_SIZE = 128 @@ -1291,13 +1436,14 @@ def _read_chunk(self): """ Read and decode the next chunk of data from the BufferedReader. - - The return value is True unless EOF was reached. The decoded string - is placed in self._decoded_chars (replacing its previous value). - The entire input chunk is sent to the decoder, though some of it - may remain buffered in the decoder, yet to be converted. """ + # The return value is True unless EOF was reached. The decoded + # string is placed in self._decoded_chars (replacing its previous + # value). The entire input chunk is sent to the decoder, though + # some of it may remain buffered in the decoder, yet to be + # converted. + if self._decoder is None: raise ValueError("no decoder") @@ -1575,6 +1721,12 @@ return self._decoder.newlines if self._decoder else None class StringIO(TextIOWrapper): + """StringIO([initial_value[, encoding, [errors, [newline]]]]) + + An in-memory stream for text. The initial_value argument sets the + value of object. The other arguments are like those of TextIOWrapper's + constructor. + """ # XXX This is really slow, but fully functional From python-3000-checkins at python.org Sun Apr 13 04:21:13 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Sun, 13 Apr 2008 04:21:13 +0200 (CEST) Subject: [Python-3000-checkins] r62312 - python/branches/py3k Message-ID: <20080413022113.1715D1E400A@bag.python.org> Author: benjamin.peterson Date: Sun Apr 13 04:21:12 2008 New Revision: 62312 Log: Blocked revisions 62309-62310 via svnmerge ........ r62309 | benjamin.peterson | 2008-04-12 21:01:27 -0500 (Sat, 12 Apr 2008) | 2 lines Backported io module docs ........ r62310 | benjamin.peterson | 2008-04-12 21:05:48 -0500 (Sat, 12 Apr 2008) | 2 lines Backport the removal of a __repr__ from 62251 ........ Modified: python/branches/py3k/ (props changed) From g.brandl at gmx.net Sun Apr 13 09:04:13 2008 From: g.brandl at gmx.net (Georg Brandl) Date: Sun, 13 Apr 2008 09:04:13 +0200 Subject: [Python-3000-checkins] r62307 - in python/branches/py3k: Doc/library/io.rst Lib/io.py In-Reply-To: <20080413002746.BD5831E400A@bag.python.org> References: <20080413002746.BD5831E400A@bag.python.org> Message-ID: benjamin.peterson schrieb: > Author: benjamin.peterson > Date: Sun Apr 13 02:27:46 2008 > New Revision: 62307 > > Log: > Fleshed out docstrings in the io module, improving the reST one as I went. > > > Modified: > python/branches/py3k/Doc/library/io.rst > python/branches/py3k/Lib/io.py > > Modified: python/branches/py3k/Doc/library/io.rst > ============================================================================== > --- python/branches/py3k/Doc/library/io.rst (original) > +++ python/branches/py3k/Doc/library/io.rst Sun Apr 13 02:27:46 2008 > @@ -27,11 +27,14 @@ > buffered interface to random access streams. :class:`BytesIO` is a simple > stream of in-memory bytes. > > -Another :class:`IOBase` subclass, :class:`TextIOBase` deals with the encoding > +Another :class:`IOBase` subclass, :class:`TextIOBase`, deals with the encoding > and decoding of streams into text. :class:`TextIOWrapper`, which extends it, is > a buffered text interface to a buffered raw stream (:class:`BufferedIOBase`). > Finally, :class:`StringIO` is a in-memory stream for text. > > +Argument names are not part of the specification, and only the arguments of > +:func:`open()` are intended to be used as keyword arguments. Please don't add parentheses in :func:`foo` etc.; they are added automatically by Sphinx. > .. method:: flush() > > - Flush the write buffers of the stream if applicable. This is a no-op for > - read-only and non-blocking streams. > + Flush the write buffers of the stream if applicable. This is not > + implemented for read-only and non-blocking streams. "Not implemented" is ambiguous -- does it raise an error? Does it do nothing? > -.. class:: BufferedReader(raw, [buffer_size]) > +.. class:: BufferedReader(raw[, buffer_size]) > > - A buffer for a readable sequential RawIO object. It inherits > + A buffer for a readable, sequential :class:`BaseRawIO` object. It inherits > :class:`BufferedIOBase`. I guess this means RawIOBase? > *errors* determines the strictness of encoding and decoding (see the errors > - argument of :func:`codecs.open`) and defaults to "strict". > + argument of :func:`codecs.register`) and defaults to ``'strict'``. The "errors" argument should be documented in this file too. Georg -- Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are right out. From python-3000-checkins at python.org Sun Apr 13 15:53:35 2008 From: python-3000-checkins at python.org (christian.heimes) Date: Sun, 13 Apr 2008 15:53:35 +0200 (CEST) Subject: [Python-3000-checkins] r62322 - in python/branches/py3k: Doc/conf.py Doc/library/warnings.rst Doc/library/xml.dom.minidom.rst Doc/reference/simple_stmts.rst Doc/tutorial/appetite.rst Doc/whatsnew/2.6.rst Include/Python.h Include/pyerrors.h Include/sysmodule.h Include/traceback.h Include/warnings.h Lib/ftplib.py Lib/test/test_array.py Lib/test/test_deque.py Lib/test/test_support.py Lib/test/test_uu.py Lib/test/test_warnings.py Lib/warnings.py Makefile.pre.in Misc/developers.txt Modules/_ctypes/_ctypes.c Modules/config.c.in Modules/main.c Objects/bytesobject.c Objects/stringobject.c Objects/unicodeobject.c PC/config.c PCbuild/pythoncore.vcproj Python/_warnings.c Python/errors.c Python/getopt.c Python/pythonrun.c Python/sysmodule.c Python/traceback.c Message-ID: <20080413135335.A11DA1E4013@bag.python.org> Author: christian.heimes Date: Sun Apr 13 15:53:33 2008 New Revision: 62322 Log: Merged revisions 62260-62261,62266,62271,62277-62279,62289-62290,62293-62298,62302-62306,62308,62311,62313-62315,62319-62321 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62260 | gregory.p.smith | 2008-04-10 01:11:56 +0200 (Thu, 10 Apr 2008) | 2 lines better diagnostics ........ r62261 | gregory.p.smith | 2008-04-10 01:16:37 +0200 (Thu, 10 Apr 2008) | 3 lines Raise SystemError when size < 0 is passed into PyString_FromStringAndSize, PyBytes_FromStringAndSize or PyUnicode_FromStringAndSize. [issue2587] ........ r62266 | neal.norwitz | 2008-04-10 07:46:39 +0200 (Thu, 10 Apr 2008) | 5 lines Remove the test file before writing it in case there is no write permission. This might help fix some of the failures on Windows box(es). It doesn't hurt either way and ensure the tests are a little more self contained (ie have less assumptions). ........ r62271 | gregory.p.smith | 2008-04-10 21:50:36 +0200 (Thu, 10 Apr 2008) | 2 lines get rid of assert (size >= 0) now that an explicit if (size < 0) is in the code. ........ r62277 | andrew.kuchling | 2008-04-10 23:27:10 +0200 (Thu, 10 Apr 2008) | 1 line Remove forward-looking statement ........ r62278 | andrew.kuchling | 2008-04-10 23:28:51 +0200 (Thu, 10 Apr 2008) | 1 line Add punctuation ........ r62279 | andrew.kuchling | 2008-04-10 23:29:01 +0200 (Thu, 10 Apr 2008) | 1 line Use issue directive ........ r62289 | thomas.heller | 2008-04-11 15:05:38 +0200 (Fri, 11 Apr 2008) | 3 lines Move backwards compatibility macro to the correct place; PyIndex_Check() was introduced in Python 2.5. ........ r62290 | thomas.heller | 2008-04-11 16:20:26 +0200 (Fri, 11 Apr 2008) | 2 lines Performance improvements. ........ r62293 | christian.heimes | 2008-04-12 15:03:03 +0200 (Sat, 12 Apr 2008) | 2 lines Applied patch #2617 from Frank Wierzbicki wit some extras from me -J and -X are now reserved for Jython and non-standard arguments (e.g. IronPython). I've added some extra comments to make sure the reservation don't get missed in the future. ........ r62294 | georg.brandl | 2008-04-12 20:11:18 +0200 (Sat, 12 Apr 2008) | 2 lines Use absolute path in sys.path. ........ r62295 | georg.brandl | 2008-04-12 20:36:09 +0200 (Sat, 12 Apr 2008) | 2 lines #2615: small consistency update by Jeroen Ruigrok van der Werven. ........ r62296 | georg.brandl | 2008-04-12 21:00:20 +0200 (Sat, 12 Apr 2008) | 2 lines Add Jeroen. ........ r62297 | georg.brandl | 2008-04-12 21:05:37 +0200 (Sat, 12 Apr 2008) | 2 lines Don't offend snake lovers. ........ r62298 | gregory.p.smith | 2008-04-12 22:37:48 +0200 (Sat, 12 Apr 2008) | 2 lines fix compiler warnings ........ r62302 | gregory.p.smith | 2008-04-13 00:24:04 +0200 (Sun, 13 Apr 2008) | 3 lines socket.error inherits from IOError, it no longer needs listing in the all_errors tuple. ........ r62303 | brett.cannon | 2008-04-13 01:44:07 +0200 (Sun, 13 Apr 2008) | 8 lines Re-implement the 'warnings' module in C. This allows for usage of the 'warnings' code in places where it was previously not possible (e.g., the parser). It could also potentially lead to a speed-up in interpreter start-up if the C version of the code (_warnings) is imported over the use of the Python version in key places. Closes issue #1631171. ........ r62304 | gregory.p.smith | 2008-04-13 02:03:25 +0200 (Sun, 13 Apr 2008) | 3 lines Adds a profile-opt target for easy compilation of a python binary using gcc's profile guided optimization. ........ r62305 | brett.cannon | 2008-04-13 02:18:44 +0200 (Sun, 13 Apr 2008) | 3 lines Fix a bug in PySys_HasWarnOption() where it was not properly checking the length of the list storing the warning options. ........ r62306 | brett.cannon | 2008-04-13 02:25:15 +0200 (Sun, 13 Apr 2008) | 2 lines Fix an accidental bug of an non-existent init function. ........ r62308 | andrew.kuchling | 2008-04-13 03:05:59 +0200 (Sun, 13 Apr 2008) | 1 line Mention -J, -X ........ r62311 | benjamin.peterson | 2008-04-13 04:20:05 +0200 (Sun, 13 Apr 2008) | 2 lines Give the "Interactive Interpreter Changes" section in 2.6 whatsnew a unique link name ........ r62313 | brett.cannon | 2008-04-13 04:42:36 +0200 (Sun, 13 Apr 2008) | 3 lines Fix test_warnings by making the state of things more consistent for each test when it is run. ........ r62314 | skip.montanaro | 2008-04-13 05:17:30 +0200 (Sun, 13 Apr 2008) | 2 lines spelling ........ r62315 | georg.brandl | 2008-04-13 09:07:44 +0200 (Sun, 13 Apr 2008) | 2 lines Fix markup. ........ r62319 | christian.heimes | 2008-04-13 11:30:17 +0200 (Sun, 13 Apr 2008) | 1 line Fix compiler warning Include/warnings.h:19:28: warning: no newline at end of file ........ r62320 | christian.heimes | 2008-04-13 11:33:24 +0200 (Sun, 13 Apr 2008) | 1 line Use PyString_InternFromString instead of PyString_FromString for static vars ........ r62321 | christian.heimes | 2008-04-13 11:37:05 +0200 (Sun, 13 Apr 2008) | 1 line Added new files to the pcbuild files ........ Added: python/branches/py3k/Include/warnings.h - copied, changed from r62308, /python/trunk/Include/warnings.h python/branches/py3k/Python/_warnings.c - copied, changed from r62308, /python/trunk/Python/_warnings.c Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/conf.py python/branches/py3k/Doc/library/warnings.rst python/branches/py3k/Doc/library/xml.dom.minidom.rst python/branches/py3k/Doc/reference/simple_stmts.rst python/branches/py3k/Doc/tutorial/appetite.rst python/branches/py3k/Doc/whatsnew/2.6.rst python/branches/py3k/Include/Python.h python/branches/py3k/Include/pyerrors.h python/branches/py3k/Include/sysmodule.h python/branches/py3k/Include/traceback.h python/branches/py3k/Lib/ftplib.py python/branches/py3k/Lib/test/test_array.py python/branches/py3k/Lib/test/test_deque.py python/branches/py3k/Lib/test/test_support.py python/branches/py3k/Lib/test/test_uu.py python/branches/py3k/Lib/test/test_warnings.py python/branches/py3k/Lib/warnings.py python/branches/py3k/Makefile.pre.in python/branches/py3k/Misc/developers.txt python/branches/py3k/Modules/_ctypes/_ctypes.c python/branches/py3k/Modules/config.c.in python/branches/py3k/Modules/main.c python/branches/py3k/Objects/bytesobject.c python/branches/py3k/Objects/stringobject.c python/branches/py3k/Objects/unicodeobject.c python/branches/py3k/PC/config.c python/branches/py3k/PCbuild/pythoncore.vcproj python/branches/py3k/Python/errors.c python/branches/py3k/Python/getopt.c python/branches/py3k/Python/pythonrun.c python/branches/py3k/Python/sysmodule.c python/branches/py3k/Python/traceback.c Modified: python/branches/py3k/Doc/conf.py ============================================================================== --- python/branches/py3k/Doc/conf.py (original) +++ python/branches/py3k/Doc/conf.py Sun Apr 13 15:53:33 2008 @@ -8,7 +8,7 @@ # that aren't pickleable (module imports are okay, they're removed automatically). import sys, os, time -sys.path.append('tools/sphinxext') +sys.path.append(os.path.abspath('tools/sphinxext')) # General configuration # --------------------- Modified: python/branches/py3k/Doc/library/warnings.rst ============================================================================== --- python/branches/py3k/Doc/library/warnings.rst (original) +++ python/branches/py3k/Doc/library/warnings.rst Sun Apr 13 15:53:33 2008 @@ -202,16 +202,16 @@ sources). -.. function:: showwarning(message, category, filename, lineno[, file]) +.. function:: showwarning(message, category, filename, lineno[, file[, line]]) Write a warning to a file. The default implementation calls - ``formatwarning(message, category, filename, lineno)`` and writes the resulting - string to *file*, which defaults to ``sys.stderr``. You may replace this - function with an alternative implementation by assigning to + ``formatwarning(message, category, filename, lineno, line)`` and writes the + resulting string to *file*, which defaults to ``sys.stderr``. You may replace + this function with an alternative implementation by assigning to ``warnings.showwarning``. -.. function:: formatwarning(message, category, filename, lineno) +.. function:: formatwarning(message, category, filename, lineno[, line]) Format a warning the standard way. This returns a string which may contain embedded newlines and ends in a newline. Modified: python/branches/py3k/Doc/library/xml.dom.minidom.rst ============================================================================== --- python/branches/py3k/Doc/library/xml.dom.minidom.rst (original) +++ python/branches/py3k/Doc/library/xml.dom.minidom.rst Sun Apr 13 15:53:33 2008 @@ -126,7 +126,7 @@ to discard children of that node. -.. method:: Node.writexml(writer[,indent=""[,addindent=""[,newl=""]]]) +.. method:: Node.writexml(writer[, indent=""[, addindent=""[, newl=""[, encoding=""]]]]) Write XML to the writer object. The writer should have a :meth:`write` method which matches that of the file object interface. The *indent* parameter is the @@ -153,7 +153,7 @@ encoding argument should be specified as "utf-8". -.. method:: Node.toprettyxml([indent[, newl[, encoding]]]) +.. method:: Node.toprettyxml([indent=""[, newl=""[, encoding=""]]]) Return a pretty-printed version of the document. *indent* specifies the indentation string and defaults to a tabulator; *newl* specifies the string Modified: python/branches/py3k/Doc/reference/simple_stmts.rst ============================================================================== --- python/branches/py3k/Doc/reference/simple_stmts.rst (original) +++ python/branches/py3k/Doc/reference/simple_stmts.rst Sun Apr 13 15:53:33 2008 @@ -438,7 +438,36 @@ and is only used in the body of the generator function. Using a :keyword:`yield` statement in a function definition is sufficient to cause that definition to create a generator function instead of a normal function. ->>>>>>> .merge-right.r59773 +When a generator function is called, it returns an iterator known as a generator +iterator, or more commonly, a generator. The body of the generator function is +executed by calling the generator's :meth:`next` method repeatedly until it +raises an exception. + +When a :keyword:`yield` statement is executed, the state of the generator is +frozen and the value of :token:`expression_list` is returned to :meth:`next`'s +caller. By "frozen" we mean that all local state is retained, including the +current bindings of local variables, the instruction pointer, and the internal +evaluation stack: enough information is saved so that the next time :meth:`next` +is invoked, the function can proceed exactly as if the :keyword:`yield` +statement were just another external call. + +As of Python version 2.5, the :keyword:`yield` statement is now allowed in the +:keyword:`try` clause of a :keyword:`try` ... :keyword:`finally` construct. If +the generator is not resumed before it is finalized (by reaching a zero +reference count or by being garbage collected), the generator-iterator's +:meth:`close` method will be called, allowing any pending :keyword:`finally` +clauses to execute. + + +.. seealso:: + + :pep:`0255` - Simple Generators + The proposal for adding generators and the :keyword:`yield` statement to Python. + + :pep:`0342` - Coroutines via Enhanced Generators + The proposal that, among other generator enhancements, proposed allowing + :keyword:`yield` to appear inside a :keyword:`try` ... :keyword:`finally` block. + .. _raise: Modified: python/branches/py3k/Doc/tutorial/appetite.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/appetite.rst (original) +++ python/branches/py3k/Doc/tutorial/appetite.rst Sun Apr 13 15:53:33 2008 @@ -68,7 +68,7 @@ application. By the way, the language is named after the BBC show "Monty Python's Flying -Circus" and has nothing to do with nasty reptiles. Making references to Monty +Circus" and has nothing to do with reptiles. Making references to Monty Python skits in documentation is not only allowed, it is encouraged! Now that you are all excited about Python, you'll want to examine it in some Modified: python/branches/py3k/Doc/whatsnew/2.6.rst ============================================================================== --- python/branches/py3k/Doc/whatsnew/2.6.rst (original) +++ python/branches/py3k/Doc/whatsnew/2.6.rst Sun Apr 13 15:53:33 2008 @@ -40,12 +40,11 @@ * Credit the author of a patch or bugfix. Just the name is sufficient; the e-mail address isn't necessary. - * It's helpful to add the bug/patch number as a comment: + * It's helpful to add the bug/patch number in an parenthetical - .. Patch 12345 XXX Describe the transmogrify() function added to the socket module. - (Contributed by P.Y. Developer.) + (Contributed by P.Y. Developer; :issue:`12345`.) This saves the maintainer the effort of going through the SVN logs when researching a change. @@ -53,11 +52,13 @@ This article explains the new features in Python 2.6. No release date for Python 2.6 has been set; it will probably be released in mid 2008. -This article doesn't attempt to provide a complete specification of the new -features, but instead provides a convenient overview. For full details, you -should refer to the documentation for Python 2.6. If you want to understand the -complete implementation and design rationale, refer to the PEP for a particular -new feature. +This article doesn't attempt to provide a complete specification of +the new features, but instead provides a convenient overview. For +full details, you should refer to the documentation for Python 2.6. If +you want to understand the complete implementation and design +rationale, refer to the PEP for a particular new feature. For smaller +changes, this edition of "What's New in Python" links to the bug/patch +item for each change whenever possible. .. Compare with previous release in 2 - 3 sentences here. add hyperlink when the documentation becomes available online. @@ -147,9 +148,13 @@ set up at http://bugs.python.org. One installation of Roundup can host multiple trackers, and this server now also hosts issue trackers for Jython and for the Python web site. It will surely find -other uses in the future. - -Hosting is kindly provided by `Upfront Systems `__ of Stellenbosch, South Africa. Martin von Loewis put a +other uses in the future. Where possible, +this edition of "What's New in Python" links to the bug/patch +item for each change. + +Hosting is kindly provided by +`Upfront Systems `__ +of Stellenbosch, South Africa. Martin von Loewis put a lot of effort into importing existing bugs and patches from SourceForge; his scripts for this import operation are at http://svn.python.org/view/tracker/importer/. @@ -187,16 +192,15 @@ SGML or, later, XML, but performing a good conversion is a major task and no one pursued the task to completion. -During the 2.6 development cycle, Georg Brandl put a substantial -effort into building a new toolchain called Sphinx -for processing the documentation. -The input format is reStructured Text, -a markup commonly used in the Python community that supports -custom extensions and directives. Sphinx concentrates -on HTML output, producing attractively styled -and modern HTML, though printed output is still supported through -conversion to LaTeX. Sphinx is a standalone package that -can be used in documenting other projects. +During the 2.6 development cycle, Georg Brandl put a substantial +effort into building a new toolchain for processing the documentation. +The resulting package is called Sphinx, and is available from +http://sphinx.pocoo.org/. The input format is reStructured Text, a +markup commonly used in the Python community that supports custom +extensions and directives. Sphinx concentrates on HTML output, +producing attractively styled and modern HTML, though printed output +is still supported through conversion to LaTeX. Sphinx is a +standalone package that can be used in documenting other projects. .. seealso:: @@ -1266,30 +1270,22 @@ have a :meth:`__complex__` method. In particular, the functions in the :mod:`cmath` module will now accept objects with this method. This is a backport of a Python 3.0 change. - (Contributed by Mark Dickinson.) - - .. Patch #1675423 + (Contributed by Mark Dickinson; :issue:`1675423`.) A numerical nicety: when creating a complex number from two floats on systems that support signed zeros (-0 and +0), the :func:`complex` constructor will now preserve the sign - of the zero. - - .. Patch 1507 + of the zero. (:issue:`1507`) * More floating-point features were also added. The :func:`float` function will now turn the strings ``+nan`` and ``-nan`` into the corresponding IEEE 754 Not A Number values, and ``+inf`` and ``-inf`` into positive or negative infinity. This works on any platform with - IEEE 754 semantics. (Contributed by Christian Heimes.) - - .. Patch 1635 + IEEE 754 semantics. (Contributed by Christian Heimes; :issue:`1635`.) Other functions in the :mod:`math` module, :func:`isinf` and :func:`isnan`, return true if their floating-point argument is - infinite or Not A Number. - - .. Patch 1640 + infinite or Not A Number. (:issue:`1640`) The ``math.copysign(x, y)`` function copies the sign bit of an IEEE 754 number, returning the absolute @@ -1306,34 +1302,26 @@ :exc:`BaseException` instead of :exc:`Exception`. This means that an exception handler that does ``except Exception:`` will not inadvertently catch :exc:`GeneratorExit`. - (Contributed by Chad Austin.) - - .. Patch #1537 + (Contributed by Chad Austin; :issue:`1537`.) * Generator objects now have a :attr:`gi_code` attribute that refers to the original code object backing the generator. - (Contributed by Collin Winter.) - - .. Patch #1473257 + (Contributed by Collin Winter; :issue:`1473257`.) * The :func:`compile` built-in function now accepts keyword arguments - as well as positional parameters. (Contributed by Thomas Wouters.) - - .. Patch 1444529 + as well as positional parameters. (Contributed by Thomas Wouters; + :issue:`1444529`.) * The :func:`complex` constructor now accepts strings containing parenthesized complex numbers, letting ``complex(repr(cmplx))`` will now round-trip values. For example, ``complex('(3+4j)')`` - now returns the value (3+4j). - - .. Patch 1491866 + now returns the value (3+4j). (:issue:`1491866`) * The string :meth:`translate` method now accepts ``None`` as the translation table parameter, which is treated as the identity transformation. This makes it easier to carry out operations - that only delete characters. (Contributed by Bengt Richter.) - - .. Patch 1193128 + that only delete characters. (Contributed by Bengt Richter; + :issue:`1193128`.) * The built-in :func:`dir` function now checks for a :meth:`__dir__` method on the objects it receives. This method must return a list @@ -1341,8 +1329,7 @@ and lets the object control the value that :func:`dir` produces. Objects that have :meth:`__getattr__` or :meth:`__getattribute__` methods can use this to advertise pseudo-attributes they will honor. - - .. Patch 1591665 + (:issue:`1591665`) * Instance method objects have new attributes for the object and function comprising the method; the new synonym for :attr:`im_self` is @@ -1368,9 +1355,7 @@ so the cache should remain correct even in the face of Python's dynamic nature. (Original optimization implemented by Armin Rigo, updated for - Python 2.6 by Kevin Jacobs.) - - .. Patch 1700288 + Python 2.6 by Kevin Jacobs; :issue:`1700288`.) * All of the functions in the :mod:`struct` module have been rewritten in C, thanks to work at the Need For Speed sprint. @@ -1398,6 +1383,20 @@ .. ====================================================================== +.. _new-26-interactive: + +Interactive Interpreter Changes +------------------------------- + +Two command-line options have been reserved for use by other Python +implementations. The :option:`-J` switch has been reserved for use by +Jython for Jython-specific options, such as ones that are passed to +the underlying JVM. :option:`-X` has been reserved for options +specific to a particular implementation of Python such as CPython, +Jython, or IronPython. If either option is used with Python 2.6, the +interpreter will report that the option isn't currently used. + +.. ====================================================================== New, Improved, and Deprecated Modules ===================================== @@ -1409,9 +1408,7 @@ * The :mod:`bsddb.dbshelve` module now uses the highest pickling protocol available, instead of restricting itself to protocol 1. - (Contributed by W. Barnes.) - - .. Patch 1551443 + (Contributed by W. Barnes; :issue:`1551443`.) * A new data type in the :mod:`collections` module: :class:`namedtuple(typename, fieldnames)` is a factory function that creates subclasses of the standard tuple @@ -1464,9 +1461,8 @@ (Contributed by Raymond Hettinger.) * The :mod:`ctypes` module now supports a :class:`c_bool` datatype - that represents the C99 ``bool`` type. (Contributed by David Remahl.) - - .. Patch 1649190 + that represents the C99 ``bool`` type. (Contributed by David Remahl; + :issue:`1649190`.) The :mod:`ctypes` string, buffer and array types also have improved support for extended slicing syntax, @@ -1492,9 +1488,7 @@ * The :mod:`datetime` module's :meth:`strftime` methods now support a ``%f`` format code that expands to the number of microseconds in the object, zero-padded on - the left to six places. (Contributed by Skip Montanaro.) - - .. Patch 1158 + the left to six places. (Contributed by Skip Montanaro; :issue:`1158`.) * The :mod:`decimal` module was updated to version 1.66 of `the General Decimal Specification `__. New features @@ -1527,22 +1521,17 @@ :meth:`storbinary` and :meth:`storlines` now take an optional *callback* parameter that will be called with each block of data after the data has been sent. - (Contributed by Phil Schwartz.) - - .. Patch 1221598 + (Contributed by Phil Schwartz; :issue:`1221598`.) * The :func:`reduce` built-in function is also available in the :mod:`functools` module. In Python 3.0, the built-in is dropped and it's only available from :mod:`functools`; currently there are no plans to drop the built-in in the 2.x series. (Patched by - Christian Heimes.) - - .. Patch 1739906 + Christian Heimes; :issue:`1739906`.) * The :func:`glob.glob` function can now return Unicode filenames if - a Unicode path was used and Unicode filenames are matched within the directory. - - .. Patch #1001604 + a Unicode path was used and Unicode filenames are matched within the + directory. (:issue:`1001604`) * The :mod:`gopherlib` module has been removed. @@ -1655,9 +1644,7 @@ * The :mod:`macfs` module has been removed. This in turn required the :func:`macostools.touched` function to be removed because it depended on the - :mod:`macfs` module. - - .. Patch #1490190 + :mod:`macfs` module. (:issue:`1490190`) * :class:`mmap` objects now have a :meth:`rfind` method that finds a substring, beginning at the end of the string and searching @@ -1706,49 +1693,38 @@ visit the directory's contents. For backward compatibility, the parameter's default value is false. Note that the function can fall into an infinite recursion if there's a symlink that points to a - parent directory. + parent directory. (:issue:`1273829`) - .. Patch 1273829 - * The ``os.environ`` object's :meth:`clear` method will now unset the environment variables using :func:`os.unsetenv` in addition to clearing - the object's keys. (Contributed by Martin Horcicka.) - - .. Patch #1181 + the object's keys. (Contributed by Martin Horcicka; :issue:`1181`.) * In the :mod:`os.path` module, the :func:`splitext` function has been changed to not split on leading period characters. This produces better results when operating on Unix's dot-files. For example, ``os.path.splitext('.ipython')`` now returns ``('.ipython', '')`` instead of ``('', '.ipython')``. - - .. Bug #115886 + (:issue:`115886`) A new function, :func:`relpath(path, start)` returns a relative path from the ``start`` path, if it's supplied, or from the current working directory to the destination ``path``. (Contributed by - Richard Barran.) - - .. Patch 1339796 + Richard Barran; :issue:`1339796`.) On Windows, :func:`os.path.expandvars` will now expand environment variables in the form "%var%", and "~user" will be expanded into the - user's home directory path. (Contributed by Josiah Carlson.) - - .. Patch 957650 + user's home directory path. (Contributed by Josiah Carlson; + :issue:`957650`.) * The Python debugger provided by the :mod:`pdb` module gained a new command: "run" restarts the Python program being debugged, and can optionally take new command-line arguments for the program. - (Contributed by Rocky Bernstein.) - - .. Patch #1393667 + (Contributed by Rocky Bernstein; :issue:`1393667`.) The :func:`post_mortem` function, used to enter debugging of a traceback, will now use the traceback returned by :func:`sys.exc_info` - if no traceback is supplied. (Contributed by Facundo Batista.) - - .. Patch #1106316 + if no traceback is supplied. (Contributed by Facundo Batista; + :issue:`1106316`.) * The :mod:`pickletools` module now has an :func:`optimize` function that takes a string containing a pickle and removes some unused @@ -1765,16 +1741,12 @@ ``os.closerange(*low*, *high*)`` efficiently closes all file descriptors from *low* to *high*, ignoring any errors and not including *high* itself. This function is now used by the :mod:`subprocess` module to make starting - processes faster. (Contributed by Georg Brandl.) - - .. Patch #1663329 + processes faster. (Contributed by Georg Brandl; :issue:`1663329`.) * The :mod:`pyexpat` module's :class:`Parser` objects now allow setting their :attr:`buffer_size` attribute to change the size of the buffer used to hold character data. - (Contributed by Achim Gaedke.) - - .. Patch 1137 + (Contributed by Achim Gaedke; :issue:`1137`.) * The :mod:`Queue` module now provides queue classes that retrieve entries in different orders. The :class:`PriorityQueue` class stores @@ -1788,25 +1760,19 @@ system, and vice versa. Unfortunately, this change also means that Python 2.6's :class:`Random` objects can't be unpickled correctly on earlier versions of Python. - (Contributed by Shawn Ligocki.) - - .. Issue 1727780 + (Contributed by Shawn Ligocki; :issue:`1727780`.) The new ``triangular(low, high, mode)`` function returns random numbers following a triangular distribution. The returned values are between *low* and *high*, not including *high* itself, and with *mode* as the mode, the most frequently occurring value in the distribution. (Contributed by Wladmir van der Laan and - Raymond Hettinger.) - - .. Patch 1681432 + Raymond Hettinger; :issue:`1681432`.) * Long regular expression searches carried out by the :mod:`re` module will now check for signals being delivered, so especially long searches can now be interrupted. - (Contributed by Josh Hoyt and Ralf Schmitt.) - - .. Patch 846388 + (Contributed by Josh Hoyt and Ralf Schmitt; :issue:`846388`.) * The :mod:`rgbimg` module has been removed. @@ -1814,9 +1780,7 @@ have a read-only :attr:`queue` attribute that returns the contents of the scheduler's queue, represented as a list of named tuples with the fields ``(time, priority, action, argument)``. - (Contributed by Raymond Hettinger.) - - .. Patch 1861 + (Contributed by Raymond Hettinger; :issue:`1861`.) * The :mod:`select` module now has wrapper functions for the Linux :cfunc:`epoll` and BSD :cfunc:`kqueue` system calls. @@ -1824,11 +1788,7 @@ objects; ``pollobj.modify(fd, eventmask)`` takes a file descriptor or file object and an event mask, - (Contributed by Christian Heimes.) - - .. Patch 1657 - - .. XXX + (Contributed by Christian Heimes; :issue:`1657`.) * The :mod:`sets` module has been deprecated; it's better to use the built-in :class:`set` and :class:`frozenset` types. @@ -1850,9 +1810,7 @@ On receiving a signal, a byte will be written and the main event loop will be woken up, without the need to poll. - (Contributed by Adam Olsen.) - - .. Patch 1583 + (Contributed by Adam Olsen; :issue:`1583`.) The :func:`siginterrupt` function is now available from Python code, and allows changing whether signals can interrupt system calls or not. @@ -1863,10 +1821,7 @@ allows setting interval timers that will cause a signal to be delivered to the process after a specified time, measured in wall-clock time, consumed process time, or combined process+system - time. (Contributed by Guilherme Polo.) - - .. Patch 2240 - + time. (Contributed by Guilherme Polo; :issue:`2240`.) * The :mod:`smtplib` module now supports SMTP over SSL thanks to the addition of the :class:`SMTP_SSL` class. This class supports an @@ -1881,22 +1836,17 @@ (SMTP over SSL contributed by Monty Taylor; timeout parameter added by Facundo Batista; LMTP implemented by Leif - Hedstrom.) - - .. Patch #957003 + Hedstrom; :issue:`957003`.) * In the :mod:`smtplib` module, SMTP.starttls() now complies with :rfc:`3207` and forgets any knowledge obtained from the server not obtained from - the TLS negotiation itself. (Patch contributed by Bill Fenner.) - - .. Issue 829951 + the TLS negotiation itself. (Patch contributed by Bill Fenner; + :issue:`829951`.) * The :mod:`socket` module now supports TIPC (http://tipc.sf.net), a high-performance non-IP-based protocol designed for use in clustered environments. TIPC addresses are 4- or 5-tuples. - (Contributed by Alberto Bertogli.) - - .. Patch #1646 + (Contributed by Alberto Bertogli; :issue:`1646`.) * The base classes in the :mod:`SocketServer` module now support calling a :meth:`handle_timeout` method after a span of inactivity @@ -1904,9 +1854,8 @@ by Michael Pomraning.) The :meth:`serve_forever` method now takes an optional poll interval measured in seconds, controlling how often the server will check for a shutdown request. - (Contributed by Pedro Werneck and Jeffrey Yasskin.) - - .. Patch #742598, #1193577 + (Contributed by Pedro Werneck and Jeffrey Yasskin; + :issue:`742598`, :issue:`1193577`.) * The :mod:`struct` module now supports the C99 :ctype:`_Bool` type, using the format character ``'?'``. @@ -1919,9 +1868,8 @@ include :attr:`mant_dig` (number of digits in the mantissa), :attr:`epsilon` (smallest difference between 1.0 and the next largest value - representable), and several others. (Contributed by Christian Heimes.) - - .. Patch 1534 + representable), and several others. (Contributed by Christian Heimes; + :issue:`1534`.) Another new variable, :attr:`dont_write_bytecode`, controls whether Python writes any :file:`.pyc` or :file:`.pyo` files on importing a module. @@ -1943,9 +1891,7 @@ It's now possible to determine the current profiler and tracer functions by calling :func:`sys.getprofile` and :func:`sys.gettrace`. - (Contributed by Georg Brandl.) - - .. Patch #1648 + (Contributed by Georg Brandl; :issue:`1648`.) * The :mod:`tarfile` module now supports POSIX.1-2001 (pax) and POSIX.1-1988 (ustar) format tarfiles, in addition to the GNU tar @@ -1979,9 +1925,7 @@ * The :class:`tempfile.NamedTemporaryFile` class usually deletes the temporary file it created when the file is closed. This behaviour can now be changed by passing ``delete=False`` to the - constructor. (Contributed by Damien Miller.) - - .. Patch #1537850 + constructor. (Contributed by Damien Miller; :issue:`1537850`.) A new class, :class:`SpooledTemporaryFile`, behaves like a temporary file but stores its data in memory until a maximum size is @@ -1991,9 +1935,7 @@ The :class:`NamedTemporaryFile` and :class:`SpooledTemporaryFile` classes both work as context managers, so you can write ``with tempfile.NamedTemporaryFile() as tmp: ...``. - (Contributed by Alexander Belopolsky.) - - .. Issue #2021 + (Contributed by Alexander Belopolsky; :issue:`2021`.) * The :mod:`test.test_support` module now contains a :func:`EnvironmentVarGuard` @@ -2030,9 +1972,7 @@ whitespace. >>> - (Contributed by Dwayne Bailey.) - - .. Patch #1581073 + (Contributed by Dwayne Bailey; :issue:`1581073`.) * The :mod:`timeit` module now accepts callables as well as strings for the statement being timed and for the setup code. @@ -2040,9 +1980,8 @@ :class:`Timer` instances: ``repeat(stmt, setup, time, repeat, number)`` and ``timeit(stmt, setup, time, number)`` create an instance and call - the corresponding method. (Contributed by Erik Demaine.) - - .. Patch #1533909 + the corresponding method. (Contributed by Erik Demaine; + :issue:`1533909`.) * An optional ``timeout`` parameter was added to the :func:`urllib.urlopen` function and the @@ -2065,9 +2004,7 @@ :attr:`allow_reuse_address` attribute before calling the :meth:`server_bind` and :meth:`server_activate` methods to open the socket and begin listening for connections. - (Contributed by Peter Parente.) - - .. Patch 1599845 + (Contributed by Peter Parente; :issue:`1599845`.) :class:`SimpleXMLRPCServer` also has a :attr:`_send_traceback_header` attribute; if true, the exception and formatted traceback are returned @@ -2090,9 +2027,7 @@ # Unpack all the files in the archive. z.extractall() - (Contributed by Alan McIntyre.) - - .. Patch 467924 + (Contributed by Alan McIntyre; :issue:`467924`.) .. ====================================================================== .. whole new modules get described in subsections here @@ -2178,9 +2113,12 @@ * The BerkeleyDB module now has a C API object, available as ``bsddb.db.api``. This object can be used by other C extensions that wish to use the :mod:`bsddb` module for their own purposes. - (Contributed by Duncan Grisby.) + (Contributed by Duncan Grisby; :issue:`1551895`.) - .. Patch 1551895 +* The new buffer interface, previously described in + `the PEP 3118 section <#pep-3118-revised-buffer-protocol>`__, + adds :cfunc:`PyObject_GetBuffer` and :cfunc:`PyObject_ReleaseBuffer`, + as well as a few other functions. * Python's use of the C stdio library is now thread-safe, or at least as thread-safe as the underlying library is. A long-standing potential @@ -2195,6 +2133,14 @@ immediately after the GIL is re-acquired. (Contributed by Antoine Pitrou and Gregory P. Smith.) +* Importing modules simultaneously in two different threads no longer + deadlocks; it will now raise an :exc:`ImportError`. A new API + function, :cfunc:`PyImport_ImportModuleNoBlock`, will look for a + module in ``sys.modules`` first, then try to import it after + acquiring an import lock. If the import lock is held by another + thread, the :exc:`ImportError` is raised. + (Contributed by Christian Heimes.) + * Several functions return information about the platform's floating-point support. :cfunc:`PyFloat_GetMax` returns the maximum representable floating point value, @@ -2204,16 +2150,12 @@ ``"mant_dig"`` (number of digits in the mantissa), ``"epsilon"`` (smallest difference between 1.0 and the next largest value representable), and several others. - (Contributed by Christian Heimes.) - - .. Issue 1534 + (Contributed by Christian Heimes; :issue:`1534`.) * Python's C API now includes two functions for case-insensitive string comparisons, ``PyOS_stricmp(char*, char*)`` and ``PyOS_strnicmp(char*, char*, Py_ssize_t)``. - (Contributed by Christian Heimes.) - - .. Issue 1635 + (Contributed by Christian Heimes; :issue:`1635`.) * Many C extensions define their own little macro for adding integers and strings to the module's dictionary in the @@ -2229,14 +2171,11 @@ :cmacro:`Py_Refcnt()` became :cmacro:`Py_REFCNT()`. The mixed-case macros are still available in Python 2.6 for backward compatibility. - - .. Issue 1629 + (:issue:`1629`) * Distutils now places C extensions it builds in a different directory when running on a debug version of Python. - (Contributed by Collin Winter.) - - .. Patch 1530959 + (Contributed by Collin Winter; :issue:`1530959`.) * Several basic data types, such as integers and strings, maintain internal free lists of objects that can be re-used. The data @@ -2284,8 +2223,7 @@ exposing the :func:`DisableReflectionKey`, :func:`EnableReflectionKey`, and :func:`QueryReflectionKey` functions, which enable and disable registry reflection for 32-bit processes running on 64-bit systems. - - .. Patch 1753245 + (:issue:`1753245`) * The new default compiler on Windows is Visual Studio 2008 (VS 9.0). The build directories for Visual Studio 2003 (VS7.1) and 2005 (VS8.0) @@ -2346,21 +2284,21 @@ the implementation now explicitly checks for this case and raises an :exc:`ImportError`. +* C API: the :cfunc:`PyImport_Import` and :cfunc:`PyImport_ImportModule` + functions now default to absolute imports, not relative imports. + This will affect C extensions that import other modules. + * The :mod:`socket` module exception :exc:`socket.error` now inherits from :exc:`IOError`. Previously it wasn't a subclass of :exc:`StandardError` but now it is, through :exc:`IOError`. - (Implemented by Gregory P. Smith.) - - .. Issue 1706815 + (Implemented by Gregory P. Smith; :issue:`1706815`.) * The :mod:`xmlrpclib` module no longer automatically converts :class:`datetime.date` and :class:`datetime.time` to the :class:`xmlrpclib.DateTime` type; the conversion semantics were not necessarily correct for all applications. Code using :mod:`xmlrpclib` should convert :class:`date` and :class:`time` - instances. - - .. Issue 1330538 + instances. (:issue:`1330538`) * (3.0-warning mode) The :class:`Exception` class now warns when accessed using slicing or index access; having @@ -2384,5 +2322,6 @@ ================ The author would like to thank the following people for offering suggestions, -corrections and assistance with various drafts of this article: Jim Jewett. +corrections and assistance with various drafts of this article: +Georg Brandl, Jim Jewett. Modified: python/branches/py3k/Include/Python.h ============================================================================== --- python/branches/py3k/Include/Python.h (original) +++ python/branches/py3k/Include/Python.h Sun Apr 13 15:53:33 2008 @@ -93,6 +93,7 @@ #include "iterobject.h" #include "genobject.h" #include "descrobject.h" +#include "warnings.h" #include "weakrefobject.h" #include "codecs.h" Modified: python/branches/py3k/Include/pyerrors.h ============================================================================== --- python/branches/py3k/Include/pyerrors.h (original) +++ python/branches/py3k/Include/pyerrors.h Sun Apr 13 15:53:33 2008 @@ -218,13 +218,6 @@ PyObject *dict); PyAPI_FUNC(void) PyErr_WriteUnraisable(PyObject *); -/* Issue a warning or exception */ -PyAPI_FUNC(int) PyErr_WarnEx(PyObject *category, const char *msg, - Py_ssize_t stack_level); -PyAPI_FUNC(int) PyErr_WarnExplicit(PyObject *, const char *, - const char *, int, - const char *, PyObject *); - /* In sigcheck.c or signalmodule.c */ PyAPI_FUNC(int) PyErr_CheckSignals(void); PyAPI_FUNC(void) PyErr_SetInterrupt(void); Modified: python/branches/py3k/Include/sysmodule.h ============================================================================== --- python/branches/py3k/Include/sysmodule.h (original) +++ python/branches/py3k/Include/sysmodule.h Sun Apr 13 15:53:33 2008 @@ -22,6 +22,7 @@ PyAPI_FUNC(void) PySys_ResetWarnOptions(void); PyAPI_FUNC(void) PySys_AddWarnOption(const wchar_t *); +PyAPI_FUNC(int) PySys_HasWarnOptions(void); #ifdef __cplusplus } Modified: python/branches/py3k/Include/traceback.h ============================================================================== --- python/branches/py3k/Include/traceback.h (original) +++ python/branches/py3k/Include/traceback.h Sun Apr 13 15:53:33 2008 @@ -19,6 +19,7 @@ PyAPI_FUNC(int) PyTraceBack_Here(struct _frame *); PyAPI_FUNC(int) PyTraceBack_Print(PyObject *, PyObject *); +PyAPI_FUNC(int) Py_DisplaySourceLine(PyObject *, const char *, int); /* Reveal traceback type so we can typecheck traceback objects */ PyAPI_DATA(PyTypeObject) PyTraceBack_Type; Copied: python/branches/py3k/Include/warnings.h (from r62308, /python/trunk/Include/warnings.h) ============================================================================== --- /python/trunk/Include/warnings.h (original) +++ python/branches/py3k/Include/warnings.h Sun Apr 13 15:53:33 2008 @@ -16,4 +16,5 @@ #ifdef __cplusplus } #endif -#endif /* !Py_WARNINGS_H */ \ No newline at end of file +#endif /* !Py_WARNINGS_H */ + Modified: python/branches/py3k/Lib/ftplib.py ============================================================================== --- python/branches/py3k/Lib/ftplib.py (original) +++ python/branches/py3k/Lib/ftplib.py Sun Apr 13 15:53:33 2008 @@ -65,7 +65,7 @@ # All exceptions (hopefully) that may be raised here and that aren't # (always) programming errors on our side -all_errors = (Error, socket.error, IOError, EOFError) +all_errors = (Error, IOError, EOFError) # Line terminators (we always output CRLF, but accept any of CRLF, CR, LF) Modified: python/branches/py3k/Lib/test/test_array.py ============================================================================== --- python/branches/py3k/Lib/test/test_array.py (original) +++ python/branches/py3k/Lib/test/test_array.py Sun Apr 13 15:53:33 2008 @@ -162,6 +162,7 @@ def test_tofromfile(self): a = array.array(self.typecode, 2*self.example) self.assertRaises(TypeError, a.tofile) + test_support.unlink(test_support.TESTFN) f = open(test_support.TESTFN, 'wb') try: a.tofile(f) Modified: python/branches/py3k/Lib/test/test_deque.py ============================================================================== --- python/branches/py3k/Lib/test/test_deque.py (original) +++ python/branches/py3k/Lib/test/test_deque.py Sun Apr 13 15:53:33 2008 @@ -64,6 +64,7 @@ self.assertEqual(list(d), [7, 8, 9]) d = deque(range(200), maxlen=10) d.append(d) + test_support.unlink(test_support.TESTFN) fo = open(test_support.TESTFN, "w") try: fo.write(str(d)) @@ -283,6 +284,7 @@ d = deque(range(200)) d.append(d) try: + test_support.unlink(test_support.TESTFN) fo = open(test_support.TESTFN, "w") print(d, file=fo, end='') fo.close() Modified: python/branches/py3k/Lib/test/test_support.py ============================================================================== --- python/branches/py3k/Lib/test/test_support.py (original) +++ python/branches/py3k/Lib/test/test_support.py Sun Apr 13 15:53:33 2008 @@ -354,14 +354,26 @@ self.filename = None self.lineno = None - def _showwarning(self, message, category, filename, lineno, file=None): + def _showwarning(self, message, category, filename, lineno, file=None, + line=None): self.message = message self.category = category self.filename = filename self.lineno = lineno + self.line = line + + def reset(self): + self._showwarning(*((None,)*6)) + + def __str__(self): + return ("{message : %r, category : %r, filename : %r, lineno : %s, " + "line : %r}" % (self.message, + self.category.__name__ if self.category else None, + self.filename, self.lineno, self.line)) + @contextlib.contextmanager -def catch_warning(): +def catch_warning(module=warnings): """ Guard the warnings filter from being permanently changed and record the data of the last warning that has been issued. @@ -372,15 +384,15 @@ warnings.warn("foo") assert str(w.message) == "foo" """ - warning = WarningMessage() - original_filters = warnings.filters[:] - original_showwarning = warnings.showwarning - warnings.showwarning = warning._showwarning + warning_obj = WarningMessage() + original_filters = module.filters[:] + original_showwarning = module.showwarning + module.showwarning = warning_obj._showwarning try: - yield warning + yield warning_obj finally: - warnings.showwarning = original_showwarning - warnings.filters = original_filters + module.showwarning = original_showwarning + module.filters = original_filters class EnvironmentVarGuard(object): @@ -542,7 +554,7 @@ 'minsize' is the minimum useful size for the test (in arbitrary, test-interpreted units.) 'memuse' is the number of 'bytes per size' for the test, or a good estimate of it. 'overhead' specifies fixed overhead, - independant of the testsize, and defaults to 5Mb. + independent of the testsize, and defaults to 5Mb. The decorator tries to guess a good value for 'size' and passes it to the decorated test function. If minsize * memuse is more than the Modified: python/branches/py3k/Lib/test/test_uu.py ============================================================================== --- python/branches/py3k/Lib/test/test_uu.py (original) +++ python/branches/py3k/Lib/test/test_uu.py Sun Apr 13 15:53:33 2008 @@ -121,6 +121,7 @@ def test_encode(self): fin = fout = None try: + test_support.unlink(self.tmpin) fin = open(self.tmpin, 'wb') fin.write(plaintext) fin.close() @@ -150,6 +151,7 @@ def test_decode(self): f = None try: + test_support.unlink(self.tmpin) f = open(self.tmpin, 'wb') f.write(encodedtextwrapped(0o644, self.tmpout)) f.close() Modified: python/branches/py3k/Lib/test/test_warnings.py ============================================================================== --- python/branches/py3k/Lib/test/test_warnings.py (original) +++ python/branches/py3k/Lib/test/test_warnings.py Sun Apr 13 15:53:33 2008 @@ -1,4 +1,4 @@ -import warnings +from contextlib import contextmanager import linecache import os from io import StringIO @@ -8,112 +8,358 @@ from test import warning_tests -class TestModule(unittest.TestCase): - def setUp(self): - self.ignored = [w[2].__name__ for w in warnings.filters - if w[0]=='ignore' and w[1] is None and w[3] is None] +import warnings as original_warnings - def test_warn_default_category(self): - with test_support.catch_warning() as w: - for i in range(4): - text = 'multi %d' %i # Different text on each call - warnings.warn(text) - self.assertEqual(str(w.message), text) - self.assert_(w.category is UserWarning) +sys.modules['_warnings'] = 0 +del sys.modules['warnings'] + +import warnings as py_warnings + +del sys.modules['_warnings'] +del sys.modules['warnings'] + +import warnings as c_warnings + +sys.modules['warnings'] = original_warnings + + + at contextmanager +def warnings_state(module): + """Use a specific warnings implementation in warning_tests.""" + global __warningregistry__ + for to_clear in (sys, warning_tests): + try: + to_clear.__warningregistry__.clear() + except AttributeError: + pass + try: + __warningregistry__.clear() + except NameError: + pass + original_warnings = warning_tests.warnings + try: + warning_tests.warnings = module + yield + finally: + warning_tests.warnings = original_warnings - def test_warn_specific_category(self): - with test_support.catch_warning() as w: - text = 'None' - for category in [DeprecationWarning, FutureWarning, - PendingDeprecationWarning, RuntimeWarning, - SyntaxWarning, UserWarning, Warning]: - if category.__name__ in self.ignored: - text = 'filtered out' + category.__name__ - warnings.warn(text, category) - self.assertNotEqual(w.message, text) + +class BaseTest(unittest.TestCase): + + """Basic bookkeeping required for testing.""" + + def setUp(self): + # The __warningregistry__ needs to be in a pristine state for tests + # to work properly. + if '__warningregistry__' in globals(): + del globals()['__warningregistry__'] + if hasattr(warning_tests, '__warningregistry__'): + del warning_tests.__warningregistry__ + if hasattr(sys, '__warningregistry__'): + del sys.__warningregistry__ + # The 'warnings' module must be explicitly set so that the proper + # interaction between _warnings and 'warnings' can be controlled. + sys.modules['warnings'] = self.module + super(BaseTest, self).setUp() + + def tearDown(self): + sys.modules['warnings'] = original_warnings + super(BaseTest, self).tearDown() + + +class FilterTests(object): + + """Testing the filtering functionality.""" + + def test_error(self): + with test_support.catch_warning(self.module) as w: + self.module.resetwarnings() + self.module.filterwarnings("error", category=UserWarning) + self.assertRaises(UserWarning, self.module.warn, + "FilterTests.test_error") + + def test_ignore(self): + with test_support.catch_warning(self.module) as w: + self.module.resetwarnings() + self.module.filterwarnings("ignore", category=UserWarning) + self.module.warn("FilterTests.test_ignore", UserWarning) + self.assert_(not w.message) + + def test_always(self): + with test_support.catch_warning(self.module) as w: + self.module.resetwarnings() + self.module.filterwarnings("always", category=UserWarning) + message = "FilterTests.test_always" + self.module.warn(message, UserWarning) + self.assert_(message, w.message) + w.message = None # Reset. + self.module.warn(message, UserWarning) + self.assert_(w.message, message) + + def test_default(self): + with test_support.catch_warning(self.module) as w: + self.module.resetwarnings() + self.module.filterwarnings("default", category=UserWarning) + message = UserWarning("FilterTests.test_default") + for x in range(2): + self.module.warn(message, UserWarning) + if x == 0: + self.assertEquals(w.message, message) + w.reset() + elif x == 1: + self.assert_(not w.message, "unexpected warning: " + str(w)) else: - text = 'unfiltered %s' % category.__name__ - warnings.warn(text, category) - self.assertEqual(str(w.message), text) - self.assert_(w.category is category) + raise ValueError("loop variant unhandled") + + def test_module(self): + with test_support.catch_warning(self.module) as w: + self.module.resetwarnings() + self.module.filterwarnings("module", category=UserWarning) + message = UserWarning("FilterTests.test_module") + self.module.warn(message, UserWarning) + self.assertEquals(w.message, message) + w.reset() + self.module.warn(message, UserWarning) + self.assert_(not w.message, "unexpected message: " + str(w)) + + def test_once(self): + with test_support.catch_warning(self.module) as w: + self.module.resetwarnings() + self.module.filterwarnings("once", category=UserWarning) + message = UserWarning("FilterTests.test_once") + self.module.warn_explicit(message, UserWarning, "test_warnings.py", + 42) + self.assertEquals(w.message, message) + w.reset() + self.module.warn_explicit(message, UserWarning, "test_warnings.py", + 13) + self.assert_(not w.message) + self.module.warn_explicit(message, UserWarning, "test_warnings2.py", + 42) + self.assert_(not w.message) + + def test_inheritance(self): + with test_support.catch_warning(self.module) as w: + self.module.resetwarnings() + self.module.filterwarnings("error", category=Warning) + self.assertRaises(UserWarning, self.module.warn, + "FilterTests.test_inheritance", UserWarning) + + def test_ordering(self): + with test_support.catch_warning(self.module) as w: + self.module.resetwarnings() + self.module.filterwarnings("ignore", category=UserWarning) + self.module.filterwarnings("error", category=UserWarning, + append=True) + w.reset() + try: + self.module.warn("FilterTests.test_ordering", UserWarning) + except UserWarning: + self.fail("order handling for actions failed") + self.assert_(not w.message) - def test_filtering(self): + def test_filterwarnings(self): # Test filterwarnings(). # Implicitly also tests resetwarnings(). - with test_support.catch_warning() as w: - warnings.filterwarnings("error", "", Warning, "", 0) - self.assertRaises(UserWarning, warnings.warn, 'convert to error') + with test_support.catch_warning(self.module) as w: + self.module.filterwarnings("error", "", Warning, "", 0) + self.assertRaises(UserWarning, self.module.warn, 'convert to error') - warnings.resetwarnings() + self.module.resetwarnings() text = 'handle normally' - warnings.warn(text) + self.module.warn(text) self.assertEqual(str(w.message), text) self.assert_(w.category is UserWarning) - warnings.filterwarnings("ignore", "", Warning, "", 0) + self.module.filterwarnings("ignore", "", Warning, "", 0) text = 'filtered out' - warnings.warn(text) + self.module.warn(text) self.assertNotEqual(str(w.message), text) - warnings.resetwarnings() - warnings.filterwarnings("error", "hex*", Warning, "", 0) - self.assertRaises(UserWarning, warnings.warn, 'hex/oct') + self.module.resetwarnings() + self.module.filterwarnings("error", "hex*", Warning, "", 0) + self.assertRaises(UserWarning, self.module.warn, 'hex/oct') text = 'nonmatching text' - warnings.warn(text) + self.module.warn(text) self.assertEqual(str(w.message), text) self.assert_(w.category is UserWarning) - def test_options(self): - # Uses the private _setoption() function to test the parsing - # of command-line warning arguments - with test_support.catch_warning(): - self.assertRaises(warnings._OptionError, - warnings._setoption, '1:2:3:4:5:6') - self.assertRaises(warnings._OptionError, - warnings._setoption, 'bogus::Warning') - self.assertRaises(warnings._OptionError, - warnings._setoption, 'ignore:2::4:-5') - warnings._setoption('error::Warning::0') - self.assertRaises(UserWarning, warnings.warn, 'convert to error') +class CFilterTests(BaseTest, FilterTests): + module = c_warnings + +class PyFilterTests(BaseTest, FilterTests): + module = py_warnings + + +class WarnTests(unittest.TestCase): + + """Test warnings.warn() and warnings.warn_explicit().""" + + def test_message(self): + with test_support.catch_warning(self.module) as w: + for i in range(4): + text = 'multi %d' %i # Different text on each call. + self.module.warn(text) + self.assertEqual(str(w.message), text) + self.assert_(w.category is UserWarning) def test_filename(self): - with test_support.catch_warning() as w: - warning_tests.inner("spam1") - self.assertEqual(os.path.basename(w.filename), "warning_tests.py") - warning_tests.outer("spam2") - self.assertEqual(os.path.basename(w.filename), "warning_tests.py") + with warnings_state(self.module): + with test_support.catch_warning(self.module) as w: + warning_tests.inner("spam1") + self.assertEqual(os.path.basename(w.filename), "warning_tests.py") + warning_tests.outer("spam2") + self.assertEqual(os.path.basename(w.filename), "warning_tests.py") def test_stacklevel(self): # Test stacklevel argument # make sure all messages are different, so the warning won't be skipped - with test_support.catch_warning() as w: - warning_tests.inner("spam3", stacklevel=1) - self.assertEqual(os.path.basename(w.filename), "warning_tests.py") - warning_tests.outer("spam4", stacklevel=1) - self.assertEqual(os.path.basename(w.filename), "warning_tests.py") - - warning_tests.inner("spam5", stacklevel=2) - self.assertEqual(os.path.basename(w.filename), "test_warnings.py") - warning_tests.outer("spam6", stacklevel=2) - self.assertEqual(os.path.basename(w.filename), "warning_tests.py") + with warnings_state(self.module): + with test_support.catch_warning(self.module) as w: + warning_tests.inner("spam3", stacklevel=1) + self.assertEqual(os.path.basename(w.filename), "warning_tests.py") + warning_tests.outer("spam4", stacklevel=1) + self.assertEqual(os.path.basename(w.filename), "warning_tests.py") + + warning_tests.inner("spam5", stacklevel=2) + self.assertEqual(os.path.basename(w.filename), "test_warnings.py") + warning_tests.outer("spam6", stacklevel=2) + self.assertEqual(os.path.basename(w.filename), "warning_tests.py") + + warning_tests.inner("spam7", stacklevel=9999) + self.assertEqual(os.path.basename(w.filename), "sys") + - warning_tests.inner("spam7", stacklevel=9999) - self.assertEqual(os.path.basename(w.filename), "sys") +class CWarnTests(BaseTest, WarnTests): + module = c_warnings + +class PyWarnTests(BaseTest, WarnTests): + module = py_warnings + + +class WCmdLineTests(unittest.TestCase): + + def test_improper_input(self): + # Uses the private _setoption() function to test the parsing + # of command-line warning arguments + with test_support.catch_warning(self.module): + self.assertRaises(self.module._OptionError, + self.module._setoption, '1:2:3:4:5:6') + self.assertRaises(self.module._OptionError, + self.module._setoption, 'bogus::Warning') + self.assertRaises(self.module._OptionError, + self.module._setoption, 'ignore:2::4:-5') + self.module._setoption('error::Warning::0') + self.assertRaises(UserWarning, self.module.warn, 'convert to error') + +class CWCmdLineTests(BaseTest, WCmdLineTests): + module = c_warnings + +class PyWCmdLineTests(BaseTest, WCmdLineTests): + module = py_warnings + + +class _WarningsTests(BaseTest): + + """Tests specific to the _warnings module.""" + + module = c_warnings + + def test_filter(self): + # Everything should function even if 'filters' is not in warnings. + with test_support.catch_warning(self.module) as w: + self.module.filterwarnings("error", "", Warning, "", 0) + self.assertRaises(UserWarning, self.module.warn, + 'convert to error') + del self.module.filters + self.assertRaises(UserWarning, self.module.warn, + 'convert to error') + + def test_onceregistry(self): + # Replacing or removing the onceregistry should be okay. + global __warningregistry__ + message = UserWarning('onceregistry test') + try: + original_registry = self.module.onceregistry + __warningregistry__ = {} + with test_support.catch_warning(self.module) as w: + self.module.resetwarnings() + self.module.filterwarnings("once", category=UserWarning) + self.module.warn_explicit(message, UserWarning, "file", 42) + self.failUnlessEqual(w.message, message) + w.reset() + self.module.warn_explicit(message, UserWarning, "file", 42) + self.assert_(not w.message) + # Test the resetting of onceregistry. + self.module.onceregistry = {} + __warningregistry__ = {} + self.module.warn('onceregistry test') + self.failUnlessEqual(w.message.args, message.args) + # Removal of onceregistry is okay. + w.reset() + del self.module.onceregistry + __warningregistry__ = {} + self.module.warn_explicit(message, UserWarning, "file", 42) + self.failUnless(not w.message) + finally: + self.module.onceregistry = original_registry + + def test_showwarning_missing(self): + # Test that showwarning() missing is okay. + text = 'del showwarning test' + with test_support.catch_warning(self.module): + self.module.filterwarnings("always", category=UserWarning) + del self.module.showwarning + with test_support.captured_output('stderr') as stream: + self.module.warn(text) + result = stream.getvalue() + self.failUnless(text in result) + + def test_show_warning_output(self): + # With showarning() missing, make sure that output is okay. + text = 'test show_warning' + with test_support.catch_warning(self.module): + self.module.filterwarnings("always", category=UserWarning) + del self.module.showwarning + with test_support.captured_output('stderr') as stream: + warning_tests.inner(text) + result = stream.getvalue() + self.failUnlessEqual(result.count('\n'), 2, + "Too many newlines in %r" % result) + first_line, second_line = result.split('\n', 1) + expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py' + path, line, warning_class, message = first_line.split(':') + line = int(line) + self.failUnlessEqual(expected_file, path) + self.failUnlessEqual(warning_class, ' ' + UserWarning.__name__) + self.failUnlessEqual(message, ' ' + text) + expected_line = ' ' + linecache.getline(path, line).strip() + '\n' + assert expected_line + self.failUnlessEqual(second_line, expected_line) class WarningsDisplayTests(unittest.TestCase): + """Test the displaying of warnings and the ability to overload functions + related to displaying warnings.""" + def test_formatwarning(self): message = "msg" category = Warning file_name = os.path.splitext(warning_tests.__file__)[0] + '.py' line_num = 3 file_line = linecache.getline(file_name, line_num).strip() - expect = "%s:%s: %s: %s\n %s\n" % (file_name, line_num, category.__name__, - message, file_line) - self.failUnlessEqual(warnings.formatwarning(message, category, - file_name, line_num), - expect) + format = "%s:%s: %s: %s\n %s\n" + expect = format % (file_name, line_num, category.__name__, message, + file_line) + self.failUnlessEqual(expect, self.module.formatwarning(message, + category, file_name, line_num)) + # Test the 'line' argument. + file_line += " for the win!" + expect = format % (file_name, line_num, category.__name__, message, + file_line) + self.failUnlessEqual(expect, self.module.formatwarning(message, + category, file_name, line_num, file_line)) def test_showwarning(self): file_name = os.path.splitext(warning_tests.__file__)[0] + '.py' @@ -122,22 +368,37 @@ message = 'msg' category = Warning file_object = StringIO() - expect = warnings.formatwarning(message, category, file_name, line_num) - warnings.showwarning(message, category, file_name, line_num, + expect = self.module.formatwarning(message, category, file_name, + line_num) + self.module.showwarning(message, category, file_name, line_num, file_object) self.failUnlessEqual(file_object.getvalue(), expect) + # Test 'line' argument. + expected_file_line += "for the win!" + expect = self.module.formatwarning(message, category, file_name, + line_num, expected_file_line) + file_object = StringIO() + self.module.showwarning(message, category, file_name, line_num, + file_object, expected_file_line) + self.failUnlessEqual(expect, file_object.getvalue()) + +class CWarningsDisplayTests(BaseTest, WarningsDisplayTests): + module = c_warnings + +class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests): + module = py_warnings + + +def test_main(): + test_support.run_unittest(CFilterTests, + PyFilterTests, + CWarnTests, + PyWarnTests, + CWCmdLineTests, PyWCmdLineTests, + _WarningsTests, + CWarningsDisplayTests, PyWarningsDisplayTests, + ) -def test_main(verbose=None): - # Obscure hack so that this test passes after reloads or repeated calls - # to test_main (regrtest -R). - if '__warningregistry__' in globals(): - del globals()['__warningregistry__'] - if hasattr(warning_tests, '__warningregistry__'): - del warning_tests.__warningregistry__ - if hasattr(sys, '__warningregistry__'): - del sys.__warningregistry__ - test_support.run_unittest(TestModule, WarningsDisplayTests) - if __name__ == "__main__": - test_main(verbose=True) + test_main() Modified: python/branches/py3k/Lib/warnings.py ============================================================================== --- python/branches/py3k/Lib/warnings.py (original) +++ python/branches/py3k/Lib/warnings.py Sun Apr 13 15:53:33 2008 @@ -3,143 +3,30 @@ # Note: function level imports should *not* be used # in this module as it may cause import lock deadlock. # See bug 683658. -import sys import linecache +import sys +import types __all__ = ["warn", "showwarning", "formatwarning", "filterwarnings", "resetwarnings"] -# filters contains a sequence of filter 5-tuples -# The components of the 5-tuple are: -# - an action: error, ignore, always, default, module, or once -# - a compiled regex that must match the warning message -# - a class representing the warning category -# - a compiled regex that must match the module that is being warned -# - a line number for the line being warning, or 0 to mean any line -# If either if the compiled regexs are None, match anything. -filters = [] -defaultaction = "default" -onceregistry = {} - -def warn(message, category=None, stacklevel=1): - """Issue a warning, or maybe ignore it or raise an exception.""" - # Check if message is already a Warning object - if isinstance(message, Warning): - category = message.__class__ - # Check category argument - if category is None: - category = UserWarning - assert issubclass(category, Warning) - # Get context information - try: - caller = sys._getframe(stacklevel) - except ValueError: - globals = sys.__dict__ - lineno = 1 - else: - globals = caller.f_globals - lineno = caller.f_lineno - if '__name__' in globals: - module = globals['__name__'] - else: - module = "" - filename = globals.get('__file__') - if filename: - fnl = filename.lower() - if fnl.endswith((".pyc", ".pyo")): - filename = filename[:-1] - else: - if module == "__main__": - try: - filename = sys.argv[0] - except AttributeError: - # embedded interpreters don't have sys.argv, see bug #839151 - filename = '__main__' - if not filename: - filename = module - registry = globals.setdefault("__warningregistry__", {}) - warn_explicit(message, category, filename, lineno, module, registry, - globals) - -def warn_explicit(message, category, filename, lineno, - module=None, registry=None, module_globals=None): - if module is None: - module = filename or "" - if module[-3:].lower() == ".py": - module = module[:-3] # XXX What about leading pathname? - if registry is None: - registry = {} - if isinstance(message, Warning): - text = str(message) - category = message.__class__ - else: - text = message - message = category(message) - key = (text, category, lineno) - # Quick test for common case - if registry.get(key): - return - # Search the filters - for item in filters: - action, msg, cat, mod, ln = item - if ((msg is None or msg.match(text)) and - issubclass(category, cat) and - (mod is None or mod.match(module)) and - (ln == 0 or lineno == ln)): - break - else: - action = defaultaction - # Early exit actions - if action == "ignore": - registry[key] = 1 - return - - # Prime the linecache for formatting, in case the - # "file" is actually in a zipfile or something. - linecache.getlines(filename, module_globals) - - if action == "error": - raise message - # Other actions - if action == "once": - registry[key] = 1 - oncekey = (text, category) - if onceregistry.get(oncekey): - return - onceregistry[oncekey] = 1 - elif action == "always": - pass - elif action == "module": - registry[key] = 1 - altkey = (text, category, 0) - if registry.get(altkey): - return - registry[altkey] = 1 - elif action == "default": - registry[key] = 1 - else: - # Unrecognized actions are errors - raise RuntimeError( - "Unrecognized action (%r) in warnings.filters:\n %s" % - (action, item)) - # Print message and context - showwarning(message, category, filename, lineno) -def showwarning(message, category, filename, lineno, file=None): +def showwarning(message, category, filename, lineno, file=None, line=None): """Hook to write a warning to a file; replace if you like.""" if file is None: file = sys.stderr try: - file.write(formatwarning(message, category, filename, lineno)) + file.write(formatwarning(message, category, filename, lineno, line)) except IOError: pass # the file (probably stderr) is invalid - this warning gets lost. -def formatwarning(message, category, filename, lineno): +def formatwarning(message, category, filename, lineno, line=None): """Function to format a warning the standard way.""" s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message) - line = linecache.getline(filename, lineno).strip() + line = linecache.getline(filename, lineno) if line is None else line if line: - s = s + " " + line + "\n" + line = line.strip() + s += " %s\n" % line return s def filterwarnings(action, message="", category=Warning, module="", lineno=0, @@ -257,7 +144,145 @@ raise _OptionError("invalid warning category: %r" % (category,)) return cat + +# Code typically replaced by _warnings +def warn(message, category=None, stacklevel=1): + """Issue a warning, or maybe ignore it or raise an exception.""" + # Check if message is already a Warning object + if isinstance(message, Warning): + category = message.__class__ + # Check category argument + if category is None: + category = UserWarning + assert issubclass(category, Warning) + # Get context information + try: + caller = sys._getframe(stacklevel) + except ValueError: + globals = sys.__dict__ + lineno = 1 + else: + globals = caller.f_globals + lineno = caller.f_lineno + if '__name__' in globals: + module = globals['__name__'] + else: + module = "" + filename = globals.get('__file__') + if filename: + fnl = filename.lower() + if fnl.endswith((".pyc", ".pyo")): + filename = filename[:-1] + else: + if module == "__main__": + try: + filename = sys.argv[0] + except AttributeError: + # embedded interpreters don't have sys.argv, see bug #839151 + filename = '__main__' + if not filename: + filename = module + registry = globals.setdefault("__warningregistry__", {}) + warn_explicit(message, category, filename, lineno, module, registry, + globals) + +def warn_explicit(message, category, filename, lineno, + module=None, registry=None, module_globals=None): + if module is None: + module = filename or "" + if module[-3:].lower() == ".py": + module = module[:-3] # XXX What about leading pathname? + if registry is None: + registry = {} + if isinstance(message, Warning): + text = str(message) + category = message.__class__ + else: + text = message + message = category(message) + key = (text, category, lineno) + # Quick test for common case + if registry.get(key): + return + # Search the filters + for item in filters: + action, msg, cat, mod, ln = item + if ((msg is None or msg.match(text)) and + issubclass(category, cat) and + (mod is None or mod.match(module)) and + (ln == 0 or lineno == ln)): + break + else: + action = defaultaction + # Early exit actions + if action == "ignore": + registry[key] = 1 + return + + # Prime the linecache for formatting, in case the + # "file" is actually in a zipfile or something. + linecache.getlines(filename, module_globals) + + if action == "error": + raise message + # Other actions + if action == "once": + registry[key] = 1 + oncekey = (text, category) + if onceregistry.get(oncekey): + return + onceregistry[oncekey] = 1 + elif action == "always": + pass + elif action == "module": + registry[key] = 1 + altkey = (text, category, 0) + if registry.get(altkey): + return + registry[altkey] = 1 + elif action == "default": + registry[key] = 1 + else: + # Unrecognized actions are errors + raise RuntimeError( + "Unrecognized action (%r) in warnings.filters:\n %s" % + (action, item)) + # Print message and context + showwarning(message, category, filename, lineno) + + +# filters contains a sequence of filter 5-tuples +# The components of the 5-tuple are: +# - an action: error, ignore, always, default, module, or once +# - a compiled regex that must match the warning message +# - a class representing the warning category +# - a compiled regex that must match the module that is being warned +# - a line number for the line being warning, or 0 to mean any line +# If either if the compiled regexs are None, match anything. +_warnings_defaults = False +try: + from _warnings import (filters, default_action, once_registry, + warn, warn_explicit) + defaultaction = default_action + onceregistry = once_registry + _warnings_defaults = True +except ImportError: + filters = [] + defaultaction = "default" + onceregistry = {} + + # Module initialization _processoptions(sys.warnoptions) -simplefilter("ignore", category=PendingDeprecationWarning, append=1) -simplefilter("ignore", category=ImportWarning, append=1) +if not _warnings_defaults: + simplefilter("ignore", category=PendingDeprecationWarning, append=1) + simplefilter("ignore", category=ImportWarning, append=1) + bytes_warning = sys.flags.bytes_warning + if bytes_warning > 1: + bytes_action = "error" + elif bytes_warning: + bytes_action = "default" + else: + bytes_action = "ignore" + simplefilter(bytes_action, category=BytesWarning, append=1) +del _warnings_defaults Modified: python/branches/py3k/Makefile.pre.in ============================================================================== --- python/branches/py3k/Makefile.pre.in (original) +++ python/branches/py3k/Makefile.pre.in Sun Apr 13 15:53:33 2008 @@ -175,6 +175,10 @@ PYTHON= python$(EXE) BUILDPYTHON= python$(BUILDEXE) +# The task to run while instrument when building the profile-opt target +PROFILE_TASK= Tools/pybench/pybench.py -n 2 --with-gc --with-syscheck +#PROFILE_TASK= Lib/test/regrtest.py + # === Definitions added by makesetup === @@ -244,6 +248,7 @@ ########################################################################## # Python PYTHON_OBJS= \ + Python/_warnings.o \ Python/Python-ast.o \ Python/asdl.o \ Python/ast.o \ @@ -346,6 +351,27 @@ all: build_all build_all: $(BUILDPYTHON) oldsharedmods sharedmods +# Compile a binary with gcc profile guided optimization. +profile-opt: + @echo "Building with support for profile generation:" + $(MAKE) clean + $(MAKE) build_all_generate_profile + @echo "Running benchmark to generate profile data:" + $(MAKE) profile-removal + $(MAKE) run_profile_task + @echo "Rebuilding with profile guided optimizations:" + $(MAKE) clean + $(MAKE) build_all_use_profile + +build_all_generate_profile: + $(MAKE) all CFLAGS="$(CFLAGS) -fprofile-generate" LIBS="$(LIBS) -lgcov" + +run_profile_task: + ./$(BUILDPYTHON) $(PROFILE_TASK) + +build_all_use_profile: + $(MAKE) all CFLAGS="$(CFLAGS) -fprofile-use" + # Build the interpreter $(BUILDPYTHON): Modules/python.o $(LIBRARY) $(LDLIBRARY) $(LINKCC) $(LDFLAGS) $(LINKFORSHARED) -o $@ \ @@ -616,6 +642,7 @@ Include/tupleobject.h \ Include/ucnhash.h \ Include/unicodeobject.h \ + Include/warnings.h \ Include/weakrefobject.h \ pyconfig.h \ $(PARSER_HEADERS) @@ -1100,7 +1127,10 @@ find $(srcdir)/build -name 'fficonfig.h' -exec rm -f {} ';' || true find $(srcdir)/build -name 'fficonfig.py' -exec rm -f {} ';' || true -clobber: clean rmtestturds docclean +profile-removal: + find . -name '*.gc??' -exec rm -f {} ';' + +clobber: clean profile-removal -rm -f $(BUILDPYTHON) $(PGEN) $(LIBRARY) $(LDLIBRARY) $(DLLLIBRARY) \ tags TAGS \ config.cache config.log pyconfig.h Modules/config.c Modified: python/branches/py3k/Misc/developers.txt ============================================================================== --- python/branches/py3k/Misc/developers.txt (original) +++ python/branches/py3k/Misc/developers.txt Sun Apr 13 15:53:33 2008 @@ -17,6 +17,9 @@ Permissions History ------------------- +- Jeroen Ruigrok van der Werven was given SVN access on 12 April 2008 + by Georg Brandl, for documentation work. + - Josiah Carlson was given SVN access on 26 March 2008 by Georg Brandl, for work on asyncore/asynchat. Modified: python/branches/py3k/Modules/_ctypes/_ctypes.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/_ctypes.c (original) +++ python/branches/py3k/Modules/_ctypes/_ctypes.c Sun Apr 13 15:53:33 2008 @@ -2171,7 +2171,7 @@ return 0; } ob = CData_GetContainer(target); - if (ob->b_objects == NULL || !PyDict_Check(ob->b_objects)) { + if (ob->b_objects == NULL || !PyDict_CheckExact(ob->b_objects)) { Py_XDECREF(ob->b_objects); ob->b_objects = keep; /* refcount consumed */ return 0; @@ -4544,7 +4544,7 @@ { PyObject *value = NULL; - if (!PyArg_ParseTuple(args, "|O:POINTER", &value)) + if (!PyArg_UnpackTuple(args, "POINTER", 0, 1, &value)) return -1; if (value == NULL) return 0; @@ -4946,7 +4946,7 @@ } Py_XINCREF(obj->b_objects); result->b_objects = obj->b_objects; - if (result->b_objects && PyDict_Check(result->b_objects)) { + if (result->b_objects && PyDict_CheckExact(result->b_objects)) { PyObject *index; int rc; index = PyLong_FromVoidPtr((void *)src); Modified: python/branches/py3k/Modules/config.c.in ============================================================================== --- python/branches/py3k/Modules/config.c.in (original) +++ python/branches/py3k/Modules/config.c.in Sun Apr 13 15:53:33 2008 @@ -28,6 +28,7 @@ extern void initimp(void); extern void initgc(void); extern void init_ast(void); +extern void _PyWarnings_Init(void); struct _inittab _PyImport_Inittab[] = { @@ -50,6 +51,9 @@ /* This lives in gcmodule.c */ {"gc", initgc}, + /* This lives in _warnings.c */ + {"_warnings", _PyWarnings_Init}, + /* Sentinel */ {0, 0} }; Modified: python/branches/py3k/Modules/main.c ============================================================================== --- python/branches/py3k/Modules/main.c (original) +++ python/branches/py3k/Modules/main.c Sun Apr 13 15:53:33 2008 @@ -45,7 +45,7 @@ static int orig_argc; /* command line options */ -#define BASE_OPTS L"bBc:dEhim:OStuvVW:xX?" +#define BASE_OPTS L"bBc:dEhiJm:OStuvVW:xX?" #define PROGRAM_OPTS BASE_OPTS @@ -345,6 +345,8 @@ Py_InteractiveFlag++; break; + /* case 'J': reserved for Jython */ + case 'O': Py_OptimizeFlag++; break; @@ -378,6 +380,8 @@ skipfirstline = 1; break; + /* case 'X': reserved for non-standard arguments */ + case 'h': case '?': help++; Modified: python/branches/py3k/Objects/bytesobject.c ============================================================================== --- python/branches/py3k/Objects/bytesobject.c (original) +++ python/branches/py3k/Objects/bytesobject.c Sun Apr 13 15:53:33 2008 @@ -108,7 +108,11 @@ PyBytesObject *new; Py_ssize_t alloc; - assert(size >= 0); + if (size < 0) { + PyErr_SetString(PyExc_SystemError, + "Negative size passed to PyBytes_FromStringAndSize"); + return NULL; + } new = PyObject_New(PyBytesObject, &PyBytes_Type); if (new == NULL) Modified: python/branches/py3k/Objects/stringobject.c ============================================================================== --- python/branches/py3k/Objects/stringobject.c (original) +++ python/branches/py3k/Objects/stringobject.c Sun Apr 13 15:53:33 2008 @@ -64,7 +64,11 @@ PyString_FromStringAndSize(const char *str, Py_ssize_t size) { register PyStringObject *op; - assert(size >= 0); + if (size < 0) { + PyErr_SetString(PyExc_SystemError, + "Negative size passed to PyString_FromStringAndSize"); + return NULL; + } if (size == 0 && (op = nullstring) != NULL) { #ifdef COUNT_ALLOCS null_strings++; Modified: python/branches/py3k/Objects/unicodeobject.c ============================================================================== --- python/branches/py3k/Objects/unicodeobject.c (original) +++ python/branches/py3k/Objects/unicodeobject.c Sun Apr 13 15:53:33 2008 @@ -497,6 +497,13 @@ PyObject *PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size) { PyUnicodeObject *unicode; + + if (size < 0) { + PyErr_SetString(PyExc_SystemError, + "Negative size passed to PyUnicode_FromStringAndSize"); + return NULL; + } + /* If the Unicode data is known at construction time, we can apply some optimizations which share commonly used objects. Also, this means the input must be UTF-8, so fall back to the Modified: python/branches/py3k/PC/config.c ============================================================================== --- python/branches/py3k/PC/config.c (original) +++ python/branches/py3k/PC/config.c Sun Apr 13 15:53:33 2008 @@ -60,6 +60,7 @@ extern void init_ast(void); extern void init_fileio(void); extern void initatexit(void); +extern void _PyWarnings_Init(void); /* tools/freeze/makeconfig.py marker for additional "extern" */ /* -- ADDMODULE MARKER 1 -- */ @@ -144,7 +145,8 @@ {"__main__", NULL}, {"builtins", NULL}, {"sys", NULL}, - + {"_warnings", _PyWarnings_Init}, + {"_fileio", init_fileio}, {"atexit", initatexit}, Modified: python/branches/py3k/PCbuild/pythoncore.vcproj ============================================================================== --- python/branches/py3k/PCbuild/pythoncore.vcproj (original) +++ python/branches/py3k/PCbuild/pythoncore.vcproj Sun Apr 13 15:53:33 2008 @@ -1746,6 +1746,10 @@ RelativePath="..\Python\traceback.c" > + + "); + return PyUnicode_FromString(""); - mod_str = PyString_AsString(filename); + mod_str = PyUnicode_AsString(filename); if (mod_str == NULL) return NULL; - len = PyString_Size(filename); + len = PyUnicode_GetSize(filename); if (len < 0) return NULL; if (len >= 3 && strncmp(mod_str + (len - 3), ".py", 3) == 0) { - module = PyString_FromStringAndSize(mod_str, len-3); + module = PyUnicode_FromStringAndSize(mod_str, len-3); } else { module = filename; @@ -211,7 +211,7 @@ int rc; if (add_zero) { - zero = PyInt_FromLong(0); + zero = PyLong_FromLong(0); if (zero == NULL) return -1; altkey = PyTuple_Pack(3, text, category, zero); @@ -258,7 +258,7 @@ /* Print " source_line\n" */ PyFile_WriteString(" ", f_stderr); if (sourceline) { - char *source_line_str = PyString_AS_STRING(sourceline); + char *source_line_str = PyUnicode_AsString(sourceline); while (*source_line_str == ' ' || *source_line_str == '\t' || *source_line_str == '\014') source_line_str++; @@ -267,7 +267,7 @@ PyFile_WriteString("\n", f_stderr); } else - Py_DisplaySourceLine(f_stderr, PyString_AS_STRING(filename), lineno); + Py_DisplaySourceLine(f_stderr, PyUnicode_AsString(filename), lineno); PyErr_Clear(); } @@ -305,7 +305,7 @@ message = PyObject_CallFunction(category, "O", message); } - lineno_obj = PyInt_FromLong(lineno); + lineno_obj = PyLong_FromLong(lineno); if (lineno_obj == NULL) goto cleanup; @@ -359,7 +359,7 @@ const char *err_str = "???"; if (to_str != NULL) - err_str = PyString_AS_STRING(to_str); + err_str = PyUnicode_AsString(to_str); PyErr_Format(PyExc_RuntimeError, "Unrecognized action (%s) in warnings.filters:\n %s", action, err_str); @@ -454,7 +454,7 @@ /* Setup module. */ *module = PyDict_GetItemString(globals, "__name__"); if (*module == NULL) { - *module = PyString_FromString(""); + *module = PyUnicode_FromString(""); if (*module == NULL) goto handle_error; } @@ -464,8 +464,8 @@ /* Setup filename. */ *filename = PyDict_GetItemString(globals, "__file__"); if (*filename != NULL) { - Py_ssize_t len = PyString_Size(*filename); - const char *file_str = PyString_AsString(*filename); + Py_ssize_t len = PyUnicode_GetSize(*filename); + const char *file_str = PyUnicode_AsString(*filename); if (file_str == NULL || (len < 0 && PyErr_Occurred())) goto handle_error; @@ -476,7 +476,7 @@ tolower(file_str[len-2]) == 'y' && (tolower(file_str[len-1]) == 'c' || tolower(file_str[len-1]) == 'o')) { - *filename = PyString_FromStringAndSize(file_str, len-1); + *filename = PyUnicode_FromStringAndSize(file_str, len-1); if (*filename == NULL) goto handle_error; } @@ -484,7 +484,7 @@ Py_INCREF(*filename); } else { - const char *module_str = PyString_AsString(*module); + const char *module_str = PyUnicode_AsString(*module); if (module_str && strcmp(module_str, "__main__") == 0) { PyObject *argv = PySys_GetObject("argv"); if (argv != NULL && PyList_Size(argv) > 0) { @@ -493,7 +493,7 @@ } else { /* embedded interpreters don't have sys.argv, see bug #839151 */ - *filename = PyString_FromString("__main__"); + *filename = PyUnicode_FromString("__main__"); if (*filename == NULL) goto handle_error; } @@ -605,12 +605,12 @@ PyObject *returned; if (get_source_name == NULL) { - get_source_name = PyString_FromString("get_source"); + get_source_name = PyUnicode_InternFromString("get_source"); if (!get_source_name) return NULL; } if (splitlines_name == NULL) { - splitlines_name = PyString_FromString("splitlines"); + splitlines_name = PyUnicode_InternFromString("splitlines"); if (!splitlines_name) return NULL; } @@ -667,7 +667,7 @@ PyErr_WarnEx(PyObject *category, const char *text, Py_ssize_t stack_level) { PyObject *res; - PyObject *message = PyString_FromString(text); + PyObject *message = PyUnicode_FromString(text); if (message == NULL) return -1; @@ -701,15 +701,15 @@ const char *module_str, PyObject *registry) { PyObject *res; - PyObject *message = PyString_FromString(text); - PyObject *filename = PyString_FromString(filename_str); + PyObject *message = PyUnicode_FromString(text); + PyObject *filename = PyUnicode_FromString(filename_str); PyObject *module = NULL; int ret = -1; if (message == NULL || filename == NULL) goto exit; if (module_str != NULL) { - module = PyString_FromString(module_str); + module = PyUnicode_FromString(module_str); if (module == NULL) goto exit; } @@ -759,7 +759,7 @@ if (!strcmp(action, "ignore")) { if (ignore_str == NULL) { - ignore_str = PyString_InternFromString("ignore"); + ignore_str = PyUnicode_InternFromString("ignore"); if (ignore_str == NULL) return NULL; } @@ -767,7 +767,7 @@ } else if (!strcmp(action, "error")) { if (error_str == NULL) { - error_str = PyString_InternFromString("error"); + error_str = PyUnicode_InternFromString("error"); if (error_str == NULL) return NULL; } @@ -775,7 +775,7 @@ } else if (!strcmp(action, "default")) { if (default_str == NULL) { - default_str = PyString_InternFromString("default"); + default_str = PyUnicode_InternFromString("default"); if (default_str == NULL) return NULL; } @@ -786,7 +786,7 @@ } /* This assumes the line number is zero for now. */ - lineno = PyInt_FromLong(0); + lineno = PyLong_FromLong(0); if (lineno == NULL) return NULL; result = PyTuple_Pack(5, action_obj, Py_None, category, Py_None, lineno); @@ -848,7 +848,7 @@ if (PyModule_AddObject(m, "once_registry", _once_registry) < 0) return; - default_action = PyString_InternFromString("default"); + default_action = PyUnicode_InternFromString("default"); if (default_action == NULL) return; if (PyModule_AddObject(m, DEFAULT_ACTION_NAME, default_action) < 0) Modified: python/branches/py3k/Python/errors.c ============================================================================== --- python/branches/py3k/Python/errors.c (original) +++ python/branches/py3k/Python/errors.c Sun Apr 13 15:53:33 2008 @@ -673,70 +673,6 @@ extern PyObject *PyModule_GetWarningsModule(void); -/* Function to issue a warning message; may raise an exception. */ -int -PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level) -{ - PyObject *dict, *func = NULL; - PyObject *warnings_module = PyModule_GetWarningsModule(); - - if (warnings_module != NULL) { - dict = PyModule_GetDict(warnings_module); - if (dict != NULL) - func = PyDict_GetItemString(dict, "warn"); - } - if (func == NULL) { - PySys_WriteStderr("warning: %s\n", message); - return 0; - } - else { - PyObject *res; - - if (category == NULL) - category = PyExc_RuntimeWarning; - res = PyObject_CallFunction(func, "sOn", - message, category, stack_level); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; - } -} - -/* Warning with explicit origin */ -int -PyErr_WarnExplicit(PyObject *category, const char *message, - const char *filename, int lineno, - const char *module, PyObject *registry) -{ - PyObject *mod, *dict, *func = NULL; - - mod = PyImport_ImportModuleNoBlock("warnings"); - if (mod != NULL) { - dict = PyModule_GetDict(mod); - func = PyDict_GetItemString(dict, "warn_explicit"); - Py_DECREF(mod); - } - if (func == NULL) { - PySys_WriteStderr("warning: %s\n", message); - return 0; - } - else { - PyObject *res; - - if (category == NULL) - category = PyExc_RuntimeWarning; - if (registry == NULL) - registry = Py_None; - res = PyObject_CallFunction(func, "sOsizO", message, category, - filename, lineno, module, registry); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; - } -} - /* Set file and line information for the current exception. If the exception is not a SyntaxError, also sets additional attributes Modified: python/branches/py3k/Python/getopt.c ============================================================================== --- python/branches/py3k/Python/getopt.c (original) +++ python/branches/py3k/Python/getopt.c Sun Apr 13 15:53:33 2008 @@ -83,7 +83,18 @@ if ( (option = *opt_ptr++) == L'\0') return -1; - + + if (option == 'J') { + fprintf(stderr, "-J is reserved for Jython\n"); + return '_'; + } + + if (option == 'X') { + fprintf(stderr, + "-X is reserved for non-standard arguments\n"); + return '_'; + } + if ((ptr = wcschr(optstring, option)) == NULL) { if (_PyOS_opterr) fprintf(stderr, "Unknown option: -%c\n", (char)option); Modified: python/branches/py3k/Python/pythonrun.c ============================================================================== --- python/branches/py3k/Python/pythonrun.c (original) +++ python/branches/py3k/Python/pythonrun.c Sun Apr 13 15:53:33 2008 @@ -84,38 +84,12 @@ int Py_FrozenFlag; /* Needed by getpath.c */ int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */ -/* Reference to 'warnings' module, to avoid importing it - on the fly when the import lock may be held. See 683658/771097 -*/ -static PyObject *warnings_module = NULL; - -/* Returns a borrowed reference to the 'warnings' module, or NULL. - If the module is returned, it is guaranteed to have been obtained - without acquiring the import lock -*/ -PyObject *PyModule_GetWarningsModule(void) +/* PyModule_GetWarningsModule is no longer necessary as of 2.6 +since _warnings is builtin. This API should not be used. */ +PyObject * +PyModule_GetWarningsModule(void) { - PyObject *typ, *val, *tb; - PyObject *all_modules; - /* If we managed to get the module at init time, just use it */ - if (warnings_module) - return warnings_module; - /* If it wasn't available at init time, it may be available - now in sys.modules (common scenario is frozen apps: import - at init time fails, but the frozen init code sets up sys.path - correctly, then does an implicit import of warnings for us - */ - /* Save and restore any exceptions */ - PyErr_Fetch(&typ, &val, &tb); - - all_modules = PySys_GetObject("modules"); - if (all_modules) { - warnings_module = PyDict_GetItemString(all_modules, "warnings"); - /* We keep a ref in the global */ - Py_XINCREF(warnings_module); - } - PyErr_Restore(typ, val, tb); - return warnings_module; + return PyImport_ImportModule("warnings"); } static int initialized = 0; @@ -255,6 +229,15 @@ if (install_sigs) initsigs(); /* Signal handling stuff, including initintr() */ + + /* Initialize warnings. */ + _PyWarnings_Init(); + if (PySys_HasWarnOptions()) { + PyObject *warnings_module = PyImport_ImportModule("warnings"); + if (!warnings_module) + PyErr_Clear(); + Py_XDECREF(warnings_module); + } initmain(); /* Module __main__ */ if (initstdio() < 0) @@ -268,30 +251,6 @@ _PyGILState_Init(interp, tstate); #endif /* WITH_THREAD */ - warnings_module = PyImport_ImportModule("warnings"); - if (!warnings_module) { - PyErr_Clear(); - } - else { - PyObject *o; - char *action[8]; - - if (Py_BytesWarningFlag > 1) - *action = "error"; - else if (Py_BytesWarningFlag) - *action = "default"; - else - *action = "ignore"; - - o = PyObject_CallMethod(warnings_module, - "simplefilter", "sO", - *action, PyExc_BytesWarning); - if (o == NULL) - Py_FatalError("Py_Initialize: can't initialize" - "warning filter for BytesWarning."); - Py_DECREF(o); - } - #if defined(HAVE_LANGINFO_H) && defined(CODESET) /* On Unix, set the file system encoding according to the user's preference, if the CODESET names a well-known @@ -403,10 +362,6 @@ /* Disable signal handling */ PyOS_FiniInterrupts(); - /* drop module references we saved */ - Py_XDECREF(warnings_module); - warnings_module = NULL; - /* Clear type lookup cache */ PyType_ClearCache(); Modified: python/branches/py3k/Python/sysmodule.c ============================================================================== --- python/branches/py3k/Python/sysmodule.c (original) +++ python/branches/py3k/Python/sysmodule.c Sun Apr 13 15:53:33 2008 @@ -899,6 +899,12 @@ } } +int +PySys_HasWarnOptions(void) +{ + return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0; +} + /* XXX This doc string is too long to be a single string literal in VC++ 5.0. Two literals concatenated works just fine. If you have a K&R compiler or other abomination that however *does* understand longer strings, @@ -1101,6 +1107,7 @@ #endif /* {"unbuffered", "-u"}, */ /* {"skip_first", "-x"}, */ + {"bytes_warning", "-b"}, {0} }; @@ -1144,6 +1151,7 @@ #endif /* SetFlag(saw_unbuffered_flag); */ /* SetFlag(skipfirstline); */ + SetFlag(Py_BytesWarningFlag); #undef SetFlag if (PyErr_Occurred()) { Modified: python/branches/py3k/Python/traceback.c ============================================================================== --- python/branches/py3k/Python/traceback.c (original) +++ python/branches/py3k/Python/traceback.c Sun Apr 13 15:53:33 2008 @@ -128,16 +128,16 @@ return 0; } -static int -tb_displayline(PyObject *f, char *filename, int lineno, char *name) +int +Py_DisplaySourceLine(PyObject *f, const char *filename, int lineno) { int err = 0; - FILE *xfp; + FILE *xfp = NULL; char linebuf[2000]; int i; char namebuf[MAXPATHLEN+1]; - if (filename == NULL || name == NULL) + if (filename == NULL) return -1; /* This is needed by Emacs' compile command */ #define FMT " File \"%.500s\", line %d, in %.500s\n" @@ -145,7 +145,7 @@ if (xfp == NULL) { /* Search tail of filename in sys.path before giving up */ PyObject *path; - char *tail = strrchr(filename, SEP); + const char *tail = strrchr(filename, SEP); if (tail == NULL) tail = filename; else @@ -181,14 +181,14 @@ } } } - PyOS_snprintf(linebuf, sizeof(linebuf), FMT, filename, lineno, name); - err = PyFile_WriteString(linebuf, f); - if (xfp == NULL) - return err; - else if (err != 0) { - fclose(xfp); - return err; - } + + if (xfp == NULL) + return err; + if (err != 0) { + fclose(xfp); + return err; + } + for (i = 0; i < lineno; i++) { char* pLastChar = &linebuf[sizeof(linebuf)-2]; do { @@ -206,22 +206,38 @@ char *p = linebuf; while (*p == ' ' || *p == '\t' || *p == '\014') p++; - err = PyFile_WriteString(" ", f); - if (err == 0) { - err = PyFile_WriteString(p, f); - if (err == 0 && strchr(p, '\n') == NULL) - err = PyFile_WriteString("\n", f); - } + err = PyFile_WriteString(p, f); + if (err == 0 && strchr(p, '\n') == NULL) + err = PyFile_WriteString("\n", f); } fclose(xfp); return err; } static int -tb_printinternal(PyTracebackObject *tb, PyObject *f, int limit) +tb_displayline(PyObject *f, const char *filename, int lineno, const char *name) +{ + int err = 0; + char linebuf[2000]; + + if (filename == NULL || name == NULL) + return -1; + /* This is needed by Emacs' compile command */ +#define FMT " File \"%.500s\", line %d, in %.500s\n" + PyOS_snprintf(linebuf, sizeof(linebuf), FMT, filename, lineno, name); + err = PyFile_WriteString(linebuf, f); + if (err != 0) + return err; + + err = PyFile_WriteString(" ", f); + return Py_DisplaySourceLine(f, filename, lineno); +} + +static int +tb_printinternal(PyTracebackObject *tb, PyObject *f, long limit) { int err = 0; - int depth = 0; + long depth = 0; PyTracebackObject *tb1 = tb; while (tb1 != NULL) { depth++; @@ -250,7 +266,7 @@ { int err; PyObject *limitv; - int limit = PyTraceBack_LIMIT; + long limit = PyTraceBack_LIMIT; if (v == NULL) return 0; From python-3000-checkins at python.org Sun Apr 13 23:39:58 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Sun, 13 Apr 2008 23:39:58 +0200 (CEST) Subject: [Python-3000-checkins] r62333 - python/branches/py3k/Doc/library/io.rst Message-ID: <20080413213958.D1E711E400A@bag.python.org> Author: benjamin.peterson Date: Sun Apr 13 23:39:58 2008 New Revision: 62333 Log: A few io doc fixes Modified: python/branches/py3k/Doc/library/io.rst Modified: python/branches/py3k/Doc/library/io.rst ============================================================================== --- python/branches/py3k/Doc/library/io.rst (original) +++ python/branches/py3k/Doc/library/io.rst Sun Apr 13 23:39:58 2008 @@ -33,7 +33,7 @@ Finally, :class:`StringIO` is a in-memory stream for text. Argument names are not part of the specification, and only the arguments of -:func:`open()` are intended to be used as keyword arguments. +:func:`open` are intended to be used as keyword arguments. Module Interface @@ -42,7 +42,7 @@ .. data:: DEFAULT_BUFFER_SIZE An int containing the default buffer size used by the module's buffered I/O - classes. :func:`open()` uses the file's blksize (as obtained by + classes. :func:`open` uses the file's blksize (as obtained by :func:`os.stat`) if possible. .. function:: open(file[, mode[, buffering[, encoding[, errors[, newline[, closefd=True]]]]]]) @@ -100,13 +100,14 @@ dependent, but any encoding supported by Python can be passed. See the :mod:`codecs` module for the list of supported encodings. - *errors* is an optional string that specifies how encoding errors are to be - handled---this argument should not be used in binary mode. Pass ``'strict'`` - to raise a :exc:`ValueError` exception if there is an encoding error (the - default of ``None`` has the same effect), or pass ``'ignore'`` to ignore - errors. (Note that ignoring encoding errors can lead to data loss.) See the - documentation for :func:`codecs.register` for a list of the permitted - encoding error strings. + *errors* is an optional string that specifies how encoding and decoding + errors are to be handled---this argument should not be used in binary mode. + Pass ``'strict'`` to raise a :exc:`ValueError` exception if there is an + encoding error (the default of ``None`` has the same effect), or pass + ``'ignore'`` to ignore errors. (Note that ignoring encoding errors can lead + to data loss.) ``'replace'`` causes a replacement marker (such as ``'?'``) + to be inserted where there is malformed data. For all possible values, see + :func:`codecs.register`. *newline* controls how universal newlines works (it only applies to text mode). It can be ``None``, ``''``, ``'\n'``, ``'\r'``, and ``'\r\n'``. It @@ -130,15 +131,14 @@ when the file is closed. This does not work when a file name is given and must be ``True`` in that case. - :func:`open()` returns a file object whose type depends on the mode, and + :func:`open` returns a file object whose type depends on the mode, and through which the standard file operations such as reading and writing are - performed. When :func:`open()` is used to open a file in a text mode - (``'w'``, ``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a - :class:`TextIOWrapper`. When used to open a file in a binary mode, the - returned class varies: in read binary mode, it returns a - :class:`BufferedReader`; in write binary and append binary modes, it returns - a :class:`BufferedWriter`, and in read/write mode, it returns a - :class:`BufferedRandom`. + performed. When :func:`open` is used to open a file in a text mode (``'w'``, + ``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a :class:`TextIOWrapper`. + When used to open a file in a binary mode, the returned class varies: in read + binary mode, it returns a :class:`BufferedReader`; in write binary and append + binary modes, it returns a :class:`BufferedWriter`, and in read/write mode, + it returns a :class:`BufferedRandom`. It is also possible to use a string or bytearray as a file for both reading and writing. For strings :class:`StringIO` can be used like a file opened in @@ -220,8 +220,8 @@ .. method:: flush() - Flush the write buffers of the stream if applicable. This is not - implemented for read-only and non-blocking streams. + Flush the write buffers of the stream if applicable. This does nothing + for read-only and non-blocking streams. .. method:: isatty() @@ -238,7 +238,7 @@ *limit* bytes will be read. The line terminator is always ``b'\n'`` for binary files; for text files, - the *newlines* argument to :func:`.open()` can be used to select the line + the *newlines* argument to :func:`open` can be used to select the line terminator(s) recognized. .. method:: readlines([hint]) @@ -576,8 +576,13 @@ *encoding* gives the name of the encoding that the stream will be decoded or encoded with. It defaults to :func:`locale.getpreferredencoding`. - *errors* determines the strictness of encoding and decoding (see the errors - argument of :func:`codecs.register`) and defaults to ``'strict'``. + *errors* is an optional string that specifies how encoding and decoding + errors are to be handled. Pass ``'strict'`` to raise a :exc:`ValueError` + exception if there is an encoding error (the default of ``None`` has the same + effect), or pass ``'ignore'`` to ignore errors. (Note that ignoring encoding + errors can lead to data loss.) ``'replace'`` causes a replacement marker + (such as ``'?'``) to be inserted where there is malformed data. For all + possible values see :func:`codecs.register`. *newline* can be ``None``, ``''``, ``'\n'``, ``'\r'``, or ``'\r\n'``. It controls the handling of line endings. If it is ``None``, universal newlines From python-3000-checkins at python.org Mon Apr 14 01:11:15 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Mon, 14 Apr 2008 01:11:15 +0200 (CEST) Subject: [Python-3000-checkins] r62335 - in python/branches/py3k: Doc/Makefile Doc/make.bat Message-ID: <20080413231115.877991E4009@bag.python.org> Author: benjamin.peterson Date: Mon Apr 14 01:11:15 2008 New Revision: 62335 Log: Merged revisions 62332 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62332 | georg.brandl | 2008-04-13 15:51:27 -0500 (Sun, 13 Apr 2008) | 2 lines Check out Jinja as a separate step now that it's not included in the Sphinx package anymore. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/Makefile python/branches/py3k/Doc/make.bat Modified: python/branches/py3k/Doc/Makefile ============================================================================== --- python/branches/py3k/Doc/Makefile (original) +++ python/branches/py3k/Doc/Makefile Mon Apr 14 01:11:15 2008 @@ -34,6 +34,10 @@ echo "Checking out Docutils..."; \ svn checkout $(SVNROOT)/external/docutils-0.4/docutils tools/docutils; \ fi + @if [ ! -d tools/jinja ]; then \ + echo "Checking out Jinja..."; \ + svn checkout $(SVNROOT)/external/Jinja-1.1/jinja tools/jinja; \ + fi @if [ ! -d tools/pygments ]; then \ echo "Checking out Pygments..."; \ svn checkout $(SVNROOT)/external/Pygments-0.9/pygments tools/pygments; \ @@ -42,6 +46,7 @@ update: checkout svn update tools/sphinx svn update tools/docutils + svn update tools/jinja svn update tools/pygments build: checkout Modified: python/branches/py3k/Doc/make.bat ============================================================================== --- python/branches/py3k/Doc/make.bat (original) +++ python/branches/py3k/Doc/make.bat Mon Apr 14 01:11:15 2008 @@ -28,12 +28,14 @@ :checkout svn co %SVNROOT%/doctools/trunk/sphinx tools/sphinx svn co %SVNROOT%/external/docutils-0.4/docutils tools/docutils +svn co %SVNROOT%/external/Jinja-1.1/jinja tools/jinja svn co %SVNROOT%/external/Pygments-0.9/pygments tools/pygments goto end :update svn update tools/sphinx svn update tools/docutils +svn update tools/jinja svn update tools/pygments goto end From python-3000-checkins at python.org Mon Apr 14 01:46:28 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Mon, 14 Apr 2008 01:46:28 +0200 (CEST) Subject: [Python-3000-checkins] r62336 - python/branches/py3k/Doc/library/io.rst Message-ID: <20080413234628.3FF951E4009@bag.python.org> Author: benjamin.peterson Date: Mon Apr 14 01:46:27 2008 New Revision: 62336 Log: Another io doc fix Modified: python/branches/py3k/Doc/library/io.rst Modified: python/branches/py3k/Doc/library/io.rst ============================================================================== --- python/branches/py3k/Doc/library/io.rst (original) +++ python/branches/py3k/Doc/library/io.rst Mon Apr 14 01:46:27 2008 @@ -447,7 +447,7 @@ .. class:: BufferedReader(raw[, buffer_size]) - A buffer for a readable, sequential :class:`BaseRawIO` object. It inherits + A buffer for a readable, sequential :class:`RawIOBase` object. It inherits :class:`BufferedIOBase`. The constructor creates a :class:`BufferedReader` for the given readable From python-3000-checkins at python.org Mon Apr 14 12:05:49 2008 From: python-3000-checkins at python.org (lars.gustaebel) Date: Mon, 14 Apr 2008 12:05:49 +0200 (CEST) Subject: [Python-3000-checkins] r62337 - in python/branches/py3k: Lib/tarfile.py Misc/NEWS Message-ID: <20080414100549.AA20A1E4013@bag.python.org> Author: lars.gustaebel Date: Mon Apr 14 12:05:48 2008 New Revision: 62337 Log: Issue #2058: Remove the buf attribute and add __slots__ to the TarInfo class in order to reduce tarfile's memory usage. Modified: python/branches/py3k/Lib/tarfile.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/tarfile.py ============================================================================== --- python/branches/py3k/Lib/tarfile.py (original) +++ python/branches/py3k/Lib/tarfile.py Mon Apr 14 12:05:48 2008 @@ -767,7 +767,7 @@ self.fileobj = _FileInFile(tarfile.fileobj, tarinfo.offset_data, tarinfo.size, - getattr(tarinfo, "sparse", None)) + tarinfo.sparse) self.name = tarinfo.name self.mode = "r" self.closed = False @@ -906,6 +906,12 @@ usually created internally. """ + __slots__ = ("name", "mode", "uid", "gid", "size", "mtime", + "chksum", "type", "linkname", "uname", "gname", + "devmajor", "devminor", + "offset", "offset_data", "pax_headers", "sparse", + "tarfile", "_sparse_structs", "_link_target") + def __init__(self, name=""): """Construct a TarInfo object. name is the optional name of the member. @@ -927,6 +933,7 @@ self.offset = 0 # the tar header starts here self.offset_data = 0 # the file's data starts here + self.sparse = None # sparse member information self.pax_headers = {} # pax header information # In pax headers the "name" and "linkname" field are called @@ -1181,7 +1188,6 @@ raise HeaderError("bad checksum") obj = cls() - obj.buf = buf obj.name = nts(buf[0:100], encoding, errors) obj.mode = nti(buf[100:108]) obj.uid = nti(buf[108:116]) @@ -1202,6 +1208,24 @@ if obj.type == AREGTYPE and obj.name.endswith("/"): obj.type = DIRTYPE + # The old GNU sparse format occupies some of the unused + # space in the buffer for up to 4 sparse structures. + # Save the them for later processing in _proc_sparse(). + if obj.type == GNUTYPE_SPARSE: + pos = 386 + structs = [] + for i in range(4): + try: + offset = nti(buf[pos:pos + 12]) + numbytes = nti(buf[pos + 12:pos + 24]) + except ValueError: + break + structs.append((offset, numbytes)) + pos += 24 + isextended = bool(buf[482]) + origsize = nti(buf[483:495]) + obj._sparse_structs = (structs, isextended, origsize) + # Remove redundant slashes from directories. if obj.isdir(): obj.name = obj.name.rstrip("/") @@ -1288,31 +1312,11 @@ def _proc_sparse(self, tarfile): """Process a GNU sparse header plus extra headers. """ - buf = self.buf - sp = _ringbuffer() - pos = 386 - lastpos = 0 - realpos = 0 - # There are 4 possible sparse structs in the - # first header. - for i in range(4): - try: - offset = nti(buf[pos:pos + 12]) - numbytes = nti(buf[pos + 12:pos + 24]) - except ValueError: - break - if offset > lastpos: - sp.append(_hole(lastpos, offset - lastpos)) - sp.append(_data(offset, numbytes, realpos)) - realpos += numbytes - lastpos = offset + numbytes - pos += 24 - - isextended = bool(buf[482]) - origsize = nti(buf[483:495]) + # We already collected some sparse structures in frombuf(). + structs, isextended, origsize = self._sparse_structs + del self._sparse_structs - # If the isextended flag is given, - # there are extra headers to process. + # Collect sparse structures from extended header blocks. while isextended: buf = tarfile.fileobj.read(BLOCKSIZE) pos = 0 @@ -1322,18 +1326,23 @@ numbytes = nti(buf[pos + 12:pos + 24]) except ValueError: break - if offset > lastpos: - sp.append(_hole(lastpos, offset - lastpos)) - sp.append(_data(offset, numbytes, realpos)) - realpos += numbytes - lastpos = offset + numbytes + structs.append((offset, numbytes)) pos += 24 isextended = bool(buf[504]) + # Transform the sparse structures to something we can use + # in ExFileObject. + self.sparse = _ringbuffer() + lastpos = 0 + realpos = 0 + for offset, numbytes in structs: + if offset > lastpos: + self.sparse.append(_hole(lastpos, offset - lastpos)) + self.sparse.append(_data(offset, numbytes, realpos)) + realpos += numbytes + lastpos = offset + numbytes if lastpos < origsize: - sp.append(_hole(lastpos, origsize - lastpos)) - - self.sparse = sp + self.sparse.append(_hole(lastpos, origsize - lastpos)) self.offset_data = tarfile.fileobj.tell() tarfile.offset = self.offset_data + self._block(self.size) Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Mon Apr 14 12:05:48 2008 @@ -29,6 +29,9 @@ Library ------- +- Issue #2058: Remove the buf attribute and add __slots__ to the TarInfo + class in order to reduce tarfile's memory usage. + - Bug #2606: Avoid calling .sort() on a dict_keys object. - The bundled libffi copy is now in sync with the recently released From python-3000-checkins at python.org Mon Apr 14 18:17:33 2008 From: python-3000-checkins at python.org (thomas.heller) Date: Mon, 14 Apr 2008 18:17:33 +0200 (CEST) Subject: [Python-3000-checkins] r62339 - in python/branches/py3k: Lib/ctypes/__init__.py Modules/_ctypes/_ctypes.c Modules/_ctypes/callproc.c Modules/_ctypes/ctypes.h Message-ID: <20080414161733.91A271E400A@bag.python.org> Author: thomas.heller Date: Mon Apr 14 18:17:33 2008 New Revision: 62339 Log: Merged revisions 62338 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62338 | thomas.heller | 2008-04-14 18:10:07 +0200 (Mo, 14 Apr 2008) | 3 lines Issue #2616: Implement ctypes.pointer() and ctypes.POINTER() in C for better performance. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/ctypes/__init__.py python/branches/py3k/Modules/_ctypes/_ctypes.c python/branches/py3k/Modules/_ctypes/callproc.c python/branches/py3k/Modules/_ctypes/ctypes.h Modified: python/branches/py3k/Lib/ctypes/__init__.py ============================================================================== --- python/branches/py3k/Lib/ctypes/__init__.py (original) +++ python/branches/py3k/Lib/ctypes/__init__.py Mon Apr 14 18:17:33 2008 @@ -239,27 +239,7 @@ class c_bool(_SimpleCData): _type_ = "?" -# This cache maps types to pointers to them. -_pointer_type_cache = {} - -def POINTER(cls): - try: - return _pointer_type_cache[cls] - except KeyError: - pass - if type(cls) is str: - klass = type(_Pointer)("LP_%s" % cls, - (_Pointer,), - {}) - _pointer_type_cache[id(klass)] = klass - return klass - else: - name = "LP_%s" % cls.__name__ - klass = type(_Pointer)(name, - (_Pointer,), - {'_type_': cls}) - _pointer_type_cache[cls] = klass - return klass +from _ctypes import POINTER, pointer, _pointer_type_cache try: from _ctypes import set_conversion_mode @@ -309,10 +289,6 @@ _pointer_type_cache[cls] = pointer del _pointer_type_cache[id(pointer)] - -def pointer(inst): - return POINTER(type(inst))(inst) - # XXX Deprecated def ARRAY(typ, len): return typ * len Modified: python/branches/py3k/Modules/_ctypes/_ctypes.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/_ctypes.c (original) +++ python/branches/py3k/Modules/_ctypes/_ctypes.c Mon Apr 14 18:17:33 2008 @@ -123,6 +123,10 @@ #include "ctypes.h" PyObject *PyExc_ArgError; + +/* This dict maps ctypes types to POINTER types */ +PyObject *_pointer_type_cache; + static PyTypeObject Simple_Type; /* a callable object used for unpickling */ @@ -4994,6 +4998,12 @@ if (!m) return; + _pointer_type_cache = PyDict_New(); + if (_pointer_type_cache == NULL) + return; + + PyModule_AddObject(m, "_pointer_type_cache", (PyObject *)_pointer_type_cache); + _unpickle = PyObject_GetAttrString(m, "_unpickle"); if (_unpickle == NULL) return; Modified: python/branches/py3k/Modules/_ctypes/callproc.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/callproc.c (original) +++ python/branches/py3k/Modules/_ctypes/callproc.c Mon Apr 14 18:17:33 2008 @@ -1565,7 +1565,76 @@ return result; } +static PyObject * +POINTER(PyObject *self, PyObject *cls) +{ + PyObject *result; + PyTypeObject *typ; + PyObject *key; + char *buf; + + result = PyDict_GetItem(_pointer_type_cache, cls); + if (result) { + Py_INCREF(result); + return result; + } + if (PyUnicode_CheckExact(cls)) { + char *name = PyUnicode_AsString(cls); + buf = alloca(strlen(name) + 3 + 1); + sprintf(buf, "LP_%s", name); + result = PyObject_CallFunction((PyObject *)Py_TYPE(&Pointer_Type), + "s(O){}", + buf, + &Pointer_Type); + if (result == NULL) + return result; + key = PyLong_FromVoidPtr(result); + } else if (PyType_Check(cls)) { + typ = (PyTypeObject *)cls; + buf = alloca(strlen(typ->tp_name) + 3 + 1); + sprintf(buf, "LP_%s", typ->tp_name); + result = PyObject_CallFunction((PyObject *)Py_TYPE(&Pointer_Type), + "s(O){sO}", + buf, + &Pointer_Type, + "_type_", cls); + if (result == NULL) + return result; + Py_INCREF(cls); + key = cls; + } else { + PyErr_SetString(PyExc_TypeError, "must be a ctypes type"); + return NULL; + } + if (-1 == PyDict_SetItem(_pointer_type_cache, key, result)) { + Py_DECREF(result); + Py_DECREF(key); + return NULL; + } + Py_DECREF(key); + return result; +} + +static PyObject * +pointer(PyObject *self, PyObject *arg) +{ + PyObject *result; + PyObject *typ; + + typ = PyDict_GetItem(_pointer_type_cache, (PyObject *)Py_TYPE(arg)); + if (typ) + return PyObject_CallFunctionObjArgs(typ, arg, NULL); + typ = POINTER(NULL, (PyObject *)Py_TYPE(arg)); + if (typ == NULL) + return NULL; + result = PyObject_CallFunctionObjArgs(typ, arg, NULL); + Py_DECREF(typ); + return result; +} + PyMethodDef module_methods[] = { + {"POINTER", POINTER, METH_O }, + {"pointer", pointer, METH_O }, {"_unpickle", unpickle, METH_VARARGS }, {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"}, #ifdef CTYPES_UNICODE Modified: python/branches/py3k/Modules/_ctypes/ctypes.h ============================================================================== --- python/branches/py3k/Modules/_ctypes/ctypes.h (original) +++ python/branches/py3k/Modules/_ctypes/ctypes.h Mon Apr 14 18:17:33 2008 @@ -342,6 +342,7 @@ /* XXX better name needed! */ extern int IsSimpleSubType(PyObject *obj); +extern PyObject *_pointer_type_cache; #ifdef MS_WIN32 extern PyObject *ComError; From alexandre at peadrop.com Mon Apr 14 22:35:32 2008 From: alexandre at peadrop.com (Alexandre Vassalotti) Date: Mon, 14 Apr 2008 16:35:32 -0400 Subject: [Python-3000-checkins] r62307 - in python/branches/py3k: Doc/library/io.rst Lib/io.py In-Reply-To: <20080413002746.BD5831E400A@bag.python.org> References: <20080413002746.BD5831E400A@bag.python.org> Message-ID: > Author: benjamin.peterson > Date: Sun Apr 13 02:27:46 2008 > New Revision: 62307 > > Log: > Fleshed out docstrings in the io module, improving the reST one as I went. [snip] > - In :class:`BytesIO`, this is the same as :meth:`read`. > + In :class:`BytesIO`, this is the same as :meth:`read()`. > > .. method:: truncate([pos]) > > Truncate the file to at most *pos* bytes. *pos* defaults to the current > - stream position, as returned by :meth:`tell`. > + stream position, as returned by :meth:`tell()`. > I think the parentheses are unnecessary for :meth:`xxx`, too. > Modified: python/branches/py3k/Lib/io.py > ============================================================================== > --- python/branches/py3k/Lib/io.py (original) > +++ python/branches/py3k/Lib/io.py Sun Apr 13 02:27:46 2008 > @@ -1,24 +1,51 @@ > -"""New I/O library conforming to PEP 3116. > - > -This is a prototype; hopefully eventually some of this will be > -reimplemented in C. > +""" > +The io module provides the Python interfaces to stream handling. The > +builtin open function is defined in this module. > According to PEP 247, there shouldn't be a newline after the triple-quotes at the beginning of a docstring. > @@ -394,7 +481,16 @@ > ### Readline[s] and writelines ### > > def readline(self, limit: int = -1) -> bytes: > - """For backwards compatibility, a (slowish) readline().""" > + r"""readline(limit: int = -1) -> bytes Read and return a line from the > + stream. > + > + If limit is specified, at most limit bytes will be read. [snip] I don't for you, but personally I find the duplication of the function's signature in the docstring a bit awkward. Is there a reason for the duplication? > @@ -671,8 +770,6 @@ > > """Buffered I/O implementation using an in-memory bytes buffer.""" > > - # XXX More docs > - > def __init__(self, initial_bytes=None): > buf = bytearray() > if initial_bytes is not None: > @@ -681,6 +778,8 @@ > self._pos = 0 > > def getvalue(self): > + """getvalue() -> bytes Return the bytes value (contents) of the buffer > + """ > return bytes(self._buffer) > > def read(self, n=None): > @@ -694,6 +793,8 @@ > return bytes(b) > def read1(self, n): > + """In BytesIO, this is the same as read. > + """ > return self.read(n) > IMHO, it is bad practice to refer the class name in the docstring, since it makes the documentation of subclasses confusing. -- Alexandre From python-3000-checkins at python.org Mon Apr 14 22:51:05 2008 From: python-3000-checkins at python.org (alexandre.vassalotti) Date: Mon, 14 Apr 2008 22:51:05 +0200 (CEST) Subject: [Python-3000-checkins] r62342 - python/branches/py3k/Objects/bytesobject.c Message-ID: <20080414205105.ED09F1E400B@bag.python.org> Author: alexandre.vassalotti Date: Mon Apr 14 22:51:05 2008 New Revision: 62342 Log: Improved bytes_extend() to avoid making a full copy of the temporary buffer. This also makes the code slightly cleaner. Modified: python/branches/py3k/Objects/bytesobject.c Modified: python/branches/py3k/Objects/bytesobject.c ============================================================================== --- python/branches/py3k/Objects/bytesobject.c (original) +++ python/branches/py3k/Objects/bytesobject.c Mon Apr 14 22:51:05 2008 @@ -2585,7 +2585,7 @@ static PyObject * bytes_extend(PyBytesObject *self, PyObject *arg) { - PyObject *it, *item, *tmp, *res; + PyObject *it, *item, *bytes_obj; Py_ssize_t buf_size = 0, len = 0; int value; char *buf; @@ -2605,40 +2605,46 @@ /* Try to determine the length of the argument. 32 is abitrary. */ buf_size = _PyObject_LengthHint(arg, 32); - buf = (char *)PyMem_Malloc(buf_size * sizeof(char)); - if (buf == NULL) - return PyErr_NoMemory(); + bytes_obj = PyBytes_FromStringAndSize(NULL, buf_size); + if (bytes_obj == NULL) + return NULL; + buf = PyBytes_AS_STRING(bytes_obj); while ((item = PyIter_Next(it)) != NULL) { if (! _getbytevalue(item, &value)) { Py_DECREF(item); Py_DECREF(it); - PyMem_Free(buf); + Py_DECREF(bytes_obj); return NULL; } buf[len++] = value; Py_DECREF(item); + if (len >= buf_size) { - char *new_buf; buf_size = len + (len >> 1) + 1; - new_buf = (char *)PyMem_Realloc(buf, buf_size * sizeof(char)); - if (new_buf == NULL) { + if (PyBytes_Resize((PyObject *)bytes_obj, buf_size) < 0) { Py_DECREF(it); - PyMem_Free(buf); - return PyErr_NoMemory(); + Py_DECREF(bytes_obj); + return NULL; } - buf = new_buf; + /* Recompute the `buf' pointer, since the resizing operation may + have invalidated it. */ + buf = PyBytes_AS_STRING(bytes_obj); } } Py_DECREF(it); - /* XXX: Is possible to avoid a full copy of the buffer? */ - tmp = PyBytes_FromStringAndSize(buf, len); - res = bytes_extend(self, tmp); - Py_DECREF(tmp); - PyMem_Free(buf); + /* Resize down to exact size. */ + if (PyBytes_Resize((PyObject *)bytes_obj, len) < 0) { + Py_DECREF(bytes_obj); + return NULL; + } - return res; + if (bytes_setslice(self, Py_SIZE(self), Py_SIZE(self), bytes_obj) == -1) + return NULL; + Py_DECREF(bytes_obj); + + Py_RETURN_NONE; } PyDoc_STRVAR(pop__doc__, From python-3000-checkins at python.org Mon Apr 14 22:53:13 2008 From: python-3000-checkins at python.org (alexandre.vassalotti) Date: Mon, 14 Apr 2008 22:53:13 +0200 (CEST) Subject: [Python-3000-checkins] r62343 - python/branches/py3k/Objects/bytesobject.c Message-ID: <20080414205313.F2C3D1E400B@bag.python.org> Author: alexandre.vassalotti Date: Mon Apr 14 22:53:13 2008 New Revision: 62343 Log: Re-indented bytes_getbuffer() and bytes_releasebuffer() to 4-space indents. Modified: python/branches/py3k/Objects/bytesobject.c Modified: python/branches/py3k/Objects/bytesobject.c ============================================================================== --- python/branches/py3k/Objects/bytesobject.c (original) +++ python/branches/py3k/Objects/bytesobject.c Mon Apr 14 22:53:13 2008 @@ -52,27 +52,27 @@ static int bytes_getbuffer(PyBytesObject *obj, Py_buffer *view, int flags) { - int ret; - void *ptr; - if (view == NULL) { - obj->ob_exports++; - return 0; - } - if (obj->ob_bytes == NULL) - ptr = ""; - else - ptr = obj->ob_bytes; - ret = PyBuffer_FillInfo(view, ptr, Py_SIZE(obj), 0, flags); - if (ret >= 0) { - obj->ob_exports++; - } - return ret; + int ret; + void *ptr; + if (view == NULL) { + obj->ob_exports++; + return 0; + } + if (obj->ob_bytes == NULL) + ptr = ""; + else + ptr = obj->ob_bytes; + ret = PyBuffer_FillInfo(view, ptr, Py_SIZE(obj), 0, flags); + if (ret >= 0) { + obj->ob_exports++; + } + return ret; } static void bytes_releasebuffer(PyBytesObject *obj, Py_buffer *view) { - obj->ob_exports--; + obj->ob_exports--; } static Py_ssize_t From musiccomposition at gmail.com Mon Apr 14 23:11:03 2008 From: musiccomposition at gmail.com (Benjamin Peterson) Date: Mon, 14 Apr 2008 16:11:03 -0500 Subject: [Python-3000-checkins] r62307 - in python/branches/py3k: Doc/library/io.rst Lib/io.py In-Reply-To: References: <20080413002746.BD5831E400A@bag.python.org> Message-ID: <1afaf6160804141411pf9ab769y51e224ab9bff31b4@mail.gmail.com> [snip you're right] > > I don't for you, but personally I find the duplication of the > function's signature in the docstring a bit awkward. Is there a reason > for the duplication? It was in the module when I got there. Also there aren't any annotations in 2.6. [more snipping] -- Cheers, Benjamin Peterson From python-3000-checkins at python.org Mon Apr 14 23:30:21 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Mon, 14 Apr 2008 23:30:21 +0200 (CEST) Subject: [Python-3000-checkins] r62344 - in python/branches/py3k: Doc/library/io.rst Lib/io.py Message-ID: <20080414213021.7C0C81E4019@bag.python.org> Author: benjamin.peterson Date: Mon Apr 14 23:30:21 2008 New Revision: 62344 Log: Fix problems in the io docs noted by Alexandre Vassalotti Modified: python/branches/py3k/Doc/library/io.rst python/branches/py3k/Lib/io.py Modified: python/branches/py3k/Doc/library/io.rst ============================================================================== --- python/branches/py3k/Doc/library/io.rst (original) +++ python/branches/py3k/Doc/library/io.rst Mon Apr 14 23:30:21 2008 @@ -437,12 +437,12 @@ .. method:: read1() - In :class:`BytesIO`, this is the same as :meth:`read()`. + In :class:`BytesIO`, this is the same as :meth:`read`. .. method:: truncate([pos]) Truncate the file to at most *pos* bytes. *pos* defaults to the current - stream position, as returned by :meth:`tell()`. + stream position, as returned by :meth:`tell`. .. class:: BufferedReader(raw[, buffer_size]) Modified: python/branches/py3k/Lib/io.py ============================================================================== --- python/branches/py3k/Lib/io.py (original) +++ python/branches/py3k/Lib/io.py Mon Apr 14 23:30:21 2008 @@ -1,5 +1,4 @@ -""" -The io module provides the Python interfaces to stream handling. The +"""The io module provides the Python interfaces to stream handling. The builtin open function is defined in this module. At the top of the I/O hierarchy is the abstract base class IOBase. It @@ -78,8 +77,7 @@ def open(file, mode="r", buffering=None, encoding=None, errors=None, newline=None, closefd=True): - r""" - Open file and return a stream. If the file cannot be opened, an + r"""Open file and return a stream. If the file cannot be opened, an IOError is raised. file is either a string giving the name (and the path if the file @@ -287,8 +285,7 @@ class IOBase(metaclass=abc.ABCMeta): - """ - The abstract base class for all I/O classes, acting on streams of + """The abstract base class for all I/O classes, acting on streams of bytes. There is no public constructor. This class provides dummy implementations for many methods that @@ -793,7 +790,7 @@ return bytes(b) def read1(self, n): - """In BytesIO, this is the same as read. + """This is the same as read. """ return self.read(n) From python-3000-checkins at python.org Tue Apr 15 00:46:41 2008 From: python-3000-checkins at python.org (alexandre.vassalotti) Date: Tue, 15 Apr 2008 00:46:41 +0200 (CEST) Subject: [Python-3000-checkins] r62346 - python/branches/py3k Message-ID: <20080414224641.A71F41E400B@bag.python.org> Author: alexandre.vassalotti Date: Tue Apr 15 00:46:41 2008 New Revision: 62346 Log: Recorded merge of revisions 62345 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62345 | alexandre.vassalotti | 2008-04-14 18:40:08 -0400 (Mon, 14 Apr 2008) | 2 lines Backport manually r62342 from the py3k branch to the trunk. ........ Modified: python/branches/py3k/ (props changed) From python-3000-checkins at python.org Tue Apr 15 08:43:14 2008 From: python-3000-checkins at python.org (neal.norwitz) Date: Tue, 15 Apr 2008 08:43:14 +0200 (CEST) Subject: [Python-3000-checkins] r62349 - in python/branches/py3k: .bzrignore Doc/whatsnew/2.6.rst Include/graminit.h Lib/test/test_warnings.py Modules/main.c Objects/descrobject.c PC/VC6/pythoncore.dsp PC/VS7.1/pythoncore.vcproj PC/VS8.0/pythoncore.vcproj PCbuild/pythoncore.vcproj Parser/printgrammar.c Python/_warnings.c Python/getopt.c Python/graminit.c Message-ID: <20080415064314.9574D1E400B@bag.python.org> Author: neal.norwitz Date: Tue Apr 15 08:43:13 2008 New Revision: 62349 Log: Merged revisions 61440-61441,61443,61445-61448,61451-61452,61455-61457,61459-61464,61466-61467,61469-61470,61476-61477,61479,61481-61482,61485,61487,61490,61493-61494,61497,61499-61502,61505-61506,61508,61511-61514,61519,61521-61522,61530-61531,61533-61537,61541-61555,61557-61558,61561-61562,61566-61569,61572-61574,61578-61579,61583-61584,61588-61589,61592,61594,61598-61601,61603-61604,61607-61612,61617,61619-61620,61624,61626,61628-61630,61635-61638,61640-61643,61645,61648,61653-61655,61659-61662,61664,61666,61668-61671,61673,61675,61679-61680,61682,61685-61686,61689-61695,61697-61699,61701-61703,61706,61710,61713,61717,61723,61726-61730,61736,61738,61740,61742,61745-61752,61754-61760,61762-61764,61768,61770-61772,61774-61775,61784-61787,61789-61792,61794-61795,61797-61806,61808-61809,61811-61812,61814-61819,61824,61826-61833,61835-61840,61843-61845,61848,61850,61854-61862,61865-61866,61868,61872-61873,61876-61877,61883-61888,61890-61891,61893-61899,61901-61903,61905-61912,61914,61917,61920-61921,61927,61930,61932-61934,61939,61941-61942,61944-61951,61955,61960-61963,61980,61982-61983,61991,61994-61996,62001-62003,62008-62010,62016-62017,62022,62024,62027,62031-62034,62041,62045-62046,62055-62058,62060-62066,62068-62074,62076-62079,62081-62083,62086-62089,62092-62094,62098,62101,62104,62106-62109,62115-62122,62124-62125,62128,62130,62132,62134-62135,62137,62139-62140,62144,62146,62151,62155,62157,62162-62166,62171-62172,62175-62176,62178,62181-62186,62188-62192,62196,62200-62203,62206,62211-62213,62215-62218,62222,62224-62226,62228,62232,62236,62240-62245,62248,62250-62254,62256-62258,62262,62264-62265,62267-62270,62272-62276,62280-62288,62291-62292,62299-62301,62307,62312,62316-62318,62322-62331,62333-62337,62339-62344,62346-62348 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62323 | brett.cannon | 2008-04-13 10:09:43 -0700 (Sun, 13 Apr 2008) | 3 lines Add an explicit check for output in a test to try to diagnose a failure on Windows. ........ r62324 | brett.cannon | 2008-04-13 10:41:31 -0700 (Sun, 13 Apr 2008) | 3 lines Fix spliting on colons on Windows machines with a file path by limiting the number of splits. ........ r62329 | benjamin.peterson | 2008-04-13 13:35:56 -0700 (Sun, 13 Apr 2008) | 2 lines #2627 Let it be known what pgen generates ........ r62330 | benjamin.peterson | 2008-04-13 13:40:03 -0700 (Sun, 13 Apr 2008) | 2 lines Added an ignore file for Bazaar #2510 ........ r62331 | georg.brandl | 2008-04-13 13:50:29 -0700 (Sun, 13 Apr 2008) | 2 lines Improve -X error message. ........ r62334 | andrew.kuchling | 2008-04-13 15:39:12 -0700 (Sun, 13 Apr 2008) | 1 line Add example ........ r62340 | amaury.forgeotdarc | 2008-04-14 12:55:40 -0700 (Mon, 14 Apr 2008) | 2 lines Update project files for all Windows supported compilers ........ r62341 | amaury.forgeotdarc | 2008-04-14 13:07:48 -0700 (Mon, 14 Apr 2008) | 6 lines Correct a refleak found by "regrtest.py -R:: test_structmembers" Some other minor updates in _warnings.c: - make a function static - rename a shadowing local variable ........ r62347 | andrew.kuchling | 2008-04-14 19:24:15 -0700 (Mon, 14 Apr 2008) | 1 line Various items; begin writing the SSL section ........ r62348 | neal.norwitz | 2008-04-14 20:46:21 -0700 (Mon, 14 Apr 2008) | 1 line Prevent namespace pollution, add static for internal functions ........ Added: python/branches/py3k/.bzrignore - copied unchanged from r62331, /python/trunk/.bzrignore Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/whatsnew/2.6.rst python/branches/py3k/Include/graminit.h python/branches/py3k/Lib/test/test_warnings.py python/branches/py3k/Modules/main.c python/branches/py3k/Objects/descrobject.c python/branches/py3k/PC/VC6/pythoncore.dsp python/branches/py3k/PC/VS7.1/pythoncore.vcproj python/branches/py3k/PC/VS8.0/pythoncore.vcproj python/branches/py3k/PCbuild/pythoncore.vcproj python/branches/py3k/Parser/printgrammar.c python/branches/py3k/Python/_warnings.c python/branches/py3k/Python/getopt.c python/branches/py3k/Python/graminit.c Modified: python/branches/py3k/Doc/whatsnew/2.6.rst ============================================================================== --- python/branches/py3k/Doc/whatsnew/2.6.rst (original) +++ python/branches/py3k/Doc/whatsnew/2.6.rst Tue Apr 15 08:43:13 2008 @@ -736,7 +736,13 @@ to become Unicode strings. This means that ``\u`` escape sequences can be used to include Unicode characters. -XXX give example + from __future__ import unicode_literals + + s = ('\u751f\u3080\u304e\u3000\u751f\u3054' + '\u3081\u3000\u751f\u305f\u307e\u3054') + + print len(s) # 12 Unicode characters + .. seealso:: @@ -819,7 +825,8 @@ :pep:`3116` - New I/O PEP written by Daniel Stutzbach, Mike Verdone, and Guido van Rossum. - XXX code written by who? + Code by Guido van Rossum, Georg Brandl, Walter Doerwald, + Jeremy Hylton, Martin von Loewis, Tony Lownds, and others. .. ====================================================================== @@ -1090,8 +1097,6 @@ A = foo(bar(A)) -XXX need to find a good motivating example. - .. seealso:: :pep:`3129` - Class Decorators @@ -1848,6 +1853,10 @@ environments. TIPC addresses are 4- or 5-tuples. (Contributed by Alberto Bertogli; :issue:`1646`.) + A new function, :func:`create_connection`, takes an address + and connects to it using an optional timeout value, returning + the connected socket object. + * The base classes in the :mod:`SocketServer` module now support calling a :meth:`handle_timeout` method after a span of inactivity specified by the server's :attr:`timeout` attribute. (Contributed @@ -2036,15 +2045,21 @@ -------------------------------------------------- Bill Janssen made extensive improvements to Python 2.6's support for -SSL. - -XXX use ssl.sslsocket - subclass of socket.socket. +the Secure Sockets Layer by adding a new module, :mod:`ssl`, on top of +the `OpenSSL `__ library. This new module +provides more control over the protocol negotiated, the X.509 +certificates used, and has better support for writing SSL servers (as +opposed to clients) in Python. The existing SSL support in the +:mod:`socket` module hasn't been removed and continues to work, +though it will be removed in Python 3.0. + +To use the new module, first you must create a TCP connection in the +usual way and then pass it to the :func:`ssl.wrap_socket` function. +XXX describe parameters. XXX Can specify if certificate is required, and obtain certificate info by calling getpeercert method. -XXX sslwrap() behaves like socket.ssl - XXX Certain features require the OpenSSL package to be installed, notably the 'openssl' binary. Modified: python/branches/py3k/Include/graminit.h ============================================================================== --- python/branches/py3k/Include/graminit.h (original) +++ python/branches/py3k/Include/graminit.h Tue Apr 15 08:43:13 2008 @@ -1,3 +1,5 @@ +/* Generated by Parser/pgen */ + #define single_input 256 #define file_input 257 #define eval_input 258 Modified: python/branches/py3k/Lib/test/test_warnings.py ============================================================================== --- python/branches/py3k/Lib/test/test_warnings.py (original) +++ python/branches/py3k/Lib/test/test_warnings.py Tue Apr 15 08:43:13 2008 @@ -328,7 +328,8 @@ "Too many newlines in %r" % result) first_line, second_line = result.split('\n', 1) expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py' - path, line, warning_class, message = first_line.split(':') + first_line_parts = first_line.rsplit(':', 3) + path, line, warning_class, message = first_line_parts line = int(line) self.failUnlessEqual(expected_file, path) self.failUnlessEqual(warning_class, ' ' + UserWarning.__name__) Modified: python/branches/py3k/Modules/main.c ============================================================================== --- python/branches/py3k/Modules/main.c (original) +++ python/branches/py3k/Modules/main.c Tue Apr 15 08:43:13 2008 @@ -380,7 +380,7 @@ skipfirstline = 1; break; - /* case 'X': reserved for non-standard arguments */ + /* case 'X': reserved for implementation-specific arguments */ case 'h': case '?': Modified: python/branches/py3k/Objects/descrobject.c ============================================================================== --- python/branches/py3k/Objects/descrobject.c (original) +++ python/branches/py3k/Objects/descrobject.c Tue Apr 15 08:43:13 2008 @@ -1083,7 +1083,7 @@ PyDoc_STRVAR(getter_doc, "Descriptor to change the getter on a property."); -PyObject * +static PyObject * property_getter(PyObject *self, PyObject *getter) { return property_copy(self, getter, NULL, NULL, NULL); @@ -1093,7 +1093,7 @@ PyDoc_STRVAR(setter_doc, "Descriptor to change the setter on a property."); -PyObject * +static PyObject * property_setter(PyObject *self, PyObject *setter) { return property_copy(self, NULL, setter, NULL, NULL); @@ -1103,7 +1103,7 @@ PyDoc_STRVAR(deleter_doc, "Descriptor to change the deleter on a property."); -PyObject * +static PyObject * property_deleter(PyObject *self, PyObject *deleter) { return property_copy(self, NULL, NULL, deleter, NULL); Modified: python/branches/py3k/PC/VC6/pythoncore.dsp ============================================================================== --- python/branches/py3k/PC/VC6/pythoncore.dsp (original) +++ python/branches/py3k/PC/VC6/pythoncore.dsp Tue Apr 15 08:43:13 2008 @@ -193,6 +193,10 @@ # End Source File # Begin Source File +SOURCE=..\..\Python\_warnings.c +# End Source File +# Begin Source File + SOURCE=..\..\Python\asdl.c # End Source File # Begin Source File Modified: python/branches/py3k/PC/VS7.1/pythoncore.vcproj ============================================================================== --- python/branches/py3k/PC/VS7.1/pythoncore.vcproj (original) +++ python/branches/py3k/PC/VS7.1/pythoncore.vcproj Tue Apr 15 08:43:13 2008 @@ -410,6 +410,9 @@ RelativePath="..\..\Modules\arraymodule.c"> + + + + Modified: python/branches/py3k/PCbuild/pythoncore.vcproj ============================================================================== --- python/branches/py3k/PCbuild/pythoncore.vcproj (original) +++ python/branches/py3k/PCbuild/pythoncore.vcproj Tue Apr 15 08:43:13 2008 @@ -1587,6 +1587,10 @@ Name="Python" > + + @@ -1746,10 +1750,6 @@ RelativePath="..\Python\traceback.c" > - - g_dfa; for (i = g->g_ndfas; --i >= 0; d++) fprintf(fp, "#define %s %d\n", d->d_name, d->d_type); Modified: python/branches/py3k/Python/_warnings.c ============================================================================== --- python/branches/py3k/Python/_warnings.c (original) +++ python/branches/py3k/Python/_warnings.c Tue Apr 15 08:43:13 2008 @@ -61,7 +61,7 @@ } -PyObject * +static PyObject * get_once_registry(void) { PyObject *registry; @@ -378,16 +378,17 @@ show_warning(filename, lineno, text, category, sourceline); } else { - PyObject *result; + PyObject *res; - result = PyObject_CallFunctionObjArgs(show_fxn, message, category, + res = PyObject_CallFunctionObjArgs(show_fxn, message, category, filename, lineno_obj, Py_None, sourceline ? sourceline: Py_None, NULL); - Py_XDECREF(result); - if (result == NULL) + Py_DECREF(show_fxn); + Py_XDECREF(res); + if (res == NULL) goto cleanup; } } Modified: python/branches/py3k/Python/getopt.c ============================================================================== --- python/branches/py3k/Python/getopt.c (original) +++ python/branches/py3k/Python/getopt.c Tue Apr 15 08:43:13 2008 @@ -91,7 +91,7 @@ if (option == 'X') { fprintf(stderr, - "-X is reserved for non-standard arguments\n"); + "-X is reserved for implementation-specific arguments\n"); return '_'; } Modified: python/branches/py3k/Python/graminit.c ============================================================================== --- python/branches/py3k/Python/graminit.c (original) +++ python/branches/py3k/Python/graminit.c Tue Apr 15 08:43:13 2008 @@ -1,3 +1,5 @@ +/* Generated by Parser/pgen */ + #include "pgenheaders.h" #include "grammar.h" static arc arcs_0_0[3] = { From python-3000-checkins at python.org Tue Apr 15 23:42:42 2008 From: python-3000-checkins at python.org (mark.dickinson) Date: Tue, 15 Apr 2008 23:42:42 +0200 (CEST) Subject: [Python-3000-checkins] r62356 - in python/branches/py3k: Misc/NEWS Objects/longobject.c Message-ID: <20080415214242.AE2B51E4013@bag.python.org> Author: mark.dickinson Date: Tue Apr 15 23:42:42 2008 New Revision: 62356 Log: PyLong_FromSsize_t was incorrect when sizeof(size_t) > sizeof(long); rewrite it so that it doesn't care about relative sizes of size_t, long and long long. The rewrite is modeled on PyLong_FromLong, instead of using PyLong_FromByteArray; this makes the algorithm simpler and more direct, and possibly also slightly faster. Modified: python/branches/py3k/Misc/NEWS python/branches/py3k/Objects/longobject.c Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Tue Apr 15 23:42:42 2008 @@ -12,6 +12,9 @@ Core and Builtins ----------------- +- Fix misbehaviour of PyLong_FromSsize_t on systems where sizeof(size_t) > + sizeof(long). + - Issue #2221: Corrected a SystemError "error return without exception set", when the code executed by exec() raises an exception, and sys.stdout.flush() also raises an error. Modified: python/branches/py3k/Objects/longobject.c ============================================================================== --- python/branches/py3k/Objects/longobject.c (original) +++ python/branches/py3k/Objects/longobject.c Tue Apr 15 23:42:42 2008 @@ -1099,13 +1099,39 @@ PyObject * PyLong_FromSsize_t(Py_ssize_t ival) { - Py_ssize_t bytes = ival; - int one = 1; - if (ival < PyLong_BASE) - return PyLong_FromLong(ival); - return _PyLong_FromByteArray( - (unsigned char *)&bytes, - SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1); + PyLongObject *v; + size_t abs_ival; + size_t t; /* unsigned so >> doesn't propagate sign bit */ + int ndigits = 0; + int negative = 0; + + CHECK_SMALL_INT(ival); + if (ival < 0) { + /* avoid signed overflow when ival = SIZE_T_MIN */ + abs_ival = (size_t)(-1-ival)+1; + negative = 1; + } + else { + abs_ival = (size_t)ival; + } + + /* Count the number of Python digits. */ + t = abs_ival; + while (t) { + ++ndigits; + t >>= PyLong_SHIFT; + } + v = _PyLong_New(ndigits); + if (v != NULL) { + digit *p = v->ob_digit; + Py_SIZE(v) = negative ? -ndigits : ndigits; + t = abs_ival; + while (t) { + *p++ = (digit)(t & PyLong_MASK); + t >>= PyLong_SHIFT; + } + } + return (PyObject *)v; } /* Create a new long int object from a C size_t. */ @@ -1113,13 +1139,28 @@ PyObject * PyLong_FromSize_t(size_t ival) { - size_t bytes = ival; - int one = 1; + PyLongObject *v; + size_t t; + int ndigits = 0; + if (ival < PyLong_BASE) return PyLong_FromLong(ival); - return _PyLong_FromByteArray( - (unsigned char *)&bytes, - SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0); + /* Count the number of Python digits. */ + t = ival; + while (t) { + ++ndigits; + t >>= PyLong_SHIFT; + } + v = _PyLong_New(ndigits); + if (v != NULL) { + digit *p = v->ob_digit; + Py_SIZE(v) = ndigits; + while (ival) { + *p++ = (digit)(ival & PyLong_MASK); + ival >>= PyLong_SHIFT; + } + } + return (PyObject *)v; } /* Get a C PY_LONG_LONG int from a long int object. From python-3000-checkins at python.org Thu Apr 17 06:21:10 2008 From: python-3000-checkins at python.org (brett.cannon) Date: Thu, 17 Apr 2008 06:21:10 +0200 (CEST) Subject: [Python-3000-checkins] r62360 - python/branches/py3k/Lib/test/test_coding.py Message-ID: <20080417042110.B6AF61E4006@bag.python.org> Author: brett.cannon Date: Thu Apr 17 06:21:10 2008 New Revision: 62360 Log: Have test_coding conditionally remove test files instead of assuming that they are always there. Modified: python/branches/py3k/Lib/test/test_coding.py Modified: python/branches/py3k/Lib/test/test_coding.py ============================================================================== --- python/branches/py3k/Lib/test/test_coding.py (original) +++ python/branches/py3k/Lib/test/test_coding.py Thu Apr 17 06:21:10 2008 @@ -1,6 +1,6 @@ import test.test_support, unittest -from test.test_support import TESTFN +from test.test_support import TESTFN, unlink import os, sys class CodingTest(unittest.TestCase): @@ -45,8 +45,8 @@ __import__(TESTFN) finally: f.close() - os.remove(TESTFN+".py") - os.remove(TESTFN+".pyc") + unlink(TESTFN+".py") + unlink(TESTFN+".pyc") sys.path.pop(0) def test_main(): From python-3000-checkins at python.org Sat Apr 19 02:31:41 2008 From: python-3000-checkins at python.org (christian.heimes) Date: Sat, 19 Apr 2008 02:31:41 +0200 (CEST) Subject: [Python-3000-checkins] r62384 - in python/branches/py3k: Doc/library/cmath.rst Doc/library/math.rst Include/Python.h Include/complexobject.h Include/floatobject.h Include/pymath.h Include/pyport.h Lib/test/cmath_testcases.txt Lib/test/ieee754.txt Lib/test/test_cmath.py Lib/test/test_float.py Lib/test/test_math.py Makefile.pre.in Modules/cmathmodule.c Modules/mathmodule.c Objects/complexobject.c Objects/doubledigits.c Objects/floatobject.c Objects/longobject.c PC/VC6/pythoncore.dsp PC/VS7.1/pythoncore.vcproj PC/VS8.0/pythoncore.vcproj PC/pyconfig.h PCbuild/pythoncore.vcproj Python/hypot.c Python/pymath.c configure Message-ID: <20080419003141.0FAD21E4007@bag.python.org> Author: christian.heimes Date: Sat Apr 19 02:31:39 2008 New Revision: 62384 Log: Merged revisions 62380,62382-62383 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62380 | christian.heimes | 2008-04-19 01:13:07 +0200 (Sat, 19 Apr 2008) | 3 lines I finally got the time to update and merge Mark's and my trunk-math branch. The patch is collaborated work of Mark Dickinson and me. It was mostly done a few months ago. The patch fixes a lot of loose ends and edge cases related to operations with NaN, INF, very small values and complex math. The patch also adds acosh, asinh, atanh, log1p and copysign to all platforms. Finally it fixes differences between platforms like different results or exceptions for edge cases. Have fun :) ........ r62382 | christian.heimes | 2008-04-19 01:40:40 +0200 (Sat, 19 Apr 2008) | 2 lines Added new files to Windows project files More Windows related fixes are coming soon ........ r62383 | christian.heimes | 2008-04-19 01:49:11 +0200 (Sat, 19 Apr 2008) | 1 line Stupid me. Py_RETURN_NAN should actually return something ... ........ Added: python/branches/py3k/Include/pymath.h - copied unchanged from r62380, /python/trunk/Include/pymath.h python/branches/py3k/Lib/test/cmath_testcases.txt - copied unchanged from r62380, /python/trunk/Lib/test/cmath_testcases.txt python/branches/py3k/Lib/test/ieee754.txt - copied unchanged from r62380, /python/trunk/Lib/test/ieee754.txt python/branches/py3k/Python/pymath.c - copied unchanged from r62380, /python/trunk/Python/pymath.c Removed: python/branches/py3k/Objects/doubledigits.c python/branches/py3k/Python/hypot.c Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/cmath.rst python/branches/py3k/Doc/library/math.rst python/branches/py3k/Include/Python.h python/branches/py3k/Include/complexobject.h python/branches/py3k/Include/floatobject.h python/branches/py3k/Include/pyport.h python/branches/py3k/Lib/test/test_cmath.py python/branches/py3k/Lib/test/test_float.py python/branches/py3k/Lib/test/test_math.py python/branches/py3k/Makefile.pre.in python/branches/py3k/Modules/cmathmodule.c python/branches/py3k/Modules/mathmodule.c python/branches/py3k/Objects/complexobject.c python/branches/py3k/Objects/floatobject.c python/branches/py3k/Objects/longobject.c python/branches/py3k/PC/VC6/pythoncore.dsp python/branches/py3k/PC/VS7.1/pythoncore.vcproj python/branches/py3k/PC/VS8.0/pythoncore.vcproj python/branches/py3k/PC/pyconfig.h python/branches/py3k/PCbuild/pythoncore.vcproj python/branches/py3k/configure Modified: python/branches/py3k/Doc/library/cmath.rst ============================================================================== --- python/branches/py3k/Doc/library/cmath.rst (original) +++ python/branches/py3k/Doc/library/cmath.rst Sat Apr 19 02:31:39 2008 @@ -14,8 +14,81 @@ floating-point number, respectively, and the function is then applied to the result of the conversion. -The functions are: +.. note:: + On platforms with hardware and system-level support for signed + zeros, functions involving branch cuts are continuous on *both* + sides of the branch cut: the sign of the zero distinguishes one + side of the branch cut from the other. On platforms that do not + support signed zeros the continuity is as specified below. + + +Complex coordinates +------------------- + +Complex numbers can be expressed by two important coordinate systems. +Python's :class:`complex` type uses rectangular coordinates where a number +on the complex plain is defined by two floats, the real part and the imaginary +part. + +Definition:: + + z = x + 1j * y + + x := real(z) + y := imag(z) + +In engineering the polar coordinate system is popular for complex numbers. In +polar coordinates a complex number is defined by the radius *r* and the phase +angle *?*. The radius *r* is the absolute value of the complex, which can be +viewed as distance from (0, 0). The radius *r* is always 0 or a positive float. +The phase angle *?* is the counter clockwise angle from the positive x axis, +e.g. *1* has the angle *0*, *1j* has the angle *?/2* and *-1* the angle *-?*. + +.. note:: + While :func:`phase` and func:`polar` return *+?* for a negative real they + may return *-?* for a complex with a very small negative imaginary + part, e.g. *-1-1E-300j*. + + +Definition:: + + z = r * exp(1j * ?) + z = r * cis(?) + + r := abs(z) := sqrt(real(z)**2 + imag(z)**2) + phi := phase(z) := atan2(imag(z), real(z)) + cis(?) := cos(?) + 1j * sin(?) + + +.. function:: phase(x) + + Return phase, also known as the argument, of a complex. + + .. versionadded:: 2.6 + + +.. function:: polar(x) + + Convert a :class:`complex` from rectangular coordinates to polar + coordinates. The function returns a tuple with the two elements + *r* and *phi*. *r* is the distance from 0 and *phi* the phase + angle. + + .. versionadded:: 2.6 + + +.. function:: rect(r, phi) + + Convert from polar coordinates to rectangular coordinates and return + a :class:`complex`. + + .. versionadded:: 2.6 + + + +cmath functions +--------------- .. function:: acos(x) @@ -37,30 +110,35 @@ .. function:: asinh(x) - Return the hyperbolic arc sine of *x*. There are two branch cuts, extending - left from ``?1j`` to ``??j``, both continuous from above. These branch cuts - should be considered a bug to be corrected in a future release. The correct - branch cuts should extend along the imaginary axis, one from ``1j`` up to - ``?j`` and continuous from the right, and one from ``-1j`` down to ``-?j`` - and continuous from the left. + Return the hyperbolic arc sine of *x*. There are two branch cuts: + One extends from ``1j`` along the imaginary axis to ``?j``, + continuous from the right. The other extends from ``-1j`` along + the imaginary axis to ``-?j``, continuous from the left. + + .. versionchanged:: 2.6 + branch cuts moved to match those recommended by the C99 standard .. function:: atan(x) Return the arc tangent of *x*. There are two branch cuts: One extends from - ``1j`` along the imaginary axis to ``?j``, continuous from the left. The + ``1j`` along the imaginary axis to ``?j``, continuous from the right. The other extends from ``-1j`` along the imaginary axis to ``-?j``, continuous - from the left. (This should probably be changed so the upper cut becomes - continuous from the other side.) + from the left. + + .. versionchanged:: 2.6 + direction of continuity of upper cut reversed .. function:: atanh(x) Return the hyperbolic arc tangent of *x*. There are two branch cuts: One - extends from ``1`` along the real axis to ``?``, continuous from above. The + extends from ``1`` along the real axis to ``?``, continuous from below. The other extends from ``-1`` along the real axis to ``-?``, continuous from - above. (This should probably be changed so the right cut becomes continuous - from the other side.) + above. + + .. versionchanged:: 2.6 + direction of continuity of right cut reversed .. function:: cos(x) @@ -78,6 +156,21 @@ Return the exponential value ``e**x``. +.. function:: isinf(x) + + Return *True* if the real or the imaginary part of x is positive + or negative infinity. + + .. versionadded:: 2.6 + + +.. function:: isnan(x) + + Return *True* if the real or imaginary part of x is not a number (NaN). + + .. versionadded:: 2.6 + + .. function:: log(x[, base]) Returns the logarithm of *x* to the given *base*. If the *base* is not @@ -151,3 +244,4 @@ nothing's sign bit. In Iserles, A., and Powell, M. (eds.), The state of the art in numerical analysis. Clarendon Press (1987) pp165-211. + Modified: python/branches/py3k/Doc/library/math.rst ============================================================================== --- python/branches/py3k/Doc/library/math.rst (original) +++ python/branches/py3k/Doc/library/math.rst Sat Apr 19 02:31:39 2008 @@ -128,6 +128,14 @@ return the natural logarithm of *x* (that is, the logarithm to base *e*). +.. function:: log1p(x) + + Return the natural logarithm of *1+x* (base *e*). The + result is calculated in a way which is accurate for *x* near zero. + + .. versionadded:: 2.6 + + .. function:: log10(x) Return the base-10 logarithm of *x*. @@ -135,7 +143,11 @@ .. function:: pow(x, y) - Return ``x**y``. + Return ``x**y``. ``1.0**y`` returns *1.0*, even for ``1.0**nan``. ``0**y`` + returns *0.* for all positive *y*, *0* and *NAN*. + + .. versionchanged:: 2.6 + The outcome of ``1**nan`` and ``0**nan`` was undefined. .. function:: sqrt(x) @@ -186,6 +198,13 @@ Return the sine of *x* radians. +.. function:: asinh(x) + + Return the inverse hyperbolic sine of *x*, in radians. + + .. versionadded:: 2.6 + + .. function:: tan(x) Return the tangent of *x* radians. @@ -210,6 +229,13 @@ Return the hyperbolic cosine of *x*. +.. function:: acosh(x) + + Return the inverse hyperbolic cosine of *x*, in radians. + + .. versionadded:: 2.6 + + .. function:: sinh(x) Return the hyperbolic sine of *x*. @@ -219,6 +245,14 @@ Return the hyperbolic tangent of *x*. + +.. function:: atanh(x) + + Return the inverse hyperbolic tangent of *x*, in radians. + + .. versionadded:: 2.6 + + The module also defines two mathematical constants: @@ -231,6 +265,7 @@ The mathematical constant *e*. + .. note:: The :mod:`math` module consists mostly of thin wrappers around the platform C @@ -244,9 +279,17 @@ :exc:`OverflowError` isn't defined, and in cases where ``math.log(0)`` raises :exc:`OverflowError`, ``math.log(0L)`` may raise :exc:`ValueError` instead. + All functions return a quite *NaN* if at least one of the args is *NaN*. + Signaling *NaN*s raise an exception. The exception type still depends on the + platform and libm implementation. It's usually :exc:`ValueError` for *EDOM* + and :exc:`OverflowError` for errno *ERANGE*. + + ..versionchanged:: 2.6 + In earlier versions of Python the outcome of an operation with NaN as + input depended on platform and libm implementation. + .. seealso:: Module :mod:`cmath` Complex number versions of many of these functions. - Modified: python/branches/py3k/Include/Python.h ============================================================================== --- python/branches/py3k/Include/Python.h (original) +++ python/branches/py3k/Include/Python.h Sat Apr 19 02:31:39 2008 @@ -57,6 +57,7 @@ #if defined(PYMALLOC_DEBUG) && !defined(WITH_PYMALLOC) #error "PYMALLOC_DEBUG requires WITH_PYMALLOC" #endif +#include "pymath.h" #include "pymem.h" #include "object.h" Modified: python/branches/py3k/Include/complexobject.h ============================================================================== --- python/branches/py3k/Include/complexobject.h (original) +++ python/branches/py3k/Include/complexobject.h Sat Apr 19 02:31:39 2008 @@ -19,6 +19,7 @@ #define c_prod _Py_c_prod #define c_quot _Py_c_quot #define c_pow _Py_c_pow +#define c_abs _Py_c_abs PyAPI_FUNC(Py_complex) c_sum(Py_complex, Py_complex); PyAPI_FUNC(Py_complex) c_diff(Py_complex, Py_complex); @@ -26,6 +27,7 @@ PyAPI_FUNC(Py_complex) c_prod(Py_complex, Py_complex); PyAPI_FUNC(Py_complex) c_quot(Py_complex, Py_complex); PyAPI_FUNC(Py_complex) c_pow(Py_complex, Py_complex); +PyAPI_FUNC(double) c_abs(Py_complex); /* Complex object interface */ Modified: python/branches/py3k/Include/floatobject.h ============================================================================== --- python/branches/py3k/Include/floatobject.h (original) +++ python/branches/py3k/Include/floatobject.h Sat Apr 19 02:31:39 2008 @@ -21,6 +21,17 @@ #define PyFloat_Check(op) PyObject_TypeCheck(op, &PyFloat_Type) #define PyFloat_CheckExact(op) (Py_TYPE(op) == &PyFloat_Type) +#ifdef Py_NAN +#define Py_RETURN_NAN return PyFloat_FromDouble(Py_NAN) +#endif + +#define Py_RETURN_INF(sign) do \ + if (copysign(1., sign) == 1.) { \ + return PyFloat_FromDouble(Py_HUGE_VAL); \ + } else { \ + return PyFloat_FromDouble(-Py_HUGE_VAL); \ + } while(0) + PyAPI_FUNC(double) PyFloat_GetMax(void); PyAPI_FUNC(double) PyFloat_GetMin(void); PyAPI_FUNC(PyObject *) PyFloat_GetInfo(void); Modified: python/branches/py3k/Include/pyport.h ============================================================================== --- python/branches/py3k/Include/pyport.h (original) +++ python/branches/py3k/Include/pyport.h Sat Apr 19 02:31:39 2008 @@ -336,123 +336,6 @@ #define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) (NARROW)(VALUE) #endif -/* High precision defintion of pi and e (Euler) - * The values are taken from libc6's math.h. - */ -#ifndef Py_MATH_PIl -#define Py_MATH_PIl 3.1415926535897932384626433832795029L -#endif -#ifndef Py_MATH_PI -#define Py_MATH_PI 3.14159265358979323846 -#endif - -#ifndef Py_MATH_El -#define Py_MATH_El 2.7182818284590452353602874713526625L -#endif - -#ifndef Py_MATH_E -#define Py_MATH_E 2.7182818284590452354 -#endif - -/* Py_IS_NAN(X) - * Return 1 if float or double arg is a NaN, else 0. - * Caution: - * X is evaluated more than once. - * This may not work on all platforms. Each platform has *some* - * way to spell this, though -- override in pyconfig.h if you have - * a platform where it doesn't work. - */ -#ifndef Py_IS_NAN -#ifdef HAVE_ISNAN -#define Py_IS_NAN(X) isnan(X) -#else -#define Py_IS_NAN(X) ((X) != (X)) -#endif -#endif - -/* Py_IS_INFINITY(X) - * Return 1 if float or double arg is an infinity, else 0. - * Caution: - * X is evaluated more than once. - * This implementation may set the underflow flag if |X| is very small; - * it really can't be implemented correctly (& easily) before C99. - * Override in pyconfig.h if you have a better spelling on your platform. - */ -#ifndef Py_IS_INFINITY -#ifdef HAVE_ISINF -#define Py_IS_INFINITY(X) isinf(X) -#else -#define Py_IS_INFINITY(X) ((X) && (X)*0.5 == (X)) -#endif -#endif - -/* Py_IS_FINITE(X) - * Return 1 if float or double arg is neither infinite nor NAN, else 0. - * Some compilers (e.g. VisualStudio) have intrisics for this, so a special - * macro for this particular test is useful - */ -#ifndef Py_IS_FINITE -#ifdef HAVE_FINITE -#define Py_IS_FINITE(X) finite(X) -#else -#define Py_IS_FINITE(X) (!Py_IS_INFINITY(X) && !Py_IS_NAN(X)) -#endif -#endif - -/* HUGE_VAL is supposed to expand to a positive double infinity. Python - * uses Py_HUGE_VAL instead because some platforms are broken in this - * respect. We used to embed code in pyport.h to try to worm around that, - * but different platforms are broken in conflicting ways. If you're on - * a platform where HUGE_VAL is defined incorrectly, fiddle your Python - * config to #define Py_HUGE_VAL to something that works on your platform. - */ -#ifndef Py_HUGE_VAL -#define Py_HUGE_VAL HUGE_VAL -#endif - -/* Py_NAN - * A value that evaluates to a NaN. On IEEE 754 platforms INF*0 or - * INF/INF works. Define Py_NO_NAN in pyconfig.h if your platform - * doesn't support NaNs. - */ -#if !defined(Py_NAN) && !defined(Py_NO_NAN) -#define Py_NAN (Py_HUGE_VAL * 0.) -#endif - -/* Py_OVERFLOWED(X) - * Return 1 iff a libm function overflowed. Set errno to 0 before calling - * a libm function, and invoke this macro after, passing the function - * result. - * Caution: - * This isn't reliable. C99 no longer requires libm to set errno under - * any exceptional condition, but does require +- HUGE_VAL return - * values on overflow. A 754 box *probably* maps HUGE_VAL to a - * double infinity, and we're cool if that's so, unless the input - * was an infinity and an infinity is the expected result. A C89 - * system sets errno to ERANGE, so we check for that too. We're - * out of luck if a C99 754 box doesn't map HUGE_VAL to +Inf, or - * if the returned result is a NaN, or if a C89 box returns HUGE_VAL - * in non-overflow cases. - * X is evaluated more than once. - * Some platforms have better way to spell this, so expect some #ifdef'ery. - * - * OpenBSD uses 'isinf()' because a compiler bug on that platform causes - * the longer macro version to be mis-compiled. This isn't optimal, and - * should be removed once a newer compiler is available on that platform. - * The system that had the failure was running OpenBSD 3.2 on Intel, with - * gcc 2.95.3. - * - * According to Tim's checkin, the FreeBSD systems use isinf() to work - * around a FPE bug on that platform. - */ -#if defined(__FreeBSD__) || defined(__OpenBSD__) -#define Py_OVERFLOWED(X) isinf(X) -#else -#define Py_OVERFLOWED(X) ((X) != 0.0 && (errno == ERANGE || \ - (X) == Py_HUGE_VAL || \ - (X) == -Py_HUGE_VAL)) -#endif - /* Py_SET_ERRNO_ON_MATH_ERROR(x) * If a libm function did not set errno, but it looks like the result * overflowed or not-a-number, set errno to ERANGE or EDOM. Set errno @@ -559,15 +442,6 @@ #endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) */ -/************************ - * WRAPPER FOR * - ************************/ - -#ifndef HAVE_HYPOT -extern double hypot(double, double); -#endif - - /* On 4.4BSD-descendants, ctype functions serves the whole range of * wchar_t character set rather than single byte code points only. * This characteristic can break some operations of string object Modified: python/branches/py3k/Lib/test/test_cmath.py ============================================================================== --- python/branches/py3k/Lib/test/test_cmath.py (original) +++ python/branches/py3k/Lib/test/test_cmath.py Sat Apr 19 02:31:39 2008 @@ -1,6 +1,81 @@ from test.test_support import run_unittest +from test.test_math import parse_testfile, test_file import unittest +import os, sys import cmath, math +from cmath import phase, polar, rect, pi + +INF = float('inf') +NAN = float('nan') + +complex_zeros = [complex(x, y) for x in [0.0, -0.0] for y in [0.0, -0.0]] +complex_infinities = [complex(x, y) for x, y in [ + (INF, 0.0), # 1st quadrant + (INF, 2.3), + (INF, INF), + (2.3, INF), + (0.0, INF), + (-0.0, INF), # 2nd quadrant + (-2.3, INF), + (-INF, INF), + (-INF, 2.3), + (-INF, 0.0), + (-INF, -0.0), # 3rd quadrant + (-INF, -2.3), + (-INF, -INF), + (-2.3, -INF), + (-0.0, -INF), + (0.0, -INF), # 4th quadrant + (2.3, -INF), + (INF, -INF), + (INF, -2.3), + (INF, -0.0) + ]] +complex_nans = [complex(x, y) for x, y in [ + (NAN, -INF), + (NAN, -2.3), + (NAN, -0.0), + (NAN, 0.0), + (NAN, 2.3), + (NAN, INF), + (-INF, NAN), + (-2.3, NAN), + (-0.0, NAN), + (0.0, NAN), + (2.3, NAN), + (INF, NAN) + ]] + +def almostEqualF(a, b, rel_err=2e-15, abs_err = 5e-323): + """Determine whether floating-point values a and b are equal to within + a (small) rounding error. The default values for rel_err and + abs_err are chosen to be suitable for platforms where a float is + represented by an IEEE 754 double. They allow an error of between + 9 and 19 ulps.""" + + # special values testing + if math.isnan(a): + return math.isnan(b) + if math.isinf(a): + return a == b + + # if both a and b are zero, check whether they have the same sign + # (in theory there are examples where it would be legitimate for a + # and b to have opposite signs; in practice these hardly ever + # occur). + if not a and not b: + return math.copysign(1., a) == math.copysign(1., b) + + # if a-b overflows, or b is infinite, return False. Again, in + # theory there are examples where a is within a few ulps of the + # max representable float, and then b could legitimately be + # infinite. In practice these examples are rare. + try: + absolute_error = abs(b-a) + except OverflowError: + return False + else: + return absolute_error <= max(abs_err, rel_err * abs(a)) class CMathTests(unittest.TestCase): # list of all functions in cmath @@ -12,25 +87,51 @@ test_functions.append(lambda x : cmath.log(x, 1729. + 0j)) test_functions.append(lambda x : cmath.log(14.-27j, x)) - def cAssertAlmostEqual(self, a, b, rel_eps = 1e-10, abs_eps = 1e-100): - """Check that two complex numbers are almost equal.""" - # the two complex numbers are considered almost equal if - # either the relative error is <= rel_eps or the absolute error - # is tiny, <= abs_eps. - if a == b == 0: - return - absolute_error = abs(a-b) - relative_error = absolute_error/max(abs(a), abs(b)) - if relative_error > rel_eps and absolute_error > abs_eps: - self.fail("%s and %s are not almost equal" % (a, b)) + def setUp(self): + self.test_values = open(test_file) + + def tearDown(self): + self.test_values.close() + + def rAssertAlmostEqual(self, a, b, rel_err = 2e-15, abs_err = 5e-323): + """Check that two floating-point numbers are almost equal.""" + + # special values testing + if math.isnan(a): + if math.isnan(b): + return + self.fail("%s should be nan" % repr(b)) + + if math.isinf(a): + if a == b: + return + self.fail("finite result where infinity excpected: " + "expected %s, got %s" % (repr(a), repr(b))) + + if not a and not b: + if math.atan2(a, -1.) != math.atan2(b, -1.): + self.fail("zero has wrong sign: expected %s, got %s" % + (repr(a), repr(b))) + + # test passes if either the absolute error or the relative + # error is sufficiently small. The defaults amount to an + # error of between 9 ulps and 19 ulps on an IEEE-754 compliant + # machine. + + try: + absolute_error = abs(b-a) + except OverflowError: + pass + else: + if absolute_error <= max(abs_err, rel_err * abs(a)): + return + self.fail("%s and %s are not sufficiently close" % (repr(a), repr(b))) def test_constants(self): e_expected = 2.71828182845904523536 pi_expected = 3.14159265358979323846 - self.assertAlmostEqual(cmath.pi, pi_expected, places=9, - msg="cmath.pi is %s; should be %s" % (cmath.pi, pi_expected)) - self.assertAlmostEqual(cmath.e, e_expected, places=9, - msg="cmath.e is %s; should be %s" % (cmath.e, e_expected)) + self.assertAlmostEqual(cmath.pi, pi_expected) + self.assertAlmostEqual(cmath.e, e_expected) def test_user_object(self): # Test automatic calling of __complex__ and __float__ by cmath @@ -109,13 +210,13 @@ for f in self.test_functions: # usual usage - self.cAssertAlmostEqual(f(MyComplex(cx_arg)), f(cx_arg)) - self.cAssertAlmostEqual(f(MyComplexOS(cx_arg)), f(cx_arg)) + self.assertEqual(f(MyComplex(cx_arg)), f(cx_arg)) + self.assertEqual(f(MyComplexOS(cx_arg)), f(cx_arg)) # other combinations of __float__ and __complex__ - self.cAssertAlmostEqual(f(FloatAndComplex()), f(cx_arg)) - self.cAssertAlmostEqual(f(FloatAndComplexOS()), f(cx_arg)) - self.cAssertAlmostEqual(f(JustFloat()), f(flt_arg)) - self.cAssertAlmostEqual(f(JustFloatOS()), f(flt_arg)) + self.assertEqual(f(FloatAndComplex()), f(cx_arg)) + self.assertEqual(f(FloatAndComplexOS()), f(cx_arg)) + self.assertEqual(f(JustFloat()), f(flt_arg)) + self.assertEqual(f(JustFloatOS()), f(flt_arg)) # TypeError should be raised for classes not providing # either __complex__ or __float__, even if they provide # __int__, __long__ or __index__. An old-style class @@ -138,7 +239,7 @@ # functions, by virtue of providing a __float__ method for f in self.test_functions: for arg in [2, 2.]: - self.cAssertAlmostEqual(f(arg), f(arg.__float__())) + self.assertEqual(f(arg), f(arg.__float__())) # but strings should give a TypeError for f in self.test_functions: @@ -182,12 +283,201 @@ float_fn = getattr(math, fn) complex_fn = getattr(cmath, fn) for v in values: - self.cAssertAlmostEqual(float_fn(v), complex_fn(v)) + z = complex_fn(v) + self.rAssertAlmostEqual(float_fn(v), z.real) + self.assertEqual(0., z.imag) # test two-argument version of log with various bases for base in [0.5, 2., 10.]: for v in positive: - self.cAssertAlmostEqual(cmath.log(v, base), math.log(v, base)) + z = cmath.log(v, base) + self.rAssertAlmostEqual(math.log(v, base), z.real) + self.assertEqual(0., z.imag) + + def test_specific_values(self): + if not float.__getformat__("double").startswith("IEEE"): + return + + def rect_complex(z): + """Wrapped version of rect that accepts a complex number instead of + two float arguments.""" + return cmath.rect(z.real, z.imag) + + def polar_complex(z): + """Wrapped version of polar that returns a complex number instead of + two floats.""" + return complex(*polar(z)) + + for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file): + arg = complex(ar, ai) + expected = complex(er, ei) + if fn == 'rect': + function = rect_complex + elif fn == 'polar': + function = polar_complex + else: + function = getattr(cmath, fn) + if 'divide-by-zero' in flags or 'invalid' in flags: + try: + actual = function(arg) + except ValueError: + continue + else: + test_str = "%s: %s(complex(%r, %r))" % (id, fn, ar, ai) + self.fail('ValueError not raised in test %s' % test_str) + + if 'overflow' in flags: + try: + actual = function(arg) + except OverflowError: + continue + else: + test_str = "%s: %s(complex(%r, %r))" % (id, fn, ar, ai) + self.fail('OverflowError not raised in test %s' % test_str) + + actual = function(arg) + + if 'ignore-real-sign' in flags: + actual = complex(abs(actual.real), actual.imag) + expected = complex(abs(expected.real), expected.imag) + if 'ignore-imag-sign' in flags: + actual = complex(actual.real, abs(actual.imag)) + expected = complex(expected.real, abs(expected.imag)) + + # for the real part of the log function, we allow an + # absolute error of up to 2e-15. + if fn in ('log', 'log10'): + real_abs_err = 2e-15 + else: + real_abs_err = 5e-323 + + if not (almostEqualF(expected.real, actual.real, + abs_err = real_abs_err) and + almostEqualF(expected.imag, actual.imag)): + error_message = ( + "%s: %s(complex(%r, %r))\n" % (id, fn, ar, ai) + + "Expected: complex(%r, %r)\n" % + (expected.real, expected.imag) + + "Received: complex(%r, %r)\n" % + (actual.real, actual.imag) + + "Received value insufficiently close to expected value.") + self.fail(error_message) + + def assertCISEqual(self, a, b): + eps = 1E-7 + if abs(a[0] - b[0]) > eps or abs(a[1] - b[1]) > eps: + self.fail((a ,b)) + + def test_polar(self): + self.assertCISEqual(polar(0), (0., 0.)) + self.assertCISEqual(polar(1.), (1., 0.)) + self.assertCISEqual(polar(-1.), (1., pi)) + self.assertCISEqual(polar(1j), (1., pi/2)) + self.assertCISEqual(polar(-1j), (1., -pi/2)) + + def test_phase(self): + self.assertAlmostEqual(phase(0), 0.) + self.assertAlmostEqual(phase(1.), 0.) + self.assertAlmostEqual(phase(-1.), pi) + self.assertAlmostEqual(phase(-1.+1E-300j), pi) + self.assertAlmostEqual(phase(-1.-1E-300j), -pi) + self.assertAlmostEqual(phase(1j), pi/2) + self.assertAlmostEqual(phase(-1j), -pi/2) + + # zeros + self.assertEqual(phase(complex(0.0, 0.0)), 0.0) + self.assertEqual(phase(complex(0.0, -0.0)), -0.0) + self.assertEqual(phase(complex(-0.0, 0.0)), pi) + self.assertEqual(phase(complex(-0.0, -0.0)), -pi) + + # infinities + self.assertAlmostEqual(phase(complex(-INF, -0.0)), -pi) + self.assertAlmostEqual(phase(complex(-INF, -2.3)), -pi) + self.assertAlmostEqual(phase(complex(-INF, -INF)), -0.75*pi) + self.assertAlmostEqual(phase(complex(-2.3, -INF)), -pi/2) + self.assertAlmostEqual(phase(complex(-0.0, -INF)), -pi/2) + self.assertAlmostEqual(phase(complex(0.0, -INF)), -pi/2) + self.assertAlmostEqual(phase(complex(2.3, -INF)), -pi/2) + self.assertAlmostEqual(phase(complex(INF, -INF)), -pi/4) + self.assertEqual(phase(complex(INF, -2.3)), -0.0) + self.assertEqual(phase(complex(INF, -0.0)), -0.0) + self.assertEqual(phase(complex(INF, 0.0)), 0.0) + self.assertEqual(phase(complex(INF, 2.3)), 0.0) + self.assertAlmostEqual(phase(complex(INF, INF)), pi/4) + self.assertAlmostEqual(phase(complex(2.3, INF)), pi/2) + self.assertAlmostEqual(phase(complex(0.0, INF)), pi/2) + self.assertAlmostEqual(phase(complex(-0.0, INF)), pi/2) + self.assertAlmostEqual(phase(complex(-2.3, INF)), pi/2) + self.assertAlmostEqual(phase(complex(-INF, INF)), 0.75*pi) + self.assertAlmostEqual(phase(complex(-INF, 2.3)), pi) + self.assertAlmostEqual(phase(complex(-INF, 0.0)), pi) + + # real or imaginary part NaN + for z in complex_nans: + self.assert_(math.isnan(phase(z))) + + def test_abs(self): + # zeros + for z in complex_zeros: + self.assertEqual(abs(z), 0.0) + + # infinities + for z in complex_infinities: + self.assertEqual(abs(z), INF) + + # real or imaginary part NaN + self.assertEqual(abs(complex(NAN, -INF)), INF) + self.assert_(math.isnan(abs(complex(NAN, -2.3)))) + self.assert_(math.isnan(abs(complex(NAN, -0.0)))) + self.assert_(math.isnan(abs(complex(NAN, 0.0)))) + self.assert_(math.isnan(abs(complex(NAN, 2.3)))) + self.assertEqual(abs(complex(NAN, INF)), INF) + self.assertEqual(abs(complex(-INF, NAN)), INF) + self.assert_(math.isnan(abs(complex(-2.3, NAN)))) + self.assert_(math.isnan(abs(complex(-0.0, NAN)))) + self.assert_(math.isnan(abs(complex(0.0, NAN)))) + self.assert_(math.isnan(abs(complex(2.3, NAN)))) + self.assertEqual(abs(complex(INF, NAN)), INF) + self.assert_(math.isnan(abs(complex(NAN, NAN)))) + + # result overflows + if float.__getformat__("double").startswith("IEEE"): + self.assertRaises(OverflowError, abs, complex(1.4e308, 1.4e308)) + + def assertCEqual(self, a, b): + eps = 1E-7 + if abs(a.real - b[0]) > eps or abs(a.imag - b[1]) > eps: + self.fail((a ,b)) + + def test_rect(self): + self.assertCEqual(rect(0, 0), (0, 0)) + self.assertCEqual(rect(1, 0), (1., 0)) + self.assertCEqual(rect(1, -pi), (-1., 0)) + self.assertCEqual(rect(1, pi/2), (0, 1.)) + self.assertCEqual(rect(1, -pi/2), (0, -1.)) + + def test_isnan(self): + self.failIf(cmath.isnan(1)) + self.failIf(cmath.isnan(1j)) + self.failIf(cmath.isnan(INF)) + self.assert_(cmath.isnan(NAN)) + self.assert_(cmath.isnan(complex(NAN, 0))) + self.assert_(cmath.isnan(complex(0, NAN))) + self.assert_(cmath.isnan(complex(NAN, NAN))) + self.assert_(cmath.isnan(complex(NAN, INF))) + self.assert_(cmath.isnan(complex(INF, NAN))) + + def test_isinf(self): + self.failIf(cmath.isinf(1)) + self.failIf(cmath.isinf(1j)) + self.failIf(cmath.isinf(NAN)) + self.assert_(cmath.isinf(INF)) + self.assert_(cmath.isinf(complex(INF, 0))) + self.assert_(cmath.isinf(complex(0, INF))) + self.assert_(cmath.isinf(complex(INF, INF))) + self.assert_(cmath.isinf(complex(NAN, INF))) + self.assert_(cmath.isinf(complex(INF, NAN))) + def test_main(): run_unittest(CMathTests) Modified: python/branches/py3k/Lib/test/test_float.py ============================================================================== --- python/branches/py3k/Lib/test/test_float.py (original) +++ python/branches/py3k/Lib/test/test_float.py Sat Apr 19 02:31:39 2008 @@ -2,12 +2,12 @@ import unittest, struct import os from test import test_support +import math +from math import isinf, isnan +import operator -def isinf(x): - return x * 0.5 == x - -def isnan(x): - return x != x +INF = float("inf") +NAN = float("nan") class FormatFunctionsTestCase(unittest.TestCase): @@ -239,6 +239,17 @@ self.assertEqual(str(1e300 * 1e300 * 0), "nan") self.assertEqual(str(-1e300 * 1e300 * 0), "nan") + def notest_float_nan(self): + self.assert_(NAN.is_nan()) + self.failIf(INF.is_nan()) + self.failIf((0.).is_nan()) + + def notest_float_inf(self): + self.assert_(INF.is_inf()) + self.failIf(NAN.is_inf()) + self.failIf((0.).is_inf()) + + def test_main(): test_support.run_unittest( FormatFunctionsTestCase, Modified: python/branches/py3k/Lib/test/test_math.py ============================================================================== --- python/branches/py3k/Lib/test/test_math.py (original) +++ python/branches/py3k/Lib/test/test_math.py Sat Apr 19 02:31:39 2008 @@ -4,9 +4,45 @@ from test.test_support import run_unittest, verbose import unittest import math +import os +import sys -seps='1e-05' -eps = eval(seps) +eps = 1E-05 +NAN = float('nan') +INF = float('inf') +NINF = float('-inf') + +# locate file with test values +if __name__ == '__main__': + file = sys.argv[0] +else: + file = __file__ +test_dir = os.path.dirname(file) or os.curdir +test_file = os.path.join(test_dir, 'cmath_testcases.txt') + +def parse_testfile(fname): + """Parse a file with test values + + Empty lines or lines starting with -- are ignored + yields id, fn, arg_real, arg_imag, exp_real, exp_imag + """ + with open(fname) as fp: + for line in fp: + # skip comment lines and blank lines + if line.startswith('--') or not line.strip(): + continue + + lhs, rhs = line.split('->') + id, fn, arg_real, arg_imag = lhs.split() + rhs_pieces = rhs.split() + exp_real, exp_imag = rhs_pieces[0], rhs_pieces[1] + flags = rhs_pieces[2:] + + yield (id, fn, + float(arg_real), float(arg_imag), + float(exp_real), float(exp_imag), + flags + ) class MathTests(unittest.TestCase): @@ -28,18 +64,57 @@ self.ftest('acos(-1)', math.acos(-1), math.pi) self.ftest('acos(0)', math.acos(0), math.pi/2) self.ftest('acos(1)', math.acos(1), 0) + self.assertRaises(ValueError, math.acos, INF) + self.assertRaises(ValueError, math.acos, NINF) + self.assert_(math.isnan(math.acos(NAN))) + + def testAcosh(self): + self.assertRaises(TypeError, math.acosh) + self.ftest('acosh(1)', math.acosh(1), 0) + self.ftest('acosh(2)', math.acosh(2), 1.3169578969248168) + self.assertRaises(ValueError, math.acosh, 0) + self.assertRaises(ValueError, math.acosh, -1) + self.assertEquals(math.acosh(INF), INF) + self.assertRaises(ValueError, math.acosh, NINF) + self.assert_(math.isnan(math.acosh(NAN))) def testAsin(self): self.assertRaises(TypeError, math.asin) self.ftest('asin(-1)', math.asin(-1), -math.pi/2) self.ftest('asin(0)', math.asin(0), 0) self.ftest('asin(1)', math.asin(1), math.pi/2) + self.assertRaises(ValueError, math.asin, INF) + self.assertRaises(ValueError, math.asin, NINF) + self.assert_(math.isnan(math.asin(NAN))) + + def testAsinh(self): + self.assertRaises(TypeError, math.asinh) + self.ftest('asinh(0)', math.asinh(0), 0) + self.ftest('asinh(1)', math.asinh(1), 0.88137358701954305) + self.ftest('asinh(-1)', math.asinh(-1), -0.88137358701954305) + self.assertEquals(math.asinh(INF), INF) + self.assertEquals(math.asinh(NINF), NINF) + self.assert_(math.isnan(math.asinh(NAN))) def testAtan(self): self.assertRaises(TypeError, math.atan) self.ftest('atan(-1)', math.atan(-1), -math.pi/4) self.ftest('atan(0)', math.atan(0), 0) self.ftest('atan(1)', math.atan(1), math.pi/4) + self.ftest('atan(inf)', math.atan(INF), math.pi/2) + self.ftest('atan(-inf)', math.atan(-INF), -math.pi/2) + self.assert_(math.isnan(math.atan(NAN))) + + def testAtanh(self): + self.assertRaises(TypeError, math.atan) + self.ftest('atanh(0)', math.atanh(0), 0) + self.ftest('atanh(0.5)', math.atanh(0.5), 0.54930614433405489) + self.ftest('atanh(-0.5)', math.atanh(-0.5), -0.54930614433405489) + self.assertRaises(ValueError, math.atanh, 1) + self.assertRaises(ValueError, math.atanh, -1) + self.assertRaises(ValueError, math.atanh, INF) + self.assertRaises(ValueError, math.atanh, NINF) + self.assert_(math.isnan(math.atanh(NAN))) def testAtan2(self): self.assertRaises(TypeError, math.atan2) @@ -58,6 +133,9 @@ self.ftest('ceil(-0.5)', math.ceil(-0.5), 0) self.ftest('ceil(-1.0)', math.ceil(-1.0), -1) self.ftest('ceil(-1.5)', math.ceil(-1.5), -1) + #self.assertEquals(math.ceil(INF), INF) + #self.assertEquals(math.ceil(NINF), NINF) + #self.assert_(math.isnan(math.ceil(NAN))) class TestCeil: def __ceil__(self): @@ -72,17 +150,55 @@ self.assertRaises(TypeError, math.ceil, t) self.assertRaises(TypeError, math.ceil, t, 0) + if float.__getformat__("double").startswith("IEEE"): + def testCopysign(self): + self.assertRaises(TypeError, math.copysign) + # copysign should let us distinguish signs of zeros + self.assertEquals(copysign(1., 0.), 1.) + self.assertEquals(copysign(1., -0.), -1.) + self.assertEquals(copysign(INF, 0.), INF) + self.assertEquals(copysign(INF, -0.), NINF) + self.assertEquals(copysign(NINF, 0.), INF) + self.assertEquals(copysign(NINF, -0.), NINF) + # and of infinities + self.assertEquals(copysign(1., INF), 1.) + self.assertEquals(copysign(1., NINF), -1.) + self.assertEquals(copysign(INF, INF), INF) + self.assertEquals(copysign(INF, NINF), NINF) + self.assertEquals(copysign(NINF, INF), INF) + self.assertEquals(copysign(NINF, NINF), NINF) + self.assert_(math.isnan(copysign(NAN, 1.))) + self.assert_(math.isnan(copysign(NAN, INF))) + self.assert_(math.isnan(copysign(NAN, NINF))) + self.assert_(math.isnan(copysign(NAN, NAN))) + # copysign(INF, NAN) may be INF or it may be NINF, since + # we don't know whether the sign bit of NAN is set on any + # given platform. + self.assert_(math.isinf(copysign(INF, NAN))) + # similarly, copysign(2., NAN) could be 2. or -2. + self.assertEquals(abs(copysign(2., NAN)), 2.) + def testCos(self): self.assertRaises(TypeError, math.cos) self.ftest('cos(-pi/2)', math.cos(-math.pi/2), 0) self.ftest('cos(0)', math.cos(0), 1) self.ftest('cos(pi/2)', math.cos(math.pi/2), 0) self.ftest('cos(pi)', math.cos(math.pi), -1) + try: + self.assert_(math.isnan(math.cos(INF))) + self.assert_(math.isnan(math.cos(NINF))) + except ValueError: + self.assertRaises(ValueError, math.cos, INF) + self.assertRaises(ValueError, math.cos, NINF) + self.assert_(math.isnan(math.cos(NAN))) def testCosh(self): self.assertRaises(TypeError, math.cosh) self.ftest('cosh(0)', math.cosh(0), 1) self.ftest('cosh(2)-2*cosh(1)**2', math.cosh(2)-2*math.cosh(1)**2, -1) # Thanks to Lambert + self.assertEquals(math.cosh(INF), INF) + self.assertEquals(math.cosh(NINF), INF) + self.assert_(math.isnan(math.cosh(NAN))) def testDegrees(self): self.assertRaises(TypeError, math.degrees) @@ -95,6 +211,9 @@ self.ftest('exp(-1)', math.exp(-1), 1/math.e) self.ftest('exp(0)', math.exp(0), 1) self.ftest('exp(1)', math.exp(1), math.e) + self.assertEquals(math.exp(INF), INF) + self.assertEquals(math.exp(NINF), 0.) + self.assert_(math.isnan(math.exp(NAN))) def testFabs(self): self.assertRaises(TypeError, math.fabs) @@ -115,6 +234,9 @@ # This fails on some platforms - so check it here self.ftest('floor(1.23e167)', math.floor(1.23e167), 1.23e167) self.ftest('floor(-1.23e167)', math.floor(-1.23e167), -1.23e167) + #self.assertEquals(math.ceil(INF), INF) + #self.assertEquals(math.ceil(NINF), NINF) + #self.assert_(math.isnan(math.floor(NAN))) class TestFloor: def __floor__(self): @@ -137,6 +259,19 @@ self.ftest('fmod(-10,1)', math.fmod(-10,1), 0) self.ftest('fmod(-10,0.5)', math.fmod(-10,0.5), 0) self.ftest('fmod(-10,1.5)', math.fmod(-10,1.5), -1) + self.assert_(math.isnan(math.fmod(NAN, 1.))) + self.assert_(math.isnan(math.fmod(1., NAN))) + self.assert_(math.isnan(math.fmod(NAN, NAN))) + self.assertRaises(ValueError, math.fmod, 1., 0.) + self.assertRaises(ValueError, math.fmod, INF, 1.) + self.assertRaises(ValueError, math.fmod, NINF, 1.) + self.assertRaises(ValueError, math.fmod, INF, 0.) + self.assertEquals(math.fmod(3.0, INF), 3.0) + self.assertEquals(math.fmod(-3.0, INF), -3.0) + self.assertEquals(math.fmod(3.0, NINF), 3.0) + self.assertEquals(math.fmod(-3.0, NINF), -3.0) + self.assertEquals(math.fmod(0.0, 3.0), 0.0) + self.assertEquals(math.fmod(0.0, NINF), 0.0) def testFrexp(self): self.assertRaises(TypeError, math.frexp) @@ -152,10 +287,20 @@ testfrexp('frexp(1)', math.frexp(1), (0.5, 1)) testfrexp('frexp(2)', math.frexp(2), (0.5, 2)) + self.assertEquals(math.frexp(INF)[0], INF) + self.assertEquals(math.frexp(NINF)[0], NINF) + self.assert_(math.isnan(math.frexp(NAN)[0])) + def testHypot(self): self.assertRaises(TypeError, math.hypot) self.ftest('hypot(0,0)', math.hypot(0,0), 0) self.ftest('hypot(3,4)', math.hypot(3,4), 5) + self.assertEqual(math.hypot(NAN, INF), INF) + self.assertEqual(math.hypot(INF, NAN), INF) + self.assertEqual(math.hypot(NAN, NINF), INF) + self.assertEqual(math.hypot(NINF, NAN), INF) + self.assert_(math.isnan(math.hypot(1.0, NAN))) + self.assert_(math.isnan(math.hypot(NAN, -2.0))) def testLdexp(self): self.assertRaises(TypeError, math.ldexp) @@ -163,6 +308,13 @@ self.ftest('ldexp(1,1)', math.ldexp(1,1), 2) self.ftest('ldexp(1,-1)', math.ldexp(1,-1), 0.5) self.ftest('ldexp(-1,1)', math.ldexp(-1,1), -2) + self.assertRaises(OverflowError, math.ldexp, 1., 1000000) + self.assertRaises(OverflowError, math.ldexp, -1., 1000000) + self.assertEquals(math.ldexp(1., -1000000), 0.) + self.assertEquals(math.ldexp(-1., -1000000), -0.) + self.assertEquals(math.ldexp(INF, 30), INF) + self.assertEquals(math.ldexp(NINF, -213), NINF) + self.assert_(math.isnan(math.ldexp(NAN, 0))) def testLog(self): self.assertRaises(TypeError, math.log) @@ -172,12 +324,31 @@ self.ftest('log(32,2)', math.log(32,2), 5) self.ftest('log(10**40, 10)', math.log(10**40, 10), 40) self.ftest('log(10**40, 10**20)', math.log(10**40, 10**20), 2) + self.assertEquals(math.log(INF), INF) + self.assertRaises(ValueError, math.log, NINF) + self.assert_(math.isnan(math.log(NAN))) + + def testLog1p(self): + self.assertRaises(TypeError, math.log1p) + self.ftest('log1p(1/e -1)', math.log1p(1/math.e-1), -1) + self.ftest('log1p(0)', math.log1p(0), 0) + self.ftest('log1p(e-1)', math.log1p(math.e-1), 1) + self.ftest('log1p(1)', math.log1p(1), math.log(2)) + self.assertEquals(math.log1p(INF), INF) + self.assertRaises(ValueError, math.log1p, NINF) + self.assert_(math.isnan(math.log1p(NAN))) + n= 2**90 + self.assertAlmostEquals(math.log1p(n), 62.383246250395075) + self.assertAlmostEquals(math.log1p(n), math.log1p(float(n))) def testLog10(self): self.assertRaises(TypeError, math.log10) self.ftest('log10(0.1)', math.log10(0.1), -1) self.ftest('log10(1)', math.log10(1), 0) self.ftest('log10(10)', math.log10(10), 1) + self.assertEquals(math.log(INF), INF) + self.assertRaises(ValueError, math.log10, NINF) + self.assert_(math.isnan(math.log10(NAN))) def testModf(self): self.assertRaises(TypeError, math.modf) @@ -191,12 +362,35 @@ testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0)) testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0)) + self.assertEquals(math.modf(INF), (0.0, INF)) + self.assertEquals(math.modf(NINF), (-0.0, NINF)) + + modf_nan = math.modf(NAN) + self.assert_(math.isnan(modf_nan[0])) + self.assert_(math.isnan(modf_nan[1])) + def testPow(self): self.assertRaises(TypeError, math.pow) self.ftest('pow(0,1)', math.pow(0,1), 0) self.ftest('pow(1,0)', math.pow(1,0), 1) self.ftest('pow(2,1)', math.pow(2,1), 2) self.ftest('pow(2,-1)', math.pow(2,-1), 0.5) + self.assertEqual(math.pow(INF, 1), INF) + self.assertEqual(math.pow(NINF, 1), NINF) + self.assertEqual((math.pow(1, INF)), 1.) + self.assertEqual((math.pow(1, NINF)), 1.) + self.assert_(math.isnan(math.pow(NAN, 1))) + self.assert_(math.isnan(math.pow(2, NAN))) + self.assert_(math.isnan(math.pow(0, NAN))) + self.assertEqual(math.pow(1, NAN), 1) + self.assertEqual(1**NAN, 1) + self.assertEqual(1**INF, 1) + self.assertEqual(1**NINF, 1) + self.assertEqual(1**0, 1) + self.assertEqual(1.**NAN, 1) + self.assertEqual(1.**INF, 1) + self.assertEqual(1.**NINF, 1) + self.assertEqual(1.**0, 1) def testRadians(self): self.assertRaises(TypeError, math.radians) @@ -209,29 +403,52 @@ self.ftest('sin(0)', math.sin(0), 0) self.ftest('sin(pi/2)', math.sin(math.pi/2), 1) self.ftest('sin(-pi/2)', math.sin(-math.pi/2), -1) + try: + self.assert_(math.isnan(math.sin(INF))) + self.assert_(math.isnan(math.sin(NINF))) + except ValueError: + self.assertRaises(ValueError, math.sin, INF) + self.assertRaises(ValueError, math.sin, NINF) + self.assert_(math.isnan(math.sin(NAN))) def testSinh(self): self.assertRaises(TypeError, math.sinh) self.ftest('sinh(0)', math.sinh(0), 0) self.ftest('sinh(1)**2-cosh(1)**2', math.sinh(1)**2-math.cosh(1)**2, -1) self.ftest('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0) + self.assertEquals(math.sinh(INF), INF) + self.assertEquals(math.sinh(-INF), -INF) + self.assert_(math.isnan(math.sinh(NAN))) def testSqrt(self): self.assertRaises(TypeError, math.sqrt) self.ftest('sqrt(0)', math.sqrt(0), 0) self.ftest('sqrt(1)', math.sqrt(1), 1) self.ftest('sqrt(4)', math.sqrt(4), 2) + self.assertEquals(math.sqrt(INF), INF) + self.assertRaises(ValueError, math.sqrt, NINF) + self.assert_(math.isnan(math.sqrt(NAN))) def testTan(self): self.assertRaises(TypeError, math.tan) self.ftest('tan(0)', math.tan(0), 0) self.ftest('tan(pi/4)', math.tan(math.pi/4), 1) self.ftest('tan(-pi/4)', math.tan(-math.pi/4), -1) + try: + self.assert_(math.isnan(math.tan(INF))) + self.assert_(math.isnan(math.tan(NINF))) + except: + self.assertRaises(ValueError, math.tan, INF) + self.assertRaises(ValueError, math.tan, NINF) + self.assert_(math.isnan(math.tan(NAN))) def testTanh(self): self.assertRaises(TypeError, math.tanh) self.ftest('tanh(0)', math.tanh(0), 0) self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0) + self.ftest('tanh(inf)', math.tanh(INF), 1) + self.ftest('tanh(-inf)', math.tanh(NINF), -1) + self.assert_(math.isnan(math.tanh(NAN))) def test_trunc(self): self.assertEqual(math.trunc(1), 1) @@ -326,9 +543,27 @@ else: self.fail("sqrt(-1) didn't raise ValueError") + def test_testfile(self): + if not float.__getformat__("double").startswith("IEEE"): + return + for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file): + # Skip if either the input or result is complex, or if + # flags is nonempty + if ai != 0. or ei != 0. or flags: + continue + if fn in ['rect', 'polar']: + # no real versions of rect, polar + continue + func = getattr(math, fn) + result = func(ar) + self.ftest("%s:%s(%r)" % (id, fn, ar), result, er) def test_main(): - run_unittest(MathTests) + from doctest import DocFileSuite + suite = unittest.TestSuite() + suite.addTest(unittest.makeSuite(MathTests)) + suite.addTest(DocFileSuite("ieee754.txt")) + run_unittest(suite) if __name__ == '__main__': test_main() Modified: python/branches/py3k/Makefile.pre.in ============================================================================== --- python/branches/py3k/Makefile.pre.in (original) +++ python/branches/py3k/Makefile.pre.in Sat Apr 19 02:31:39 2008 @@ -276,6 +276,7 @@ Python/peephole.o \ Python/pyarena.o \ Python/pyfpe.o \ + Python/pymath.o \ Python/pystate.o \ Python/pythonrun.o \ Python/structmember.o \ @@ -622,6 +623,7 @@ Include/pydebug.h \ Include/pyerrors.h \ Include/pyfpe.h \ + Include/pymath.h \ Include/pygetopt.h \ Include/pymem.h \ Include/pyport.h \ Modified: python/branches/py3k/Modules/cmathmodule.c ============================================================================== --- python/branches/py3k/Modules/cmathmodule.c (original) +++ python/branches/py3k/Modules/cmathmodule.c Sat Apr 19 02:31:39 2008 @@ -3,31 +3,172 @@ /* much code borrowed from mathmodule.c */ #include "Python.h" +/* we need DBL_MAX, DBL_MIN, DBL_EPSILON, DBL_MANT_DIG and FLT_RADIX from + float.h. We assume that FLT_RADIX is either 2 or 16. */ +#include -#ifndef M_PI -#define M_PI (3.141592653589793239) +#if (FLT_RADIX != 2 && FLT_RADIX != 16) +#error "Modules/cmathmodule.c expects FLT_RADIX to be 2 or 16" #endif -/* First, the C functions that do the real work */ +#ifndef M_LN2 +#define M_LN2 (0.6931471805599453094) /* natural log of 2 */ +#endif + +#ifndef M_LN10 +#define M_LN10 (2.302585092994045684) /* natural log of 10 */ +#endif -/* constants */ -static Py_complex c_one = {1., 0.}; -static Py_complex c_half = {0.5, 0.}; -static Py_complex c_i = {0., 1.}; -static Py_complex c_halfi = {0., 0.5}; +/* + CM_LARGE_DOUBLE is used to avoid spurious overflow in the sqrt, log, + inverse trig and inverse hyperbolic trig functions. Its log is used in the + evaluation of exp, cos, cosh, sin, sinh, tan, and tanh to avoid unecessary + overflow. + */ + +#define CM_LARGE_DOUBLE (DBL_MAX/4.) +#define CM_SQRT_LARGE_DOUBLE (sqrt(CM_LARGE_DOUBLE)) +#define CM_LOG_LARGE_DOUBLE (log(CM_LARGE_DOUBLE)) +#define CM_SQRT_DBL_MIN (sqrt(DBL_MIN)) + +/* + CM_SCALE_UP is an odd integer chosen such that multiplication by + 2**CM_SCALE_UP is sufficient to turn a subnormal into a normal. + CM_SCALE_DOWN is (-(CM_SCALE_UP+1)/2). These scalings are used to compute + square roots accurately when the real and imaginary parts of the argument + are subnormal. +*/ + +#if FLT_RADIX==2 +#define CM_SCALE_UP (2*(DBL_MANT_DIG/2) + 1) +#elif FLT_RADIX==16 +#define CM_SCALE_UP (4*DBL_MANT_DIG+1) +#endif +#define CM_SCALE_DOWN (-(CM_SCALE_UP+1)/2) /* forward declarations */ -static Py_complex c_log(Py_complex); -static Py_complex c_prodi(Py_complex); +static Py_complex c_asinh(Py_complex); +static Py_complex c_atanh(Py_complex); +static Py_complex c_cosh(Py_complex); +static Py_complex c_sinh(Py_complex); static Py_complex c_sqrt(Py_complex); +static Py_complex c_tanh(Py_complex); static PyObject * math_error(void); +/* Code to deal with special values (infinities, NaNs, etc.). */ + +/* special_type takes a double and returns an integer code indicating + the type of the double as follows: +*/ + +enum special_types { + ST_NINF, /* 0, negative infinity */ + ST_NEG, /* 1, negative finite number (nonzero) */ + ST_NZERO, /* 2, -0. */ + ST_PZERO, /* 3, +0. */ + ST_POS, /* 4, positive finite number (nonzero) */ + ST_PINF, /* 5, positive infinity */ + ST_NAN, /* 6, Not a Number */ +}; + +static enum special_types +special_type(double d) +{ + if (Py_IS_FINITE(d)) { + if (d != 0) { + if (copysign(1., d) == 1.) + return ST_POS; + else + return ST_NEG; + } + else { + if (copysign(1., d) == 1.) + return ST_PZERO; + else + return ST_NZERO; + } + } + if (Py_IS_NAN(d)) + return ST_NAN; + if (copysign(1., d) == 1.) + return ST_PINF; + else + return ST_NINF; +} + +#define SPECIAL_VALUE(z, table) \ + if (!Py_IS_FINITE((z).real) || !Py_IS_FINITE((z).imag)) { \ + errno = 0; \ + return table[special_type((z).real)] \ + [special_type((z).imag)]; \ + } + +#define P Py_MATH_PI +#define P14 0.25*Py_MATH_PI +#define P12 0.5*Py_MATH_PI +#define P34 0.75*Py_MATH_PI +#ifdef MS_WINDOWS +/* On Windows HUGE_VAL is an extern variable and not a constant. Since the + special value arrays need a constant we have to roll our own infinity + and nan. */ +# define INF (DBL_MAX*DBL_MAX) +# define N (INF*0.) +#else +# define INF Py_HUGE_VAL +# define N Py_NAN +#endif /* MS_WINDOWS */ +#define U -9.5426319407711027e33 /* unlikely value, used as placeholder */ + +/* First, the C functions that do the real work. Each of the c_* + functions computes and returns the C99 Annex G recommended result + and also sets errno as follows: errno = 0 if no floating-point + exception is associated with the result; errno = EDOM if C99 Annex + G recommends raising divide-by-zero or invalid for this result; and + errno = ERANGE where the overflow floating-point signal should be + raised. +*/ + +static Py_complex acos_special_values[7][7] = { + {{P34,INF},{P,INF}, {P,INF}, {P,-INF}, {P,-INF}, {P34,-INF},{N,INF}}, + {{P12,INF},{U,U}, {U,U}, {U,U}, {U,U}, {P12,-INF},{N,N}}, + {{P12,INF},{U,U}, {P12,0.},{P12,-0.},{U,U}, {P12,-INF},{P12,N}}, + {{P12,INF},{U,U}, {P12,0.},{P12,-0.},{U,U}, {P12,-INF},{P12,N}}, + {{P12,INF},{U,U}, {U,U}, {U,U}, {U,U}, {P12,-INF},{N,N}}, + {{P14,INF},{0.,INF},{0.,INF},{0.,-INF},{0.,-INF},{P14,-INF},{N,INF}}, + {{N,INF}, {N,N}, {N,N}, {N,N}, {N,N}, {N,-INF}, {N,N}} +}; static Py_complex -c_acos(Py_complex x) +c_acos(Py_complex z) { - return c_neg(c_prodi(c_log(c_sum(x,c_prod(c_i, - c_sqrt(c_diff(c_one,c_prod(x,x)))))))); + Py_complex s1, s2, r; + + SPECIAL_VALUE(z, acos_special_values); + + if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { + /* avoid unnecessary overflow for large arguments */ + r.real = atan2(fabs(z.imag), z.real); + /* split into cases to make sure that the branch cut has the + correct continuity on systems with unsigned zeros */ + if (z.real < 0.) { + r.imag = -copysign(log(hypot(z.real/2., z.imag/2.)) + + M_LN2*2., z.imag); + } else { + r.imag = copysign(log(hypot(z.real/2., z.imag/2.)) + + M_LN2*2., -z.imag); + } + } else { + s1.real = 1.-z.real; + s1.imag = -z.imag; + s1 = c_sqrt(s1); + s2.real = 1.+z.real; + s2.imag = z.imag; + s2 = c_sqrt(s2); + r.real = 2.*atan2(s1.real, s2.real); + r.imag = asinh(s2.real*s1.imag - s2.imag*s1.real); + } + errno = 0; + return r; } PyDoc_STRVAR(c_acos_doc, @@ -36,14 +177,39 @@ "Return the arc cosine of x."); +static Py_complex acosh_special_values[7][7] = { + {{INF,-P34},{INF,-P}, {INF,-P}, {INF,P}, {INF,P}, {INF,P34},{INF,N}}, + {{INF,-P12},{U,U}, {U,U}, {U,U}, {U,U}, {INF,P12},{N,N}}, + {{INF,-P12},{U,U}, {0.,-P12},{0.,P12},{U,U}, {INF,P12},{N,N}}, + {{INF,-P12},{U,U}, {0.,-P12},{0.,P12},{U,U}, {INF,P12},{N,N}}, + {{INF,-P12},{U,U}, {U,U}, {U,U}, {U,U}, {INF,P12},{N,N}}, + {{INF,-P14},{INF,-0.},{INF,-0.},{INF,0.},{INF,0.},{INF,P14},{INF,N}}, + {{INF,N}, {N,N}, {N,N}, {N,N}, {N,N}, {INF,N}, {N,N}} +}; + static Py_complex -c_acosh(Py_complex x) +c_acosh(Py_complex z) { - Py_complex z; - z = c_sqrt(c_half); - z = c_log(c_prod(z, c_sum(c_sqrt(c_sum(x,c_one)), - c_sqrt(c_diff(x,c_one))))); - return c_sum(z, z); + Py_complex s1, s2, r; + + SPECIAL_VALUE(z, acosh_special_values); + + if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { + /* avoid unnecessary overflow for large arguments */ + r.real = log(hypot(z.real/2., z.imag/2.)) + M_LN2*2.; + r.imag = atan2(z.imag, z.real); + } else { + s1.real = z.real - 1.; + s1.imag = z.imag; + s1 = c_sqrt(s1); + s2.real = z.real + 1.; + s2.imag = z.imag; + s2 = c_sqrt(s2); + r.real = asinh(s1.real*s2.real + s1.imag*s2.imag); + r.imag = 2.*atan2(s1.imag, s2.real); + } + errno = 0; + return r; } PyDoc_STRVAR(c_acosh_doc, @@ -53,14 +219,16 @@ static Py_complex -c_asin(Py_complex x) +c_asin(Py_complex z) { - /* -i * log[(sqrt(1-x**2) + i*x] */ - const Py_complex squared = c_prod(x, x); - const Py_complex sqrt_1_minus_x_sq = c_sqrt(c_diff(c_one, squared)); - return c_neg(c_prodi(c_log( - c_sum(sqrt_1_minus_x_sq, c_prodi(x)) - ) ) ); + /* asin(z) = -i asinh(iz) */ + Py_complex s, r; + s.real = -z.imag; + s.imag = z.real; + s = c_asinh(s); + r.real = s.imag; + r.imag = -s.real; + return r; } PyDoc_STRVAR(c_asin_doc, @@ -69,14 +237,44 @@ "Return the arc sine of x."); +static Py_complex asinh_special_values[7][7] = { + {{-INF,-P14},{-INF,-0.},{-INF,-0.},{-INF,0.},{-INF,0.},{-INF,P14},{-INF,N}}, + {{-INF,-P12},{U,U}, {U,U}, {U,U}, {U,U}, {-INF,P12},{N,N}}, + {{-INF,-P12},{U,U}, {-0.,-0.}, {-0.,0.}, {U,U}, {-INF,P12},{N,N}}, + {{INF,-P12}, {U,U}, {0.,-0.}, {0.,0.}, {U,U}, {INF,P12}, {N,N}}, + {{INF,-P12}, {U,U}, {U,U}, {U,U}, {U,U}, {INF,P12}, {N,N}}, + {{INF,-P14}, {INF,-0.}, {INF,-0.}, {INF,0.}, {INF,0.}, {INF,P14}, {INF,N}}, + {{INF,N}, {N,N}, {N,-0.}, {N,0.}, {N,N}, {INF,N}, {N,N}} +}; + static Py_complex -c_asinh(Py_complex x) +c_asinh(Py_complex z) { - Py_complex z; - z = c_sqrt(c_half); - z = c_log(c_prod(z, c_sum(c_sqrt(c_sum(x, c_i)), - c_sqrt(c_diff(x, c_i))))); - return c_sum(z, z); + Py_complex s1, s2, r; + + SPECIAL_VALUE(z, asinh_special_values); + + if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { + if (z.imag >= 0.) { + r.real = copysign(log(hypot(z.real/2., z.imag/2.)) + + M_LN2*2., z.real); + } else { + r.real = -copysign(log(hypot(z.real/2., z.imag/2.)) + + M_LN2*2., -z.real); + } + r.imag = atan2(z.imag, fabs(z.real)); + } else { + s1.real = 1.+z.imag; + s1.imag = -z.real; + s1 = c_sqrt(s1); + s2.real = 1.-z.imag; + s2.imag = z.real; + s2 = c_sqrt(s2); + r.real = asinh(s1.real*s2.imag-s2.real*s1.imag); + r.imag = atan2(z.imag, s1.real*s2.real-s1.imag*s2.imag); + } + errno = 0; + return r; } PyDoc_STRVAR(c_asinh_doc, @@ -86,9 +284,37 @@ static Py_complex -c_atan(Py_complex x) +c_atan(Py_complex z) { - return c_prod(c_halfi,c_log(c_quot(c_sum(c_i,x),c_diff(c_i,x)))); + /* atan(z) = -i atanh(iz) */ + Py_complex s, r; + s.real = -z.imag; + s.imag = z.real; + s = c_atanh(s); + r.real = s.imag; + r.imag = -s.real; + return r; +} + +/* Windows screws up atan2 for inf and nan */ +static double +c_atan2(Py_complex z) +{ + if (Py_IS_NAN(z.real) || Py_IS_NAN(z.imag)) + return Py_NAN; + if (Py_IS_INFINITY(z.imag)) { + if (Py_IS_INFINITY(z.real)) { + if (copysign(1., z.real) == 1.) + /* atan2(+-inf, +inf) == +-pi/4 */ + return copysign(0.25*Py_MATH_PI, z.imag); + else + /* atan2(+-inf, -inf) == +-pi*3/4 */ + return copysign(0.75*Py_MATH_PI, z.imag); + } + /* atan2(+-inf, x) == +-pi/2 for finite x */ + return copysign(0.5*Py_MATH_PI, z.imag); + } + return atan2(z.imag, z.real); } PyDoc_STRVAR(c_atan_doc, @@ -97,10 +323,61 @@ "Return the arc tangent of x."); +static Py_complex atanh_special_values[7][7] = { + {{-0.,-P12},{-0.,-P12},{-0.,-P12},{-0.,P12},{-0.,P12},{-0.,P12},{-0.,N}}, + {{-0.,-P12},{U,U}, {U,U}, {U,U}, {U,U}, {-0.,P12},{N,N}}, + {{-0.,-P12},{U,U}, {-0.,-0.}, {-0.,0.}, {U,U}, {-0.,P12},{-0.,N}}, + {{0.,-P12}, {U,U}, {0.,-0.}, {0.,0.}, {U,U}, {0.,P12}, {0.,N}}, + {{0.,-P12}, {U,U}, {U,U}, {U,U}, {U,U}, {0.,P12}, {N,N}}, + {{0.,-P12}, {0.,-P12}, {0.,-P12}, {0.,P12}, {0.,P12}, {0.,P12}, {0.,N}}, + {{0.,-P12}, {N,N}, {N,N}, {N,N}, {N,N}, {0.,P12}, {N,N}} +}; + static Py_complex -c_atanh(Py_complex x) +c_atanh(Py_complex z) { - return c_prod(c_half,c_log(c_quot(c_sum(c_one,x),c_diff(c_one,x)))); + Py_complex r; + double ay, h; + + SPECIAL_VALUE(z, atanh_special_values); + + /* Reduce to case where z.real >= 0., using atanh(z) = -atanh(-z). */ + if (z.real < 0.) { + return c_neg(c_atanh(c_neg(z))); + } + + ay = fabs(z.imag); + if (z.real > CM_SQRT_LARGE_DOUBLE || ay > CM_SQRT_LARGE_DOUBLE) { + /* + if abs(z) is large then we use the approximation + atanh(z) ~ 1/z +/- i*pi/2 (+/- depending on the sign + of z.imag) + */ + h = hypot(z.real/2., z.imag/2.); /* safe from overflow */ + r.real = z.real/4./h/h; + /* the two negations in the next line cancel each other out + except when working with unsigned zeros: they're there to + ensure that the branch cut has the correct continuity on + systems that don't support signed zeros */ + r.imag = -copysign(Py_MATH_PI/2., -z.imag); + errno = 0; + } else if (z.real == 1. && ay < CM_SQRT_DBL_MIN) { + /* C99 standard says: atanh(1+/-0.) should be inf +/- 0i */ + if (ay == 0.) { + r.real = INF; + r.imag = z.imag; + errno = EDOM; + } else { + r.real = -log(sqrt(ay)/sqrt(hypot(ay, 2.))); + r.imag = copysign(atan2(2., -ay)/2, z.imag); + errno = 0; + } + } else { + r.real = log1p(4.*z.real/((1-z.real)*(1-z.real) + ay*ay))/4.; + r.imag = -atan2(-2.*z.imag, (1-z.real)*(1+z.real) - ay*ay)/2.; + errno = 0; + } + return r; } PyDoc_STRVAR(c_atanh_doc, @@ -110,11 +387,13 @@ static Py_complex -c_cos(Py_complex x) +c_cos(Py_complex z) { + /* cos(z) = cosh(iz) */ Py_complex r; - r.real = cos(x.real)*cosh(x.imag); - r.imag = -sin(x.real)*sinh(x.imag); + r.real = -z.imag; + r.imag = z.real; + r = c_cosh(r); return r; } @@ -124,12 +403,64 @@ "Return the cosine of x."); +/* cosh(infinity + i*y) needs to be dealt with specially */ +static Py_complex cosh_special_values[7][7] = { + {{INF,N},{U,U},{INF,0.}, {INF,-0.},{U,U},{INF,N},{INF,N}}, + {{N,N}, {U,U},{U,U}, {U,U}, {U,U},{N,N}, {N,N}}, + {{N,0.}, {U,U},{1.,0.}, {1.,-0.}, {U,U},{N,0.}, {N,0.}}, + {{N,0.}, {U,U},{1.,-0.}, {1.,0.}, {U,U},{N,0.}, {N,0.}}, + {{N,N}, {U,U},{U,U}, {U,U}, {U,U},{N,N}, {N,N}}, + {{INF,N},{U,U},{INF,-0.},{INF,0.}, {U,U},{INF,N},{INF,N}}, + {{N,N}, {N,N},{N,0.}, {N,0.}, {N,N},{N,N}, {N,N}} +}; + static Py_complex -c_cosh(Py_complex x) +c_cosh(Py_complex z) { Py_complex r; - r.real = cos(x.imag)*cosh(x.real); - r.imag = sin(x.imag)*sinh(x.real); + double x_minus_one; + + /* special treatment for cosh(+/-inf + iy) if y is not a NaN */ + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) && + (z.imag != 0.)) { + if (z.real > 0) { + r.real = copysign(INF, cos(z.imag)); + r.imag = copysign(INF, sin(z.imag)); + } + else { + r.real = copysign(INF, cos(z.imag)); + r.imag = -copysign(INF, sin(z.imag)); + } + } + else { + r = cosh_special_values[special_type(z.real)] + [special_type(z.imag)]; + } + /* need to set errno = EDOM if y is +/- infinity and x is not + a NaN */ + if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real)) + errno = EDOM; + else + errno = 0; + return r; + } + + if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { + /* deal correctly with cases where cosh(z.real) overflows but + cosh(z) does not. */ + x_minus_one = z.real - copysign(1., z.real); + r.real = cos(z.imag) * cosh(x_minus_one) * Py_MATH_E; + r.imag = sin(z.imag) * sinh(x_minus_one) * Py_MATH_E; + } else { + r.real = cos(z.imag) * cosh(z.real); + r.imag = sin(z.imag) * sinh(z.real); + } + /* detect overflow, and set errno accordingly */ + if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) + errno = ERANGE; + else + errno = 0; return r; } @@ -139,13 +470,65 @@ "Return the hyperbolic cosine of x."); +/* exp(infinity + i*y) and exp(-infinity + i*y) need special treatment for + finite y */ +static Py_complex exp_special_values[7][7] = { + {{0.,0.},{U,U},{0.,-0.}, {0.,0.}, {U,U},{0.,0.},{0.,0.}}, + {{N,N}, {U,U},{U,U}, {U,U}, {U,U},{N,N}, {N,N}}, + {{N,N}, {U,U},{1.,-0.}, {1.,0.}, {U,U},{N,N}, {N,N}}, + {{N,N}, {U,U},{1.,-0.}, {1.,0.}, {U,U},{N,N}, {N,N}}, + {{N,N}, {U,U},{U,U}, {U,U}, {U,U},{N,N}, {N,N}}, + {{INF,N},{U,U},{INF,-0.},{INF,0.},{U,U},{INF,N},{INF,N}}, + {{N,N}, {N,N},{N,-0.}, {N,0.}, {N,N},{N,N}, {N,N}} +}; + static Py_complex -c_exp(Py_complex x) +c_exp(Py_complex z) { Py_complex r; - double l = exp(x.real); - r.real = l*cos(x.imag); - r.imag = l*sin(x.imag); + double l; + + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) + && (z.imag != 0.)) { + if (z.real > 0) { + r.real = copysign(INF, cos(z.imag)); + r.imag = copysign(INF, sin(z.imag)); + } + else { + r.real = copysign(0., cos(z.imag)); + r.imag = copysign(0., sin(z.imag)); + } + } + else { + r = exp_special_values[special_type(z.real)] + [special_type(z.imag)]; + } + /* need to set errno = EDOM if y is +/- infinity and x is not + a NaN and not -infinity */ + if (Py_IS_INFINITY(z.imag) && + (Py_IS_FINITE(z.real) || + (Py_IS_INFINITY(z.real) && z.real > 0))) + errno = EDOM; + else + errno = 0; + return r; + } + + if (z.real > CM_LOG_LARGE_DOUBLE) { + l = exp(z.real-1.); + r.real = l*cos(z.imag)*Py_MATH_E; + r.imag = l*sin(z.imag)*Py_MATH_E; + } else { + l = exp(z.real); + r.real = l*cos(z.imag); + r.imag = l*sin(z.imag); + } + /* detect overflow, and set errno accordingly */ + if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) + errno = ERANGE; + else + errno = 0; return r; } @@ -155,24 +538,97 @@ "Return the exponential value e**x."); +static Py_complex log_special_values[7][7] = { + {{INF,-P34},{INF,-P}, {INF,-P}, {INF,P}, {INF,P}, {INF,P34}, {INF,N}}, + {{INF,-P12},{U,U}, {U,U}, {U,U}, {U,U}, {INF,P12}, {N,N}}, + {{INF,-P12},{U,U}, {-INF,-P}, {-INF,P}, {U,U}, {INF,P12}, {N,N}}, + {{INF,-P12},{U,U}, {-INF,-0.},{-INF,0.},{U,U}, {INF,P12}, {N,N}}, + {{INF,-P12},{U,U}, {U,U}, {U,U}, {U,U}, {INF,P12}, {N,N}}, + {{INF,-P14},{INF,-0.},{INF,-0.}, {INF,0.}, {INF,0.},{INF,P14}, {INF,N}}, + {{INF,N}, {N,N}, {N,N}, {N,N}, {N,N}, {INF,N}, {N,N}} +}; + static Py_complex -c_log(Py_complex x) +c_log(Py_complex z) { + /* + The usual formula for the real part is log(hypot(z.real, z.imag)). + There are four situations where this formula is potentially + problematic: + + (1) the absolute value of z is subnormal. Then hypot is subnormal, + so has fewer than the usual number of bits of accuracy, hence may + have large relative error. This then gives a large absolute error + in the log. This can be solved by rescaling z by a suitable power + of 2. + + (2) the absolute value of z is greater than DBL_MAX (e.g. when both + z.real and z.imag are within a factor of 1/sqrt(2) of DBL_MAX) + Again, rescaling solves this. + + (3) the absolute value of z is close to 1. In this case it's + difficult to achieve good accuracy, at least in part because a + change of 1ulp in the real or imaginary part of z can result in a + change of billions of ulps in the correctly rounded answer. + + (4) z = 0. The simplest thing to do here is to call the + floating-point log with an argument of 0, and let its behaviour + (returning -infinity, signaling a floating-point exception, setting + errno, or whatever) determine that of c_log. So the usual formula + is fine here. + + */ + Py_complex r; - double l = hypot(x.real,x.imag); - r.imag = atan2(x.imag, x.real); - r.real = log(l); + double ax, ay, am, an, h; + + SPECIAL_VALUE(z, log_special_values); + + ax = fabs(z.real); + ay = fabs(z.imag); + + if (ax > CM_LARGE_DOUBLE || ay > CM_LARGE_DOUBLE) { + r.real = log(hypot(ax/2., ay/2.)) + M_LN2; + } else if (ax < DBL_MIN && ay < DBL_MIN) { + if (ax > 0. || ay > 0.) { + /* catch cases where hypot(ax, ay) is subnormal */ + r.real = log(hypot(ldexp(ax, DBL_MANT_DIG), + ldexp(ay, DBL_MANT_DIG))) - DBL_MANT_DIG*M_LN2; + } + else { + /* log(+/-0. +/- 0i) */ + r.real = -INF; + r.imag = atan2(z.imag, z.real); + errno = EDOM; + return r; + } + } else { + h = hypot(ax, ay); + if (0.71 <= h && h <= 1.73) { + am = ax > ay ? ax : ay; /* max(ax, ay) */ + an = ax > ay ? ay : ax; /* min(ax, ay) */ + r.real = log1p((am-1)*(am+1)+an*an)/2.; + } else { + r.real = log(h); + } + } + r.imag = atan2(z.imag, z.real); + errno = 0; return r; } static Py_complex -c_log10(Py_complex x) +c_log10(Py_complex z) { Py_complex r; - double l = hypot(x.real,x.imag); - r.imag = atan2(x.imag, x.real)/log(10.); - r.real = log10(l); + int errno_save; + + r = c_log(z); + errno_save = errno; /* just in case the divisions affect errno */ + r.real = r.real / M_LN10; + r.imag = r.imag / M_LN10; + errno = errno_save; return r; } @@ -182,23 +638,16 @@ "Return the base-10 logarithm of x."); -/* internal function not available from Python */ static Py_complex -c_prodi(Py_complex x) +c_sin(Py_complex z) { - Py_complex r; - r.real = -x.imag; - r.imag = x.real; - return r; -} - - -static Py_complex -c_sin(Py_complex x) -{ - Py_complex r; - r.real = sin(x.real) * cosh(x.imag); - r.imag = cos(x.real) * sinh(x.imag); + /* sin(z) = -i sin(iz) */ + Py_complex s, r; + s.real = -z.imag; + s.imag = z.real; + s = c_sinh(s); + r.real = s.imag; + r.imag = -s.real; return r; } @@ -208,12 +657,63 @@ "Return the sine of x."); +/* sinh(infinity + i*y) needs to be dealt with specially */ +static Py_complex sinh_special_values[7][7] = { + {{INF,N},{U,U},{-INF,-0.},{-INF,0.},{U,U},{INF,N},{INF,N}}, + {{N,N}, {U,U},{U,U}, {U,U}, {U,U},{N,N}, {N,N}}, + {{0.,N}, {U,U},{-0.,-0.}, {-0.,0.}, {U,U},{0.,N}, {0.,N}}, + {{0.,N}, {U,U},{0.,-0.}, {0.,0.}, {U,U},{0.,N}, {0.,N}}, + {{N,N}, {U,U},{U,U}, {U,U}, {U,U},{N,N}, {N,N}}, + {{INF,N},{U,U},{INF,-0.}, {INF,0.}, {U,U},{INF,N},{INF,N}}, + {{N,N}, {N,N},{N,-0.}, {N,0.}, {N,N},{N,N}, {N,N}} +}; + static Py_complex -c_sinh(Py_complex x) +c_sinh(Py_complex z) { Py_complex r; - r.real = cos(x.imag) * sinh(x.real); - r.imag = sin(x.imag) * cosh(x.real); + double x_minus_one; + + /* special treatment for sinh(+/-inf + iy) if y is finite and + nonzero */ + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) + && (z.imag != 0.)) { + if (z.real > 0) { + r.real = copysign(INF, cos(z.imag)); + r.imag = copysign(INF, sin(z.imag)); + } + else { + r.real = -copysign(INF, cos(z.imag)); + r.imag = copysign(INF, sin(z.imag)); + } + } + else { + r = sinh_special_values[special_type(z.real)] + [special_type(z.imag)]; + } + /* need to set errno = EDOM if y is +/- infinity and x is not + a NaN */ + if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real)) + errno = EDOM; + else + errno = 0; + return r; + } + + if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { + x_minus_one = z.real - copysign(1., z.real); + r.real = cos(z.imag) * sinh(x_minus_one) * Py_MATH_E; + r.imag = sin(z.imag) * cosh(x_minus_one) * Py_MATH_E; + } else { + r.real = cos(z.imag) * sinh(z.real); + r.imag = sin(z.imag) * cosh(z.real); + } + /* detect overflow, and set errno accordingly */ + if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) + errno = ERANGE; + else + errno = 0; return r; } @@ -223,29 +723,80 @@ "Return the hyperbolic sine of x."); +static Py_complex sqrt_special_values[7][7] = { + {{INF,-INF},{0.,-INF},{0.,-INF},{0.,INF},{0.,INF},{INF,INF},{N,INF}}, + {{INF,-INF},{U,U}, {U,U}, {U,U}, {U,U}, {INF,INF},{N,N}}, + {{INF,-INF},{U,U}, {0.,-0.}, {0.,0.}, {U,U}, {INF,INF},{N,N}}, + {{INF,-INF},{U,U}, {0.,-0.}, {0.,0.}, {U,U}, {INF,INF},{N,N}}, + {{INF,-INF},{U,U}, {U,U}, {U,U}, {U,U}, {INF,INF},{N,N}}, + {{INF,-INF},{INF,-0.},{INF,-0.},{INF,0.},{INF,0.},{INF,INF},{INF,N}}, + {{INF,-INF},{N,N}, {N,N}, {N,N}, {N,N}, {INF,INF},{N,N}} +}; + static Py_complex -c_sqrt(Py_complex x) +c_sqrt(Py_complex z) { + /* + Method: use symmetries to reduce to the case when x = z.real and y + = z.imag are nonnegative. Then the real part of the result is + given by + + s = sqrt((x + hypot(x, y))/2) + + and the imaginary part is + + d = (y/2)/s + + If either x or y is very large then there's a risk of overflow in + computation of the expression x + hypot(x, y). We can avoid this + by rewriting the formula for s as: + + s = 2*sqrt(x/8 + hypot(x/8, y/8)) + + This costs us two extra multiplications/divisions, but avoids the + overhead of checking for x and y large. + + If both x and y are subnormal then hypot(x, y) may also be + subnormal, so will lack full precision. We solve this by rescaling + x and y by a sufficiently large power of 2 to ensure that x and y + are normal. + */ + + Py_complex r; double s,d; - if (x.real == 0. && x.imag == 0.) - r = x; - else { - s = sqrt(0.5*(fabs(x.real) + hypot(x.real,x.imag))); - d = 0.5*x.imag/s; - if (x.real > 0.) { - r.real = s; - r.imag = d; - } - else if (x.imag >= 0.) { - r.real = d; - r.imag = s; - } - else { - r.real = -d; - r.imag = -s; - } + double ax, ay; + + SPECIAL_VALUE(z, sqrt_special_values); + + if (z.real == 0. && z.imag == 0.) { + r.real = 0.; + r.imag = z.imag; + return r; } + + ax = fabs(z.real); + ay = fabs(z.imag); + + if (ax < DBL_MIN && ay < DBL_MIN && (ax > 0. || ay > 0.)) { + /* here we catch cases where hypot(ax, ay) is subnormal */ + ax = ldexp(ax, CM_SCALE_UP); + s = ldexp(sqrt(ax + hypot(ax, ldexp(ay, CM_SCALE_UP))), + CM_SCALE_DOWN); + } else { + ax /= 8.; + s = 2.*sqrt(ax + hypot(ax, ay/8.)); + } + d = ay/(2.*s); + + if (z.real >= 0.) { + r.real = s; + r.imag = copysign(d, z.imag); + } else { + r.real = d; + r.imag = copysign(s, z.imag); + } + errno = 0; return r; } @@ -256,23 +807,15 @@ static Py_complex -c_tan(Py_complex x) +c_tan(Py_complex z) { - Py_complex r; - double sr,cr,shi,chi; - double rs,is,rc,ic; - double d; - sr = sin(x.real); - cr = cos(x.real); - shi = sinh(x.imag); - chi = cosh(x.imag); - rs = sr * chi; - is = cr * shi; - rc = cr * chi; - ic = -sr * shi; - d = rc*rc + ic * ic; - r.real = (rs*rc + is*ic) / d; - r.imag = (is*rc - rs*ic) / d; + /* tan(z) = -i tanh(iz) */ + Py_complex s, r; + s.real = -z.imag; + s.imag = z.real; + s = c_tanh(s); + r.real = s.imag; + r.imag = -s.real; return r; } @@ -282,24 +825,78 @@ "Return the tangent of x."); +/* tanh(infinity + i*y) needs to be dealt with specially */ +static Py_complex tanh_special_values[7][7] = { + {{-1.,0.},{U,U},{-1.,-0.},{-1.,0.},{U,U},{-1.,0.},{-1.,0.}}, + {{N,N}, {U,U},{U,U}, {U,U}, {U,U},{N,N}, {N,N}}, + {{N,N}, {U,U},{-0.,-0.},{-0.,0.},{U,U},{N,N}, {N,N}}, + {{N,N}, {U,U},{0.,-0.}, {0.,0.}, {U,U},{N,N}, {N,N}}, + {{N,N}, {U,U},{U,U}, {U,U}, {U,U},{N,N}, {N,N}}, + {{1.,0.}, {U,U},{1.,-0.}, {1.,0.}, {U,U},{1.,0.}, {1.,0.}}, + {{N,N}, {N,N},{N,-0.}, {N,0.}, {N,N},{N,N}, {N,N}} +}; + static Py_complex -c_tanh(Py_complex x) +c_tanh(Py_complex z) { + /* Formula: + + tanh(x+iy) = (tanh(x)(1+tan(y)^2) + i tan(y)(1-tanh(x))^2) / + (1+tan(y)^2 tanh(x)^2) + + To avoid excessive roundoff error, 1-tanh(x)^2 is better computed + as 1/cosh(x)^2. When abs(x) is large, we approximate 1-tanh(x)^2 + by 4 exp(-2*x) instead, to avoid possible overflow in the + computation of cosh(x). + + */ + Py_complex r; - double si,ci,shr,chr; - double rs,is,rc,ic; - double d; - si = sin(x.imag); - ci = cos(x.imag); - shr = sinh(x.real); - chr = cosh(x.real); - rs = ci * shr; - is = si * chr; - rc = ci * chr; - ic = si * shr; - d = rc*rc + ic*ic; - r.real = (rs*rc + is*ic) / d; - r.imag = (is*rc - rs*ic) / d; + double tx, ty, cx, txty, denom; + + /* special treatment for tanh(+/-inf + iy) if y is finite and + nonzero */ + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) + && (z.imag != 0.)) { + if (z.real > 0) { + r.real = 1.0; + r.imag = copysign(0., + 2.*sin(z.imag)*cos(z.imag)); + } + else { + r.real = -1.0; + r.imag = copysign(0., + 2.*sin(z.imag)*cos(z.imag)); + } + } + else { + r = tanh_special_values[special_type(z.real)] + [special_type(z.imag)]; + } + /* need to set errno = EDOM if z.imag is +/-infinity and + z.real is finite */ + if (Py_IS_INFINITY(z.imag) && Py_IS_FINITE(z.real)) + errno = EDOM; + else + errno = 0; + return r; + } + + /* danger of overflow in 2.*z.imag !*/ + if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { + r.real = copysign(1., z.real); + r.imag = 4.*sin(z.imag)*cos(z.imag)*exp(-2.*fabs(z.real)); + } else { + tx = tanh(z.real); + ty = tan(z.imag); + cx = 1./cosh(z.real); + txty = tx*ty; + denom = 1. + txty*txty; + r.real = tx*(1.+ty*ty)/denom; + r.imag = ((ty/denom)*cx)*cx; + } + errno = 0; return r; } @@ -308,6 +905,7 @@ "\n" "Return the hyperbolic tangent of x."); + static PyObject * cmath_log(PyObject *self, PyObject *args) { @@ -325,7 +923,6 @@ PyFPE_END_PROTECT(x) if (errno != 0) return math_error(); - Py_ADJUST_ERANGE2(x.real, x.imag); return PyComplex_FromCComplex(x); } @@ -351,18 +948,24 @@ static PyObject * math_1(PyObject *args, Py_complex (*func)(Py_complex)) { - Py_complex x; + Py_complex x,r ; if (!PyArg_ParseTuple(args, "D", &x)) return NULL; errno = 0; - PyFPE_START_PROTECT("complex function", return 0) - x = (*func)(x); - PyFPE_END_PROTECT(x) - Py_ADJUST_ERANGE2(x.real, x.imag); - if (errno != 0) - return math_error(); - else - return PyComplex_FromCComplex(x); + PyFPE_START_PROTECT("complex function", return 0); + r = (*func)(x); + PyFPE_END_PROTECT(r); + if (errno == EDOM) { + PyErr_SetString(PyExc_ValueError, "math domain error"); + return NULL; + } + else if (errno == ERANGE) { + PyErr_SetString(PyExc_OverflowError, "math range error"); + return NULL; + } + else { + return PyComplex_FromCComplex(r); + } } #define FUNC1(stubname, func) \ @@ -386,6 +989,151 @@ FUNC1(cmath_tan, c_tan) FUNC1(cmath_tanh, c_tanh) +static PyObject * +cmath_phase(PyObject *self, PyObject *args) +{ + Py_complex z; + double phi; + if (!PyArg_ParseTuple(args, "D:phase", &z)) + return NULL; + errno = 0; + PyFPE_START_PROTECT("arg function", return 0) + phi = c_atan2(z); + PyFPE_END_PROTECT(r) + if (errno != 0) + return math_error(); + else + return PyFloat_FromDouble(phi); +} + +PyDoc_STRVAR(cmath_phase_doc, +"phase(z) -> float\n\n\ +Return argument, also known as the phase angle, of a complex."); + +static PyObject * +cmath_polar(PyObject *self, PyObject *args) +{ + Py_complex z; + double r, phi; + if (!PyArg_ParseTuple(args, "D:polar", &z)) + return NULL; + PyFPE_START_PROTECT("polar function", return 0) + phi = c_atan2(z); /* should not cause any exception */ + r = c_abs(z); /* sets errno to ERANGE on overflow; otherwise 0 */ + PyFPE_END_PROTECT(r) + if (errno != 0) + return math_error(); + else + return Py_BuildValue("dd", r, phi); +} + +PyDoc_STRVAR(cmath_polar_doc, +"polar(z) -> r: float, phi: float\n\n\ +Convert a complex from rectangular coordinates to polar coordinates. r is\n\ +the distance from 0 and phi the phase angle."); + +/* + rect() isn't covered by the C99 standard, but it's not too hard to + figure out 'spirit of C99' rules for special value handing: + + rect(x, t) should behave like exp(log(x) + it) for positive-signed x + rect(x, t) should behave like -exp(log(-x) + it) for negative-signed x + rect(nan, t) should behave like exp(nan + it), except that rect(nan, 0) + gives nan +- i0 with the sign of the imaginary part unspecified. + +*/ + +static Py_complex rect_special_values[7][7] = { + {{INF,N},{U,U},{-INF,0.},{-INF,-0.},{U,U},{INF,N},{INF,N}}, + {{N,N}, {U,U},{U,U}, {U,U}, {U,U},{N,N}, {N,N}}, + {{0.,0.},{U,U},{-0.,0.}, {-0.,-0.}, {U,U},{0.,0.},{0.,0.}}, + {{0.,0.},{U,U},{0.,-0.}, {0.,0.}, {U,U},{0.,0.},{0.,0.}}, + {{N,N}, {U,U},{U,U}, {U,U}, {U,U},{N,N}, {N,N}}, + {{INF,N},{U,U},{INF,-0.},{INF,0.}, {U,U},{INF,N},{INF,N}}, + {{N,N}, {N,N},{N,0.}, {N,0.}, {N,N},{N,N}, {N,N}} +}; + +static PyObject * +cmath_rect(PyObject *self, PyObject *args) +{ + Py_complex z; + double r, phi; + if (!PyArg_ParseTuple(args, "dd:rect", &r, &phi)) + return NULL; + errno = 0; + PyFPE_START_PROTECT("rect function", return 0) + + /* deal with special values */ + if (!Py_IS_FINITE(r) || !Py_IS_FINITE(phi)) { + /* if r is +/-infinity and phi is finite but nonzero then + result is (+-INF +-INF i), but we need to compute cos(phi) + and sin(phi) to figure out the signs. */ + if (Py_IS_INFINITY(r) && (Py_IS_FINITE(phi) + && (phi != 0.))) { + if (r > 0) { + z.real = copysign(INF, cos(phi)); + z.imag = copysign(INF, sin(phi)); + } + else { + z.real = -copysign(INF, cos(phi)); + z.imag = -copysign(INF, sin(phi)); + } + } + else { + z = rect_special_values[special_type(r)] + [special_type(phi)]; + } + /* need to set errno = EDOM if r is a nonzero number and phi + is infinite */ + if (r != 0. && !Py_IS_NAN(r) && Py_IS_INFINITY(phi)) + errno = EDOM; + else + errno = 0; + } + else { + z.real = r * cos(phi); + z.imag = r * sin(phi); + errno = 0; + } + + PyFPE_END_PROTECT(z) + if (errno != 0) + return math_error(); + else + return PyComplex_FromCComplex(z); +} + +PyDoc_STRVAR(cmath_rect_doc, +"rect(r, phi) -> z: complex\n\n\ +Convert from polar coordinates to rectangular coordinates."); + +static PyObject * +cmath_isnan(PyObject *self, PyObject *args) +{ + Py_complex z; + if (!PyArg_ParseTuple(args, "D:isnan", &z)) + return NULL; + return PyBool_FromLong(Py_IS_NAN(z.real) || Py_IS_NAN(z.imag)); +} + +PyDoc_STRVAR(cmath_isnan_doc, +"isnan(z) -> bool\n\ +Checks if the real or imaginary part of z not a number (NaN)"); + +static PyObject * +cmath_isinf(PyObject *self, PyObject *args) +{ + Py_complex z; + if (!PyArg_ParseTuple(args, "D:isnan", &z)) + return NULL; + return PyBool_FromLong(Py_IS_INFINITY(z.real) || + Py_IS_INFINITY(z.imag)); +} + +PyDoc_STRVAR(cmath_isinf_doc, +"isinf(z) -> bool\n\ +Checks if the real or imaginary part of z is infinite."); + PyDoc_STRVAR(module_doc, "This module is always available. It provides access to mathematical\n" @@ -401,8 +1149,13 @@ {"cos", cmath_cos, METH_VARARGS, c_cos_doc}, {"cosh", cmath_cosh, METH_VARARGS, c_cosh_doc}, {"exp", cmath_exp, METH_VARARGS, c_exp_doc}, + {"isinf", cmath_isinf, METH_VARARGS, cmath_isinf_doc}, + {"isnan", cmath_isnan, METH_VARARGS, cmath_isnan_doc}, {"log", cmath_log, METH_VARARGS, cmath_log_doc}, {"log10", cmath_log10, METH_VARARGS, c_log10_doc}, + {"phase", cmath_phase, METH_VARARGS, cmath_phase_doc}, + {"polar", cmath_polar, METH_VARARGS, cmath_polar_doc}, + {"rect", cmath_rect, METH_VARARGS, cmath_rect_doc}, {"sin", cmath_sin, METH_VARARGS, c_sin_doc}, {"sinh", cmath_sinh, METH_VARARGS, c_sinh_doc}, {"sqrt", cmath_sqrt, METH_VARARGS, c_sqrt_doc}, @@ -421,6 +1174,6 @@ return; PyModule_AddObject(m, "pi", - PyFloat_FromDouble(atan(1.0) * 4.0)); - PyModule_AddObject(m, "e", PyFloat_FromDouble(exp(1.0))); + PyFloat_FromDouble(Py_MATH_PI)); + PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E)); } Modified: python/branches/py3k/Modules/mathmodule.c ============================================================================== --- python/branches/py3k/Modules/mathmodule.c (original) +++ python/branches/py3k/Modules/mathmodule.c Sat Apr 19 02:31:39 2008 @@ -1,17 +1,60 @@ /* Math module -- standard C math library functions, pi and e */ +/* Here are some comments from Tim Peters, extracted from the + discussion attached to http://bugs.python.org/issue1640. They + describe the general aims of the math module with respect to + special values, IEEE-754 floating-point exceptions, and Python + exceptions. + +These are the "spirit of 754" rules: + +1. If the mathematical result is a real number, but of magnitude too +large to approximate by a machine float, overflow is signaled and the +result is an infinity (with the appropriate sign). + +2. If the mathematical result is a real number, but of magnitude too +small to approximate by a machine float, underflow is signaled and the +result is a zero (with the appropriate sign). + +3. At a singularity (a value x such that the limit of f(y) as y +approaches x exists and is an infinity), "divide by zero" is signaled +and the result is an infinity (with the appropriate sign). This is +complicated a little by that the left-side and right-side limits may +not be the same; e.g., 1/x approaches +inf or -inf as x approaches 0 +from the positive or negative directions. In that specific case, the +sign of the zero determines the result of 1/0. + +4. At a point where a function has no defined result in the extended +reals (i.e., the reals plus an infinity or two), invalid operation is +signaled and a NaN is returned. + +And these are what Python has historically /tried/ to do (but not +always successfully, as platform libm behavior varies a lot): + +For #1, raise OverflowError. + +For #2, return a zero (with the appropriate sign if that happens by +accident ;-)). + +For #3 and #4, raise ValueError. It may have made sense to raise +Python's ZeroDivisionError in #3, but historically that's only been +raised for division by zero and mod by zero. + +*/ + +/* + In general, on an IEEE-754 platform the aim is to follow the C99 + standard, including Annex 'F', whenever possible. Where the + standard recommends raising the 'divide-by-zero' or 'invalid' + floating-point exceptions, Python should raise a ValueError. Where + the standard recommends raising 'overflow', Python should raise an + OverflowError. In all other circumstances a value should be + returned. + */ + #include "Python.h" #include "longintrepr.h" /* just for SHIFT */ -#ifndef _MSC_VER -#ifndef __STDC__ -extern double fmod (double, double); -extern double frexp (double, int *); -extern double ldexp (double, int); -extern double modf (double, double *); -#endif /* __STDC__ */ -#endif /* _MSC_VER */ - #ifdef _OSF_SOURCE /* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */ extern double copysign(double, double); @@ -52,41 +95,111 @@ return result; } +/* + math_1 is used to wrap a libm function f that takes a double + arguments and returns a double. + + The error reporting follows these rules, which are designed to do + the right thing on C89/C99 platforms and IEEE 754/non IEEE 754 + platforms. + + - a NaN result from non-NaN inputs causes ValueError to be raised + - an infinite result from finite inputs causes OverflowError to be + raised if can_overflow is 1, or raises ValueError if can_overflow + is 0. + - if the result is finite and errno == EDOM then ValueError is + raised + - if the result is finite and nonzero and errno == ERANGE then + OverflowError is raised + + The last rule is used to catch overflow on platforms which follow + C89 but for which HUGE_VAL is not an infinity. + + For the majority of one-argument functions these rules are enough + to ensure that Python's functions behave as specified in 'Annex F' + of the C99 standard, with the 'invalid' and 'divide-by-zero' + floating-point exceptions mapping to Python's ValueError and the + 'overflow' floating-point exception mapping to OverflowError. + math_1 only works for functions that don't have singularities *and* + the possibility of overflow; fortunately, that covers everything we + care about right now. +*/ + static PyObject * math_1_to_whatever(PyObject *arg, double (*func) (double), - PyObject *(*from_double_func) (double)) + PyObject *(*from_double_func) (double), + int can_overflow) { - double x = PyFloat_AsDouble(arg); + double x, r; + x = PyFloat_AsDouble(arg); if (x == -1.0 && PyErr_Occurred()) return NULL; errno = 0; - PyFPE_START_PROTECT("in math_1", return 0) - x = (*func)(x); - PyFPE_END_PROTECT(x) - Py_SET_ERRNO_ON_MATH_ERROR(x); - if (errno && is_error(x)) + PyFPE_START_PROTECT("in math_1", return 0); + r = (*func)(x); + PyFPE_END_PROTECT(r); + if (Py_IS_NAN(r)) { + if (!Py_IS_NAN(x)) + errno = EDOM; + else + errno = 0; + } + else if (Py_IS_INFINITY(r)) { + if (Py_IS_FINITE(x)) + errno = can_overflow ? ERANGE : EDOM; + else + errno = 0; + } + if (errno && is_error(r)) return NULL; else - return (*from_double_func)(x); + return (*from_double_func)(r); } +/* + math_2 is used to wrap a libm function f that takes two double + arguments and returns a double. + + The error reporting follows these rules, which are designed to do + the right thing on C89/C99 platforms and IEEE 754/non IEEE 754 + platforms. + + - a NaN result from non-NaN inputs causes ValueError to be raised + - an infinite result from finite inputs causes OverflowError to be + raised. + - if the result is finite and errno == EDOM then ValueError is + raised + - if the result is finite and nonzero and errno == ERANGE then + OverflowError is raised + + The last rule is used to catch overflow on platforms which follow + C89 but for which HUGE_VAL is not an infinity. + + For most two-argument functions (copysign, fmod, hypot, atan2) + these rules are enough to ensure that Python's functions behave as + specified in 'Annex F' of the C99 standard, with the 'invalid' and + 'divide-by-zero' floating-point exceptions mapping to Python's + ValueError and the 'overflow' floating-point exception mapping to + OverflowError. +*/ + static PyObject * -math_1(PyObject *arg, double (*func) (double)) +math_1(PyObject *arg, double (*func) (double), int can_overflow) { - return math_1_to_whatever(arg, func, PyFloat_FromDouble); + return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow); } static PyObject * -math_1_to_int(PyObject *arg, double (*func) (double)) +math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow) { - return math_1_to_whatever(arg, func, PyLong_FromDouble); + return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow); } static PyObject * math_2(PyObject *args, double (*func) (double, double), char *funcname) { PyObject *ox, *oy; - double x, y; + double x, y, r; if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy)) return NULL; x = PyFloat_AsDouble(ox); @@ -94,19 +207,30 @@ if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) return NULL; errno = 0; - PyFPE_START_PROTECT("in math_2", return 0) - x = (*func)(x, y); - PyFPE_END_PROTECT(x) - Py_SET_ERRNO_ON_MATH_ERROR(x); - if (errno && is_error(x)) + PyFPE_START_PROTECT("in math_2", return 0); + r = (*func)(x, y); + PyFPE_END_PROTECT(r); + if (Py_IS_NAN(r)) { + if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) + errno = EDOM; + else + errno = 0; + } + else if (Py_IS_INFINITY(r)) { + if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) + errno = ERANGE; + else + errno = 0; + } + if (errno && is_error(r)) return NULL; else - return PyFloat_FromDouble(x); + return PyFloat_FromDouble(r); } -#define FUNC1(funcname, func, docstring) \ +#define FUNC1(funcname, func, can_overflow, docstring) \ static PyObject * math_##funcname(PyObject *self, PyObject *args) { \ - return math_1(args, func); \ + return math_1(args, func, can_overflow); \ }\ PyDoc_STRVAR(math_##funcname##_doc, docstring); @@ -116,15 +240,21 @@ }\ PyDoc_STRVAR(math_##funcname##_doc, docstring); -FUNC1(acos, acos, +FUNC1(acos, acos, 0, "acos(x)\n\nReturn the arc cosine (measured in radians) of x.") -FUNC1(asin, asin, +FUNC1(acosh, acosh, 0, + "acosh(x)\n\nReturn the hyperbolic arc cosine (measured in radians) of x.") +FUNC1(asin, asin, 0, "asin(x)\n\nReturn the arc sine (measured in radians) of x.") -FUNC1(atan, atan, +FUNC1(asinh, asinh, 0, + "asinh(x)\n\nReturn the hyperbolic arc sine (measured in radians) of x.") +FUNC1(atan, atan, 0, "atan(x)\n\nReturn the arc tangent (measured in radians) of x.") FUNC2(atan2, atan2, "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n" "Unlike atan(y/x), the signs of both x and y are considered.") +FUNC1(atanh, atanh, 0, + "atanh(x)\n\nReturn the hyperbolic arc tangent (measured in radians) of x.") static PyObject * math_ceil(PyObject *self, PyObject *number) { static PyObject *ceil_str = NULL; @@ -138,7 +268,7 @@ method = _PyType_Lookup(Py_TYPE(number), ceil_str); if (method == NULL) - return math_1_to_int(number, ceil); + return math_1_to_int(number, ceil, 0); else return PyObject_CallFunction(method, "O", number); } @@ -147,23 +277,15 @@ "ceil(x)\n\nReturn the ceiling of x as an int.\n" "This is the smallest integral value >= x."); -FUNC1(cos, cos, +FUNC2(copysign, copysign, + "copysign(x,y)\n\nReturn x with the sign of y.") +FUNC1(cos, cos, 0, "cos(x)\n\nReturn the cosine of x (measured in radians).") -FUNC1(cosh, cosh, +FUNC1(cosh, cosh, 1, "cosh(x)\n\nReturn the hyperbolic cosine of x.") - -#ifdef MS_WINDOWS -# define copysign _copysign -# define HAVE_COPYSIGN 1 -#endif -#ifdef HAVE_COPYSIGN -FUNC2(copysign, copysign, - "copysign(x,y)\n\nReturn x with the sign of y."); -#endif - -FUNC1(exp, exp, +FUNC1(exp, exp, 1, "exp(x)\n\nReturn e raised to the power of x.") -FUNC1(fabs, fabs, +FUNC1(fabs, fabs, 0, "fabs(x)\n\nReturn the absolute value of the float x.") static PyObject * math_floor(PyObject *self, PyObject *number) { @@ -178,7 +300,7 @@ method = _PyType_Lookup(Py_TYPE(number), floor_str); if (method == NULL) - return math_1_to_int(number, floor); + return math_1_to_int(number, floor, 0); else return PyObject_CallFunction(method, "O", number); } @@ -187,22 +309,18 @@ "floor(x)\n\nReturn the floor of x as an int.\n" "This is the largest integral value <= x."); -FUNC2(fmod, fmod, - "fmod(x,y)\n\nReturn fmod(x, y), according to platform C." - " x % y may differ.") -FUNC2(hypot, hypot, - "hypot(x,y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).") -FUNC2(pow, pow, - "pow(x,y)\n\nReturn x**y (x to the power of y).") -FUNC1(sin, sin, +FUNC1(log1p, log1p, 1, + "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n\ + The result is computed in a way which is accurate for x near zero.") +FUNC1(sin, sin, 0, "sin(x)\n\nReturn the sine of x (measured in radians).") -FUNC1(sinh, sinh, +FUNC1(sinh, sinh, 1, "sinh(x)\n\nReturn the hyperbolic sine of x.") -FUNC1(sqrt, sqrt, +FUNC1(sqrt, sqrt, 0, "sqrt(x)\n\nReturn the square root of x.") -FUNC1(tan, tan, +FUNC1(tan, tan, 0, "tan(x)\n\nReturn the tangent of x (measured in radians).") -FUNC1(tanh, tanh, +FUNC1(tanh, tanh, 0, "tanh(x)\n\nReturn the hyperbolic tangent of x.") static PyObject * @@ -244,13 +362,17 @@ double x = PyFloat_AsDouble(arg); if (x == -1.0 && PyErr_Occurred()) return NULL; - errno = 0; - x = frexp(x, &i); - Py_SET_ERRNO_ON_MATH_ERROR(x); - if (errno && is_error(x)) - return NULL; - else - return Py_BuildValue("(di)", x, i); + /* deal with special cases directly, to sidestep platform + differences */ + if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) { + i = 0; + } + else { + PyFPE_START_PROTECT("in math_frexp", return 0); + x = frexp(x, &i); + PyFPE_END_PROTECT(x); + } + return Py_BuildValue("(di)", x, i); } PyDoc_STRVAR(math_frexp_doc, @@ -263,19 +385,24 @@ static PyObject * math_ldexp(PyObject *self, PyObject *args) { - double x; + double x, r; int exp; if (! PyArg_ParseTuple(args, "di:ldexp", &x, &exp)) return NULL; errno = 0; - PyFPE_START_PROTECT("ldexp", return 0) - x = ldexp(x, exp); - PyFPE_END_PROTECT(x) - Py_SET_ERRNO_ON_MATH_ERROR(x); - if (errno && is_error(x)) + PyFPE_START_PROTECT("in math_ldexp", return 0) + r = ldexp(x, exp); + PyFPE_END_PROTECT(r) + if (Py_IS_FINITE(x) && Py_IS_INFINITY(r)) + errno = ERANGE; + /* Windows MSVC8 sets errno = EDOM on ldexp(NaN, i); + we unset it to avoid raising a ValueError here. */ + if (errno == EDOM) + errno = 0; + if (errno && is_error(r)) return NULL; else - return PyFloat_FromDouble(x); + return PyFloat_FromDouble(r); } PyDoc_STRVAR(math_ldexp_doc, @@ -288,12 +415,10 @@ if (x == -1.0 && PyErr_Occurred()) return NULL; errno = 0; + PyFPE_START_PROTECT("in math_modf", return 0); x = modf(x, &y); - Py_SET_ERRNO_ON_MATH_ERROR(x); - if (errno && is_error(x)) - return NULL; - else - return Py_BuildValue("(dd)", x, y); + PyFPE_END_PROTECT(x); + return Py_BuildValue("(dd)", x, y); } PyDoc_STRVAR(math_modf_doc, @@ -332,7 +457,7 @@ } /* Else let libm handle it by itself. */ - return math_1(arg, func); + return math_1(arg, func, 0); } static PyObject * @@ -375,6 +500,141 @@ PyDoc_STRVAR(math_log10_doc, "log10(x) -> the base 10 logarithm of x."); +static PyObject * +math_fmod(PyObject *self, PyObject *args) +{ + PyObject *ox, *oy; + double r, x, y; + if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy)) + return NULL; + x = PyFloat_AsDouble(ox); + y = PyFloat_AsDouble(oy); + if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) + return NULL; + /* fmod(x, +/-Inf) returns x for finite x. */ + if (Py_IS_INFINITY(y) && Py_IS_FINITE(x)) + return PyFloat_FromDouble(x); + errno = 0; + PyFPE_START_PROTECT("in math_fmod", return 0); + r = fmod(x, y); + PyFPE_END_PROTECT(r); + if (Py_IS_NAN(r)) { + if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) + errno = EDOM; + else + errno = 0; + } + if (errno && is_error(r)) + return NULL; + else + return PyFloat_FromDouble(r); +} + +PyDoc_STRVAR(math_fmod_doc, +"fmod(x,y)\n\nReturn fmod(x, y), according to platform C." +" x % y may differ."); + +static PyObject * +math_hypot(PyObject *self, PyObject *args) +{ + PyObject *ox, *oy; + double r, x, y; + if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy)) + return NULL; + x = PyFloat_AsDouble(ox); + y = PyFloat_AsDouble(oy); + if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) + return NULL; + /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */ + if (Py_IS_INFINITY(x)) + return PyFloat_FromDouble(fabs(x)); + if (Py_IS_INFINITY(y)) + return PyFloat_FromDouble(fabs(y)); + errno = 0; + PyFPE_START_PROTECT("in math_hypot", return 0); + r = hypot(x, y); + PyFPE_END_PROTECT(r); + if (Py_IS_NAN(r)) { + if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) + errno = EDOM; + else + errno = 0; + } + else if (Py_IS_INFINITY(r)) { + if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) + errno = ERANGE; + else + errno = 0; + } + if (errno && is_error(r)) + return NULL; + else + return PyFloat_FromDouble(r); +} + +PyDoc_STRVAR(math_hypot_doc, +"hypot(x,y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y)."); + +/* pow can't use math_2, but needs its own wrapper: the problem is + that an infinite result can arise either as a result of overflow + (in which case OverflowError should be raised) or as a result of + e.g. 0.**-5. (for which ValueError needs to be raised.) +*/ + +static PyObject * +math_pow(PyObject *self, PyObject *args) +{ + PyObject *ox, *oy; + double r, x, y; + + if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy)) + return NULL; + x = PyFloat_AsDouble(ox); + y = PyFloat_AsDouble(oy); + if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) + return NULL; + /* 1**x and x**0 return 1., even if x is a NaN or infinity. */ + if (x == 1.0 || y == 0.0) + return PyFloat_FromDouble(1.); + errno = 0; + PyFPE_START_PROTECT("in math_pow", return 0); + r = pow(x, y); + PyFPE_END_PROTECT(r); + if (Py_IS_NAN(r)) { + if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) + errno = EDOM; + else + errno = 0; + } + /* an infinite result arises either from: + + (A) (+/-0.)**negative, + (B) overflow of x**y with both x and y finite (and x nonzero) + (C) (+/-inf)**positive, or + (D) x**inf with |x| > 1, or x**-inf with |x| < 1. + + In case (A) we want ValueError to be raised. In case (B) + OverflowError should be raised. In cases (C) and (D) the infinite + result should be returned. + */ + else if (Py_IS_INFINITY(r)) { + if (x == 0.) + errno = EDOM; + else if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) + errno = ERANGE; + else + errno = 0; + } + + if (errno && is_error(r)) + return NULL; + else + return PyFloat_FromDouble(r); +} + +PyDoc_STRVAR(math_pow_doc, +"pow(x,y)\n\nReturn x**y (x to the power of y)."); + static const double degToRad = Py_MATH_PI / 180.0; static const double radToDeg = 180.0 / Py_MATH_PI; @@ -428,16 +688,16 @@ "isinf(x) -> bool\n\ Checks if float x is infinite (positive or negative)"); - static PyMethodDef math_methods[] = { {"acos", math_acos, METH_O, math_acos_doc}, + {"acosh", math_acosh, METH_O, math_acosh_doc}, {"asin", math_asin, METH_O, math_asin_doc}, + {"asinh", math_asinh, METH_O, math_asinh_doc}, {"atan", math_atan, METH_O, math_atan_doc}, {"atan2", math_atan2, METH_VARARGS, math_atan2_doc}, + {"atanh", math_atanh, METH_O, math_atanh_doc}, {"ceil", math_ceil, METH_O, math_ceil_doc}, -#ifdef HAVE_COPYSIGN {"copysign", math_copysign, METH_VARARGS, math_copysign_doc}, -#endif {"cos", math_cos, METH_O, math_cos_doc}, {"cosh", math_cosh, METH_O, math_cosh_doc}, {"degrees", math_degrees, METH_O, math_degrees_doc}, @@ -451,6 +711,7 @@ {"isnan", math_isnan, METH_O, math_isnan_doc}, {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc}, {"log", math_log, METH_VARARGS, math_log_doc}, + {"log1p", math_log1p, METH_O, math_log1p_doc}, {"log10", math_log10, METH_O, math_log10_doc}, {"modf", math_modf, METH_O, math_modf_doc}, {"pow", math_pow, METH_VARARGS, math_pow_doc}, @@ -472,27 +733,15 @@ PyMODINIT_FUNC initmath(void) { - PyObject *m, *d, *v; + PyObject *m; m = Py_InitModule3("math", math_methods, module_doc); if (m == NULL) goto finally; - d = PyModule_GetDict(m); - if (d == NULL) - goto finally; - if (!(v = PyFloat_FromDouble(Py_MATH_PI))) - goto finally; - if (PyDict_SetItemString(d, "pi", v) < 0) - goto finally; - Py_DECREF(v); - - if (!(v = PyFloat_FromDouble(Py_MATH_E))) - goto finally; - if (PyDict_SetItemString(d, "e", v) < 0) - goto finally; - Py_DECREF(v); + PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI)); + PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E)); - finally: + finally: return; } Modified: python/branches/py3k/Objects/complexobject.c ============================================================================== --- python/branches/py3k/Objects/complexobject.c (original) +++ python/branches/py3k/Objects/complexobject.c Sat Apr 19 02:31:39 2008 @@ -187,6 +187,38 @@ } +double +c_abs(Py_complex z) +{ + /* sets errno = ERANGE on overflow; otherwise errno = 0 */ + double result; + + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + /* C99 rules: if either the real or the imaginary part is an + infinity, return infinity, even if the other part is a + NaN. */ + if (Py_IS_INFINITY(z.real)) { + result = fabs(z.real); + errno = 0; + return result; + } + if (Py_IS_INFINITY(z.imag)) { + result = fabs(z.imag); + errno = 0; + return result; + } + /* either the real or imaginary part is a NaN, + and neither is infinite. Result should be NaN. */ + return Py_NAN; + } + result = hypot(z.real, z.imag); + if (!Py_IS_FINITE(result)) + errno = ERANGE; + else + errno = 0; + return result; +} + static PyObject * complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval) { @@ -321,8 +353,7 @@ if (!Py_IS_FINITE(v->cval.imag)) { if (Py_IS_NAN(v->cval.imag)) strncpy(buf, "nan*j", 6); - /* else if (copysign(1, v->cval.imag) == 1) */ - else if (v->cval.imag > 0) + else if (copysign(1, v->cval.imag) == 1) strncpy(buf, "inf*j", 6); else strncpy(buf, "-inf*j", 7); @@ -578,9 +609,16 @@ complex_abs(PyComplexObject *v) { double result; + PyFPE_START_PROTECT("complex_abs", return 0) - result = hypot(v->cval.real,v->cval.imag); + result = c_abs(v->cval); PyFPE_END_PROTECT(result) + + if (errno == ERANGE) { + PyErr_SetString(PyExc_OverflowError, + "absolute value too large"); + return NULL; + } return PyFloat_FromDouble(result); } @@ -658,9 +696,29 @@ return Py_BuildValue("(D)", &v->cval); } +#if 0 +static PyObject * +complex_is_finite(PyObject *self) +{ + Py_complex c; + c = ((PyComplexObject *)self)->cval; + return PyBool_FromLong((long)(Py_IS_FINITE(c.real) && + Py_IS_FINITE(c.imag))); +} + +PyDoc_STRVAR(complex_is_finite_doc, +"complex.is_finite() -> bool\n" +"\n" +"Returns True if the real and the imaginary part is finite."); +#endif + static PyMethodDef complex_methods[] = { {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS, complex_conjugate_doc}, +#if 0 + {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS, + complex_is_finite_doc}, +#endif {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS}, {NULL, NULL} /* sentinel */ }; Deleted: python/branches/py3k/Objects/doubledigits.c ============================================================================== --- python/branches/py3k/Objects/doubledigits.c Sat Apr 19 02:31:39 2008 +++ (empty file) @@ -1,601 +0,0 @@ -/* Free-format floating point printer - * - * Based on "Floating-Point Printer Sample Code", by Robert G. Burger, - * http://www.cs.indiana.edu/~burger/fp/index.html - */ - -#include "Python.h" - -#if defined(__alpha) || defined(__i386) || defined(_M_IX86) || defined(_M_X64) || defined(_M_IA64) -#define LITTLE_ENDIAN_IEEE_DOUBLE -#elif !(defined(__ppc__) || defined(sparc) || defined(__sgi) || defined(_IBMR2) || defined(hpux)) -#error unknown machine type -#endif - -#if defined(_M_IX86) -#define UNSIGNED64 unsigned __int64 -#elif defined(__alpha) -#define UNSIGNED64 unsigned long -#else -#define UNSIGNED64 unsigned long long -#endif - -#ifndef U32 -#define U32 unsigned int -#endif - -/* exponent stored + 1024, hidden bit to left of decimal point */ -#define bias 1023 -#define bitstoright 52 -#define m1mask 0xf -#define hidden_bit 0x100000 -#ifdef LITTLE_ENDIAN_IEEE_DOUBLE -struct dblflt { - unsigned int m4: 16; - unsigned int m3: 16; - unsigned int m2: 16; - unsigned int m1: 4; - unsigned int e: 11; - unsigned int s: 1; -}; -#else -/* Big Endian IEEE Double Floats */ -struct dblflt { - unsigned int s: 1; - unsigned int e: 11; - unsigned int m1: 4; - unsigned int m2: 16; - unsigned int m3: 16; - unsigned int m4: 16; -}; -#endif -#define float_radix 2.147483648e9 - - -typedef UNSIGNED64 Bigit; -#define BIGSIZE 24 -#define MIN_E -1074 -#define MAX_FIVE 325 -#define B_P1 ((Bigit)1 << 52) - -typedef struct { - int l; - Bigit d[BIGSIZE]; -} Bignum; - -static Bignum R, S, MP, MM, five[MAX_FIVE]; -static Bignum S2, S3, S4, S5, S6, S7, S8, S9; -static int ruf, k, s_n, use_mp, qr_shift, sl, slr; - -static void mul10(Bignum *x); -static void big_short_mul(Bignum *x, Bigit y, Bignum *z); -/* -static void print_big(Bignum *x); -*/ -static int estimate(int n); -static void one_shift_left(int y, Bignum *z); -static void short_shift_left(Bigit x, int y, Bignum *z); -static void big_shift_left(Bignum *x, int y, Bignum *z); -static int big_comp(Bignum *x, Bignum *y); -static int sub_big(Bignum *x, Bignum *y, Bignum *z); -static void add_big(Bignum *x, Bignum *y, Bignum *z); -static int add_cmp(void); -static int qr(void); - -/*static int _PyFloat_Digits(char *buf, double v, int *signum);*/ -/*static void _PyFloat_DigitsInit(void);*/ - -#define ADD(x, y, z, k) {\ - Bigit x_add, z_add;\ - x_add = (x);\ - if ((k))\ - z_add = x_add + (y) + 1, (k) = (z_add <= x_add);\ - else\ - z_add = x_add + (y), (k) = (z_add < x_add);\ - (z) = z_add;\ -} - -#define SUB(x, y, z, b) {\ - Bigit x_sub, y_sub;\ - x_sub = (x); y_sub = (y);\ - if ((b))\ - (z) = x_sub - y_sub - 1, b = (y_sub >= x_sub);\ - else\ - (z) = x_sub - y_sub, b = (y_sub > x_sub);\ -} - -#define MUL(x, y, z, k) {\ - Bigit x_mul, low, high;\ - x_mul = (x);\ - low = (x_mul & 0xffffffff) * (y) + (k);\ - high = (x_mul >> 32) * (y) + (low >> 32);\ - (k) = high >> 32;\ - (z) = (low & 0xffffffff) | (high << 32);\ -} - -#define SLL(x, y, z, k) {\ - Bigit x_sll = (x);\ - (z) = (x_sll << (y)) | (k);\ - (k) = x_sll >> (64 - (y));\ -} - -static void -mul10(Bignum *x) -{ - int i, l; - Bigit *p, k; - - l = x->l; - for (i = l, p = &x->d[0], k = 0; i >= 0; i--) - MUL(*p, 10, *p++, k); - if (k != 0) - *p = k, x->l = l+1; -} - -static void -big_short_mul(Bignum *x, Bigit y, Bignum *z) -{ - int i, xl, zl; - Bigit *xp, *zp, k; - U32 high, low; - - xl = x->l; - xp = &x->d[0]; - zl = xl; - zp = &z->d[0]; - high = y >> 32; - low = y & 0xffffffff; - for (i = xl, k = 0; i >= 0; i--, xp++, zp++) { - Bigit xlow, xhigh, z0, t, c, z1; - xlow = *xp & 0xffffffff; - xhigh = *xp >> 32; - z0 = (xlow * low) + k; /* Cout is (z0 < k) */ - t = xhigh * low; - z1 = (xlow * high) + t; - c = (z1 < t); - t = z0 >> 32; - z1 += t; - c += (z1 < t); - *zp = (z1 << 32) | (z0 & 0xffffffff); - k = (xhigh * high) + (c << 32) + (z1 >> 32) + (z0 < k); - } - if (k != 0) - *zp = k, zl++; - z->l = zl; -} - -/* -static void -print_big(Bignum *x) -{ - int i; - Bigit *p; - - printf("#x"); - i = x->l; - p = &x->d[i]; - for (p = &x->d[i]; i >= 0; i--) { - Bigit b = *p--; - printf("%08x%08x", (int)(b >> 32), (int)(b & 0xffffffff)); - } -} -*/ - -static int -estimate(int n) -{ - if (n < 0) - return (int)(n*0.3010299956639812); - else - return 1+(int)(n*0.3010299956639811); -} - -static void -one_shift_left(int y, Bignum *z) -{ - int n, m, i; - Bigit *zp; - - n = y / 64; - m = y % 64; - zp = &z->d[0]; - for (i = n; i > 0; i--) *zp++ = 0; - *zp = (Bigit)1 << m; - z->l = n; -} - -static void -short_shift_left(Bigit x, int y, Bignum *z) -{ - int n, m, i, zl; - Bigit *zp; - - n = y / 64; - m = y % 64; - zl = n; - zp = &(z->d[0]); - for (i = n; i > 0; i--) *zp++ = 0; - if (m == 0) - *zp = x; - else { - Bigit high = x >> (64 - m); - *zp = x << m; - if (high != 0) - *++zp = high, zl++; - } - z->l = zl; -} - -static void -big_shift_left(Bignum *x, int y, Bignum *z) -{ - int n, m, i, xl, zl; - Bigit *xp, *zp, k; - - n = y / 64; - m = y % 64; - xl = x->l; - xp = &(x->d[0]); - zl = xl + n; - zp = &(z->d[0]); - for (i = n; i > 0; i--) *zp++ = 0; - if (m == 0) - for (i = xl; i >= 0; i--) *zp++ = *xp++; - else { - for (i = xl, k = 0; i >= 0; i--) - SLL(*xp++, m, *zp++, k); - if (k != 0) - *zp = k, zl++; - } - z->l = zl; -} - - -static int -big_comp(Bignum *x, Bignum *y) -{ - int i, xl, yl; - Bigit *xp, *yp; - - xl = x->l; - yl = y->l; - if (xl > yl) return 1; - if (xl < yl) return -1; - xp = &x->d[xl]; - yp = &y->d[xl]; - for (i = xl; i >= 0; i--, xp--, yp--) { - Bigit a = *xp; - Bigit b = *yp; - - if (a > b) return 1; - else if (a < b) return -1; - } - return 0; -} - -static int -sub_big(Bignum *x, Bignum *y, Bignum *z) -{ - int xl, yl, zl, b, i; - Bigit *xp, *yp, *zp; - - xl = x->l; - yl = y->l; - if (yl > xl) return 1; - xp = &x->d[0]; - yp = &y->d[0]; - zp = &z->d[0]; - - for (i = yl, b = 0; i >= 0; i--) - SUB(*xp++, *yp++, *zp++, b); - for (i = xl-yl; b && i > 0; i--) { - Bigit x_sub; - x_sub = *xp++; - *zp++ = x_sub - 1; - b = (x_sub == 0); - } - for (; i > 0; i--) *zp++ = *xp++; - if (b) return 1; - zl = xl; - while (*--zp == 0) zl--; - z->l = zl; - return 0; -} - -static void -add_big(Bignum *x, Bignum *y, Bignum *z) -{ - int xl, yl, k, i; - Bigit *xp, *yp, *zp; - - xl = x->l; - yl = y->l; - if (yl > xl) { - int tl; - Bignum *tn; - tl = xl; xl = yl; yl = tl; - tn = x; x = y; y = tn; - } - - xp = &x->d[0]; - yp = &y->d[0]; - zp = &z->d[0]; - - for (i = yl, k = 0; i >= 0; i--) - ADD(*xp++, *yp++, *zp++, k); - for (i = xl-yl; k && i > 0; i--) { - Bigit z_add; - z_add = *xp++ + 1; - k = (z_add == 0); - *zp++ = z_add; - } - for (; i > 0; i--) *zp++ = *xp++; - if (k) - *zp = 1, z->l = xl+1; - else - z->l = xl; -} - -static int -add_cmp() -{ - int rl, ml, sl, suml; - static Bignum sum; - - rl = R.l; - ml = (use_mp ? MP.l : MM.l); - sl = S.l; - - suml = rl >= ml ? rl : ml; - if ((sl > suml+1) || ((sl == suml+1) && (S.d[sl] > 1))) return -1; - if (sl < suml) return 1; - - add_big(&R, (use_mp ? &MP : &MM), &sum); - return big_comp(&sum, &S); -} - -static int -qr() -{ - if (big_comp(&R, &S5) < 0) - if (big_comp(&R, &S2) < 0) - if (big_comp(&R, &S) < 0) - return 0; - else { - sub_big(&R, &S, &R); - return 1; - } - else if (big_comp(&R, &S3) < 0) { - sub_big(&R, &S2, &R); - return 2; - } - else if (big_comp(&R, &S4) < 0) { - sub_big(&R, &S3, &R); - return 3; - } - else { - sub_big(&R, &S4, &R); - return 4; - } - else if (big_comp(&R, &S7) < 0) - if (big_comp(&R, &S6) < 0) { - sub_big(&R, &S5, &R); - return 5; - } - else { - sub_big(&R, &S6, &R); - return 6; - } - else if (big_comp(&R, &S9) < 0) - if (big_comp(&R, &S8) < 0) { - sub_big(&R, &S7, &R); - return 7; - } - else { - sub_big(&R, &S8, &R); - return 8; - } - else { - sub_big(&R, &S9, &R); - return 9; - } -} - -#define OUTDIG(d) { *buf++ = (d) + '0'; *buf = 0; return k; } - -int -_PyFloat_Digits(char *buf, double v, int *signum) -{ - struct dblflt *x; - int sign, e, f_n, m_n, i, d, tc1, tc2; - Bigit f; - - /* decompose float into sign, mantissa & exponent */ - x = (struct dblflt *)&v; - sign = x->s; - e = x->e; - f = (Bigit)(x->m1 << 16 | x->m2) << 32 | (U32)(x->m3 << 16 | x->m4); - if (e != 0) { - e = e - bias - bitstoright; - f |= (Bigit)hidden_bit << 32; - } - else if (f != 0) - /* denormalized */ - e = 1 - bias - bitstoright; - - *signum = sign; - if (f == 0) { - *buf++ = '0'; - *buf = 0; - return 0; - } - - ruf = !(f & 1); /* ruf = (even? f) */ - - /* Compute the scaling factor estimate, k */ - if (e > MIN_E) - k = estimate(e+52); - else { - int n; - Bigit y; - - for (n = e+52, y = (Bigit)1 << 52; f < y; n--) y >>= 1; - k = estimate(n); - } - - if (e >= 0) - if (f != B_P1) - use_mp = 0, f_n = e+1, s_n = 1, m_n = e; - else - use_mp = 1, f_n = e+2, s_n = 2, m_n = e; - else - if ((e == MIN_E) || (f != B_P1)) - use_mp = 0, f_n = 1, s_n = 1-e, m_n = 0; - else - use_mp = 1, f_n = 2, s_n = 2-e, m_n = 0; - - /* Scale it! */ - if (k == 0) { - short_shift_left(f, f_n, &R); - one_shift_left(s_n, &S); - one_shift_left(m_n, &MM); - if (use_mp) one_shift_left(m_n+1, &MP); - qr_shift = 1; - } - else if (k > 0) { - s_n += k; - if (m_n >= s_n) - f_n -= s_n, m_n -= s_n, s_n = 0; - else - f_n -= m_n, s_n -= m_n, m_n = 0; - short_shift_left(f, f_n, &R); - big_shift_left(&five[k-1], s_n, &S); - one_shift_left(m_n, &MM); - if (use_mp) one_shift_left(m_n+1, &MP); - qr_shift = 0; - } - else { - Bignum *power = &five[-k-1]; - - s_n += k; - big_short_mul(power, f, &S); - big_shift_left(&S, f_n, &R); - one_shift_left(s_n, &S); - big_shift_left(power, m_n, &MM); - if (use_mp) big_shift_left(power, m_n+1, &MP); - qr_shift = 1; - } - - /* fixup */ - if (add_cmp() <= -ruf) { - k--; - mul10(&R); - mul10(&MM); - if (use_mp) mul10(&MP); - } - - /* - printf("\nk = %d\n", k); - printf("R = "); print_big(&R); - printf("\nS = "); print_big(&S); - printf("\nM- = "); print_big(&MM); - if (use_mp) printf("\nM+ = "), print_big(&MP); - putchar('\n'); - fflush(0); - */ - - if (qr_shift) { - sl = s_n / 64; - slr = s_n % 64; - } - else { - big_shift_left(&S, 1, &S2); - add_big(&S2, &S, &S3); - big_shift_left(&S2, 1, &S4); - add_big(&S4, &S, &S5); - add_big(&S4, &S2, &S6); - add_big(&S4, &S3, &S7); - big_shift_left(&S4, 1, &S8); - add_big(&S8, &S, &S9); - } - -again: - if (qr_shift) { /* Take advantage of the fact that S = (ash 1 s_n) */ - if (R.l < sl) - d = 0; - else if (R.l == sl) { - Bigit *p; - - p = &R.d[sl]; - d = *p >> slr; - *p &= ((Bigit)1 << slr) - 1; - for (i = sl; (i > 0) && (*p == 0); i--) p--; - R.l = i; - } - else { - Bigit *p; - - p = &R.d[sl+1]; - d = *p << (64 - slr) | *(p-1) >> slr; - p--; - *p &= ((Bigit)1 << slr) - 1; - for (i = sl; (i > 0) && (*p == 0); i--) p--; - R.l = i; - } - } - else /* We need to do quotient-remainder */ - d = qr(); - - tc1 = big_comp(&R, &MM) < ruf; - tc2 = add_cmp() > -ruf; - if (!tc1) - if (!tc2) { - mul10(&R); - mul10(&MM); - if (use_mp) mul10(&MP); - *buf++ = d + '0'; - goto again; - } - else - OUTDIG(d+1) - else - if (!tc2) - OUTDIG(d) - else { - big_shift_left(&R, 1, &MM); - if (big_comp(&MM, &S) == -1) - OUTDIG(d) - else - OUTDIG(d+1) - } -} - -void -_PyFloat_DigitsInit() -{ - int n, i, l; - Bignum *b; - Bigit *xp, *zp, k; - - five[0].l = l = 0; - five[0].d[0] = 5; - for (n = MAX_FIVE-1, b = &five[0]; n > 0; n--) { - xp = &b->d[0]; - b++; - zp = &b->d[0]; - for (i = l, k = 0; i >= 0; i--) - MUL(*xp++, 5, *zp++, k); - if (k != 0) - *zp = k, l++; - b->l = l; - } - - /* - for (n = 1, b = &five[0]; n <= MAX_FIVE; n++) { - big_shift_left(b++, n, &R); - print_big(&R); - putchar('\n'); - } - fflush(0); - */ -} Modified: python/branches/py3k/Objects/floatobject.c ============================================================================== --- python/branches/py3k/Objects/floatobject.c (original) +++ python/branches/py3k/Objects/floatobject.c Sat Apr 19 02:31:39 2008 @@ -16,10 +16,6 @@ #include #endif -#if !defined(__STDC__) -extern double fmod(double, double); -extern double pow(double, double); -#endif #ifdef _OSF_SOURCE /* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */ @@ -224,11 +220,11 @@ p++; } if (PyOS_strnicmp(p, "inf", 4) == 0) { - return PyFloat_FromDouble(sign * Py_HUGE_VAL); + Py_RETURN_INF(sign); } #ifdef Py_NAN if(PyOS_strnicmp(p, "nan", 4) == 0) { - return PyFloat_FromDouble(Py_NAN); + Py_RETURN_NAN; } #endif PyOS_snprintf(buffer, sizeof(buffer), @@ -378,110 +374,6 @@ format_double(buf, buflen, PyFloat_AS_DOUBLE(v), precision); } -#ifdef Py_BROKEN_REPR -/* The following function is based on Tcl_PrintDouble, - * from tclUtil.c. - */ - -#define is_infinite(d) ( (d) > DBL_MAX || (d) < -DBL_MAX ) -#define is_nan(d) ((d) != (d)) - -static void -format_double_repr(char *dst, double value) -{ - char *p, c; - int exp; - int signum; - char buffer[30]; - - /* - * Handle NaN. - */ - - if (is_nan(value)) { - strcpy(dst, "nan"); - return; - } - - /* - * Handle infinities. - */ - - if (is_infinite(value)) { - if (value < 0) { - strcpy(dst, "-inf"); - } else { - strcpy(dst, "inf"); - } - return; - } - - /* - * Ordinary (normal and denormal) values. - */ - - exp = _PyFloat_Digits(buffer, value, &signum)+1; - if (signum) { - *dst++ = '-'; - } - p = buffer; - if (exp < -3 || exp > 17) { - /* - * E format for numbers < 1e-3 or >= 1e17. - */ - - *dst++ = *p++; - c = *p; - if (c != '\0') { - *dst++ = '.'; - while (c != '\0') { - *dst++ = c; - c = *++p; - } - } - sprintf(dst, "e%+d", exp-1); - } else { - /* - * F format for others. - */ - - if (exp <= 0) { - *dst++ = '0'; - } - c = *p; - while (exp-- > 0) { - if (c != '\0') { - *dst++ = c; - c = *++p; - } else { - *dst++ = '0'; - } - } - *dst++ = '.'; - if (c == '\0') { - *dst++ = '0'; - } else { - while (++exp < 0) { - *dst++ = '0'; - } - while (c != '\0') { - *dst++ = c; - c = *++p; - } - } - *dst++ = '\0'; - } -} - -static void -format_float_repr(char *buf, PyFloatObject *v) -{ - assert(PyFloat_Check(v)); - format_double_repr(buf, PyFloat_AS_DOUBLE(v)); -} - -#endif /* Py_BROKEN_REPR */ - /* Macro and helper that convert PyObject obj to a C double and store the value in dbl. If conversion to double raises an exception, obj is set to NULL, and the function invoking this macro returns NULL. If @@ -534,13 +426,8 @@ static PyObject * float_repr(PyFloatObject *v) { -#ifdef Py_BROKEN_REPR - char buf[30]; - format_float_repr(buf, v); -#else char buf[100]; format_float(buf, sizeof(buf), v, PREC_REPR); -#endif return PyUnicode_FromString(buf); } @@ -804,10 +691,13 @@ double a,b; CONVERT_TO_DOUBLE(v, a); CONVERT_TO_DOUBLE(w, b); +#ifdef Py_NAN if (b == 0.0) { - PyErr_SetString(PyExc_ZeroDivisionError, "float division"); + PyErr_SetString(PyExc_ZeroDivisionError, + "float division"); return NULL; } +#endif PyFPE_START_PROTECT("divide", return 0) a = a / b; PyFPE_END_PROTECT(a) @@ -819,12 +709,15 @@ { double vx, wx; double mod; - CONVERT_TO_DOUBLE(v, vx); - CONVERT_TO_DOUBLE(w, wx); + CONVERT_TO_DOUBLE(v, vx); + CONVERT_TO_DOUBLE(w, wx); +#ifdef Py_NAN if (wx == 0.0) { - PyErr_SetString(PyExc_ZeroDivisionError, "float modulo"); + PyErr_SetString(PyExc_ZeroDivisionError, + "float modulo"); return NULL; } +#endif PyFPE_START_PROTECT("modulo", return 0) mod = fmod(vx, wx); /* note: checking mod*wx < 0 is incorrect -- underflows to @@ -928,6 +821,9 @@ } return PyFloat_FromDouble(0.0); } + if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */ + return PyFloat_FromDouble(1.0); + } if (iv < 0.0) { /* Whether this is an error is a mess, and bumps into libm * bugs so we have to figure it out ourselves. @@ -995,6 +891,57 @@ } static PyObject * +float_is_integer(PyObject *v) +{ + double x = PyFloat_AsDouble(v); + PyObject *o; + + if (x == -1.0 && PyErr_Occurred()) + return NULL; + if (!Py_IS_FINITE(x)) + Py_RETURN_FALSE; + PyFPE_START_PROTECT("is_integer", return NULL) + o = (floor(x) == x) ? Py_True : Py_False; + PyFPE_END_PROTECT(x) + if (errno != 0) { + PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError : + PyExc_ValueError); + return NULL; + } + Py_INCREF(o); + return o; +} + +#if 0 +static PyObject * +float_is_inf(PyObject *v) +{ + double x = PyFloat_AsDouble(v); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)Py_IS_INFINITY(x)); +} + +static PyObject * +float_is_nan(PyObject *v) +{ + double x = PyFloat_AsDouble(v); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)Py_IS_NAN(x)); +} + +static PyObject * +float_is_finite(PyObject *v) +{ + double x = PyFloat_AsDouble(v); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)Py_IS_FINITE(x)); +} +#endif + +static PyObject * float_trunc(PyObject *v) { double x = PyFloat_AsDouble(v); @@ -1368,7 +1315,7 @@ static PyMethodDef float_methods[] = { - {"conjugate", (PyCFunction)float_float, METH_NOARGS, + {"conjugate", (PyCFunction)float_float, METH_NOARGS, "Returns self, the complex conjugate of any float."}, {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS, "Returns the Integral closest to x between 0 and x."}, @@ -1377,6 +1324,16 @@ "When an argument is passed, works like built-in round(x, ndigits)."}, {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS, float_as_integer_ratio_doc}, + {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS, + "Returns True if the float is an integer."}, +#if 0 + {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS, + "Returns True if the float is positive or negative infinite."}, + {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS, + "Returns True if the float is finite, neither infinite nor NaN."}, + {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS, + "Returns True if the float is not a number (NaN)."}, +#endif {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS}, {"__getformat__", (PyCFunction)float_getformat, METH_O|METH_CLASS, float_getformat_doc}, @@ -1534,10 +1491,6 @@ double_format = detected_double_format; float_format = detected_float_format; -#ifdef Py_BROKEN_REPR - /* Initialize floating point repr */ - _PyFloat_DigitsInit(); -#endif /* Init float info */ if (FloatInfoType.tp_name == 0) PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc); Modified: python/branches/py3k/Objects/longobject.c ============================================================================== --- python/branches/py3k/Objects/longobject.c (original) +++ python/branches/py3k/Objects/longobject.c Sat Apr 19 02:31:39 2008 @@ -3611,9 +3611,21 @@ #undef UNDEF_NDIGITS } +#if 0 +static PyObject * +long_is_finite(PyObject *v) +{ + Py_RETURN_TRUE; +} +#endif + static PyMethodDef long_methods[] = { {"conjugate", (PyCFunction)long_long, METH_NOARGS, "Returns self, the complex conjugate of any int."}, +#if 0 + {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS, + "Returns always True."}, +#endif {"__trunc__", (PyCFunction)long_long, METH_NOARGS, "Truncating an Integral returns itself."}, {"__floor__", (PyCFunction)long_long, METH_NOARGS, Modified: python/branches/py3k/PC/VC6/pythoncore.dsp ============================================================================== --- python/branches/py3k/PC/VC6/pythoncore.dsp (original) +++ python/branches/py3k/PC/VC6/pythoncore.dsp Sat Apr 19 02:31:39 2008 @@ -587,6 +587,10 @@ # End Source File # Begin Source File +SOURCE=..\..\Python\pymath.c +# End Source File +# Begin Source File + SOURCE=..\..\Python\pystate.c # End Source File # Begin Source File Modified: python/branches/py3k/PC/VS7.1/pythoncore.vcproj ============================================================================== --- python/branches/py3k/PC/VS7.1/pythoncore.vcproj (original) +++ python/branches/py3k/PC/VS7.1/pythoncore.vcproj Sat Apr 19 02:31:39 2008 @@ -698,6 +698,9 @@ RelativePath="..\..\Python\pyfpe.c"> + + + + Modified: python/branches/py3k/PC/pyconfig.h ============================================================================== --- python/branches/py3k/PC/pyconfig.h (original) +++ python/branches/py3k/PC/pyconfig.h Sat Apr 19 02:31:39 2008 @@ -207,12 +207,13 @@ #endif /* MS_WIN32 && !MS_WIN64 */ typedef int pid_t; -#define hypot _hypot #include #define Py_IS_NAN _isnan #define Py_IS_INFINITY(X) (!_finite(X) && !_isnan(X)) #define Py_IS_FINITE(X) _finite(X) +#define copysign _copysign +#define hypot _hypot #endif /* _MSC_VER */ @@ -392,7 +393,7 @@ /* Fairly standard from here! */ /* Define to 1 if you have the `copysign' function. */ -/* #define HAVE_COPYSIGN 1*/ +#define HAVE_COPYSIGN 1 /* Define to 1 if you have the `isinf' function. */ #define HAVE_ISINF 1 Modified: python/branches/py3k/PCbuild/pythoncore.vcproj ============================================================================== --- python/branches/py3k/PCbuild/pythoncore.vcproj (original) +++ python/branches/py3k/PCbuild/pythoncore.vcproj Sat Apr 19 02:31:39 2008 @@ -871,6 +871,10 @@ > + + @@ -1707,6 +1711,10 @@ > + + Deleted: python/branches/py3k/Python/hypot.c ============================================================================== --- python/branches/py3k/Python/hypot.c Sat Apr 19 02:31:39 2008 +++ (empty file) @@ -1,25 +0,0 @@ -/* hypot() replacement */ - -#include "Python.h" - -#ifndef HAVE_HYPOT -double hypot(double x, double y) -{ - double yx; - - x = fabs(x); - y = fabs(y); - if (x < y) { - double temp = x; - x = y; - y = temp; - } - if (x == 0.) - return 0.; - else { - yx = y/x; - return x*sqrt(1.+yx*yx); - } -} -#endif /* HAVE_HYPOT */ - Modified: python/branches/py3k/configure ============================================================================== --- python/branches/py3k/configure (original) +++ python/branches/py3k/configure Sat Apr 19 02:31:39 2008 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 62003 . +# From configure.in Revision: 62146 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.61 for python 3.0. # From python-3000-checkins at python.org Sat Apr 19 02:55:38 2008 From: python-3000-checkins at python.org (christian.heimes) Date: Sat, 19 Apr 2008 02:55:38 +0200 (CEST) Subject: [Python-3000-checkins] r62385 - in python/branches/py3k: Doc/ACKS.txt Doc/howto/doanddont.rst Doc/library/decimal.rst Doc/library/itertools.rst Doc/library/mmap.rst Doc/library/pkgutil.rst Doc/library/profile.rst Doc/library/ssl.rst Doc/reference/compound_stmts.rst Doc/tutorial/controlflow.rst Lib/pkgutil.py Lib/test/regrtest.py Lib/test/test_frozen.py Lib/test/test_pkg.py Lib/test/test_pkgutil.py Lib/test/test_profile.py Lib/test/test_structmembers.py Lib/test/test_warnings.py Lib/test/test_xmlrpc.py Lib/xmlrpclib.py Objects/longobject.c Python/sysmodule.c Message-ID: <20080419005538.D54031E4015@bag.python.org> Author: christian.heimes Date: Sat Apr 19 02:55:37 2008 New Revision: 62385 Log: Merged revisions 62350-62355,62358-62359,62364-62365,62370,62372-62375,62378-62379,62381 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62350 | nick.coghlan | 2008-04-15 12:25:31 +0200 (Tue, 15 Apr 2008) | 1 line Issue 2439: add pkgutils.get_data() as a convenience wrapper for the PEP 302 get_data() API (contributed by Paul Moore) ........ r62351 | nick.coghlan | 2008-04-15 12:28:14 +0200 (Tue, 15 Apr 2008) | 1 line Add test file missing from rev 62350 ........ r62352 | benjamin.peterson | 2008-04-15 13:58:46 +0200 (Tue, 15 Apr 2008) | 2 lines Add myself to Doc/ACKS.txt ........ r62353 | andrew.kuchling | 2008-04-15 15:10:07 +0200 (Tue, 15 Apr 2008) | 6 lines Add *,**,@ to index, as suggested by http://farmdev.com/thoughts/24/what-does-the-def-star-variable-or-def-asterisk-parameter-syntax-do-in-python-/ The right entry type to use isn't clear; operator seems wrong, because *,**,@ aren't being used in expressions here. I put them as 'statement'; 'syntax' might be better. ........ r62354 | andrew.kuchling | 2008-04-15 15:10:41 +0200 (Tue, 15 Apr 2008) | 1 line Typo fix ........ r62355 | mark.dickinson | 2008-04-15 22:51:18 +0200 (Tue, 15 Apr 2008) | 3 lines Fix for possible signed overflow: the behaviour of -LONG_MIN is undefined in ANSI C. ........ r62358 | jeroen.ruigrok | 2008-04-16 14:47:01 +0200 (Wed, 16 Apr 2008) | 2 lines Reformat to 80 columns prior to adding documentation. ........ r62359 | jeroen.ruigrok | 2008-04-16 14:57:43 +0200 (Wed, 16 Apr 2008) | 2 lines Add details about the return value for mmap.flush(). ........ r62364 | raymond.hettinger | 2008-04-17 12:48:31 +0200 (Thu, 17 Apr 2008) | 1 line Issue 2648: Add leading zero to money format recipe in the docs. ........ r62365 | jeroen.ruigrok | 2008-04-17 14:39:45 +0200 (Thu, 17 Apr 2008) | 2 lines Be consistent in the use of read-only. ........ r62370 | andrew.kuchling | 2008-04-17 22:44:06 +0200 (Thu, 17 Apr 2008) | 1 line Typo fixes ........ r62372 | andrew.kuchling | 2008-04-18 04:40:47 +0200 (Fri, 18 Apr 2008) | 1 line Use correct parameter name ........ r62373 | andrew.kuchling | 2008-04-18 18:53:09 +0200 (Fri, 18 Apr 2008) | 1 line #2654: fix typo ........ r62374 | andrew.kuchling | 2008-04-18 20:28:23 +0200 (Fri, 18 Apr 2008) | 4 lines Remove personal note from Jim Roskind; it no longer applies, and the e-mail address is for a previous employer. Can we move the big long copyright statement into a sidebar or something? ........ r62375 | andrew.kuchling | 2008-04-18 20:39:55 +0200 (Fri, 18 Apr 2008) | 1 line Rewrite introductory section, and remove old section. (It was already commented-out, but why keep it?) ........ r62378 | skip.montanaro | 2008-04-18 22:35:46 +0200 (Fri, 18 Apr 2008) | 1 line resolve issue 2014 ........ r62379 | benjamin.peterson | 2008-04-18 22:45:33 +0200 (Fri, 18 Apr 2008) | 2 lines Fix indentation in sysmodule.c ........ r62381 | amaury.forgeotdarc | 2008-04-19 01:31:33 +0200 (Sat, 19 Apr 2008) | 3 lines Some tests did not pass on repeated calls (regrtest -R::) Perform additional cleanup, mostly deleting from sys.modules, or clearing the warnings registry. ........ Added: python/branches/py3k/Lib/test/test_pkgutil.py - copied, changed from r62379, /python/trunk/Lib/test/test_pkgutil.py Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/ACKS.txt python/branches/py3k/Doc/howto/doanddont.rst python/branches/py3k/Doc/library/decimal.rst python/branches/py3k/Doc/library/itertools.rst python/branches/py3k/Doc/library/mmap.rst python/branches/py3k/Doc/library/pkgutil.rst python/branches/py3k/Doc/library/profile.rst python/branches/py3k/Doc/library/ssl.rst python/branches/py3k/Doc/reference/compound_stmts.rst python/branches/py3k/Doc/tutorial/controlflow.rst python/branches/py3k/Lib/pkgutil.py python/branches/py3k/Lib/test/regrtest.py python/branches/py3k/Lib/test/test_frozen.py python/branches/py3k/Lib/test/test_pkg.py python/branches/py3k/Lib/test/test_profile.py python/branches/py3k/Lib/test/test_structmembers.py python/branches/py3k/Lib/test/test_warnings.py python/branches/py3k/Lib/test/test_xmlrpc.py python/branches/py3k/Lib/xmlrpclib.py python/branches/py3k/Objects/longobject.c python/branches/py3k/Python/sysmodule.c Modified: python/branches/py3k/Doc/ACKS.txt ============================================================================== --- python/branches/py3k/Doc/ACKS.txt (original) +++ python/branches/py3k/Doc/ACKS.txt Sat Apr 19 02:55:37 2008 @@ -145,6 +145,7 @@ * Harri Pasanen * Bo Peng * Tim Peters + * Benjamin Peterson * Christopher Petrilli * Justin D. Pettit * Chris Phoenix Modified: python/branches/py3k/Doc/howto/doanddont.rst ============================================================================== --- python/branches/py3k/Doc/howto/doanddont.rst (original) +++ python/branches/py3k/Doc/howto/doanddont.rst Sat Apr 19 02:55:37 2008 @@ -4,7 +4,7 @@ :Author: Moshe Zadka -This document is placed in the public doman. +This document is placed in the public domain. .. topic:: Abstract Modified: python/branches/py3k/Doc/library/decimal.rst ============================================================================== --- python/branches/py3k/Doc/library/decimal.rst (original) +++ python/branches/py3k/Doc/library/decimal.rst Sat Apr 19 02:55:37 2008 @@ -1374,7 +1374,7 @@ >>> moneyfmt(Decimal(123456789), sep=' ') '123 456 789.00' >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>') - '<.02>' + '<0.02>' """ q = Decimal(10) ** -places # 2 places --> '0.01' @@ -1387,6 +1387,8 @@ for i in range(places): build(next() if digits else '0') build(dp) + if not digits: + build('0') i = 0 while digits: build(next()) Modified: python/branches/py3k/Doc/library/itertools.rst ============================================================================== --- python/branches/py3k/Doc/library/itertools.rst (original) +++ python/branches/py3k/Doc/library/itertools.rst Sat Apr 19 02:55:37 2008 @@ -96,7 +96,7 @@ .. function:: combinations(iterable, r) - Return successive *r* length combinations of elements in the *iterable*. + Return *r* length subsequences of elements from the input *iterable*. Combinations are emitted in lexicographic sort order. So, if the input *iterable* is sorted, the combination tuples will be produced @@ -106,9 +106,6 @@ value. So if the input elements are unique, there will be no repeat values in each combination. - Each result tuple is ordered to match the input order. So, every - combination is a subsequence of the input *iterable*. - Equivalent to:: def combinations(iterable, r): @@ -375,11 +372,10 @@ Equivalent to nested for-loops in a generator expression. For example, ``product(A, B)`` returns the same as ``((x,y) for x in A for y in B)``. - The leftmost iterators correspond to the outermost for-loop, so the output - tuples cycle like an odometer (with the rightmost element changing on every - iteration). This results in a lexicographic ordering so that if the - inputs iterables are sorted, the product tuples are emitted - in sorted order. + The nested loops cycle like an odometer with the rightmost element advancing + on every iteration. This pattern creates a lexicographic ordering so that if + the input's iterables are sorted, the product tuples are emitted in sorted + order. To compute the product of an iterable with itself, specify the number of repetitions with the optional *repeat* keyword argument. For example, Modified: python/branches/py3k/Doc/library/mmap.rst ============================================================================== --- python/branches/py3k/Doc/library/mmap.rst (original) +++ python/branches/py3k/Doc/library/mmap.rst Sat Apr 19 02:55:37 2008 @@ -8,54 +8,55 @@ Memory-mapped file objects behave like both strings and like file objects. Unlike normal string objects, however, these are mutable. You can use mmap -objects in most places where strings are expected; for example, you can use the -:mod:`re` module to search through a memory-mapped file. Since they're mutable, -you can change a single character by doing ``obj[index] = 'a'``, or change a -substring by assigning to a slice: ``obj[i1:i2] = '...'``. You can also read -and write data starting at the current file position, and :meth:`seek` through -the file to different positions. - -A memory-mapped file is created by the :class:`mmap` constructor, which is different -on Unix and on Windows. In either case you must provide a file descriptor for a -file opened for update. If you wish to map an existing Python file object, use -its :meth:`fileno` method to obtain the correct value for the *fileno* -parameter. Otherwise, you can open the file using the :func:`os.open` function, -which returns a file descriptor directly (the file still needs to be closed when -done). +objects in most places where strings are expected; for example, you can use +the :mod:`re` module to search through a memory-mapped file. Since they're +mutable, you can change a single character by doing ``obj[index] = 'a'``, or +change a substring by assigning to a slice: ``obj[i1:i2] = '...'``. You can +also read and write data starting at the current file position, and +:meth:`seek` through the file to different positions. + +A memory-mapped file is created by the :class:`mmap` constructor, which is +different on Unix and on Windows. In either case you must provide a file +descriptor for a file opened for update. If you wish to map an existing Python +file object, use its :meth:`fileno` method to obtain the correct value for the +*fileno* parameter. Otherwise, you can open the file using the +:func:`os.open` function, which returns a file descriptor directly (the file +still needs to be closed when done). For both the Unix and Windows versions of the constructor, *access* may be specified as an optional keyword parameter. *access* accepts one of three -values: :const:`ACCESS_READ`, :const:`ACCESS_WRITE`, or :const:`ACCESS_COPY` to -specify readonly, write-through or copy-on-write memory respectively. *access* -can be used on both Unix and Windows. If *access* is not specified, Windows -mmap returns a write-through mapping. The initial memory values for all three -access types are taken from the specified file. Assignment to an -:const:`ACCESS_READ` memory map raises a :exc:`TypeError` exception. Assignment -to an :const:`ACCESS_WRITE` memory map affects both memory and the underlying -file. Assignment to an :const:`ACCESS_COPY` memory map affects memory but does -not update the underlying file. +values: :const:`ACCESS_READ`, :const:`ACCESS_WRITE`, or :const:`ACCESS_COPY` +to specify read-only, write-through or copy-on-write memory respectively. +*access* can be used on both Unix and Windows. If *access* is not specified, +Windows mmap returns a write-through mapping. The initial memory values for +all three access types are taken from the specified file. Assignment to an +:const:`ACCESS_READ` memory map raises a :exc:`TypeError` exception. +Assignment to an :const:`ACCESS_WRITE` memory map affects both memory and the +underlying file. Assignment to an :const:`ACCESS_COPY` memory map affects +memory but does not update the underlying file. To map anonymous memory, -1 should be passed as the fileno along with the length. .. class:: mmap(fileno, length[, tagname[, access[, offset]]]) - **(Windows version)** Maps *length* bytes from the file specified by the file - handle *fileno*, and creates a mmap object. If *length* is larger than the - current size of the file, the file is extended to contain *length* bytes. If - *length* is ``0``, the maximum length of the map is the current size of the - file, except that if the file is empty Windows raises an exception (you cannot - create an empty mapping on Windows). - - *tagname*, if specified and not ``None``, is a string giving a tag name for the - mapping. Windows allows you to have many different mappings against the same - file. If you specify the name of an existing tag, that tag is opened, otherwise - a new tag of this name is created. If this parameter is omitted or ``None``, - the mapping is created without a name. Avoiding the use of the tag parameter - will assist in keeping your code portable between Unix and Windows. - - *offset* may be specified as a non-negative integer offset. mmap references will - be relative to the offset from the beginning of the file. *offset* defaults to 0. - *offset* must be a multiple of the ALLOCATIONGRANULARITY. + **(Windows version)** Maps *length* bytes from the file specified by the + file handle *fileno*, and creates a mmap object. If *length* is larger + than the current size of the file, the file is extended to contain *length* + bytes. If *length* is ``0``, the maximum length of the map is the current + size of the file, except that if the file is empty Windows raises an + exception (you cannot create an empty mapping on Windows). + + *tagname*, if specified and not ``None``, is a string giving a tag name for + the mapping. Windows allows you to have many different mappings against + the same file. If you specify the name of an existing tag, that tag is + opened, otherwise a new tag of this name is created. If this parameter is + omitted or ``None``, the mapping is created without a name. Avoiding the + use of the tag parameter will assist in keeping your code portable between + Unix and Windows. + + *offset* may be specified as a non-negative integer offset. mmap references + will be relative to the offset from the beginning of the file. *offset* + defaults to 0. *offset* must be a multiple of the ALLOCATIONGRANULARITY. .. class:: mmap(fileno, length[, flags[, prot[, access[, offset]]]]) @@ -63,26 +64,29 @@ **(Unix version)** Maps *length* bytes from the file specified by the file descriptor *fileno*, and returns a mmap object. If *length* is ``0``, the - maximum length of the map will be the current size of the file when :class:`mmap` - is called. + maximum length of the map will be the current size of the file when + :class:`mmap` is called. *flags* specifies the nature of the mapping. :const:`MAP_PRIVATE` creates a - private copy-on-write mapping, so changes to the contents of the mmap object - will be private to this process, and :const:`MAP_SHARED` creates a mapping - that's shared with all other processes mapping the same areas of the file. The - default value is :const:`MAP_SHARED`. - - *prot*, if specified, gives the desired memory protection; the two most useful - values are :const:`PROT_READ` and :const:`PROT_WRITE`, to specify that the pages - may be read or written. *prot* defaults to :const:`PROT_READ \| PROT_WRITE`. - - *access* may be specified in lieu of *flags* and *prot* as an optional keyword - parameter. It is an error to specify both *flags*, *prot* and *access*. See - the description of *access* above for information on how to use this parameter. - - *offset* may be specified as a non-negative integer offset. mmap references will - be relative to the offset from the beginning of the file. *offset* defaults to 0. - *offset* must be a multiple of the PAGESIZE or ALLOCATIONGRANULARITY. + private copy-on-write mapping, so changes to the contents of the mmap + object will be private to this process, and :const:`MAP_SHARED` creates a + mapping that's shared with all other processes mapping the same areas of + the file. The default value is :const:`MAP_SHARED`. + + *prot*, if specified, gives the desired memory protection; the two most + useful values are :const:`PROT_READ` and :const:`PROT_WRITE`, to specify + that the pages may be read or written. *prot* defaults to + :const:`PROT_READ \| PROT_WRITE`. + + *access* may be specified in lieu of *flags* and *prot* as an optional + keyword parameter. It is an error to specify both *flags*, *prot* and + *access*. See the description of *access* above for information on how to + use this parameter. + + *offset* may be specified as a non-negative integer offset. mmap references + will be relative to the offset from the beginning of the file. *offset* + defaults to 0. *offset* must be a multiple of the PAGESIZE or + ALLOCATIONGRANULARITY. This example shows a simple way of using :class:`mmap`:: @@ -132,32 +136,38 @@ .. method:: mmap.close() - Close the file. Subsequent calls to other methods of the object will result in - an exception being raised. + Close the file. Subsequent calls to other methods of the object will + result in an exception being raised. .. method:: mmap.find(string[, start[, end]]) - Returns the lowest index in the object where the substring *string* is found, - such that *string* is contained in the range [*start*, *end*]. Optional - arguments *start* and *end* are interpreted as in slice notation. + Returns the lowest index in the object where the substring *string* is + found, such that *string* is contained in the range [*start*, *end*]. + Optional arguments *start* and *end* are interpreted as in slice notation. Returns ``-1`` on failure. .. method:: mmap.flush([offset, size]) - Flushes changes made to the in-memory copy of a file back to disk. Without use - of this call there is no guarantee that changes are written back before the - object is destroyed. If *offset* and *size* are specified, only changes to the - given range of bytes will be flushed to disk; otherwise, the whole extent of the - mapping is flushed. + Flushes changes made to the in-memory copy of a file back to disk. Without + use of this call there is no guarantee that changes are written back before + the object is destroyed. If *offset* and *size* are specified, only + changes to the given range of bytes will be flushed to disk; otherwise, the + whole extent of the mapping is flushed. + + **(Windows version)** A nonzero value returned indicates success; zero + indicates failure. + + **(Unix version)** A zero value is returned to indicate success. An + exception is raised when the call failed. .. method:: mmap.move(dest, src, count) - Copy the *count* bytes starting at offset *src* to the destination index *dest*. - If the mmap was created with :const:`ACCESS_READ`, then calls to move will throw - a :exc:`TypeError` exception. + Copy the *count* bytes starting at offset *src* to the destination index + *dest*. If the mmap was created with :const:`ACCESS_READ`, then calls to + move will throw a :exc:`TypeError` exception. .. method:: mmap.read(num) @@ -175,31 +185,31 @@ .. method:: mmap.readline() - Returns a single line, starting at the current file position and up to the next - newline. + Returns a single line, starting at the current file position and up to the + next newline. .. method:: mmap.resize(newsize) - Resizes the map and the underlying file, if any. If the mmap was created with - :const:`ACCESS_READ` or :const:`ACCESS_COPY`, resizing the map will throw a - :exc:`TypeError` exception. + Resizes the map and the underlying file, if any. If the mmap was created + with :const:`ACCESS_READ` or :const:`ACCESS_COPY`, resizing the map will + throw a :exc:`TypeError` exception. .. method:: mmap.rfind(string[, start[, end]]) Returns the highest index in the object where the substring *string* is - found, such that *string* is contained in the range [*start*, - *end*]. Optional arguments *start* and *end* are interpreted as in slice - notation. Returns ``-1`` on failure. + found, such that *string* is contained in the range [*start*, *end*]. + Optional arguments *start* and *end* are interpreted as in slice notation. + Returns ``-1`` on failure. .. method:: mmap.seek(pos[, whence]) - Set the file's current position. *whence* argument is optional and defaults to - ``os.SEEK_SET`` or ``0`` (absolute file positioning); other values are - ``os.SEEK_CUR`` or ``1`` (seek relative to the current position) and - ``os.SEEK_END`` or ``2`` (seek relative to the file's end). + Set the file's current position. *whence* argument is optional and + defaults to ``os.SEEK_SET`` or ``0`` (absolute file positioning); other + values are ``os.SEEK_CUR`` or ``1`` (seek relative to the current position) + and ``os.SEEK_END`` or ``2`` (seek relative to the file's end). .. method:: mmap.size() @@ -217,15 +227,15 @@ Write the bytes in *string* into memory at the current position of the file pointer; the file position is updated to point after the bytes that were - written. If the mmap was created with :const:`ACCESS_READ`, then writing to it - will throw a :exc:`TypeError` exception. + written. If the mmap was created with :const:`ACCESS_READ`, then writing to + it will throw a :exc:`TypeError` exception. .. method:: mmap.write_byte(byte) - Write the single-character string *byte* into memory at the current position of - the file pointer; the file position is advanced by ``1``. If the mmap was - created with :const:`ACCESS_READ`, then writing to it will throw a - :exc:`TypeError` exception. + Write the single-character string *byte* into memory at the current + position of the file pointer; the file position is advanced by ``1``. If + the mmap was created with :const:`ACCESS_READ`, then writing to it will + throw a :exc:`TypeError` exception. Modified: python/branches/py3k/Doc/library/pkgutil.rst ============================================================================== --- python/branches/py3k/Doc/library/pkgutil.rst (original) +++ python/branches/py3k/Doc/library/pkgutil.rst Sat Apr 19 02:55:37 2008 @@ -6,7 +6,7 @@ :synopsis: Utilities to support extension of packages. -This module provides a single function: +This module provides functions to manipulate packages: .. function:: extend_path(path, name) @@ -38,3 +38,24 @@ ``sys.path`` that cause errors when used as filenames may cause this function to raise an exception (in line with :func:`os.path.isdir` behavior). +.. function:: get_data(package, resource) + + Get a resource from a package. + + This is a wrapper round the PEP 302 loader :func:`get_data` API. The package + argument should be the name of a package, in standard module format + (foo.bar). The resource argument should be in the form of a relative + filename, using ``/`` as the path separator. The parent directory name + ``..`` is not allowed, and nor is a rooted name (starting with a ``/``). + + The function returns a binary string, which is the contents of the + specified resource. + + For packages located in the filesystem, which have already been imported, + this is the rough equivalent of:: + + d = os.path.dirname(sys.modules[package].__file__) + data = open(os.path.join(d, resource), 'rb').read() + + If the package cannot be located or loaded, or it uses a PEP 302 loader + which does not support :func:`get_data`, then None is returned. Modified: python/branches/py3k/Doc/library/profile.rst ============================================================================== --- python/branches/py3k/Doc/library/profile.rst (original) +++ python/branches/py3k/Doc/library/profile.rst Sat Apr 19 02:55:37 2008 @@ -32,15 +32,6 @@ WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -The profiler was written after only programming in Python for 3 weeks. As a -result, it is probably clumsy code, but I don't know for sure yet 'cause I'm a -beginner :-). I did work hard to make the code run fast, so that profiling -would be a reasonable thing to do. I tried not to repeat code fragments, but -I'm sure I did some stuff in really awkward ways at times. Please send -suggestions for improvements to: jar at netscape.com. I won't promise *any* -support. ...but I'd appreciate the feedback. - - .. _profiler-introduction: Introduction to the profilers @@ -50,69 +41,38 @@ single: deterministic profiling single: profiling, deterministic -A :dfn:`profiler` is a program that describes the run time performance of a -program, providing a variety of statistics. This documentation describes the -profiler functionality provided in the modules :mod:`profile` and :mod:`pstats`. -This profiler provides :dfn:`deterministic profiling` of any Python programs. -It also provides a series of report generation tools to allow users to rapidly +A :dfn:`profiler` is a program that describes the run time performance +of a program, providing a variety of statistics. This documentation +describes the profiler functionality provided in the modules +:mod:`cProfile`, :mod:`profile` and :mod:`pstats`. This profiler +provides :dfn:`deterministic profiling` of Python programs. It also +provides a series of report generation tools to allow users to rapidly examine the results of a profile operation. The Python standard library provides two different profilers: -#. :mod:`profile`, a pure Python module, described in the sequel. Copyright ? - 1994, by InfoSeek Corporation. - -#. :mod:`cProfile`, a module written in C, with a reasonable overhead that makes - it suitable for profiling long-running programs. Based on :mod:`lsprof`, - contributed by Brett Rosen and Ted Czotter. +#. :mod:`cProfile` is recommended for most users; it's a C extension + with reasonable overhead + that makes it suitable for profiling long-running programs. + Based on :mod:`lsprof`, + contributed by Brett Rosen and Ted Czotter. + +#. :mod:`profile`, a pure Python module whose interface is imitated by + :mod:`cProfile`. Adds significant overhead to profiled programs. + If you're trying to extend + the profiler in some way, the task might be easier with this module. + Copyright ? 1994, by InfoSeek Corporation. The :mod:`profile` and :mod:`cProfile` modules export the same interface, so -they are mostly interchangeables; :mod:`cProfile` has a much lower overhead but -is not so far as well-tested and might not be available on all systems. +they are mostly interchangeable; :mod:`cProfile` has a much lower overhead but +is newer and might not be available on all systems. :mod:`cProfile` is really a compatibility layer on top of the internal +<<<<<<< .working :mod:`_lsprof` module. - -.. \section{How Is This Profiler Different From The Old Profiler?} - \nodename{Profiler Changes} - - (This section is of historical importance only; the old profiler - discussed here was last seen in Python 1.1.) - - The big changes from old profiling module are that you get more - information, and you pay less CPU time. It's not a trade-off, it's a - trade-up. - - To be specific: - - \begin{description} - - \item[Bugs removed:] - Local stack frame is no longer molested, execution time is now charged - to correct functions. - - \item[Accuracy increased:] - Profiler execution time is no longer charged to user's code, - calibration for platform is supported, file reads are not done \emph{by} - profiler \emph{during} profiling (and charged to user's code!). - - \item[Speed increased:] - Overhead CPU cost was reduced by more than a factor of two (perhaps a - factor of five), lightweight profiler module is all that must be - loaded, and the report generating module (\module{pstats}) is not needed - during profiling. - - \item[Recursive functions support:] - Cumulative times in recursive functions are correctly calculated; - recursive entries are counted. - - \item[Large growth in report generating UI:] - Distinct profiles runs can be added together forming a comprehensive - report; functions that import statistics take arbitrary lists of - files; sorting criteria is now based on keywords (instead of 4 integer - options); reports shows what functions were profiled as well as what - profile file was referenced; output format has been improved. - - \end{description} +======= +:mod:`_lsprof` module. The :mod:`hotshot` module is reserved for specialized +usage. +>>>>>>> .merge-right.r62379 .. _profile-instant: Modified: python/branches/py3k/Doc/library/ssl.rst ============================================================================== --- python/branches/py3k/Doc/library/ssl.rst (original) +++ python/branches/py3k/Doc/library/ssl.rst Sat Apr 19 02:55:37 2008 @@ -543,7 +543,7 @@ server_side=True, certfile="mycertfile", keyfile="mykeyfile", - ssl_protocol=ssl.PROTOCOL_TLSv1) + ssl_version=ssl.PROTOCOL_TLSv1) deal_with_client(connstream) Then you'd read data from the ``connstream`` and do something with it till you are finished with the client (or the client is finished with you):: Modified: python/branches/py3k/Doc/reference/compound_stmts.rst ============================================================================== --- python/branches/py3k/Doc/reference/compound_stmts.rst (original) +++ python/branches/py3k/Doc/reference/compound_stmts.rst Sat Apr 19 02:55:37 2008 @@ -446,6 +446,9 @@ The function definition does not execute the function body; this gets executed only when the function is called. +.. index:: + statement: @ + A function definition may be wrapped by one or more :term:`decorator` expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is @@ -486,7 +489,11 @@ penguin.append("property of the zoo") return penguin -Function call semantics are described in more detail in section :ref:`calls`. A +.. index:: + statement: * + statement: ** + +Function call semantics are described in more detail in section :ref:`calls`. A function call always assigns values to all parameters mentioned in the parameter list, either from position arguments, from keyword arguments, or from default values. If the form "``*identifier``" is present, it is initialized to a tuple Modified: python/branches/py3k/Doc/tutorial/controlflow.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/controlflow.rst (original) +++ python/branches/py3k/Doc/tutorial/controlflow.rst Sat Apr 19 02:55:37 2008 @@ -467,6 +467,9 @@ Arbitrary Argument Lists ------------------------ +.. index:: + statement: * + Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple. Before the variable number of arguments, zero or more normal @@ -508,6 +511,9 @@ >>> list(range(*args)) # call with arguments unpacked from a list [3, 4, 5] +.. index:: + statement: ** + In the same fashion, dictionaries can deliver keyword arguments with the ``**``\ -operator:: @@ -610,7 +616,7 @@ Making it easy for others to read your code is always a good idea, and adopting a nice coding style helps tremendously for that. -For Python, :pep:`8` has emerged as the style guide that most projects adher to; +For Python, :pep:`8` has emerged as the style guide that most projects adhere to; it promotes a very readable and eye-pleasing coding style. Every Python developer should read it at some point; here are the most important points extracted for you: Modified: python/branches/py3k/Lib/pkgutil.py ============================================================================== --- python/branches/py3k/Lib/pkgutil.py (original) +++ python/branches/py3k/Lib/pkgutil.py Sat Apr 19 02:55:37 2008 @@ -542,3 +542,40 @@ f.close() return path + +def get_data(package, resource): + """Get a resource from a package. + + This is a wrapper round the PEP 302 loader get_data API. The package + argument should be the name of a package, in standard module format + (foo.bar). The resource argument should be in the form of a relative + filename, using '/' as the path separator. The parent directory name '..' + is not allowed, and nor is a rooted name (starting with a '/'). + + The function returns a binary string, which is the contents of the + specified resource. + + For packages located in the filesystem, which have already been imported, + this is the rough equivalent of + + d = os.path.dirname(sys.modules[package].__file__) + data = open(os.path.join(d, resource), 'rb').read() + + If the package cannot be located or loaded, or it uses a PEP 302 loader + which does not support get_data(), then None is returned. + """ + + loader = get_loader(package) + if loader is None or not hasattr(loader, 'get_data'): + return None + mod = sys.modules.get(package) or loader.load_module(package) + if mod is None or not hasattr(mod, '__file__'): + return None + + # Modify the resource name to be compatible with the loader.get_data + # signature - an os.path format "filename" starting with the dirname of + # the package's __file__ + parts = resource.split('/') + parts.insert(0, os.path.dirname(mod.__file__)) + resource_name = os.path.join(*parts) + return loader.get_data(resource_name) Modified: python/branches/py3k/Lib/test/regrtest.py ============================================================================== --- python/branches/py3k/Lib/test/regrtest.py (original) +++ python/branches/py3k/Lib/test/regrtest.py Sat Apr 19 02:55:37 2008 @@ -731,6 +731,11 @@ from distutils.dir_util import _path_created from weakref import WeakSet + # Clear the warnings registry, so they can be displayed again + for mod in sys.modules.values(): + if hasattr(mod, '__warningregistry__'): + del mod.__warningregistry__ + # Restore some original values. warnings.filters[:] = fs copy_reg.dispatch_table.clear() Modified: python/branches/py3k/Lib/test/test_frozen.py ============================================================================== --- python/branches/py3k/Lib/test/test_frozen.py (original) +++ python/branches/py3k/Lib/test/test_frozen.py Sat Apr 19 02:55:37 2008 @@ -39,6 +39,18 @@ else: self.fail("import __phello__.foo should have failed") + if sys.platform != "mac": # On the Mac this import does succeed. + try: + import __phello__.foo + except ImportError: + pass + else: + self.fail("import __phello__.foo should have failed") + + del sys.modules['__hello__'] + del sys.modules['__phello__'] + del sys.modules['__phello__.spam'] + def test_main(): run_unittest(FrozenTests) Modified: python/branches/py3k/Lib/test/test_pkg.py ============================================================================== --- python/branches/py3k/Lib/test/test_pkg.py (original) +++ python/branches/py3k/Lib/test/test_pkg.py Sat Apr 19 02:55:37 2008 @@ -46,6 +46,7 @@ def setUp(self): self.root = None + self.pkgname = None self.syspath = list(sys.path) self.sysmodules = sys.modules.copy() @@ -56,6 +57,13 @@ del self.sysmodules cleanout(self.root) + # delete all modules concerning the tested hiearchy + if self.pkgname: + modules = [name for name in sys.modules + if self.pkgname in name.split('.')] + for name in modules: + del sys.modules[name] + def run_code(self, code): exec(textwrap.dedent(code), globals(), {"self": self}) @@ -78,6 +86,8 @@ f.write('\n') f.close() self.root = root + # package name is the name of the first item + self.pkgname = descr[0][0] def test_1(self): hier = [("t1", None), ("t1 __init__.py", "")] Copied: python/branches/py3k/Lib/test/test_pkgutil.py (from r62379, /python/trunk/Lib/test/test_pkgutil.py) ============================================================================== --- /python/trunk/Lib/test/test_pkgutil.py (original) +++ python/branches/py3k/Lib/test/test_pkgutil.py Sat Apr 19 02:55:37 2008 @@ -25,7 +25,7 @@ pkg = 'test_getdata_filesys' # Include a LF and a CRLF, to test that binary data is read back - RESOURCE_DATA = 'Hello, world!\nSecond line\r\nThird line' + RESOURCE_DATA = b'Hello, world!\nSecond line\r\nThird line' # Make a package with some resources package_dir = os.path.join(self.dirname, pkg) @@ -48,12 +48,14 @@ res2 = pkgutil.get_data(pkg, 'sub/res.txt') self.assertEqual(res2, RESOURCE_DATA) + del sys.modules[pkg] + def test_getdata_zipfile(self): zip = 'test_getdata_zipfile.zip' pkg = 'test_getdata_zipfile' # Include a LF and a CRLF, to test that binary data is read back - RESOURCE_DATA = 'Hello, world!\nSecond line\r\nThird line' + RESOURCE_DATA = b'Hello, world!\nSecond line\r\nThird line' # Make a package with some resources zip_file = os.path.join(self.dirname, zip) @@ -74,6 +76,8 @@ self.assertEqual(res2, RESOURCE_DATA) del sys.path[0] + del sys.modules[pkg] + class PkgutilPEP302Tests(unittest.TestCase): class MyTestLoader(object): Modified: python/branches/py3k/Lib/test/test_profile.py ============================================================================== --- python/branches/py3k/Lib/test/test_profile.py (original) +++ python/branches/py3k/Lib/test/test_profile.py Sat Apr 19 02:55:37 2008 @@ -22,8 +22,9 @@ def do_profiling(cls): results = [] prof = cls.profilerclass(timer, 0.001) + start_timer = timer() prof.runctx("testfunc()", globals(), locals()) - results.append(timer()) + results.append(timer() - start_timer) for methodname in cls.methodnames: s = StringIO() stats = pstats.Stats(prof, stream=s) @@ -40,7 +41,7 @@ def test_cprofile(self): results = self.do_profiling() - self.assertEqual(results[0], 43000) + self.assertEqual(results[0], 1000) for i, method in enumerate(self.methodnames): if results[i+1] != self.expected_output[method]: print("Stats.%s output for %s doesn't fit expectation!" % Modified: python/branches/py3k/Lib/test/test_structmembers.py ============================================================================== --- python/branches/py3k/Lib/test/test_structmembers.py (original) +++ python/branches/py3k/Lib/test/test_structmembers.py Sat Apr 19 02:55:37 2008 @@ -101,12 +101,6 @@ def test_main(verbose=None): - # Obscure hack so that this test passes after reloads or repeated calls - # to test_main (regrtest -R). - if '__warningregistry__' in globals(): - del globals()['__warningregistry__'] - if hasattr(sys, '__warningregistry__'): - del sys.__warningregistry__ test_support.run_unittest(__name__) if __name__ == "__main__": Modified: python/branches/py3k/Lib/test/test_warnings.py ============================================================================== --- python/branches/py3k/Lib/test/test_warnings.py (original) +++ python/branches/py3k/Lib/test/test_warnings.py Sat Apr 19 02:55:37 2008 @@ -391,6 +391,8 @@ def test_main(): + py_warnings.onceregistry.clear() + c_warnings.onceregistry.clear() test_support.run_unittest(CFilterTests, PyFilterTests, CWarnTests, Modified: python/branches/py3k/Lib/test/test_xmlrpc.py ============================================================================== --- python/branches/py3k/Lib/test/test_xmlrpc.py (original) +++ python/branches/py3k/Lib/test/test_xmlrpc.py Sat Apr 19 02:55:37 2008 @@ -49,6 +49,17 @@ (newdt,), m = xmlrpclib.loads(s, use_datetime=0) self.assertEquals(newdt, xmlrpclib.DateTime('20050210T11:41:23')) + def test_datetime_before_1900(self): + # same as before but with an date before 1900 + dt = datetime.datetime(1, 2, 10, 11, 41, 23) + s = xmlrpclib.dumps((dt,)) + (newdt,), m = xmlrpclib.loads(s, use_datetime=1) + self.assertEquals(newdt, dt) + self.assertEquals(m, None) + + (newdt,), m = xmlrpclib.loads(s, use_datetime=0) + self.assertEquals(newdt, xmlrpclib.DateTime('00010210T11:41:23')) + def test_cmp_datetime_DateTime(self): now = datetime.datetime.now() dt = xmlrpclib.DateTime(now.timetuple()) Modified: python/branches/py3k/Lib/xmlrpclib.py ============================================================================== --- python/branches/py3k/Lib/xmlrpclib.py (original) +++ python/branches/py3k/Lib/xmlrpclib.py Sat Apr 19 02:55:37 2008 @@ -287,6 +287,20 @@ # @param value The time, given as an ISO 8601 string, a time # tuple, or a integer time value. +def _strftime(value): + if datetime: + if isinstance(value, datetime.datetime): + return "%04d%02d%02dT%02d:%02d:%02d" % ( + value.year, value.month, value.day, + value.hour, value.minute, value.second) + + if not isinstance(value, (tuple, time.struct_time)): + if value == 0: + value = time.time() + value = time.localtime(value) + + return "%04d%02d%02dT%02d:%02d:%02d" % value[:6] + class DateTime: """DateTime wrapper for an ISO 8601 string or time tuple or localtime integer value to generate 'dateTime.iso8601' XML-RPC @@ -294,16 +308,10 @@ """ def __init__(self, value=0): - if not isinstance(value, str): - if datetime and isinstance(value, datetime.datetime): - self.value = value.strftime("%Y%m%dT%H:%M:%S") - return - if not isinstance(value, (tuple, time.struct_time)): - if value == 0: - value = time.time() - value = time.localtime(value) - value = time.strftime("%Y%m%dT%H:%M:%S", value) - self.value = value + if isinstance(value, str): + self.value = value + else: + self.value = _strftime(value) def make_comparable(self, other): if isinstance(other, DateTime): @@ -700,7 +708,7 @@ if datetime: def dump_datetime(self, value, write): write("") - write(value.strftime("%Y%m%dT%H:%M:%S")) + write(_strftime(value)) write("\n") dispatch[datetime.datetime] = dump_datetime Modified: python/branches/py3k/Objects/longobject.c ============================================================================== --- python/branches/py3k/Objects/longobject.c (original) +++ python/branches/py3k/Objects/longobject.c Sat Apr 19 02:55:37 2008 @@ -160,6 +160,7 @@ PyLong_FromLong(long ival) { PyLongObject *v; + unsigned long abs_ival; unsigned long t; /* unsigned so >> doesn't propagate sign bit */ int ndigits = 0; int sign = 1; @@ -167,9 +168,15 @@ CHECK_SMALL_INT(ival); if (ival < 0) { - ival = -ival; + /* if LONG_MIN == -LONG_MAX-1 (true on most platforms) then + ANSI C says that the result of -ival is undefined when ival + == LONG_MIN. Hence the following workaround. */ + abs_ival = (unsigned long)(-1-ival) + 1; sign = -1; } + else { + abs_ival = (unsigned long)ival; + } /* Fast path for single-digits ints */ if (!(ival>>PyLong_SHIFT)) { @@ -193,7 +200,7 @@ } /* Larger numbers: loop to determine number of digits */ - t = (unsigned long)ival; + t = abs_ival; while (t) { ++ndigits; t >>= PyLong_SHIFT; @@ -202,7 +209,7 @@ if (v != NULL) { digit *p = v->ob_digit; Py_SIZE(v) = ndigits*sign; - t = (unsigned long)ival; + t = abs_ival; while (t) { *p++ = (digit)(t & PyLong_MASK); t >>= PyLong_SHIFT; @@ -1033,21 +1040,27 @@ PyLong_FromLongLong(PY_LONG_LONG ival) { PyLongObject *v; + unsigned PY_LONG_LONG abs_ival; unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */ int ndigits = 0; int negative = 0; CHECK_SMALL_INT(ival); if (ival < 0) { - ival = -ival; + /* avoid signed overflow on negation; see comments + in PyLong_FromLong above. */ + abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1; negative = 1; } + else { + abs_ival = (unsigned PY_LONG_LONG)ival; + } /* Count the number of Python digits. We used to pick 5 ("big enough for anything"), but that's a waste of time and space given that 5*15 = 75 bits are rarely needed. */ - t = (unsigned PY_LONG_LONG)ival; + t = abs_ival; while (t) { ++ndigits; t >>= PyLong_SHIFT; @@ -1056,7 +1069,7 @@ if (v != NULL) { digit *p = v->ob_digit; Py_SIZE(v) = negative ? -ndigits : ndigits; - t = (unsigned PY_LONG_LONG)ival; + t = abs_ival; while (t) { *p++ = (digit)(t & PyLong_MASK); t >>= PyLong_SHIFT; Modified: python/branches/py3k/Python/sysmodule.c ============================================================================== --- python/branches/py3k/Python/sysmodule.c (original) +++ python/branches/py3k/Python/sysmodule.c Sat Apr 19 02:55:37 2008 @@ -1191,9 +1191,9 @@ /* stdin/stdout/stderr are now set by pythonrun.c */ PyDict_SetItemString(sysdict, "__displayhook__", - PyDict_GetItemString(sysdict, "displayhook")); + PyDict_GetItemString(sysdict, "displayhook")); PyDict_SetItemString(sysdict, "__excepthook__", - PyDict_GetItemString(sysdict, "excepthook")); + PyDict_GetItemString(sysdict, "excepthook")); SET_SYS_FROM_STRING("version", PyUnicode_FromString(Py_GetVersion())); SET_SYS_FROM_STRING("hexversion", @@ -1203,7 +1203,7 @@ Py_BuildValue("(UUU)", "CPython", branch, svn_revision)); SET_SYS_FROM_STRING("dont_write_bytecode", - PyBool_FromLong(Py_DontWriteBytecodeFlag)); + PyBool_FromLong(Py_DontWriteBytecodeFlag)); /* * These release level checks are mutually exclusive and cover * the field, so don't get too fancy with the pre-processor! From python-3000-checkins at python.org Sat Apr 19 21:32:08 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Sat, 19 Apr 2008 21:32:08 +0200 (CEST) Subject: [Python-3000-checkins] r62397 - python/branches/py3k/Doc/library/io.rst Message-ID: <20080419193208.9AB381E400A@bag.python.org> Author: benjamin.peterson Date: Sat Apr 19 21:32:08 2008 New Revision: 62397 Log: the io module was added in 2.6 (I know not really, but the end user isn't going to care about backporting.) Modified: python/branches/py3k/Doc/library/io.rst Modified: python/branches/py3k/Doc/library/io.rst ============================================================================== --- python/branches/py3k/Doc/library/io.rst (original) +++ python/branches/py3k/Doc/library/io.rst Sat Apr 19 21:32:08 2008 @@ -7,6 +7,7 @@ .. moduleauthor:: Mike Verdone .. moduleauthor:: Mark Russell .. sectionauthor:: Benjamin Peterson +.. versionadded:: 2.6 The :mod:`io` module provides the Python interfaces to stream handling. The builtin :func:`open` function is defined in this module. From python-3000-checkins at python.org Sat Apr 19 21:38:01 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Sat, 19 Apr 2008 21:38:01 +0200 (CEST) Subject: [Python-3000-checkins] r62399 - python/branches/py3k Message-ID: <20080419193801.095E91E400C@bag.python.org> Author: benjamin.peterson Date: Sat Apr 19 21:38:00 2008 New Revision: 62399 Log: Blocked revisions 62398 via svnmerge ........ r62398 | benjamin.peterson | 2008-04-19 14:34:05 -0500 (Sat, 19 Apr 2008) | 2 lines Copy io documentation back from py3k branch so changes can be merged into it. ........ Modified: python/branches/py3k/ (props changed) From g.brandl at gmx.net Sat Apr 19 23:14:35 2008 From: g.brandl at gmx.net (Georg Brandl) Date: Sat, 19 Apr 2008 23:14:35 +0200 Subject: [Python-3000-checkins] r62397 - python/branches/py3k/Doc/library/io.rst In-Reply-To: <20080419193208.9AB381E400A@bag.python.org> References: <20080419193208.9AB381E400A@bag.python.org> Message-ID: Please revert this -- there are to be no versionadded/changed tags in the 3.0 documentation. Georg benjamin.peterson schrieb: > Author: benjamin.peterson > Date: Sat Apr 19 21:32:08 2008 > New Revision: 62397 > > Log: > the io module was added in 2.6 (I know not really, but the end user isn't going to care about backporting.) > > > Modified: > python/branches/py3k/Doc/library/io.rst > > Modified: python/branches/py3k/Doc/library/io.rst > ============================================================================== > --- python/branches/py3k/Doc/library/io.rst (original) > +++ python/branches/py3k/Doc/library/io.rst Sat Apr 19 21:32:08 2008 > @@ -7,6 +7,7 @@ > .. moduleauthor:: Mike Verdone > .. moduleauthor:: Mark Russell > .. sectionauthor:: Benjamin Peterson > +.. versionadded:: 2.6 > > The :mod:`io` module provides the Python interfaces to stream handling. The > builtin :func:`open` function is defined in this module. -- Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are right out. From musiccomposition at gmail.com Sat Apr 19 23:18:26 2008 From: musiccomposition at gmail.com (Benjamin Peterson) Date: Sat, 19 Apr 2008 16:18:26 -0500 Subject: [Python-3000-checkins] r62397 - python/branches/py3k/Doc/library/io.rst In-Reply-To: References: <20080419193208.9AB381E400A@bag.python.org> Message-ID: <1afaf6160804191418q52a7b540hbc6f546cf72117f0@mail.gmail.com> On Sat, Apr 19, 2008 at 4:14 PM, Georg Brandl wrote: > Please revert this -- there are to be no versionadded/changed tags in the 3.0 > documentation. Ok. Just out of curiosity, why? -- Cheers, Benjamin Peterson From g.brandl at gmx.net Sat Apr 19 23:20:59 2008 From: g.brandl at gmx.net (Georg Brandl) Date: Sat, 19 Apr 2008 23:20:59 +0200 Subject: [Python-3000-checkins] r62397 - python/branches/py3k/Doc/library/io.rst In-Reply-To: <1afaf6160804191418q52a7b540hbc6f546cf72117f0@mail.gmail.com> References: <20080419193208.9AB381E400A@bag.python.org> <1afaf6160804191418q52a7b540hbc6f546cf72117f0@mail.gmail.com> Message-ID: Benjamin Peterson schrieb: > On Sat, Apr 19, 2008 at 4:14 PM, Georg Brandl wrote: >> Please revert this -- there are to be no versionadded/changed tags in the 3.0 >> documentation. > > Ok. Just out of curiosity, why? The tags are there to help programmers stay backward-compatible with earlier Python versions. This obviously isn't compatible with Python 3000's goals, so we can as well get rid of them, resulting in a streamlined documentation. Of course, there will be such tags for things added/changed within the 3.x series of releases. Georg -- Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are right out. From python-3000-checkins at python.org Sat Apr 19 23:24:29 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Sat, 19 Apr 2008 23:24:29 +0200 (CEST) Subject: [Python-3000-checkins] r62405 - python/branches/py3k/Doc/library/io.rst Message-ID: <20080419212429.879F51E400C@bag.python.org> Author: benjamin.peterson Date: Sat Apr 19 23:24:29 2008 New Revision: 62405 Log: Reverted 62397; no versionadded/changed in 3.0 docs Modified: python/branches/py3k/Doc/library/io.rst Modified: python/branches/py3k/Doc/library/io.rst ============================================================================== --- python/branches/py3k/Doc/library/io.rst (original) +++ python/branches/py3k/Doc/library/io.rst Sat Apr 19 23:24:29 2008 @@ -7,7 +7,6 @@ .. moduleauthor:: Mike Verdone .. moduleauthor:: Mark Russell .. sectionauthor:: Benjamin Peterson -.. versionadded:: 2.6 The :mod:`io` module provides the Python interfaces to stream handling. The builtin :func:`open` function is defined in this module. From musiccomposition at gmail.com Sun Apr 20 00:12:06 2008 From: musiccomposition at gmail.com (Benjamin Peterson) Date: Sat, 19 Apr 2008 17:12:06 -0500 Subject: [Python-3000-checkins] r62397 - python/branches/py3k/Doc/library/io.rst In-Reply-To: References: <20080419193208.9AB381E400A@bag.python.org> <1afaf6160804191418q52a7b540hbc6f546cf72117f0@mail.gmail.com> Message-ID: <1afaf6160804191512h1128e13ana62a73417d7ae002@mail.gmail.com> On Sat, Apr 19, 2008 at 4:20 PM, Georg Brandl wrote: > Benjamin Peterson schrieb: > The tags are there to help programmers stay backward-compatible with earlier > Python versions. This obviously isn't compatible with Python 3000's goals, > so we can as well get rid of them, resulting in a streamlined documentation. So, does that mean that the versionchanged directives currently in 3.0's docs should be removed? -- Cheers, Benjamin Peterson From g.brandl at gmx.net Sun Apr 20 00:17:19 2008 From: g.brandl at gmx.net (Georg Brandl) Date: Sun, 20 Apr 2008 00:17:19 +0200 Subject: [Python-3000-checkins] r62397 - python/branches/py3k/Doc/library/io.rst In-Reply-To: <1afaf6160804191512h1128e13ana62a73417d7ae002@mail.gmail.com> References: <20080419193208.9AB381E400A@bag.python.org> <1afaf6160804191418q52a7b540hbc6f546cf72117f0@mail.gmail.com> <1afaf6160804191512h1128e13ana62a73417d7ae002@mail.gmail.com> Message-ID: Benjamin Peterson schrieb: > On Sat, Apr 19, 2008 at 4:20 PM, Georg Brandl wrote: >> Benjamin Peterson schrieb: >> The tags are there to help programmers stay backward-compatible with earlier >> Python versions. This obviously isn't compatible with Python 3000's goals, >> so we can as well get rid of them, resulting in a streamlined documentation. > > So, does that mean that the versionchanged directives currently in > 3.0's docs should be removed? Yes. Christian normally keeps an eye on it, but it should suffice to go through the documentation once before a release is made and remove the tags. Thankfully they're easily spottable :) That said, when you remove a tag, be sure to check whether the information contained in it is already present in the remaining text. Georg -- Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are right out. From python-3000-checkins at python.org Sun Apr 20 00:18:33 2008 From: python-3000-checkins at python.org (georg.brandl) Date: Sun, 20 Apr 2008 00:18:33 +0200 (CEST) Subject: [Python-3000-checkins] r62411 - python/branches/py3k/Doc/library/functools.rst Message-ID: <20080419221833.827ED1E400C@bag.python.org> Author: georg.brandl Date: Sun Apr 20 00:18:33 2008 New Revision: 62411 Log: Remove duplicated reduce() entry. Modified: python/branches/py3k/Doc/library/functools.rst Modified: python/branches/py3k/Doc/library/functools.rst ============================================================================== --- python/branches/py3k/Doc/library/functools.rst (original) +++ python/branches/py3k/Doc/library/functools.rst Sun Apr 20 00:18:33 2008 @@ -15,13 +15,6 @@ The :mod:`functools` module defines the following functions: - -.. function:: reduce(function, iterable[, initializer]) - - This is the same function as :func:`reduce`. It is made available in this module - to allow writing code more forward-compatible with Python 3. - - .. function:: partial(func[,*args][, **keywords]) Return a new :class:`partial` object which when called will behave like *func* @@ -53,7 +46,7 @@ 18 -.. function:: reduce(function, sequence[, initializer]) +.. function:: reduce(function, iterable[, initializer]) Apply *function* of two arguments cumulatively to the items of *sequence*, from left to right, so as to reduce the sequence to a single value. For example, From python-3000-checkins at python.org Sun Apr 20 23:01:17 2008 From: python-3000-checkins at python.org (christian.heimes) Date: Sun, 20 Apr 2008 23:01:17 +0200 (CEST) Subject: [Python-3000-checkins] r62422 - in python/branches/py3k: Doc/conf.py Doc/documenting/markup.rst Doc/library/dis.rst Doc/library/io.rst Doc/library/math.rst Doc/library/os.rst Doc/library/shutil.rst Doc/library/subprocess.rst Doc/tools/sphinxext/indexcontent.html Doc/whatsnew/2.6.rst Lib/subprocess.py Lib/test/test_math.py Lib/test/test_subprocess.py Modules/cmathmodule.c Modules/mathmodule.c Message-ID: <20080420210117.05AFC1E400B@bag.python.org> Author: christian.heimes Date: Sun Apr 20 23:01:16 2008 New Revision: 62422 Log: Merged revisions 62386-62387,62389-62393,62396,62400-62402,62407,62409-62410,62412-62414,62418-62419 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62386 | christian.heimes | 2008-04-19 04:23:57 +0200 (Sat, 19 Apr 2008) | 2 lines Added kill, terminate and send_signal to subprocess.Popen The bits and pieces for the Windows side were already in place. The POSIX side is trivial (as usual) and uses os.kill(). ........ r62387 | georg.brandl | 2008-04-19 10:23:59 +0200 (Sat, 19 Apr 2008) | 2 lines Fix-up docs for revision 62386. ........ r62389 | georg.brandl | 2008-04-19 18:57:43 +0200 (Sat, 19 Apr 2008) | 2 lines #2369: clarify that copyfile() doesn't take a target directory. ........ r62390 | georg.brandl | 2008-04-19 18:58:28 +0200 (Sat, 19 Apr 2008) | 2 lines #2634: clarify meaning of env parameter to spawn/exec*e. ........ r62391 | georg.brandl | 2008-04-19 18:58:49 +0200 (Sat, 19 Apr 2008) | 2 lines #2633: clarify meaning of env parameter. ........ r62392 | georg.brandl | 2008-04-19 18:59:16 +0200 (Sat, 19 Apr 2008) | 2 lines #2631: clarify IMPORT_NAME semantics. ........ r62393 | georg.brandl | 2008-04-19 19:00:14 +0200 (Sat, 19 Apr 2008) | 2 lines :func: et al. should *not* include the parens. ........ r62396 | mark.dickinson | 2008-04-19 20:51:48 +0200 (Sat, 19 Apr 2008) | 5 lines Additional tests for math.pow, and extra special-case handling code in math.pow, in the hope of making all tests pass on the alpha Tru64 buildbot. ........ r62400 | mark.dickinson | 2008-04-19 21:41:52 +0200 (Sat, 19 Apr 2008) | 3 lines Additional special-case handling for math.pow. Windows/VS2008 doesn't like (-1)**(+-inf). ........ r62401 | benjamin.peterson | 2008-04-19 21:47:34 +0200 (Sat, 19 Apr 2008) | 2 lines Complete documentation for errors argument of io's open and TextIOWrapper ........ r62402 | mark.dickinson | 2008-04-19 22:31:16 +0200 (Sat, 19 Apr 2008) | 2 lines Document updates to math and cmath modules. ........ r62407 | georg.brandl | 2008-04-19 23:28:38 +0200 (Sat, 19 Apr 2008) | 2 lines Update template for newest Sphinx. ........ r62409 | mark.dickinson | 2008-04-19 23:35:35 +0200 (Sat, 19 Apr 2008) | 5 lines Correct documentation for math.pow; 0**nan is nan, not 0. (But nan**0 and 1**nan are 1.) Also fix minor typo: 'quite NaN' -> 'quiet NaN' ........ r62410 | mark.dickinson | 2008-04-19 23:49:22 +0200 (Sat, 19 Apr 2008) | 4 lines Move asinh documentation to the proper place. Remove meaningless 'in radians' from inverse hyperbolic functions. ........ r62412 | mark.dickinson | 2008-04-20 03:22:30 +0200 (Sun, 20 Apr 2008) | 5 lines Report additional diagnostic information in test_math, to help track down debian-alpha buildbot failure. ........ r62413 | mark.dickinson | 2008-04-20 03:39:24 +0200 (Sun, 20 Apr 2008) | 3 lines FreeBSD doesn't follow C99 for modf(inf); so add explicit special-value handling to math.modf code. ........ r62414 | mark.dickinson | 2008-04-20 06:13:13 +0200 (Sun, 20 Apr 2008) | 5 lines Yet more explicit special case handling to make math.pow behave on alpha Tru64. All IEEE 754 special values are now handled directly; only the finite**finite case is handled by libm. ........ r62418 | mark.dickinson | 2008-04-20 18:13:17 +0200 (Sun, 20 Apr 2008) | 7 lines Issue 2662: Initialize special value tables dynamically (i.e. when cmath module is loaded) instead of statically. This fixes compile-time problems on platforms where HUGE_VAL is an extern variable rather than a constant. Thanks Hirokazu Yamamoto for the patch. ........ r62419 | andrew.kuchling | 2008-04-20 18:54:02 +0200 (Sun, 20 Apr 2008) | 1 line Move description of math module changes; various edits to description of cmath changes ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/conf.py python/branches/py3k/Doc/documenting/markup.rst python/branches/py3k/Doc/library/dis.rst python/branches/py3k/Doc/library/io.rst python/branches/py3k/Doc/library/math.rst python/branches/py3k/Doc/library/os.rst python/branches/py3k/Doc/library/shutil.rst python/branches/py3k/Doc/library/subprocess.rst python/branches/py3k/Doc/tools/sphinxext/indexcontent.html python/branches/py3k/Doc/whatsnew/2.6.rst python/branches/py3k/Lib/subprocess.py python/branches/py3k/Lib/test/test_math.py python/branches/py3k/Lib/test/test_subprocess.py python/branches/py3k/Modules/cmathmodule.c python/branches/py3k/Modules/mathmodule.c Modified: python/branches/py3k/Doc/conf.py ============================================================================== --- python/branches/py3k/Doc/conf.py (original) +++ python/branches/py3k/Doc/conf.py Sun Apr 20 23:01:16 2008 @@ -75,9 +75,6 @@ # typographically correct entities. html_use_smartypants = True -# Content template for the index page, filename relative to this file. -html_index = 'indexcontent.html' - # Custom sidebar templates, filenames relative to this file. html_sidebars = { 'index': 'indexsidebar.html', @@ -86,6 +83,7 @@ # Additional templates that should be rendered to pages. html_additional_pages = { 'download': 'download.html', + 'index': 'indexcontent.html', } # Output file base name for HTML help builder. Modified: python/branches/py3k/Doc/documenting/markup.rst ============================================================================== --- python/branches/py3k/Doc/documenting/markup.rst (original) +++ python/branches/py3k/Doc/documenting/markup.rst Sun Apr 20 23:01:16 2008 @@ -319,8 +319,8 @@ .. describe:: func The name of a Python function; dotted names may be used. The role text - should include trailing parentheses to enhance readability. The parentheses - are stripped when searching for identifiers. + should not include trailing parentheses to enhance readability. The + parentheses are stripped when searching for identifiers. .. describe:: data @@ -338,7 +338,7 @@ .. describe:: meth The name of a method of an object. The role text should include the type - name, method name and the trailing parentheses. A dotted name may be used. + name and the method name. A dotted name may be used. .. describe:: attr Modified: python/branches/py3k/Doc/library/dis.rst ============================================================================== --- python/branches/py3k/Doc/library/dis.rst (original) +++ python/branches/py3k/Doc/library/dis.rst Sun Apr 20 23:01:16 2008 @@ -528,9 +528,11 @@ .. opcode:: IMPORT_NAME (namei) - Imports the module ``co_names[namei]``. The module object is pushed onto the - stack. The current namespace is not affected: for a proper import statement, a - subsequent ``STORE_FAST`` instruction modifies the namespace. + Imports the module ``co_names[namei]``. TOS and TOS1 are popped and provide + the *fromlist* and *level* arguments of :func:`__import__`. The module + object is pushed onto the stack. The current namespace is not affected: + for a proper import statement, a subsequent ``STORE_FAST`` instruction + modifies the namespace. .. opcode:: IMPORT_FROM (namei) Modified: python/branches/py3k/Doc/library/io.rst ============================================================================== --- python/branches/py3k/Doc/library/io.rst (original) +++ python/branches/py3k/Doc/library/io.rst Sun Apr 20 23:01:16 2008 @@ -101,13 +101,15 @@ :mod:`codecs` module for the list of supported encodings. *errors* is an optional string that specifies how encoding and decoding - errors are to be handled---this argument should not be used in binary mode. - Pass ``'strict'`` to raise a :exc:`ValueError` exception if there is an - encoding error (the default of ``None`` has the same effect), or pass - ``'ignore'`` to ignore errors. (Note that ignoring encoding errors can lead - to data loss.) ``'replace'`` causes a replacement marker (such as ``'?'``) - to be inserted where there is malformed data. For all possible values, see - :func:`codecs.register`. + errors are to be handled. Pass ``'strict'`` to raise a :exc:`ValueError` + exception if there is an encoding error (the default of ``None`` has the same + effect), or pass ``'ignore'`` to ignore errors. (Note that ignoring encoding + errors can lead to data loss.) ``'replace'`` causes a replacement marker + (such as ``'?'``) to be inserted where there is malformed data. When + writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character + reference) or ``'backslashreplace'`` (replace with backslashed escape + sequences) can be used. Any other error handling name that has been + registered with :func:`codecs.register_error` is also valid. *newline* controls how universal newlines works (it only applies to text mode). It can be ``None``, ``''``, ``'\n'``, ``'\r'``, and ``'\r\n'``. It @@ -581,8 +583,11 @@ exception if there is an encoding error (the default of ``None`` has the same effect), or pass ``'ignore'`` to ignore errors. (Note that ignoring encoding errors can lead to data loss.) ``'replace'`` causes a replacement marker - (such as ``'?'``) to be inserted where there is malformed data. For all - possible values see :func:`codecs.register`. + (such as ``'?'``) to be inserted where there is malformed data. When + writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character + reference) or ``'backslashreplace'`` (replace with backslashed escape + sequences) can be used. Any other error handling name that has been + registered with :func:`codecs.register_error` is also valid. *newline* can be ``None``, ``''``, ``'\n'``, ``'\r'``, or ``'\r\n'``. It controls the handling of line endings. If it is ``None``, universal newlines Modified: python/branches/py3k/Doc/library/math.rst ============================================================================== --- python/branches/py3k/Doc/library/math.rst (original) +++ python/branches/py3k/Doc/library/math.rst Sun Apr 20 23:01:16 2008 @@ -143,11 +143,15 @@ .. function:: pow(x, y) - Return ``x**y``. ``1.0**y`` returns *1.0*, even for ``1.0**nan``. ``0**y`` - returns *0.* for all positive *y*, *0* and *NAN*. + Return ``x`` raised to the power ``y``. Exceptional cases follow + Annex 'F' of the C99 standard as far as possible. In particular, + ``pow(1.0, x)`` and ``pow(x, 0.0)`` always return ``1.0``, even + when ``x`` is a zero or a NaN. If both ``x`` and ``y`` are finite, + ``x`` is negative, and ``y`` is not an integer then ``pow(x, y)`` + is undefined, and raises :exc:`ValueError`. .. versionchanged:: 2.6 - The outcome of ``1**nan`` and ``0**nan`` was undefined. + The outcome of ``1**nan`` and ``nan**0`` was undefined. .. function:: sqrt(x) @@ -198,13 +202,6 @@ Return the sine of *x* radians. -.. function:: asinh(x) - - Return the inverse hyperbolic sine of *x*, in radians. - - .. versionadded:: 2.6 - - .. function:: tan(x) Return the tangent of *x* radians. @@ -224,18 +221,32 @@ Hyperbolic functions: -.. function:: cosh(x) +.. function:: acosh(x) - Return the hyperbolic cosine of *x*. + Return the inverse hyperbolic cosine of *x*. + .. versionadded:: 2.6 -.. function:: acosh(x) - Return the inverse hyperbolic cosine of *x*, in radians. +.. function:: asinh(x) + + Return the inverse hyperbolic sine of *x*. .. versionadded:: 2.6 +.. function:: atanh(x) + + Return the inverse hyperbolic tangent of *x*. + + .. versionadded:: 2.6 + + +.. function:: cosh(x) + + Return the hyperbolic cosine of *x*. + + .. function:: sinh(x) Return the hyperbolic sine of *x*. @@ -246,12 +257,6 @@ Return the hyperbolic tangent of *x*. -.. function:: atanh(x) - - Return the inverse hyperbolic tangent of *x*, in radians. - - .. versionadded:: 2.6 - The module also defines two mathematical constants: @@ -279,7 +284,7 @@ :exc:`OverflowError` isn't defined, and in cases where ``math.log(0)`` raises :exc:`OverflowError`, ``math.log(0L)`` may raise :exc:`ValueError` instead. - All functions return a quite *NaN* if at least one of the args is *NaN*. + All functions return a quiet *NaN* if at least one of the args is *NaN*. Signaling *NaN*s raise an exception. The exception type still depends on the platform and libm implementation. It's usually :exc:`ValueError` for *EDOM* and :exc:`OverflowError` for errno *ERANGE*. Modified: python/branches/py3k/Doc/library/os.rst ============================================================================== --- python/branches/py3k/Doc/library/os.rst (original) +++ python/branches/py3k/Doc/library/os.rst Sun Apr 20 23:01:16 2008 @@ -1254,7 +1254,8 @@ For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note that these all end in "e"), the *env* parameter must be a mapping which is - used to define the environment variables for the new process; the :func:`execl`, + used to define the environment variables for the new process (these are used + instead of the current process' environment); the functions :func:`execl`, :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to inherit the environment of the current process. Availability: Macintosh, Unix, Windows. @@ -1484,7 +1485,8 @@ For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe` (note that these all end in "e"), the *env* parameter must be a mapping - which is used to define the environment variables for the new process; the + which is used to define the environment variables for the new process (they are + used instead of the current process' environment); the functions :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause the new process to inherit the environment of the current process. Modified: python/branches/py3k/Doc/library/shutil.rst ============================================================================== --- python/branches/py3k/Doc/library/shutil.rst (original) +++ python/branches/py3k/Doc/library/shutil.rst Sun Apr 20 23:01:16 2008 @@ -28,15 +28,6 @@ are not copied. -.. function:: copyfile(src, dst) - - Copy the contents (no metadata) of the file named *src* to a file named *dst*. - The destination location must be writable; otherwise, an :exc:`IOError` exception - will be raised. If *dst* already exists, it will be replaced. Special files - such as character or block devices and pipes cannot be copied with this - function. *src* and *dst* are path names given as strings. - - .. function:: copyfileobj(fsrc, fdst[, length]) Copy the contents of the file-like object *fsrc* to the file-like object *fdst*. @@ -48,6 +39,17 @@ be copied. +.. function:: copyfile(src, dst) + + Copy the contents (no metadata) of the file named *src* to a file named *dst*. + *dst* must be the complete target file name; look at :func:`copy` for a copy that + accepts a target directory path. + The destination location must be writable; otherwise, an :exc:`IOError` exception + will be raised. If *dst* already exists, it will be replaced. Special files + such as character or block devices and pipes cannot be copied with this + function. *src* and *dst* are path names given as strings. + + .. function:: copymode(src, dst) Copy the permission bits from *src* to *dst*. The file contents, owner, and Modified: python/branches/py3k/Doc/library/subprocess.rst ============================================================================== --- python/branches/py3k/Doc/library/subprocess.rst (original) +++ python/branches/py3k/Doc/library/subprocess.rst Sun Apr 20 23:01:16 2008 @@ -89,8 +89,9 @@ searching the executable, so you can't specify the program's path relative to *cwd*. - If *env* is not ``None``, it defines the environment variables for the new - process. + If *env* is not ``None``, it must be a mapping that defines the environment + variables for the new process; these are used instead of inheriting the current + process' environment, which is the default behavior. If *universal_newlines* is :const:`True`, the file objects stdout and stderr are opened as text files, but lines may be terminated by any of ``'\n'``, the Unix @@ -202,6 +203,35 @@ size is large or unlimited. +.. method:: Popen.send_signal(signal) + + Sends the signal *signal* to the child. + + .. note:: + + On Windows only SIGTERM is supported so far. It's an alias for + :meth:`terminate`. + + .. versionadded:: 2.6 + + +.. method:: Popen.terminate() + + Stop the child. On Posix OSs the method sends SIGTERM to the + child. On Windows the Win32 API function TerminateProcess is called + to stop the child. + + .. versionadded:: 2.6 + + +.. method:: Popen.kill() + + Kills the child. On Posix OSs the function sends SIGKILL to the child. + On Windows :meth:`kill` is an alias for :meth:`terminate`. + + .. versionadded:: 2.6 + + The following attributes are also available: .. attribute:: Popen.stdin Modified: python/branches/py3k/Doc/tools/sphinxext/indexcontent.html ============================================================================== --- python/branches/py3k/Doc/tools/sphinxext/indexcontent.html (original) +++ python/branches/py3k/Doc/tools/sphinxext/indexcontent.html Sun Apr 20 23:01:16 2008 @@ -1,3 +1,5 @@ +{% extends "defindex.html" %} +{% block tables %}

Parts of the documentation:

@@ -54,3 +56,4 @@
+{% endblock %} Modified: python/branches/py3k/Doc/whatsnew/2.6.rst ============================================================================== --- python/branches/py3k/Doc/whatsnew/2.6.rst (original) +++ python/branches/py3k/Doc/whatsnew/2.6.rst Sun Apr 20 23:01:16 2008 @@ -1292,11 +1292,42 @@ :func:`isnan`, return true if their floating-point argument is infinite or Not A Number. (:issue:`1640`) - The ``math.copysign(x, y)`` function - copies the sign bit of an IEEE 754 number, returning the absolute - value of *x* combined with the sign bit of *y*. For example, - ``math.copysign(1, -0.0)`` returns -1.0. (Contributed by Christian - Heimes.) +* The :mod:`math` module has seven new functions, and the existing + functions have been improved to give more consistent behaviour + across platforms, especially with respect to handling of + floating-point exceptions and IEEE 754 special values. + The new functions are: + + * :func:`isinf` and :func:`isnan` determine whether a given float is + a (positive or negative) infinity or a NaN (Not a Number), + respectively. + + * ``copysign(x, y)`` copies the sign bit of an IEEE 754 number, + returning the absolute value of *x* combined with the sign bit of + *y*. For example, ``math.copysign(1, -0.0)`` returns -1.0. + (Contributed by Christian Heimes.) + + * The inverse hyperbolic functions :func:`acosh`, :func:`asinh` and + :func:`atanh`. + + * The function :func:`log1p`, returning the natural logarithm of + *1+x* (base *e*). + + There's also a new :func:`trunc` function as a result of the + backport of `PEP 3141's type hierarchy for numbers <#pep-3141>`__. + + The existing math functions have been modified to follow the + recommendations of the C99 standard with respect to special values + whenever possible. For example, ``sqrt(-1.)`` should now give a + :exc:`ValueError` across (nearly) all platforms, while + ``sqrt(float('NaN'))`` should return a NaN on all IEEE 754 + platforms. Where Annex 'F' of the C99 standard recommends signaling + 'divide-by-zero' or 'invalid', Python will raise :exc:`ValueError`. + Where Annex 'F' of the C99 standard recommends signaling 'overflow', + Python will raise :exc:`OverflowError`. (See :issue:`711019`, + :issue:`1640`.) + + (Contributed by Christian Heimes and Mark Dickinson.) * Changes to the :class:`Exception` interface as dictated by :pep:`352` continue to be made. For 2.6, @@ -1415,6 +1446,40 @@ available, instead of restricting itself to protocol 1. (Contributed by W. Barnes; :issue:`1551443`.) +* The :mod:`cmath` module underwent an extensive set of revisions, + thanks to Mark Dickinson and Christian Heimes, that added some new + features and greatly improved the accuracy of the computations. + + Five new functions were added: + + * :func:`polar` converts a complex number to polar form, returning + the modulus and argument of that complex number. + + * :func:`rect` does the opposite, turning a (modulus, argument) pair + back into the corresponding complex number. + + * :func:`phase` returns the phase or argument of a complex number. + + * :func:`isnan` returns True if either + the real or imaginary part of its argument is a NaN. + + * :func:`isinf` returns True if either the real or imaginary part of + its argument is infinite. + + The revisions also improved the numerical soundness of the + :mod:`cmath` module. For all functions, the real and imaginary + parts of the results are accurate to within a few units of least + precision (ulps) whenever possible. See :issue:`1381` for the + details. The branch cuts for :func:`asinh`, :func:`atanh`: and + :func:`atan` have also been corrected. + + The tests for the module have been greatly expanded; nearly 2000 new + test cases exercise the algebraic functions. + + On IEEE 754 platforms, the :mod:`cmath` module now handles IEEE 754 + special values and floating-point exceptions in a manner consistent + with Annex 'G' of the C99 standard. + * A new data type in the :mod:`collections` module: :class:`namedtuple(typename, fieldnames)` is a factory function that creates subclasses of the standard tuple whose fields are accessible by name as well as index. For example:: Modified: python/branches/py3k/Lib/subprocess.py ============================================================================== --- python/branches/py3k/Lib/subprocess.py (original) +++ python/branches/py3k/Lib/subprocess.py Sun Apr 20 23:01:16 2008 @@ -290,6 +290,7 @@ import os import traceback import gc +import signal # Exception classes used by this module. class CalledProcessError(Exception): @@ -317,6 +318,7 @@ from win32process import CreateProcess, STARTUPINFO, \ GetExitCodeProcess, STARTF_USESTDHANDLES, \ STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE + from win32process import TerminateProcess from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0 else: from _subprocess import * @@ -828,6 +830,21 @@ self.wait() return (stdout, stderr) + def send_signal(self, sig): + """Send a signal to the process + """ + if sig == signal.SIGTERM: + self.terminate() + else: + raise ValueError("Only SIGTERM is supported on Windows") + + def terminate(self): + """Terminates the process + """ + TerminateProcess(self._handle, 1) + + kill = terminate + else: # # POSIX methods @@ -1115,6 +1132,21 @@ self.wait() return (stdout, stderr) + def send_signal(self, sig): + """Send a signal to the process + """ + os.kill(self.pid, sig) + + def terminate(self): + """Terminate the process with SIGTERM + """ + self.send_signal(signal.SIGTERM) + + def kill(self): + """Kill the process with SIGKILL + """ + self.send_signal(signal.SIGKILL) + def _demo_posix(): # Modified: python/branches/py3k/Lib/test/test_math.py ============================================================================== --- python/branches/py3k/Lib/test/test_math.py (original) +++ python/branches/py3k/Lib/test/test_math.py Sun Apr 20 23:01:16 2008 @@ -102,7 +102,7 @@ self.ftest('atan(0)', math.atan(0), 0) self.ftest('atan(1)', math.atan(1), math.pi/4) self.ftest('atan(inf)', math.atan(INF), math.pi/2) - self.ftest('atan(-inf)', math.atan(-INF), -math.pi/2) + self.ftest('atan(-inf)', math.atan(NINF), -math.pi/2) self.assert_(math.isnan(math.atan(NAN))) def testAtanh(self): @@ -383,14 +383,140 @@ self.assert_(math.isnan(math.pow(2, NAN))) self.assert_(math.isnan(math.pow(0, NAN))) self.assertEqual(math.pow(1, NAN), 1) - self.assertEqual(1**NAN, 1) - self.assertEqual(1**INF, 1) - self.assertEqual(1**NINF, 1) - self.assertEqual(1**0, 1) - self.assertEqual(1.**NAN, 1) - self.assertEqual(1.**INF, 1) - self.assertEqual(1.**NINF, 1) - self.assertEqual(1.**0, 1) + + # pow(0., x) + self.assertEqual(math.pow(0., INF), 0.) + self.assertEqual(math.pow(0., 3.), 0.) + self.assertEqual(math.pow(0., 2.3), 0.) + self.assertEqual(math.pow(0., 2.), 0.) + self.assertEqual(math.pow(0., 0.), 1.) + self.assertEqual(math.pow(0., -0.), 1.) + self.assertRaises(ValueError, math.pow, 0., -2.) + self.assertRaises(ValueError, math.pow, 0., -2.3) + self.assertRaises(ValueError, math.pow, 0., -3.) + self.assertRaises(ValueError, math.pow, 0., NINF) + self.assert_(math.isnan(math.pow(0., NAN))) + + # pow(INF, x) + self.assertEqual(math.pow(INF, INF), INF) + self.assertEqual(math.pow(INF, 3.), INF) + self.assertEqual(math.pow(INF, 2.3), INF) + self.assertEqual(math.pow(INF, 2.), INF) + self.assertEqual(math.pow(INF, 0.), 1.) + self.assertEqual(math.pow(INF, -0.), 1.) + self.assertEqual(math.pow(INF, -2.), 0.) + self.assertEqual(math.pow(INF, -2.3), 0.) + self.assertEqual(math.pow(INF, -3.), 0.) + self.assertEqual(math.pow(INF, NINF), 0.) + self.assert_(math.isnan(math.pow(INF, NAN))) + + # pow(-0., x) + self.assertEqual(math.pow(-0., INF), 0.) + self.assertEqual(math.pow(-0., 3.), -0.) + self.assertEqual(math.pow(-0., 2.3), 0.) + self.assertEqual(math.pow(-0., 2.), 0.) + self.assertEqual(math.pow(-0., 0.), 1.) + self.assertEqual(math.pow(-0., -0.), 1.) + self.assertRaises(ValueError, math.pow, -0., -2.) + self.assertRaises(ValueError, math.pow, -0., -2.3) + self.assertRaises(ValueError, math.pow, -0., -3.) + self.assertRaises(ValueError, math.pow, -0., NINF) + self.assert_(math.isnan(math.pow(-0., NAN))) + + # pow(NINF, x) + self.assertEqual(math.pow(NINF, INF), INF) + self.assertEqual(math.pow(NINF, 3.), NINF) + self.assertEqual(math.pow(NINF, 2.3), INF) + self.assertEqual(math.pow(NINF, 2.), INF) + self.assertEqual(math.pow(NINF, 0.), 1.) + self.assertEqual(math.pow(NINF, -0.), 1.) + self.assertEqual(math.pow(NINF, -2.), 0.) + self.assertEqual(math.pow(NINF, -2.3), 0.) + self.assertEqual(math.pow(NINF, -3.), -0.) + self.assertEqual(math.pow(NINF, NINF), 0.) + self.assert_(math.isnan(math.pow(NINF, NAN))) + + # pow(-1, x) + self.assertEqual(math.pow(-1., INF), 1.) + self.assertEqual(math.pow(-1., 3.), -1.) + self.assertRaises(ValueError, math.pow, -1., 2.3) + self.assertEqual(math.pow(-1., 2.), 1.) + self.assertEqual(math.pow(-1., 0.), 1.) + self.assertEqual(math.pow(-1., -0.), 1.) + self.assertEqual(math.pow(-1., -2.), 1.) + self.assertRaises(ValueError, math.pow, -1., -2.3) + self.assertEqual(math.pow(-1., -3.), -1.) + self.assertEqual(math.pow(-1., NINF), 1.) + self.assert_(math.isnan(math.pow(-1., NAN))) + + # pow(1, x) + self.assertEqual(math.pow(1., INF), 1.) + self.assertEqual(math.pow(1., 3.), 1.) + self.assertEqual(math.pow(1., 2.3), 1.) + self.assertEqual(math.pow(1., 2.), 1.) + self.assertEqual(math.pow(1., 0.), 1.) + self.assertEqual(math.pow(1., -0.), 1.) + self.assertEqual(math.pow(1., -2.), 1.) + self.assertEqual(math.pow(1., -2.3), 1.) + self.assertEqual(math.pow(1., -3.), 1.) + self.assertEqual(math.pow(1., NINF), 1.) + self.assertEqual(math.pow(1., NAN), 1.) + + # pow(x, 0) should be 1 for any x + self.assertEqual(math.pow(2.3, 0.), 1.) + self.assertEqual(math.pow(-2.3, 0.), 1.) + self.assertEqual(math.pow(NAN, 0.), 1.) + self.assertEqual(math.pow(2.3, -0.), 1.) + self.assertEqual(math.pow(-2.3, -0.), 1.) + self.assertEqual(math.pow(NAN, -0.), 1.) + + # pow(x, y) is invalid if x is negative and y is not integral + self.assertRaises(ValueError, math.pow, -1., 2.3) + self.assertRaises(ValueError, math.pow, -15., -3.1) + + # pow(x, NINF) + self.assertEqual(math.pow(1.9, NINF), 0.) + self.assertEqual(math.pow(1.1, NINF), 0.) + self.assertEqual(math.pow(0.9, NINF), INF) + self.assertEqual(math.pow(0.1, NINF), INF) + self.assertEqual(math.pow(-0.1, NINF), INF) + self.assertEqual(math.pow(-0.9, NINF), INF) + self.assertEqual(math.pow(-1.1, NINF), 0.) + self.assertEqual(math.pow(-1.9, NINF), 0.) + + # pow(x, INF) + self.assertEqual(math.pow(1.9, INF), INF) + self.assertEqual(math.pow(1.1, INF), INF) + self.assertEqual(math.pow(0.9, INF), 0.) + self.assertEqual(math.pow(0.1, INF), 0.) + self.assertEqual(math.pow(-0.1, INF), 0.) + self.assertEqual(math.pow(-0.9, INF), 0.) + self.assertEqual(math.pow(-1.1, INF), INF) + self.assertEqual(math.pow(-1.9, INF), INF) + + # pow(x, y) should work for x negative, y an integer + self.ftest('(-2.)**3.', math.pow(-2.0, 3.0), -8.0) + self.ftest('(-2.)**2.', math.pow(-2.0, 2.0), 4.0) + self.ftest('(-2.)**1.', math.pow(-2.0, 1.0), -2.0) + self.ftest('(-2.)**0.', math.pow(-2.0, 0.0), 1.0) + self.ftest('(-2.)**-0.', math.pow(-2.0, -0.0), 1.0) + self.ftest('(-2.)**-1.', math.pow(-2.0, -1.0), -0.5) + self.ftest('(-2.)**-2.', math.pow(-2.0, -2.0), 0.25) + self.ftest('(-2.)**-3.', math.pow(-2.0, -3.0), -0.125) + self.assertRaises(ValueError, math.pow, -2.0, -0.5) + self.assertRaises(ValueError, math.pow, -2.0, 0.5) + + # the following tests have been commented out since they don't + # really belong here: the implementation of ** for floats is + # independent of the implemention of math.pow + #self.assertEqual(1**NAN, 1) + #self.assertEqual(1**INF, 1) + #self.assertEqual(1**NINF, 1) + #self.assertEqual(1**0, 1) + #self.assertEqual(1.**NAN, 1) + #self.assertEqual(1.**INF, 1) + #self.assertEqual(1.**NINF, 1) + #self.assertEqual(1.**0, 1) def testRadians(self): self.assertRaises(TypeError, math.radians) @@ -417,7 +543,7 @@ self.ftest('sinh(1)**2-cosh(1)**2', math.sinh(1)**2-math.cosh(1)**2, -1) self.ftest('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0) self.assertEquals(math.sinh(INF), INF) - self.assertEquals(math.sinh(-INF), -INF) + self.assertEquals(math.sinh(NINF), NINF) self.assert_(math.isnan(math.sinh(NAN))) def testSqrt(self): @@ -555,7 +681,12 @@ # no real versions of rect, polar continue func = getattr(math, fn) - result = func(ar) + try: + result = func(ar) + except ValueError: + message = ("Unexpected ValueError in " + + "test %s:%s(%r)\n" % (id, fn, ar)) + self.fail(message) self.ftest("%s:%s(%r)" % (id, fn, ar), result, er) def test_main(): Modified: python/branches/py3k/Lib/test/test_subprocess.py ============================================================================== --- python/branches/py3k/Lib/test/test_subprocess.py (original) +++ python/branches/py3k/Lib/test/test_subprocess.py Sun Apr 20 23:01:16 2008 @@ -584,6 +584,29 @@ os.remove(fname) self.assertEqual(rc, 47) + def test_send_signal(self): + p = subprocess.Popen([sys.executable, + "-c", "input()"]) + + self.assert_(p.poll() is None, p.poll()) + p.send_signal(signal.SIGINT) + self.assertNotEqual(p.wait(), 0) + + def test_kill(self): + p = subprocess.Popen([sys.executable, + "-c", "input()"]) + + self.assert_(p.poll() is None, p.poll()) + p.kill() + self.assertEqual(p.wait(), -signal.SIGKILL) + + def test_terminate(self): + p = subprocess.Popen([sys.executable, + "-c", "input()"]) + + self.assert_(p.poll() is None, p.poll()) + p.terminate() + self.assertEqual(p.wait(), -signal.SIGTERM) # # Windows tests @@ -655,6 +678,29 @@ ' -c "import sys; sys.exit(47)"') self.assertEqual(rc, 47) + def test_send_signal(self): + p = subprocess.Popen([sys.executable, + "-c", "input()"]) + + self.assert_(p.poll() is None, p.poll()) + p.send_signal(signal.SIGTERM) + self.assertNotEqual(p.wait(), 0) + + def test_kill(self): + p = subprocess.Popen([sys.executable, + "-c", "input()"]) + + self.assert_(p.poll() is None, p.poll()) + p.kill() + self.assertNotEqual(p.wait(), 0) + + def test_terminate(self): + p = subprocess.Popen([sys.executable, + "-c", "input()"]) + + self.assert_(p.poll() is None, p.poll()) + p.terminate() + self.assertNotEqual(p.wait(), 0) def test_main(): test_support.run_unittest(ProcessTestCase) Modified: python/branches/py3k/Modules/cmathmodule.c ============================================================================== --- python/branches/py3k/Modules/cmathmodule.c (original) +++ python/branches/py3k/Modules/cmathmodule.c Sun Apr 20 23:01:16 2008 @@ -107,16 +107,8 @@ #define P14 0.25*Py_MATH_PI #define P12 0.5*Py_MATH_PI #define P34 0.75*Py_MATH_PI -#ifdef MS_WINDOWS -/* On Windows HUGE_VAL is an extern variable and not a constant. Since the - special value arrays need a constant we have to roll our own infinity - and nan. */ -# define INF (DBL_MAX*DBL_MAX) -# define N (INF*0.) -#else -# define INF Py_HUGE_VAL -# define N Py_NAN -#endif /* MS_WINDOWS */ +#define INF Py_HUGE_VAL +#define N Py_NAN #define U -9.5426319407711027e33 /* unlikely value, used as placeholder */ /* First, the C functions that do the real work. Each of the c_* @@ -128,15 +120,7 @@ raised. */ -static Py_complex acos_special_values[7][7] = { - {{P34,INF},{P,INF}, {P,INF}, {P,-INF}, {P,-INF}, {P34,-INF},{N,INF}}, - {{P12,INF},{U,U}, {U,U}, {U,U}, {U,U}, {P12,-INF},{N,N}}, - {{P12,INF},{U,U}, {P12,0.},{P12,-0.},{U,U}, {P12,-INF},{P12,N}}, - {{P12,INF},{U,U}, {P12,0.},{P12,-0.},{U,U}, {P12,-INF},{P12,N}}, - {{P12,INF},{U,U}, {U,U}, {U,U}, {U,U}, {P12,-INF},{N,N}}, - {{P14,INF},{0.,INF},{0.,INF},{0.,-INF},{0.,-INF},{P14,-INF},{N,INF}}, - {{N,INF}, {N,N}, {N,N}, {N,N}, {N,N}, {N,-INF}, {N,N}} -}; +static Py_complex acos_special_values[7][7]; static Py_complex c_acos(Py_complex z) @@ -177,15 +161,7 @@ "Return the arc cosine of x."); -static Py_complex acosh_special_values[7][7] = { - {{INF,-P34},{INF,-P}, {INF,-P}, {INF,P}, {INF,P}, {INF,P34},{INF,N}}, - {{INF,-P12},{U,U}, {U,U}, {U,U}, {U,U}, {INF,P12},{N,N}}, - {{INF,-P12},{U,U}, {0.,-P12},{0.,P12},{U,U}, {INF,P12},{N,N}}, - {{INF,-P12},{U,U}, {0.,-P12},{0.,P12},{U,U}, {INF,P12},{N,N}}, - {{INF,-P12},{U,U}, {U,U}, {U,U}, {U,U}, {INF,P12},{N,N}}, - {{INF,-P14},{INF,-0.},{INF,-0.},{INF,0.},{INF,0.},{INF,P14},{INF,N}}, - {{INF,N}, {N,N}, {N,N}, {N,N}, {N,N}, {INF,N}, {N,N}} -}; +static Py_complex acosh_special_values[7][7]; static Py_complex c_acosh(Py_complex z) @@ -237,15 +213,7 @@ "Return the arc sine of x."); -static Py_complex asinh_special_values[7][7] = { - {{-INF,-P14},{-INF,-0.},{-INF,-0.},{-INF,0.},{-INF,0.},{-INF,P14},{-INF,N}}, - {{-INF,-P12},{U,U}, {U,U}, {U,U}, {U,U}, {-INF,P12},{N,N}}, - {{-INF,-P12},{U,U}, {-0.,-0.}, {-0.,0.}, {U,U}, {-INF,P12},{N,N}}, - {{INF,-P12}, {U,U}, {0.,-0.}, {0.,0.}, {U,U}, {INF,P12}, {N,N}}, - {{INF,-P12}, {U,U}, {U,U}, {U,U}, {U,U}, {INF,P12}, {N,N}}, - {{INF,-P14}, {INF,-0.}, {INF,-0.}, {INF,0.}, {INF,0.}, {INF,P14}, {INF,N}}, - {{INF,N}, {N,N}, {N,-0.}, {N,0.}, {N,N}, {INF,N}, {N,N}} -}; +static Py_complex asinh_special_values[7][7]; static Py_complex c_asinh(Py_complex z) @@ -323,15 +291,7 @@ "Return the arc tangent of x."); -static Py_complex atanh_special_values[7][7] = { - {{-0.,-P12},{-0.,-P12},{-0.,-P12},{-0.,P12},{-0.,P12},{-0.,P12},{-0.,N}}, - {{-0.,-P12},{U,U}, {U,U}, {U,U}, {U,U}, {-0.,P12},{N,N}}, - {{-0.,-P12},{U,U}, {-0.,-0.}, {-0.,0.}, {U,U}, {-0.,P12},{-0.,N}}, - {{0.,-P12}, {U,U}, {0.,-0.}, {0.,0.}, {U,U}, {0.,P12}, {0.,N}}, - {{0.,-P12}, {U,U}, {U,U}, {U,U}, {U,U}, {0.,P12}, {N,N}}, - {{0.,-P12}, {0.,-P12}, {0.,-P12}, {0.,P12}, {0.,P12}, {0.,P12}, {0.,N}}, - {{0.,-P12}, {N,N}, {N,N}, {N,N}, {N,N}, {0.,P12}, {N,N}} -}; +static Py_complex atanh_special_values[7][7]; static Py_complex c_atanh(Py_complex z) @@ -404,15 +364,7 @@ /* cosh(infinity + i*y) needs to be dealt with specially */ -static Py_complex cosh_special_values[7][7] = { - {{INF,N},{U,U},{INF,0.}, {INF,-0.},{U,U},{INF,N},{INF,N}}, - {{N,N}, {U,U},{U,U}, {U,U}, {U,U},{N,N}, {N,N}}, - {{N,0.}, {U,U},{1.,0.}, {1.,-0.}, {U,U},{N,0.}, {N,0.}}, - {{N,0.}, {U,U},{1.,-0.}, {1.,0.}, {U,U},{N,0.}, {N,0.}}, - {{N,N}, {U,U},{U,U}, {U,U}, {U,U},{N,N}, {N,N}}, - {{INF,N},{U,U},{INF,-0.},{INF,0.}, {U,U},{INF,N},{INF,N}}, - {{N,N}, {N,N},{N,0.}, {N,0.}, {N,N},{N,N}, {N,N}} -}; +static Py_complex cosh_special_values[7][7]; static Py_complex c_cosh(Py_complex z) @@ -472,15 +424,7 @@ /* exp(infinity + i*y) and exp(-infinity + i*y) need special treatment for finite y */ -static Py_complex exp_special_values[7][7] = { - {{0.,0.},{U,U},{0.,-0.}, {0.,0.}, {U,U},{0.,0.},{0.,0.}}, - {{N,N}, {U,U},{U,U}, {U,U}, {U,U},{N,N}, {N,N}}, - {{N,N}, {U,U},{1.,-0.}, {1.,0.}, {U,U},{N,N}, {N,N}}, - {{N,N}, {U,U},{1.,-0.}, {1.,0.}, {U,U},{N,N}, {N,N}}, - {{N,N}, {U,U},{U,U}, {U,U}, {U,U},{N,N}, {N,N}}, - {{INF,N},{U,U},{INF,-0.},{INF,0.},{U,U},{INF,N},{INF,N}}, - {{N,N}, {N,N},{N,-0.}, {N,0.}, {N,N},{N,N}, {N,N}} -}; +static Py_complex exp_special_values[7][7]; static Py_complex c_exp(Py_complex z) @@ -538,15 +482,7 @@ "Return the exponential value e**x."); -static Py_complex log_special_values[7][7] = { - {{INF,-P34},{INF,-P}, {INF,-P}, {INF,P}, {INF,P}, {INF,P34}, {INF,N}}, - {{INF,-P12},{U,U}, {U,U}, {U,U}, {U,U}, {INF,P12}, {N,N}}, - {{INF,-P12},{U,U}, {-INF,-P}, {-INF,P}, {U,U}, {INF,P12}, {N,N}}, - {{INF,-P12},{U,U}, {-INF,-0.},{-INF,0.},{U,U}, {INF,P12}, {N,N}}, - {{INF,-P12},{U,U}, {U,U}, {U,U}, {U,U}, {INF,P12}, {N,N}}, - {{INF,-P14},{INF,-0.},{INF,-0.}, {INF,0.}, {INF,0.},{INF,P14}, {INF,N}}, - {{INF,N}, {N,N}, {N,N}, {N,N}, {N,N}, {INF,N}, {N,N}} -}; +static Py_complex log_special_values[7][7]; static Py_complex c_log(Py_complex z) @@ -658,15 +594,7 @@ /* sinh(infinity + i*y) needs to be dealt with specially */ -static Py_complex sinh_special_values[7][7] = { - {{INF,N},{U,U},{-INF,-0.},{-INF,0.},{U,U},{INF,N},{INF,N}}, - {{N,N}, {U,U},{U,U}, {U,U}, {U,U},{N,N}, {N,N}}, - {{0.,N}, {U,U},{-0.,-0.}, {-0.,0.}, {U,U},{0.,N}, {0.,N}}, - {{0.,N}, {U,U},{0.,-0.}, {0.,0.}, {U,U},{0.,N}, {0.,N}}, - {{N,N}, {U,U},{U,U}, {U,U}, {U,U},{N,N}, {N,N}}, - {{INF,N},{U,U},{INF,-0.}, {INF,0.}, {U,U},{INF,N},{INF,N}}, - {{N,N}, {N,N},{N,-0.}, {N,0.}, {N,N},{N,N}, {N,N}} -}; +static Py_complex sinh_special_values[7][7]; static Py_complex c_sinh(Py_complex z) @@ -723,15 +651,7 @@ "Return the hyperbolic sine of x."); -static Py_complex sqrt_special_values[7][7] = { - {{INF,-INF},{0.,-INF},{0.,-INF},{0.,INF},{0.,INF},{INF,INF},{N,INF}}, - {{INF,-INF},{U,U}, {U,U}, {U,U}, {U,U}, {INF,INF},{N,N}}, - {{INF,-INF},{U,U}, {0.,-0.}, {0.,0.}, {U,U}, {INF,INF},{N,N}}, - {{INF,-INF},{U,U}, {0.,-0.}, {0.,0.}, {U,U}, {INF,INF},{N,N}}, - {{INF,-INF},{U,U}, {U,U}, {U,U}, {U,U}, {INF,INF},{N,N}}, - {{INF,-INF},{INF,-0.},{INF,-0.},{INF,0.},{INF,0.},{INF,INF},{INF,N}}, - {{INF,-INF},{N,N}, {N,N}, {N,N}, {N,N}, {INF,INF},{N,N}} -}; +static Py_complex sqrt_special_values[7][7]; static Py_complex c_sqrt(Py_complex z) @@ -826,15 +746,7 @@ /* tanh(infinity + i*y) needs to be dealt with specially */ -static Py_complex tanh_special_values[7][7] = { - {{-1.,0.},{U,U},{-1.,-0.},{-1.,0.},{U,U},{-1.,0.},{-1.,0.}}, - {{N,N}, {U,U},{U,U}, {U,U}, {U,U},{N,N}, {N,N}}, - {{N,N}, {U,U},{-0.,-0.},{-0.,0.},{U,U},{N,N}, {N,N}}, - {{N,N}, {U,U},{0.,-0.}, {0.,0.}, {U,U},{N,N}, {N,N}}, - {{N,N}, {U,U},{U,U}, {U,U}, {U,U},{N,N}, {N,N}}, - {{1.,0.}, {U,U},{1.,-0.}, {1.,0.}, {U,U},{1.,0.}, {1.,0.}}, - {{N,N}, {N,N},{N,-0.}, {N,0.}, {N,N},{N,N}, {N,N}} -}; +static Py_complex tanh_special_values[7][7]; static Py_complex c_tanh(Py_complex z) @@ -1043,15 +955,7 @@ */ -static Py_complex rect_special_values[7][7] = { - {{INF,N},{U,U},{-INF,0.},{-INF,-0.},{U,U},{INF,N},{INF,N}}, - {{N,N}, {U,U},{U,U}, {U,U}, {U,U},{N,N}, {N,N}}, - {{0.,0.},{U,U},{-0.,0.}, {-0.,-0.}, {U,U},{0.,0.},{0.,0.}}, - {{0.,0.},{U,U},{0.,-0.}, {0.,0.}, {U,U},{0.,0.},{0.,0.}}, - {{N,N}, {U,U},{U,U}, {U,U}, {U,U},{N,N}, {N,N}}, - {{INF,N},{U,U},{INF,-0.},{INF,0.}, {U,U},{INF,N},{INF,N}}, - {{N,N}, {N,N},{N,0.}, {N,0.}, {N,N},{N,N}, {N,N}} -}; +static Py_complex rect_special_values[7][7]; static PyObject * cmath_rect(PyObject *self, PyObject *args) @@ -1176,4 +1080,119 @@ PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI)); PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E)); + + /* initialize special value tables */ + +#define INIT_SPECIAL_VALUES(NAME, BODY) { Py_complex* p = (Py_complex*)NAME; BODY } +#define C(REAL, IMAG) p->real = REAL; p->imag = IMAG; ++p; + + INIT_SPECIAL_VALUES(acos_special_values, { + C(P34,INF) C(P,INF) C(P,INF) C(P,-INF) C(P,-INF) C(P34,-INF) C(N,INF) + C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N) + C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N) + C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N) + C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N) + C(P14,INF) C(0.,INF) C(0.,INF) C(0.,-INF) C(0.,-INF) C(P14,-INF) C(N,INF) + C(N,INF) C(N,N) C(N,N) C(N,N) C(N,N) C(N,-INF) C(N,N) + }) + + INIT_SPECIAL_VALUES(acosh_special_values, { + C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) + C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(asinh_special_values, { + C(-INF,-P14) C(-INF,-0.) C(-INF,-0.) C(-INF,0.) C(-INF,0.) C(-INF,P14) C(-INF,N) + C(-INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-INF,P12) C(N,N) + C(-INF,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) + C(INF,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(INF,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(atanh_special_values, { + C(-0.,-P12) C(-0.,-P12) C(-0.,-P12) C(-0.,P12) C(-0.,P12) C(-0.,P12) C(-0.,N) + C(-0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-0.,P12) C(N,N) + C(-0.,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-0.,P12) C(-0.,N) + C(0.,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,P12) C(0.,N) + C(0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(0.,P12) C(N,N) + C(0.,-P12) C(0.,-P12) C(0.,-P12) C(0.,P12) C(0.,P12) C(0.,P12) C(0.,N) + C(0.,-P12) C(N,N) C(N,N) C(N,N) C(N,N) C(0.,P12) C(N,N) + }) + + INIT_SPECIAL_VALUES(cosh_special_values, { + C(INF,N) C(U,U) C(INF,0.) C(INF,-0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(N,0.) C(U,U) C(1.,0.) C(1.,-0.) C(U,U) C(N,0.) C(N,0.) + C(N,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,0.) C(N,0.) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(exp_special_values, { + C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(log_special_values, { + C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(-INF,-P) C(-INF,P) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) + C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(sinh_special_values, { + C(INF,N) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(0.,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(0.,N) C(0.,N) + C(0.,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,N) C(0.,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(sqrt_special_values, { + C(INF,-INF) C(0.,-INF) C(0.,-INF) C(0.,INF) C(0.,INF) C(INF,INF) C(N,INF) + C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N) + C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N) + C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N) + C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N) + C(INF,-INF) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,INF) C(INF,N) + C(INF,-INF) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,INF) C(N,N) + }) + + INIT_SPECIAL_VALUES(tanh_special_values, { + C(-1.,0.) C(U,U) C(-1.,-0.) C(-1.,0.) C(U,U) C(-1.,0.) C(-1.,0.) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(1.,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(1.,0.) C(1.,0.) + C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(rect_special_values, { + C(INF,N) C(U,U) C(-INF,0.) C(-INF,-0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(0.,0.) C(U,U) C(-0.,0.) C(-0.,-0.) C(U,U) C(0.,0.) C(0.,0.) + C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) } Modified: python/branches/py3k/Modules/mathmodule.c ============================================================================== --- python/branches/py3k/Modules/mathmodule.c (original) +++ python/branches/py3k/Modules/mathmodule.c Sun Apr 20 23:01:16 2008 @@ -414,6 +414,15 @@ double y, x = PyFloat_AsDouble(arg); if (x == -1.0 && PyErr_Occurred()) return NULL; + /* some platforms don't do the right thing for NaNs and + infinities, so we take care of special cases directly. */ + if (!Py_IS_FINITE(x)) { + if (Py_IS_INFINITY(x)) + return Py_BuildValue("(dd)", copysign(0., x), x); + else if (Py_IS_NAN(x)) + return Py_BuildValue("(dd)", x, x); + } + errno = 0; PyFPE_START_PROTECT("in math_modf", return 0); x = modf(x, &y); @@ -586,6 +595,7 @@ { PyObject *ox, *oy; double r, x, y; + int odd_y; if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy)) return NULL; @@ -593,37 +603,62 @@ y = PyFloat_AsDouble(oy); if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) return NULL; - /* 1**x and x**0 return 1., even if x is a NaN or infinity. */ - if (x == 1.0 || y == 0.0) - return PyFloat_FromDouble(1.); - errno = 0; - PyFPE_START_PROTECT("in math_pow", return 0); - r = pow(x, y); - PyFPE_END_PROTECT(r); - if (Py_IS_NAN(r)) { - if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) - errno = EDOM; - else - errno = 0; - } - /* an infinite result arises either from: - (A) (+/-0.)**negative, - (B) overflow of x**y with both x and y finite (and x nonzero) - (C) (+/-inf)**positive, or - (D) x**inf with |x| > 1, or x**-inf with |x| < 1. - - In case (A) we want ValueError to be raised. In case (B) - OverflowError should be raised. In cases (C) and (D) the infinite - result should be returned. - */ - else if (Py_IS_INFINITY(r)) { - if (x == 0.) - errno = EDOM; - else if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) - errno = ERANGE; - else - errno = 0; + /* deal directly with IEEE specials, to cope with problems on various + platforms whose semantics don't exactly match C99 */ + if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) { + errno = 0; + if (Py_IS_NAN(x)) + r = y == 0. ? 1. : x; /* NaN**0 = 1 */ + else if (Py_IS_NAN(y)) + r = x == 1. ? 1. : y; /* 1**NaN = 1 */ + else if (Py_IS_INFINITY(x)) { + odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0; + if (y > 0.) + r = odd_y ? x : fabs(x); + else if (y == 0.) + r = 1.; + else /* y < 0. */ + r = odd_y ? copysign(0., x) : 0.; + } + else if (Py_IS_INFINITY(y)) { + if (fabs(x) == 1.0) + r = 1.; + else if (y > 0. && fabs(x) > 1.0) + r = y; + else if (y < 0. && fabs(x) < 1.0) { + r = -y; /* result is +inf */ + if (x == 0.) /* 0**-inf: divide-by-zero */ + errno = EDOM; + } + else + r = 0.; + } + } + else { + /* let libm handle finite**finite */ + errno = 0; + PyFPE_START_PROTECT("in math_pow", return 0); + r = pow(x, y); + PyFPE_END_PROTECT(r); + /* a NaN result should arise only from (-ve)**(finite + non-integer); in this case we want to raise ValueError. */ + if (!Py_IS_FINITE(r)) { + if (Py_IS_NAN(r)) { + errno = EDOM; + } + /* + an infinite result here arises either from: + (A) (+/-0.)**negative (-> divide-by-zero) + (B) overflow of x**y with x and y finite + */ + else if (Py_IS_INFINITY(r)) { + if (x == 0.) + errno = EDOM; + else + errno = ERANGE; + } + } } if (errno && is_error(r)) From python-3000-checkins at python.org Mon Apr 21 12:29:46 2008 From: python-3000-checkins at python.org (mark.summerfield) Date: Mon, 21 Apr 2008 12:29:46 +0200 (CEST) Subject: [Python-3000-checkins] r62430 - python/branches/py3k/Doc/library/io.rst Message-ID: <20080421102946.480D11E4002@bag.python.org> Author: mark.summerfield Date: Mon Apr 21 12:29:45 2008 New Revision: 62430 Log: A lot of small detailed revisions to the io module's doc. Modified: python/branches/py3k/Doc/library/io.rst Modified: python/branches/py3k/Doc/library/io.rst ============================================================================== --- python/branches/py3k/Doc/library/io.rst (original) +++ python/branches/py3k/Doc/library/io.rst Mon Apr 21 12:29:45 2008 @@ -18,19 +18,22 @@ Extending :class:`IOBase` is :class:`RawIOBase` which deals simply with the reading and writing of raw bytes to a stream. :class:`FileIO` subclasses -:class:`RawIOBase` to provide an interface to OS files. +:class:`RawIOBase` to provide an interface to files in the machine's +file system. :class:`BufferedIOBase` deals with buffering on a raw byte stream (:class:`RawIOBase`). Its subclasses, :class:`BufferedWriter`, :class:`BufferedReader`, and :class:`BufferedRWPair` buffer streams that are -readable, writable, and both respectively. :class:`BufferedRandom` provides a -buffered interface to random access streams. :class:`BytesIO` is a simple -stream of in-memory bytes. - -Another :class:`IOBase` subclass, :class:`TextIOBase`, deals with the encoding -and decoding of streams into text. :class:`TextIOWrapper`, which extends it, is -a buffered text interface to a buffered raw stream (:class:`BufferedIOBase`). -Finally, :class:`StringIO` is a in-memory stream for text. +readable, writable, and both readable and writable. +:class:`BufferedRandom` provides a buffered interface to random access +streams. :class:`BytesIO` is a simple stream of in-memory bytes. + +Another :class:`IOBase` subclass, :class:`TextIOBase`, deals with +streams whose bytes represent text, and handles encoding and decoding +from and to strings. :class:`TextIOWrapper`, which extends it, is a +buffered text interface to a buffered raw stream +(:class:`BufferedIOBase`). Finally, :class:`StringIO` is an in-memory +stream for text. Argument names are not part of the specification, and only the arguments of :func:`open` are intended to be used as keyword arguments. @@ -51,10 +54,10 @@ :exc:`IOError` is raised. *file* is either a string giving the name (and the path if the file isn't in - the current working directory) of the file to be opened or an integer file - descriptor of the file to be wrapped. (If a file descriptor is given, it is - closed when the returned I/O object is closed, unless *closefd* is set to - ``False``.) + the current working directory) of the file to be opened or a file + descriptor of the file to be opened. (If a file descriptor is given, + for example, from :func:`os.fdopen`, it is closed when the returned + I/O object is closed, unless *closefd* is set to ``False``.) *mode* is an optional string that specifies the mode in which the file is opened. It defaults to ``'r'`` which means open for reading in text mode. @@ -74,8 +77,8 @@ ``'b'`` binary mode ``'t'`` text mode (default) ``'+'`` open a disk file for updating (reading and writing) - ``'U'`` universal newline mode (for backwards compatibility; unneeded - for new code) + ``'U'`` universal newline mode (for backwards compatibility; should + not be used in new code) ========= =============================================================== The default mode is ``'rt'`` (open for reading text). For binary random @@ -84,9 +87,9 @@ Python distinguishes between files opened in binary and text modes, even when the underlying operating system doesn't. Files opened in binary mode - (appending ``'b'`` to the *mode* argument) return contents as ``bytes`` + (including ``'b'`` in the *mode* argument) return contents as ``bytes`` objects without any decoding. In text mode (the default, or when ``'t'`` is - appended to the *mode* argument), the contents of the file are returned as + included in the *mode* argument), the contents of the file are returned as strings, the bytes having been first decoded using a platform-dependent encoding or using the specified *encoding* if given. @@ -97,7 +100,7 @@ *encoding* is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform - dependent, but any encoding supported by Python can be passed. See the + dependent, but any encoding supported by Python can be used. See the :mod:`codecs` module for the list of supported encodings. *errors* is an optional string that specifies how encoding and decoding @@ -129,23 +132,24 @@ the other legal values, any ``'\n'`` characters written are translated to the given string. - If *closefd* is ``False``, the underlying file descriptor will be kept open - when the file is closed. This does not work when a file name is given and - must be ``True`` in that case. - - :func:`open` returns a file object whose type depends on the mode, and - through which the standard file operations such as reading and writing are - performed. When :func:`open` is used to open a file in a text mode (``'w'``, - ``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a :class:`TextIOWrapper`. - When used to open a file in a binary mode, the returned class varies: in read - binary mode, it returns a :class:`BufferedReader`; in write binary and append - binary modes, it returns a :class:`BufferedWriter`, and in read/write mode, - it returns a :class:`BufferedRandom`. + If *closefd* is ``False`` and a file descriptor rather than a + filename was given, the underlying file descriptor will be kept open + when the file is closed. If a filename is given *closefd* has no + effect but must be ``True`` (the default). + + The type of file object returned by the :func:`open` function depends + on the mode. When :func:`open` is used to open a file in a text mode + (``'w'``, ``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a + :class:`TextIOWrapper`. When used to open a file in a binary mode, + the returned class varies: in read binary mode, it returns a + :class:`BufferedReader`; in write binary and append binary modes, it + returns a :class:`BufferedWriter`, and in read/write mode, it returns + a :class:`BufferedRandom`. It is also possible to use a string or bytearray as a file for both reading and writing. For strings :class:`StringIO` can be used like a file opened in - a text mode, and for bytes a :class:`BytesIO` can be used like a file opened - in a binary mode. + a text mode, and for bytearrays a :class:`BytesIO` can be used like a + file opened in a binary mode. .. exception:: BlockingIOError @@ -176,9 +180,10 @@ The abstract base class for all I/O classes, acting on streams of bytes. There is no public constructor. - This class provides dummy implementations for many methods that derived - classes can override selectively; the default implementations represent a - file that cannot be read, written or seeked. + This class provides empty abstract implementations for many methods + that derived classes can override selectively; the default + implementations represent a file that cannot be read, written or + seeked. Even though :class:`IOBase` does not declare :meth:`read`, :meth:`readinto`, or :meth:`write` because their signatures will vary, implementations and @@ -188,8 +193,8 @@ The basic type used for binary data read from or written to a file is :class:`bytes`. :class:`bytearray`\s are accepted too, and in some cases - (such as :class:`readinto`) needed. Text I/O classes work with :class:`str` - data. + (such as :class:`readinto`) required. Text I/O classes work with + :class:`str` data. Note that calling any method (even inquiries) on a closed stream is undefined. Implementations may raise :exc:`IOError` in this case. @@ -197,13 +202,14 @@ IOBase (and its subclasses) support the iterator protocol, meaning that an :class:`IOBase` object can be iterated over yielding the lines in a stream. - IOBase also supports the :keyword:`with` statement. In this example, *fp* is - closed after the suite of the with statment is complete:: + IOBase is also a context manager and therefore supports the + :keyword:`with` statement. In this example, *file* is closed after the + :keyword:`with` statement's suite is finished---even if an exception occurs:: - with open('spam.txt', 'r') as fp: - fp.write('Spam and eggs!') + with open('spam.txt', 'w') as file: + file.write('Spam and eggs!') - :class:`IOBase` provides these methods: + :class:`IOBase` provides these data attributes and methods: .. method:: close() @@ -227,17 +233,18 @@ .. method:: isatty() - Tell if a stream is interactive (connected to a terminal/tty device). + Returns ``True`` if the stream is interactive (i.e., connected to + a terminal/tty device). .. method:: readable() - Tell if a stream can be read from. If False, :meth:`read` will raise - :exc:`IOError`. + Returns ``True`` if the stream can be read from. If False, + :meth:`read` will raise :exc:`IOError`. .. method:: readline([limit]) - Read and return a line from the stream. If *limit* is specified, at most - *limit* bytes will be read. + Reads and returns one line from the stream. If *limit* is + specified, at most *limit* bytes will be read. The line terminator is always ``b'\n'`` for binary files; for text files, the *newlines* argument to :func:`open` can be used to select the line @@ -245,45 +252,47 @@ .. method:: readlines([hint]) - Return a list of lines from the stream. *hint* can be specified to + Returns a list of lines from the stream. *hint* can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds *hint*. .. method:: seek(offset[, whence]) - Change the stream position to byte offset *offset*. *offset* is + Change the stream position to the given byte *offset*. *offset* is interpreted relative to the position indicated by *whence*. Values for *whence* are: - * ``0`` -- start of stream (the default); *pos* should be zero or positive - * ``1`` -- current stream position; *pos* may be negative - * ``2`` -- end of stream; *pos* is usually negative + * ``0`` -- start of the stream (the default); *offset* should be zero or positive + * ``1`` -- current stream position; *offset* may be negative + * ``2`` -- end of the stream; *offset* is usually negative - Return the new absolute position. + Returns the new absolute position. .. method:: seekable() - Tell if a stream supports random IO access. If ``False``, :meth:`seek`, - :meth:`tell` and :meth:`truncate` will raise :exc:`IOError`. + Returns ``True`` if the stream supports random access. If + ``False``, :meth:`seek`, :meth:`tell` and :meth:`truncate` will + raise :exc:`IOError`. .. method:: tell() - Return an integer indicating the current stream position. + Returns the current stream position. - .. method:: truncate([pos]) + .. method:: truncate([size]) - Truncate the file to at most *pos* bytes. *pos* defaults to the current + Truncates the file to at most *size* bytes. *size* defaults to the current file position, as returned by :meth:`tell`. .. method:: writable() - Tell if a stream supports writing. If ``False``, :meth:`write` and - :meth:`truncate` will raise :exc:`IOError`. + Returns ``True`` if the stream supports writing. If ``False``, + :meth:`write` and :meth:`truncate` will raise :exc:`IOError`. .. method:: writelines(lines) - Write a list of lines to the stream. The lines will not be altered; they - must contain line separators. + Writes a list of lines to the stream. Line separators are not + added, so it is usual for each of the lines provided to have a + line separator at the end. .. class:: RawIOBase @@ -291,30 +300,32 @@ Base class for raw binary I/O. It inherits :class:`IOBase`. There is no public constructor. - RawIOBase provides or overrides these methods in addition to those from - :class:`IOBase`: + In addition to the attributes and methods from :class:`IOBase`, + RawIOBase provides the following methods: .. method:: read([n]) - Read and return all bytes from the stream until EOF, or if *n* is + Reads and returns all the bytes from the stream until EOF, or if *n* is specified, up to *n* bytes. An empty bytes object is returned on EOF; ``None`` is returned if the object is set not to block and has no data to read. .. method:: readall() - Read and return all bytes from the stream until EOF, using multiple calls - to the stream. + Reads and returns all the bytes from the stream until EOF, using + multiple calls to the stream if necessary. .. method:: readinto(b) - Read up to len(b) bytes into bytearray *b* and return the number of bytes - read. + Reads up to len(b) bytes into bytearray *b* and returns the number + of bytes read. .. method:: write(b) - Write the given bytes, *b*, to the underlying raw stream and return the - number of bytes written (never less than ``len(b)``). + Writes the given bytes or bytearray object, *b*, to the underlying + raw stream and returns the number of bytes written (never less + than ``len(b)``, since if the write fails an :exc:`IOError` will + be raised). Raw File I/O @@ -322,7 +333,7 @@ .. class:: FileIO(name[, mode]) - :class:`FileIO` represents an OS file containing bytes data. It implements + :class:`FileIO` represents a file containing bytes data. It implements the :class:`RawIOBase` interface (and therefore the :class:`IOBase` interface, too). @@ -331,8 +342,9 @@ writing or appending; it will be truncated when opened for writing. Add a ``'+'`` to the mode to allow simultaneous reading and writing. - :class:`FileIO` provides or overrides these methods in addition to those from - :class:`RawIOBase` and :class:`IOBase`: + In addition to the attributes and methods from :class:`IOBase` and + :class:`RawIOBase`, :class:`FileIO` provides the following data + attributes and methods: .. attribute:: mode @@ -344,24 +356,27 @@ .. method:: read([n]) - Read and return bytes at most *n* bytes. Only one system call is made, so - less data than requested may be returned. In non-blocking mode, ``None`` - is returned when no data is available. + Reads and returns at most *n* bytes. Only one system call is made, so + it is possible that less data than was requested is returned. Call + :func:`len` on the returned bytes object to see how many bytes + were actually returned (In non-blocking mode, ``None`` is returned + when no data is available.) .. method:: readall() - Read and return as bytes all the data from the file. As much as - immediately available is returned in non-blocking mode. If the EOF has - been reached, ``b''`` is returned. - - .. method:: readinto(bytearray) - - This method should not be used on :class:`FileIO` objects. + Reads and returns the entire file's contents in a single bytes + object. As much as immediately available is returned in + non-blocking mode. If the EOF has been reached, ``b''`` is + returned. .. method:: write(b) - Write the bytes *b* to the file, and return the number actually written. - Only one system call is made, so not all of the data may be written. + Write the bytes or bytearray object, *b*, to the file, and return + the number actually written. Only one system call is made, so it + is possible that only some of the data is written. + + Note that the inherited ``readinto()`` method should not be used on + :class:`FileIO` objects. Buffered Streams @@ -390,7 +405,7 @@ .. method:: read([n]) - Read and return up to *n* bytes. If the argument is omitted, ``None``, or + Reads and returns up to *n* bytes. If the argument is omitted, ``None``, or negative, data is read and returned until EOF is reached. An empty bytes object is returned if the stream is already at EOF. @@ -405,7 +420,7 @@ .. method:: readinto(b) - Read up to len(b) bytes into bytearray *b* and return the number of bytes + Reads up to len(b) bytes into bytearray *b* and returns the number of bytes read. Like :meth:`read`, multiple reads may be issued to the underlying raw @@ -416,8 +431,10 @@ .. method:: write(b) - Write the given bytes, *b*, to the underlying raw stream and return the - number of bytes written (never less than ``len(b)``). + Writes the given bytes or bytearray object, *b*, to the underlying + raw stream and returns the number of bytes written (never less than + ``len(b)``, since if the write fails an :exc:`IOError` will + be raised). A :exc:`BlockingIOError` is raised if the buffer is full, and the underlying raw stream cannot accept more data at the moment. @@ -435,15 +452,16 @@ .. method:: getvalue() - Return the bytes value of the buffer. + Returns a bytes object containing the entire contents of the + buffer. .. method:: read1() In :class:`BytesIO`, this is the same as :meth:`read`. - .. method:: truncate([pos]) + .. method:: truncate([size]) - Truncate the file to at most *pos* bytes. *pos* defaults to the current + Truncates the buffer to at most *size* bytes. *size* defaults to the current stream position, as returned by :meth:`tell`. @@ -461,19 +479,20 @@ .. method:: peek([n]) - Return bytes from a buffer without advancing the position. The argument - indicates a desired minimal number of bytes; only one read on the raw - stream is done to satisfy it. More than the buffer's size is never - returned. + Returns 1 (or *n* if specified) bytes from a buffer without + advancing the position. Only a single read on the raw stream is done to + satisfy the call. The number of bytes returned may be less than + requested since at most all the buffer's bytes from the current + position to the end are returned. .. method:: read([n]) - Read and return *n* bytes, or if *n* is not given or negative, until EOF + Reads and returns *n* bytes, or if *n* is not given or negative, until EOF or if the read call would block in non-blocking mode. .. method:: read1(n) - Read and return up to *n* bytes with only one call on the raw stream. If + Reads and returns up to *n* bytes with only one call on the raw stream. If at least one byte is buffered, only buffered bytes are returned. Otherwise, one raw stream read call is made. @@ -494,20 +513,21 @@ .. method:: flush() Force bytes held in the buffer into the raw stream. A - :exc:`BlockingIOError` is be raised if the raw stream blocks. + :exc:`BlockingIOError` should be raised if the raw stream blocks. .. method:: write(b) - Write bytes *b* onto the raw stream and return the number written. A - :exc:`BlockingIOError` is raised when the raw stream blocks. + Writes the bytes or bytearray object, *b*, onto the raw stream and + returns the number of bytes written. A :exc:`BlockingIOError` is + raised when the raw stream blocks. .. class:: BufferedRWPair(reader, writer[, buffer_size[, max_buffer_size]]) - A buffered writer and reader object together for a raw stream that can be - written and read from. It has and supports both :meth:`read`, :meth:`write`, - and their variants. This is useful for such applications such as sockets and - two-way pipes. It inherits :class:`BufferedIOBase`. + A combined buffered writer and reader object for a raw stream that can be + written to and read from. It has and supports both :meth:`read`, :meth:`write`, + and their variants. This is useful for sockets and two-way pipes. + It inherits :class:`BufferedIOBase`. *reader* and *writer* are :class:`RawIOBase` objects that are readable and writeable respectively. If the *buffer_size* is omitted it defaults to @@ -541,33 +561,33 @@ Python's character strings are immutable. It inherits :class:`IOBase`. There is no public constructor. - :class:`TextIOBase` provides or overrides these methods in addition to those - from :class:`IOBase`: + :class:`TextIOBase` provides or overrides these data attributes and + methods in addition to those from :class:`IOBase`: .. attribute:: encoding - Return the name of the encoding used to decode the stream's bytes into + The name of the encoding used to decode the stream's bytes into strings, and to encode strings into bytes. .. attribute:: newlines - Return a string, tuple of strings, or ``None`` indicating the newlines + A string, a tuple of strings, or ``None``, indicating the newlines translated so far. .. method:: read(n) - Read and return at most *n* characters from the stream. If *n* is - negative or ``None``, read to EOF. + Reads and returns at most *n* characters from the stream as a + single :class:`str`. If *n* is negative or ``None``, reads to EOF. .. method:: readline() - Read until newline or EOF and return. If the stream is already at EOF, an - empty stream is returned. + Reads until newline or EOF and returns a single :class:`str`. If + the stream is already at EOF, an empty string is returned. .. method:: write(s) - Write string *s* to the stream and return the number of characters - written. + Writes the string *s* to the stream and returns the number of + characters written. .. class:: TextIOWrapper(buffer[, encoding[, errors[, newline[, line_buffering]]]]) @@ -601,7 +621,7 @@ If *line_buffering* is ``True``, :meth:`flush` is implied when a call to write contains a newline character. - :class:`TextIOWrapper` provides these methods in addition to those of + :class:`TextIOWrapper` provides these data attributes in addition to those of :class:`TextIOBase` and its parents: .. attribute:: errors @@ -621,12 +641,12 @@ and newline setting. See :class:`TextIOWrapper`\'s constructor for more information. - :class:`StringIO` provides these methods in addition to those from + :class:`StringIO` provides this method in addition to those from :class:`TextIOWrapper` and its parents: .. method:: getvalue() - Return a str representation of the contents of the internal buffer. + Returns a :class:`str` containing the entire contents of the buffer. .. class:: IncrementalNewlineDecoder From python-3000-checkins at python.org Mon Apr 21 13:59:37 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Mon, 21 Apr 2008 13:59:37 +0200 (CEST) Subject: [Python-3000-checkins] r62432 - python/branches/py3k Message-ID: <20080421115937.369141E4002@bag.python.org> Author: benjamin.peterson Date: Mon Apr 21 13:59:36 2008 New Revision: 62432 Log: Blocked revisions 62431 via svnmerge ........ r62431 | benjamin.peterson | 2008-04-21 06:57:40 -0500 (Mon, 21 Apr 2008) | 2 lines Moved io doc changes back ........ Modified: python/branches/py3k/ (props changed) From python-3000-checkins at python.org Mon Apr 21 15:08:12 2008 From: python-3000-checkins at python.org (christian.heimes) Date: Mon, 21 Apr 2008 15:08:12 +0200 (CEST) Subject: [Python-3000-checkins] r62433 - in python/branches/py3k: Lib/test/test_math.py Lib/test/test_pkgutil.py Modules/cmathmodule.c Modules/mathmodule.c Message-ID: <20080421130812.3A1521E4002@bag.python.org> Author: christian.heimes Date: Mon Apr 21 15:08:03 2008 New Revision: 62433 Log: Merged revisions 62420-62421,62423-62424 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62420 | mark.dickinson | 2008-04-20 20:30:05 +0200 (Sun, 20 Apr 2008) | 3 lines Even more fixes for alpha Tru64, this time for the phase and polar methods. ........ r62421 | mark.dickinson | 2008-04-20 22:38:48 +0200 (Sun, 20 Apr 2008) | 2 lines Add test for tanh(-0.) == -0. on IEEE 754 systems ........ r62423 | amaury.forgeotdarc | 2008-04-20 23:02:21 +0200 (Sun, 20 Apr 2008) | 3 lines Correct an apparent refleak in test_pkgutil: zipimport._zip_directory_cache contains info for all processed zip files, even when they are no longer used. ........ r62424 | mark.dickinson | 2008-04-20 23:39:04 +0200 (Sun, 20 Apr 2008) | 4 lines math.atan2 is misbehaving on Windows; this patch should fix the problem in the same way that the cmath.phase problems were fixed. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_math.py python/branches/py3k/Lib/test/test_pkgutil.py python/branches/py3k/Modules/cmathmodule.c python/branches/py3k/Modules/mathmodule.c Modified: python/branches/py3k/Lib/test/test_math.py ============================================================================== --- python/branches/py3k/Lib/test/test_math.py (original) +++ python/branches/py3k/Lib/test/test_math.py Mon Apr 21 15:08:03 2008 @@ -124,6 +124,59 @@ self.ftest('atan2(1, 1)', math.atan2(1, 1), math.pi/4) self.ftest('atan2(1, 0)', math.atan2(1, 0), math.pi/2) + # math.atan2(0, x) + self.ftest('atan2(0., -inf)', math.atan2(0., NINF), math.pi) + self.ftest('atan2(0., -2.3)', math.atan2(0., -2.3), math.pi) + self.ftest('atan2(0., -0.)', math.atan2(0., -0.), math.pi) + self.assertEqual(math.atan2(0., 0.), 0.) + self.assertEqual(math.atan2(0., 2.3), 0.) + self.assertEqual(math.atan2(0., INF), 0.) + self.assert_(math.isnan(math.atan2(0., NAN))) + # math.atan2(-0, x) + self.ftest('atan2(-0., -inf)', math.atan2(-0., NINF), -math.pi) + self.ftest('atan2(-0., -2.3)', math.atan2(-0., -2.3), -math.pi) + self.ftest('atan2(-0., -0.)', math.atan2(-0., -0.), -math.pi) + self.assertEqual(math.atan2(-0., 0.), -0.) + self.assertEqual(math.atan2(-0., 2.3), -0.) + self.assertEqual(math.atan2(-0., INF), -0.) + self.assert_(math.isnan(math.atan2(-0., NAN))) + # math.atan2(INF, x) + self.ftest('atan2(inf, -inf)', math.atan2(INF, NINF), math.pi*3/4) + self.ftest('atan2(inf, -2.3)', math.atan2(INF, -2.3), math.pi/2) + self.ftest('atan2(inf, -0.)', math.atan2(INF, -0.0), math.pi/2) + self.ftest('atan2(inf, 0.)', math.atan2(INF, 0.0), math.pi/2) + self.ftest('atan2(inf, 2.3)', math.atan2(INF, 2.3), math.pi/2) + self.ftest('atan2(inf, inf)', math.atan2(INF, INF), math.pi/4) + self.assert_(math.isnan(math.atan2(INF, NAN))) + # math.atan2(NINF, x) + self.ftest('atan2(-inf, -inf)', math.atan2(NINF, NINF), -math.pi*3/4) + self.ftest('atan2(-inf, -2.3)', math.atan2(NINF, -2.3), -math.pi/2) + self.ftest('atan2(-inf, -0.)', math.atan2(NINF, -0.0), -math.pi/2) + self.ftest('atan2(-inf, 0.)', math.atan2(NINF, 0.0), -math.pi/2) + self.ftest('atan2(-inf, 2.3)', math.atan2(NINF, 2.3), -math.pi/2) + self.ftest('atan2(-inf, inf)', math.atan2(NINF, INF), -math.pi/4) + self.assert_(math.isnan(math.atan2(NINF, NAN))) + # math.atan2(+finite, x) + self.ftest('atan2(2.3, -inf)', math.atan2(2.3, NINF), math.pi) + self.ftest('atan2(2.3, -0.)', math.atan2(2.3, -0.), math.pi/2) + self.ftest('atan2(2.3, 0.)', math.atan2(2.3, 0.), math.pi/2) + self.assertEqual(math.atan2(2.3, INF), 0.) + self.assert_(math.isnan(math.atan2(2.3, NAN))) + # math.atan2(-finite, x) + self.ftest('atan2(-2.3, -inf)', math.atan2(-2.3, NINF), -math.pi) + self.ftest('atan2(-2.3, -0.)', math.atan2(-2.3, -0.), -math.pi/2) + self.ftest('atan2(-2.3, 0.)', math.atan2(-2.3, 0.), -math.pi/2) + self.assertEqual(math.atan2(-2.3, INF), -0.) + self.assert_(math.isnan(math.atan2(-2.3, NAN))) + # math.atan2(NAN, x) + self.assert_(math.isnan(math.atan2(NAN, NINF))) + self.assert_(math.isnan(math.atan2(NAN, -2.3))) + self.assert_(math.isnan(math.atan2(NAN, -0.))) + self.assert_(math.isnan(math.atan2(NAN, 0.))) + self.assert_(math.isnan(math.atan2(NAN, 2.3))) + self.assert_(math.isnan(math.atan2(NAN, INF))) + self.assert_(math.isnan(math.atan2(NAN, NAN))) + def testCeil(self): self.assertRaises(TypeError, math.ceil) self.assertEquals(int, type(math.ceil(0.5))) @@ -575,6 +628,11 @@ self.ftest('tanh(inf)', math.tanh(INF), 1) self.ftest('tanh(-inf)', math.tanh(NINF), -1) self.assert_(math.isnan(math.tanh(NAN))) + # check that tanh(-0.) == -0. on IEEE 754 systems + if float.__getformat__("double").startswith("IEEE"): + self.assertEqual(math.tanh(-0.), -0.) + self.assertEqual(math.copysign(1., math.tanh(-0.)), + math.copysign(1., -0.)) def test_trunc(self): self.assertEqual(math.trunc(1), 1) Modified: python/branches/py3k/Lib/test/test_pkgutil.py ============================================================================== --- python/branches/py3k/Lib/test/test_pkgutil.py (original) +++ python/branches/py3k/Lib/test/test_pkgutil.py Mon Apr 21 15:08:03 2008 @@ -122,6 +122,9 @@ def test_main(): run_unittest(PkgutilTests, PkgutilPEP302Tests) + # this is necessary if test is run repeated (like when finding leaks) + import zipimport + zipimport._zip_directory_cache.clear() if __name__ == '__main__': test_main() Modified: python/branches/py3k/Modules/cmathmodule.c ============================================================================== --- python/branches/py3k/Modules/cmathmodule.c (original) +++ python/branches/py3k/Modules/cmathmodule.c Mon Apr 21 15:08:03 2008 @@ -264,7 +264,8 @@ return r; } -/* Windows screws up atan2 for inf and nan */ +/* Windows screws up atan2 for inf and nan, and alpha Tru64 5.1 doesn't follow + C99 for atan2(0., 0.). */ static double c_atan2(Py_complex z) { @@ -282,6 +283,14 @@ /* atan2(+-inf, x) == +-pi/2 for finite x */ return copysign(0.5*Py_MATH_PI, z.imag); } + if (Py_IS_INFINITY(z.real) || z.imag == 0.) { + if (copysign(1., z.real) == 1.) + /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */ + return copysign(0., z.imag); + else + /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */ + return copysign(Py_MATH_PI, z.imag); + } return atan2(z.imag, z.real); } Modified: python/branches/py3k/Modules/mathmodule.c ============================================================================== --- python/branches/py3k/Modules/mathmodule.c (original) +++ python/branches/py3k/Modules/mathmodule.c Mon Apr 21 15:08:03 2008 @@ -96,6 +96,42 @@ } /* + wrapper for atan2 that deals directly with special cases before + delegating to the platform libm for the remaining cases. This + is necessary to get consistent behaviour across platforms. + Windows, FreeBSD and alpha Tru64 are amongst platforms that don't + always follow C99. +*/ + +static double +m_atan2(double y, double x) +{ + if (Py_IS_NAN(x) || Py_IS_NAN(y)) + return Py_NAN; + if (Py_IS_INFINITY(y)) { + if (Py_IS_INFINITY(x)) { + if (copysign(1., x) == 1.) + /* atan2(+-inf, +inf) == +-pi/4 */ + return copysign(0.25*Py_MATH_PI, y); + else + /* atan2(+-inf, -inf) == +-pi*3/4 */ + return copysign(0.75*Py_MATH_PI, y); + } + /* atan2(+-inf, x) == +-pi/2 for finite x */ + return copysign(0.5*Py_MATH_PI, y); + } + if (Py_IS_INFINITY(x) || y == 0.) { + if (copysign(1., x) == 1.) + /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */ + return copysign(0., y); + else + /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */ + return copysign(Py_MATH_PI, y); + } + return atan2(y, x); +} + +/* math_1 is used to wrap a libm function f that takes a double arguments and returns a double. @@ -250,7 +286,7 @@ "asinh(x)\n\nReturn the hyperbolic arc sine (measured in radians) of x.") FUNC1(atan, atan, 0, "atan(x)\n\nReturn the arc tangent (measured in radians) of x.") -FUNC2(atan2, atan2, +FUNC2(atan2, m_atan2, "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n" "Unlike atan(y/x), the signs of both x and y are considered.") FUNC1(atanh, atanh, 0, From python-3000-checkins at python.org Mon Apr 21 16:47:45 2008 From: python-3000-checkins at python.org (mark.summerfield) Date: Mon, 21 Apr 2008 16:47:45 +0200 (CEST) Subject: [Python-3000-checkins] r62437 - python/branches/py3k/Doc/library/pickle.rst Message-ID: <20080421144745.A66911E400F@bag.python.org> Author: mark.summerfield Date: Mon Apr 21 16:47:45 2008 New Revision: 62437 Log: dumps() and loads() work in terms of bytes objects not strings. Modified: python/branches/py3k/Doc/library/pickle.rst Modified: python/branches/py3k/Doc/library/pickle.rst ============================================================================== --- python/branches/py3k/Doc/library/pickle.rst (original) +++ python/branches/py3k/Doc/library/pickle.rst Mon Apr 21 16:47:45 2008 @@ -194,18 +194,18 @@ .. function:: dumps(obj[, protocol]) - Return the pickled representation of the object as a string, instead of writing - it to a file. + Return the pickled representation of the object as a :class:`bytes` + object, instead of writing it to a file. If the *protocol* parameter is omitted, protocol 3 is used. If *protocol* is specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol version will be used. -.. function:: loads(string) +.. function:: loads(bytes_object) - Read a pickled object hierarchy from a string. Characters in the string past - the pickled object's representation are ignored. + Read a pickled object hierarchy from a :class:`bytes` object. + Bytes past the pickled object's representation are ignored. The :mod:`pickle` module also defines three exceptions: From python-3000-checkins at python.org Tue Apr 22 21:02:41 2008 From: python-3000-checkins at python.org (trent.nelson) Date: Tue, 22 Apr 2008 21:02:41 +0200 (CEST) Subject: [Python-3000-checkins] r62462 - in python/branches/py3k: Lib/test/test_getargs2.py Python/getargs.c Message-ID: <20080422190241.1F3FF1E4006@bag.python.org> Author: trent.nelson Date: Tue Apr 22 21:02:40 2008 New Revision: 62462 Log: Issue 2440: remove the guard around the handling of case 'n' in getargs.c's convertsimple() such that we always treat it as an index type, regardless of whether or not sizeof(size_t) == sizeof(long). Fix the test_args2.Signed_TestCase.test_n() such that it tests for adherence to PEP 357 (don't try and coerce objects that don't have nb_index slots but do have nb_int slots (i.e. floats) into indexes 'just because we can'). Three other commits are related to this one: r62269 and r62279, which were changes to PyNumber_Index (among other things) to check for nb_int slots when we lack nb_index slots -- and r62292, which is when I reverted these changes after various people pointed out that the test was in fact wrong, not the code. Modified: python/branches/py3k/Lib/test/test_getargs2.py python/branches/py3k/Python/getargs.c Modified: python/branches/py3k/Lib/test/test_getargs2.py ============================================================================== --- python/branches/py3k/Lib/test/test_getargs2.py (original) +++ python/branches/py3k/Lib/test/test_getargs2.py Tue Apr 22 21:02:40 2008 @@ -187,8 +187,8 @@ # n returns 'Py_ssize_t', and does range checking # (PY_SSIZE_T_MIN ... PY_SSIZE_T_MAX) self.assertRaises(TypeError, getargs_n, 3.14) - self.failUnlessEqual(99, getargs_n(Long())) - self.failUnlessEqual(99, getargs_n(Int())) + self.assertRaises(TypeError, getargs_n, Long()) + self.assertRaises(TypeError, getargs_n, Int()) self.assertRaises(OverflowError, getargs_n, PY_SSIZE_T_MIN-1) self.failUnlessEqual(PY_SSIZE_T_MIN, getargs_n(PY_SSIZE_T_MIN)) Modified: python/branches/py3k/Python/getargs.c ============================================================================== --- python/branches/py3k/Python/getargs.c (original) +++ python/branches/py3k/Python/getargs.c Tue Apr 22 21:02:40 2008 @@ -663,7 +663,6 @@ } case 'n': /* Py_ssize_t */ -#if SIZEOF_SIZE_T != SIZEOF_LONG { PyObject *iobj; Py_ssize_t *p = va_arg(*p_va, Py_ssize_t *); @@ -672,14 +671,12 @@ return converterr("integer", arg, msgbuf, bufsize); iobj = PyNumber_Index(arg); if (iobj != NULL) - ival = PyLong_AsSsize_t(arg); + ival = PyLong_AsSsize_t(iobj); if (ival == -1 && PyErr_Occurred()) return converterr("integer", arg, msgbuf, bufsize); *p = ival; break; } -#endif - /* Fall through from 'n' to 'l' if Py_ssize_t is int */ case 'l': {/* long int */ long *p = va_arg(*p_va, long *); long ival; From python-3000-checkins at python.org Thu Apr 24 04:34:54 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Thu, 24 Apr 2008 04:34:54 +0200 (CEST) Subject: [Python-3000-checkins] r62471 - in python/branches/py3k/Doc/library: _winreg.rst basehttpserver.rst cmath.rst ctypes.rst datetime.rst decimal.rst difflib.rst doctest.rst fractions.rst functions.rst heapq.rst itertools.rst logging.rst math.rst operator.rst pickletools.rst plistlib.rst pprint.rst py_compile.rst pyexpat.rst queue.rst random.rst sched.rst select.rst shutil.rst signal.rst sqlite3.rst subprocess.rst sys.rst zipfile.rst Message-ID: <20080424023454.C46C01E4008@bag.python.org> Author: benjamin.peterson Date: Thu Apr 24 04:34:53 2008 New Revision: 62471 Log: remove some old versionchanged and versionadded directives Modified: python/branches/py3k/Doc/library/_winreg.rst python/branches/py3k/Doc/library/basehttpserver.rst python/branches/py3k/Doc/library/cmath.rst python/branches/py3k/Doc/library/ctypes.rst python/branches/py3k/Doc/library/datetime.rst python/branches/py3k/Doc/library/decimal.rst python/branches/py3k/Doc/library/difflib.rst python/branches/py3k/Doc/library/doctest.rst python/branches/py3k/Doc/library/fractions.rst python/branches/py3k/Doc/library/functions.rst python/branches/py3k/Doc/library/heapq.rst python/branches/py3k/Doc/library/itertools.rst python/branches/py3k/Doc/library/logging.rst python/branches/py3k/Doc/library/math.rst python/branches/py3k/Doc/library/operator.rst python/branches/py3k/Doc/library/pickletools.rst python/branches/py3k/Doc/library/plistlib.rst python/branches/py3k/Doc/library/pprint.rst python/branches/py3k/Doc/library/py_compile.rst python/branches/py3k/Doc/library/pyexpat.rst python/branches/py3k/Doc/library/queue.rst python/branches/py3k/Doc/library/random.rst python/branches/py3k/Doc/library/sched.rst python/branches/py3k/Doc/library/select.rst python/branches/py3k/Doc/library/shutil.rst python/branches/py3k/Doc/library/signal.rst python/branches/py3k/Doc/library/sqlite3.rst python/branches/py3k/Doc/library/subprocess.rst python/branches/py3k/Doc/library/sys.rst python/branches/py3k/Doc/library/zipfile.rst Modified: python/branches/py3k/Doc/library/_winreg.rst ============================================================================== --- python/branches/py3k/Doc/library/_winreg.rst (original) +++ python/branches/py3k/Doc/library/_winreg.rst Thu Apr 24 04:34:53 2008 @@ -138,8 +138,6 @@ >>> ExpandEnvironmentStrings(u"%windir%") u"C:\\Windows" - .. versionadded:: 2.6 - .. function:: FlushKey(key) @@ -437,5 +435,4 @@ will automatically close *key* when control leaves the :keyword:`with` block. - .. versionadded:: 2.6 Modified: python/branches/py3k/Doc/library/basehttpserver.rst ============================================================================== --- python/branches/py3k/Doc/library/basehttpserver.rst (original) +++ python/branches/py3k/Doc/library/basehttpserver.rst Thu Apr 24 04:34:53 2008 @@ -127,9 +127,6 @@ Specifies the Content-Type HTTP header of error responses sent to the client. The default value is ``'text/html'``. - .. versionadded:: 2.6 - Previously, the content type was always ``'text/html'``. - .. attribute:: BaseHTTPRequestHandler.protocol_version Modified: python/branches/py3k/Doc/library/cmath.rst ============================================================================== --- python/branches/py3k/Doc/library/cmath.rst (original) +++ python/branches/py3k/Doc/library/cmath.rst Thu Apr 24 04:34:53 2008 @@ -65,8 +65,6 @@ Return phase, also known as the argument, of a complex. - .. versionadded:: 2.6 - .. function:: polar(x) @@ -75,16 +73,12 @@ *r* and *phi*. *r* is the distance from 0 and *phi* the phase angle. - .. versionadded:: 2.6 - .. function:: rect(r, phi) Convert from polar coordinates to rectangular coordinates and return a :class:`complex`. - .. versionadded:: 2.6 - cmath functions @@ -115,9 +109,6 @@ continuous from the right. The other extends from ``-1j`` along the imaginary axis to ``-?j``, continuous from the left. - .. versionchanged:: 2.6 - branch cuts moved to match those recommended by the C99 standard - .. function:: atan(x) @@ -126,9 +117,6 @@ other extends from ``-1j`` along the imaginary axis to ``-?j``, continuous from the left. - .. versionchanged:: 2.6 - direction of continuity of upper cut reversed - .. function:: atanh(x) @@ -137,9 +125,6 @@ other extends from ``-1`` along the real axis to ``-?``, continuous from above. - .. versionchanged:: 2.6 - direction of continuity of right cut reversed - .. function:: cos(x) @@ -161,15 +146,11 @@ Return *True* if the real or the imaginary part of x is positive or negative infinity. - .. versionadded:: 2.6 - .. function:: isnan(x) Return *True* if the real or imaginary part of x is not a number (NaN). - .. versionadded:: 2.6 - .. function:: log(x[, base]) Modified: python/branches/py3k/Doc/library/ctypes.rst ============================================================================== --- python/branches/py3k/Doc/library/ctypes.rst (original) +++ python/branches/py3k/Doc/library/ctypes.rst Thu Apr 24 04:34:53 2008 @@ -2004,14 +2004,11 @@ .. class:: _SimpleCData - This non-public class is the base class of all fundamental ctypes data types. It - is mentioned here because it contains the common attributes of the fundamental - ctypes data types. ``_SimpleCData`` is a subclass of ``_CData``, so it inherits - their methods and attributes. - - .. versionchanged:: 2.6 - ctypes data types that are not and do not contain pointers can - now be pickled. + This non-public class is the base class of all fundamental ctypes data + types. It is mentioned here because it contains the common attributes of the + fundamental ctypes data types. ``_SimpleCData`` is a subclass of ``_CData``, + so it inherits their methods and attributes. ctypes data types that are not + and do not contain pointers can now be pickled. Instances have a single attribute: Modified: python/branches/py3k/Doc/library/datetime.rst ============================================================================== --- python/branches/py3k/Doc/library/datetime.rst (original) +++ python/branches/py3k/Doc/library/datetime.rst Thu Apr 24 04:34:53 2008 @@ -1498,8 +1498,6 @@ which expands to the number of microseconds in the object, zero-padded on the left to six places. -.. versionadded:: 2.6 - For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty strings. Modified: python/branches/py3k/Doc/library/decimal.rst ============================================================================== --- python/branches/py3k/Doc/library/decimal.rst (original) +++ python/branches/py3k/Doc/library/decimal.rst Thu Apr 24 04:34:53 2008 @@ -340,9 +340,6 @@ Once constructed, :class:`Decimal` objects are immutable. - .. versionchanged:: 2.6 - leading and trailing whitespace characters are permitted when - creating a Decimal instance from a string. Decimal floating point objects share many properties with the other built-in numeric types such as :class:`float` and :class:`int`. All of the usual math @@ -367,9 +364,6 @@ Return a :term:`named tuple` representation of the number: ``DecimalTuple(sign, digits, exponent)``. - .. versionchanged:: 2.6 - Use a named tuple. - .. method:: Decimal.canonical() Modified: python/branches/py3k/Doc/library/difflib.rst ============================================================================== --- python/branches/py3k/Doc/library/difflib.rst (original) +++ python/branches/py3k/Doc/library/difflib.rst Thu Apr 24 04:34:53 2008 @@ -401,8 +401,7 @@ If no blocks match, this returns ``(alo, blo, 0)``. - .. versionchanged:: 2.6 - This method returns a :term:`named tuple` ``Match(a, b, size)``. + This method returns a :term:`named tuple` ``Match(a, b, size)``. .. method:: SequenceMatcher.get_matching_blocks() Modified: python/branches/py3k/Doc/library/doctest.rst ============================================================================== --- python/branches/py3k/Doc/library/doctest.rst (original) +++ python/branches/py3k/Doc/library/doctest.rst Thu Apr 24 04:34:53 2008 @@ -1441,9 +1441,6 @@ The optional *verbose* argument controls how detailed the summary is. If the verbosity is not specified, then the :class:`DocTestRunner`'s verbosity is used. - .. versionchanged:: 2.6 - Use a named tuple. - .. _doctest-outputchecker: Modified: python/branches/py3k/Doc/library/fractions.rst ============================================================================== --- python/branches/py3k/Doc/library/fractions.rst (original) +++ python/branches/py3k/Doc/library/fractions.rst Thu Apr 24 04:34:53 2008 @@ -6,7 +6,6 @@ :synopsis: Rational numbers. .. moduleauthor:: Jeffrey Yasskin .. sectionauthor:: Jeffrey Yasskin -.. versionadded:: 2.6 The :mod:`fractions` module defines an immutable, infinite-precision Modified: python/branches/py3k/Doc/library/functions.rst ============================================================================== --- python/branches/py3k/Doc/library/functions.rst (original) +++ python/branches/py3k/Doc/library/functions.rst Thu Apr 24 04:34:53 2008 @@ -227,9 +227,6 @@ This function raises :exc:`SyntaxError` if the compiled source is invalid, and :exc:`TypeError` if the source contains null bytes. - .. versionadded:: 2.6 - Support for compiling AST objects. - .. function:: complex([real[, imag]]) Modified: python/branches/py3k/Doc/library/heapq.rst ============================================================================== --- python/branches/py3k/Doc/library/heapq.rst (original) +++ python/branches/py3k/Doc/library/heapq.rst Thu Apr 24 04:34:53 2008 @@ -43,13 +43,13 @@ Pop and return the smallest item from the *heap*, maintaining the heap invariant. If the heap is empty, :exc:`IndexError` is raised. + .. function:: heappushpop(heap, item) Push *item* on the heap, then pop and return the smallest item from the *heap*. The combined action runs more efficiently than :func:`heappush` followed by a separate call to :func:`heappop`. - .. versionadded:: 2.6 .. function:: heapify(x) Modified: python/branches/py3k/Doc/library/itertools.rst ============================================================================== --- python/branches/py3k/Doc/library/itertools.rst (original) +++ python/branches/py3k/Doc/library/itertools.rst Thu Apr 24 04:34:53 2008 @@ -91,8 +91,6 @@ for element in it: yield element - .. versionadded:: 2.6 - .. function:: combinations(iterable, r) @@ -137,7 +135,6 @@ if sorted(indices) == list(indices): yield tuple(pool[i] for i in indices) - .. versionadded:: 2.6 .. function:: count([n]) @@ -363,7 +360,6 @@ if len(set(indices)) == r: yield tuple(pool[i] for i in indices) - .. versionadded:: 2.6 .. function:: product(*iterables[, repeat]) @@ -425,10 +421,6 @@ for args in iterable: yield function(*args) - .. versionchanged:: 2.6 - Previously, :func:`starmap` required the function arguments to be tuples. - Now, any iterable is allowed. - .. function:: takewhile(predicate, iterable) Modified: python/branches/py3k/Doc/library/logging.rst ============================================================================== --- python/branches/py3k/Doc/library/logging.rst (original) +++ python/branches/py3k/Doc/library/logging.rst Thu Apr 24 04:34:53 2008 @@ -1240,10 +1240,6 @@ 2008-01-18 14:49:54,033 d.e.f WARNING IP: 192.168.0.1 User: sheila A message at WARNING level with 2 parameters 2008-01-18 14:49:54,033 d.e.f WARNING IP: 127.0.0.1 User: jim A message at WARNING level with 2 parameters -.. versionadded:: 2.6 - -The :class:`LoggerAdapter` class was not present in previous versions. - .. _network-logging: @@ -2143,8 +2139,6 @@ LoggerAdapter Objects --------------------- -.. versionadded:: 2.6 - :class:`LoggerAdapter` instances are used to conveniently pass contextual information into logging calls. For a usage example , see the section on `adding contextual information to your logging output`__. Modified: python/branches/py3k/Doc/library/math.rst ============================================================================== --- python/branches/py3k/Doc/library/math.rst (original) +++ python/branches/py3k/Doc/library/math.rst Thu Apr 24 04:34:53 2008 @@ -102,7 +102,6 @@ Return the :class:`Real` value *x* truncated to an :class:`Integral` (usually a long integer). Delegates to ``x.__trunc__()``. - .. versionadded:: 2.6 Note that :func:`frexp` and :func:`modf` have a different call/return pattern than their C equivalents: they take a single argument and return a pair of @@ -133,8 +132,6 @@ Return the natural logarithm of *1+x* (base *e*). The result is calculated in a way which is accurate for *x* near zero. - .. versionadded:: 2.6 - .. function:: log10(x) @@ -150,9 +147,6 @@ ``x`` is negative, and ``y`` is not an integer then ``pow(x, y)`` is undefined, and raises :exc:`ValueError`. - .. versionchanged:: 2.6 - The outcome of ``1**nan`` and ``nan**0`` was undefined. - .. function:: sqrt(x) @@ -225,22 +219,16 @@ Return the inverse hyperbolic cosine of *x*. - .. versionadded:: 2.6 - .. function:: asinh(x) Return the inverse hyperbolic sine of *x*. - .. versionadded:: 2.6 - .. function:: atanh(x) Return the inverse hyperbolic tangent of *x*. - .. versionadded:: 2.6 - .. function:: cosh(x) Modified: python/branches/py3k/Doc/library/operator.rst ============================================================================== --- python/branches/py3k/Doc/library/operator.rst (original) +++ python/branches/py3k/Doc/library/operator.rst Thu Apr 24 04:34:53 2008 @@ -457,7 +457,6 @@ >>> itemgetter(slice(2,None))('ABCDEFG') 'CDEFG' - .. versionadded:: 2.4 Example of using :func:`itemgetter` to retrieve specific fields from a tuple record: Modified: python/branches/py3k/Doc/library/pickletools.rst ============================================================================== --- python/branches/py3k/Doc/library/pickletools.rst (original) +++ python/branches/py3k/Doc/library/pickletools.rst Thu Apr 24 04:34:53 2008 @@ -39,4 +39,3 @@ opcodes. The optimized pickle is shorter, takes less transmission time, requires less storage space, and unpickles more efficiently. - .. versionadded:: 2.6 Modified: python/branches/py3k/Doc/library/plistlib.rst ============================================================================== --- python/branches/py3k/Doc/library/plistlib.rst (original) +++ python/branches/py3k/Doc/library/plistlib.rst Thu Apr 24 04:34:53 2008 @@ -7,10 +7,6 @@ .. sectionauthor:: Georg Brandl .. (harvested from docstrings in the original file) -.. versionchanged:: 2.6 - This module was previously only available in the Mac-specific library, it is - now available for all platforms. - .. index:: pair: plist; file single: property list Modified: python/branches/py3k/Doc/library/pprint.rst ============================================================================== --- python/branches/py3k/Doc/library/pprint.rst (original) +++ python/branches/py3k/Doc/library/pprint.rst Thu Apr 24 04:34:53 2008 @@ -22,9 +22,6 @@ Dictionaries are sorted by key before the display is computed. -.. versionchanged:: 2.6 - Added support for :class:`set` and :class:`frozenset`. - The :mod:`pprint` module defines one class: .. First the implementation class: Modified: python/branches/py3k/Doc/library/py_compile.rst ============================================================================== --- python/branches/py3k/Doc/library/py_compile.rst (original) +++ python/branches/py3k/Doc/library/py_compile.rst Thu Apr 24 04:34:53 2008 @@ -45,10 +45,6 @@ files named on the command line. The exit status is nonzero if one of the files could not be compiled. -.. versionchanged:: 2.6 - - Added the nonzero exit status. - .. seealso:: Modified: python/branches/py3k/Doc/library/pyexpat.rst ============================================================================== --- python/branches/py3k/Doc/library/pyexpat.rst (original) +++ python/branches/py3k/Doc/library/pyexpat.rst Thu Apr 24 04:34:53 2008 @@ -182,9 +182,6 @@ to this attribute. When the size is changed, the buffer will be flushed. - .. versionchanged:: 2.6 - The buffer size can now be changed. - .. attribute:: xmlparser.buffer_text Modified: python/branches/py3k/Doc/library/queue.rst ============================================================================== --- python/branches/py3k/Doc/library/queue.rst (original) +++ python/branches/py3k/Doc/library/queue.rst Thu Apr 24 04:34:53 2008 @@ -37,8 +37,6 @@ block once this size has been reached, until queue items are consumed. If *maxsize* is less than or equal to zero, the queue size is infinite. - .. versionadded:: 2.6 - .. class:: PriorityQueue(maxsize) @@ -51,8 +49,6 @@ one returned by ``sorted(list(entries))[0]``). A typical pattern for entries is a tuple in the form: ``(priority_number, data)``. - .. versionadded:: 2.6 - .. exception:: Empty Modified: python/branches/py3k/Doc/library/random.rst ============================================================================== --- python/branches/py3k/Doc/library/random.rst (original) +++ python/branches/py3k/Doc/library/random.rst Thu Apr 24 04:34:53 2008 @@ -153,6 +153,7 @@ Return a random floating point number *N* such that ``a <= N < b``. + .. function:: triangular(low, high, mode) Return a random floating point number *N* such that ``low <= N < high`` and @@ -160,8 +161,6 @@ default to zero and one. The *mode* argument defaults to the midpoint between the bounds, giving a symmetric distribution. - .. versionadded:: 2.6 - .. function:: betavariate(alpha, beta) Modified: python/branches/py3k/Doc/library/sched.rst ============================================================================== --- python/branches/py3k/Doc/library/sched.rst (original) +++ python/branches/py3k/Doc/library/sched.rst Thu Apr 24 04:34:53 2008 @@ -129,5 +129,3 @@ Read-only attribute returning a list of upcoming events in the order they will be run. Each event is shown as a :term:`named tuple` with the following fields: time, priority, action, argument. - - .. versionadded:: 2.6 Modified: python/branches/py3k/Doc/library/select.rst ============================================================================== --- python/branches/py3k/Doc/library/select.rst (original) +++ python/branches/py3k/Doc/library/select.rst Thu Apr 24 04:34:53 2008 @@ -31,8 +31,6 @@ section :ref:`epoll-objects` below for the methods supported by epolling objects. - .. versionadded:: 2.6 - .. function:: poll() @@ -47,16 +45,12 @@ (Only supported on BSD.) Returns a kernel queue object object; see section :ref:`kqueue-objects` below for the methods supported by kqueue objects. - .. versionadded:: 2.6 - .. function:: kqueue(ident, filter=KQ_FILTER_READ, flags=KQ_ADD, fflags=0, data=0, udata=0) (Only supported on BSD.) Returns a kernel event object object; see section :ref:`kevent-objects` below for the methods supported by kqueue objects. - .. versionadded:: 2.6 - .. function:: select(iwtd, owtd, ewtd[, timeout]) @@ -224,8 +218,6 @@ that was never registered causes an :exc:`IOError` exception with errno :const:`ENOENT` to be raised. - .. versionadded:: 2.6 - .. method:: poll.unregister(fd) Modified: python/branches/py3k/Doc/library/shutil.rst ============================================================================== --- python/branches/py3k/Doc/library/shutil.rst (original) +++ python/branches/py3k/Doc/library/shutil.rst Thu Apr 24 04:34:53 2008 @@ -110,10 +110,6 @@ information return by :func:`sys.exc_info`. Exceptions raised by *onerror* will not be caught. - .. versionchanged:: 2.6 - Explicitly check for *path* being a symbolic link and raise :exc:`OSError` - in that case. - .. function:: move(src, dst) Modified: python/branches/py3k/Doc/library/signal.rst ============================================================================== --- python/branches/py3k/Doc/library/signal.rst (original) +++ python/branches/py3k/Doc/library/signal.rst Thu Apr 24 04:34:53 2008 @@ -160,15 +160,11 @@ Attempting to pass an invalid interval timer will cause a :exc:`ItimerError`. - .. versionadded:: 2.6 - .. function:: getitimer(which) Returns current value of a given interval timer specified by *which*. - .. versionadded:: 2.6 - .. function:: set_wakeup_fd(fd) @@ -195,8 +191,6 @@ behaviour to interruptible by implicitly calling :cfunc:`siginterrupt` with a true *flag* value for the given signal. - .. versionadded:: 2.6 - .. function:: signal(signalnum, handler) Modified: python/branches/py3k/Doc/library/sqlite3.rst ============================================================================== --- python/branches/py3k/Doc/library/sqlite3.rst (original) +++ python/branches/py3k/Doc/library/sqlite3.rst Thu Apr 24 04:34:53 2008 @@ -350,8 +350,6 @@ .. method:: Connection.set_progress_handler(handler, n) - .. versionadded:: 2.6 - This routine registers a callback. The callback is invoked for every *n* instructions of the SQLite virtual machine. This is useful if you want to get called from SQLite during long-running operations, for example to update @@ -414,8 +412,6 @@ the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3` shell. - .. versionadded:: 2.6 - Example:: # Convert file existing_db.db to SQL dump file dump.sql @@ -764,8 +760,6 @@ Using the connection as a context manager ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -.. versionadded:: 2.6 - Connection objects can be used as context managers that automatically commit or rollback transactions. In the event of an exception, the transaction is rolled back; otherwise, the transaction is Modified: python/branches/py3k/Doc/library/subprocess.rst ============================================================================== --- python/branches/py3k/Doc/library/subprocess.rst (original) +++ python/branches/py3k/Doc/library/subprocess.rst Thu Apr 24 04:34:53 2008 @@ -212,8 +212,6 @@ On Windows only SIGTERM is supported so far. It's an alias for :meth:`terminate`. - .. versionadded:: 2.6 - .. method:: Popen.terminate() @@ -221,16 +219,12 @@ child. On Windows the Win32 API function TerminateProcess is called to stop the child. - .. versionadded:: 2.6 - .. method:: Popen.kill() Kills the child. On Posix OSs the function sends SIGKILL to the child. On Windows :meth:`kill` is an alias for :meth:`terminate`. - .. versionadded:: 2.6 - The following attributes are also available: Modified: python/branches/py3k/Doc/library/sys.rst ============================================================================== --- python/branches/py3k/Doc/library/sys.rst (original) +++ python/branches/py3k/Doc/library/sys.rst Thu Apr 24 04:34:53 2008 @@ -66,8 +66,6 @@ This function should be used for specialized purposes only. - .. versionadded:: 2.6 - .. function:: _clear_type_cache() @@ -77,8 +75,6 @@ This function should be used for internal and specialized purposes only. - .. versionadded:: 2.6 - .. function:: _current_frames() @@ -245,8 +241,6 @@ | :const:`unicode` | -U | +------------------------------+------------------------------------------+ - .. versionadded:: 2.6 - .. data:: float_info @@ -360,8 +354,6 @@ Get the profiler function as set by :func:`setprofile`. - .. versionadded:: 2.6 - .. function:: gettrace() @@ -378,8 +370,6 @@ implementation platform, rather than part of the language definition, and thus may not be available in all Python implementations. - .. versionadded:: 2.6 - .. function:: getwindowsversion() @@ -556,8 +546,6 @@ environment variable, but you can set it yourself to control bytecode file generation. - .. versionadded:: 2.6 - .. function:: setcheckinterval(interval) Modified: python/branches/py3k/Doc/library/zipfile.rst ============================================================================== --- python/branches/py3k/Doc/library/zipfile.rst (original) +++ python/branches/py3k/Doc/library/zipfile.rst Thu Apr 24 04:34:53 2008 @@ -182,8 +182,6 @@ filename or a :class:`ZipInfo` object. *pwd* is the password used for encrypted files. - .. versionadded:: 2.6 - .. method:: ZipFile.extractall([path[, members[, pwd]]]) @@ -192,8 +190,6 @@ be a subset of the list returned by :meth:`namelist`. *pwd* is the password used for encrypted files. - .. versionadded:: 2.6 - .. method:: ZipFile.printdir() From python-3000-checkins at python.org Thu Apr 24 04:43:56 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Thu, 24 Apr 2008 04:43:56 +0200 (CEST) Subject: [Python-3000-checkins] r62472 - in python/branches/py3k/Doc/library: future_builtins.rst python.rst Message-ID: <20080424024356.E12991E4008@bag.python.org> Author: benjamin.peterson Date: Thu Apr 24 04:43:56 2008 New Revision: 62472 Log: Removed documentation for future_builtins Removed: python/branches/py3k/Doc/library/future_builtins.rst Modified: python/branches/py3k/Doc/library/python.rst Deleted: python/branches/py3k/Doc/library/future_builtins.rst ============================================================================== --- python/branches/py3k/Doc/library/future_builtins.rst Thu Apr 24 04:43:56 2008 +++ (empty file) @@ -1,53 +0,0 @@ -:mod:`future_builtins` --- Python 3 builtins -============================================ - -.. module:: future_builtins -.. sectionauthor:: Georg Brandl -.. versionadded:: 2.6 - -This module provides functions that exist in 2.x, but have different behavior in -Python 3, so they cannot be put into the 2.x builtin namespace. - -Instead, if you want to write code compatible with Python 3 builtins, import -them from this module, like this:: - - from future_builtins import map, filter - - ... code using Python 3-style map and filter ... - -The :program:`2to3` tool that ports Python 2 code to Python 3 will recognize -this usage and leave the new builtins alone. - -.. note:: - - The Python 3 :func:`print` function is already in the builtins, but cannot be - accessed from Python 2 code unless you use the appropriate future statement:: - - from __future__ import print_function - - -Available builtins are: - -.. function:: filter(function, iterable) - - Works like :func:`itertools.ifilter`. - -.. function:: hex(object) - - Works like the builtin :func:`hex`, but instead of :meth:`__hex__` it will - use the :meth:`__index__` method on its argument to get an integer that is - then converted to hexadecimal. - -.. function:: map(function, iterable, ...) - - Works like :func:`itertools.imap`. - -.. function:: oct(object) - - Works like the builtin :func:`oct`, but instead of :meth:`__oct__` it will - use the :meth:`__index__` method on its argument to get an integer that is - then converted to hexadecimal. - -.. function:: zip(*iterables) - - Works like :func:`itertools.izip`. Modified: python/branches/py3k/Doc/library/python.rst ============================================================================== --- python/branches/py3k/Doc/library/python.rst (original) +++ python/branches/py3k/Doc/library/python.rst Thu Apr 24 04:43:56 2008 @@ -14,7 +14,6 @@ sys.rst builtins.rst - future_builtins.rst __main__.rst warnings.rst contextlib.rst From python-3000-checkins at python.org Thu Apr 24 20:23:50 2008 From: python-3000-checkins at python.org (amaury.forgeotdarc) Date: Thu, 24 Apr 2008 20:23:50 +0200 (CEST) Subject: [Python-3000-checkins] r62482 - python/branches/py3k/Python/import.c Message-ID: <20080424182350.A6E791E4007@bag.python.org> Author: amaury.forgeotdarc Date: Thu Apr 24 20:23:22 2008 New Revision: 62482 Log: There is no reason for imp.get_magic() to return a mutable bytearray Modified: python/branches/py3k/Python/import.c Modified: python/branches/py3k/Python/import.c ============================================================================== --- python/branches/py3k/Python/import.c (original) +++ python/branches/py3k/Python/import.c Thu Apr 24 20:23:22 2008 @@ -2686,7 +2686,7 @@ buf[2] = (char) ((pyc_magic >> 16) & 0xff); buf[3] = (char) ((pyc_magic >> 24) & 0xff); - return PyBytes_FromStringAndSize(buf, 4); + return PyString_FromStringAndSize(buf, 4); } static PyObject * From python-3000-checkins at python.org Thu Apr 24 20:39:52 2008 From: python-3000-checkins at python.org (thomas.heller) Date: Thu, 24 Apr 2008 20:39:52 +0200 (CEST) Subject: [Python-3000-checkins] r62484 - in python/branches/py3k: Misc/NEWS Modules/_ctypes/_ctypes.c Modules/_ctypes/callbacks.c Modules/_ctypes/ctypes.h Message-ID: <20080424183952.0B5901E4007@bag.python.org> Author: thomas.heller Date: Thu Apr 24 20:39:36 2008 New Revision: 62484 Log: Merged revisions 62481 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62481 | thomas.heller | 2008-04-24 20:14:19 +0200 (Do, 24 Apr 2008) | 3 lines Remove cyclic reference in CFuncPtr instances; see issue #2682. Backport candidate for the release25-maint branch. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Misc/NEWS python/branches/py3k/Modules/_ctypes/_ctypes.c python/branches/py3k/Modules/_ctypes/callbacks.c python/branches/py3k/Modules/_ctypes/ctypes.h Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Thu Apr 24 20:39:36 2008 @@ -32,6 +32,9 @@ Library ------- +- Issue #2682: ctypes callback functions now longer contain a cyclic + reference to themselves. + - Issue #2058: Remove the buf attribute and add __slots__ to the TarInfo class in order to reduce tarfile's memory usage. Modified: python/branches/py3k/Modules/_ctypes/_ctypes.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/_ctypes.c (original) +++ python/branches/py3k/Modules/_ctypes/_ctypes.c Thu Apr 24 20:39:36 2008 @@ -3052,7 +3052,7 @@ CFuncPtrObject *self; PyObject *callable; StgDictObject *dict; - ffi_info *thunk; + CThunkObject *thunk; if (PyTuple_GET_SIZE(args) == 0) return GenericCData_new(type, args, kwds); @@ -3108,11 +3108,6 @@ return NULL; } - /*****************************************************************/ - /* The thunk keeps unowned references to callable and dict->argtypes - so we have to keep them alive somewhere else: callable is kept in self, - dict->argtypes is in the type's stgdict. - */ thunk = AllocFunctionCallback(callable, dict->argtypes, dict->restype, @@ -3121,27 +3116,22 @@ return NULL; self = (CFuncPtrObject *)GenericCData_new(type, args, kwds); - if (self == NULL) + if (self == NULL) { + Py_DECREF(thunk); return NULL; + } Py_INCREF(callable); self->callable = callable; self->thunk = thunk; - *(void **)self->b_ptr = *(void **)thunk; - - /* We store ourself in self->b_objects[0], because the whole instance - must be kept alive if stored in a structure field, for example. - Cycle GC to the rescue! And we have a unittest proving that this works - correctly... - */ - - Py_INCREF((PyObject *)self); /* for KeepRef */ - if (-1 == KeepRef((CDataObject *)self, 0, (PyObject *)self)) { + *(void **)self->b_ptr = (void *)thunk->pcl; + + Py_INCREF((PyObject *)thunk); /* for KeepRef */ + if (-1 == KeepRef((CDataObject *)self, 0, (PyObject *)thunk)) { Py_DECREF((PyObject *)self); return NULL; } - return (PyObject *)self; } @@ -3590,6 +3580,7 @@ Py_VISIT(self->argtypes); Py_VISIT(self->converters); Py_VISIT(self->paramflags); + Py_VISIT(self->thunk); return CData_traverse((CDataObject *)self, visit, arg); } @@ -3603,13 +3594,7 @@ Py_CLEAR(self->argtypes); Py_CLEAR(self->converters); Py_CLEAR(self->paramflags); - - if (self->thunk) { - FreeClosure(self->thunk->pcl); - PyMem_Free(self->thunk); - self->thunk = NULL; - } - + Py_CLEAR(self->thunk); return CData_clear((CDataObject *)self); } @@ -5011,6 +4996,9 @@ if (PyType_Ready(&PyCArg_Type) < 0) return; + if (PyType_Ready(&CThunk_Type) < 0) + return; + /* StgDict is derived from PyDict_Type */ StgDict_Type.tp_base = &PyDict_Type; if (PyType_Ready(&StgDict_Type) < 0) Modified: python/branches/py3k/Modules/_ctypes/callbacks.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/callbacks.c (original) +++ python/branches/py3k/Modules/_ctypes/callbacks.c Thu Apr 24 20:39:36 2008 @@ -7,6 +7,73 @@ #endif #include "ctypes.h" +/**************************************************************/ + +static CThunkObject_dealloc(PyObject *_self) +{ + CThunkObject *self = (CThunkObject *)_self; + Py_XDECREF(self->converters); + Py_XDECREF(self->callable); + Py_XDECREF(self->restype); + if (self->pcl) + FreeClosure(self->pcl); + PyObject_Del(self); +} + +static int +CThunkObject_traverse(PyObject *_self, visitproc visit, void *arg) +{ + CThunkObject *self = (CThunkObject *)_self; + Py_VISIT(self->converters); + Py_VISIT(self->callable); + Py_VISIT(self->restype); + return 0; +} + +static int +CThunkObject_clear(PyObject *_self) +{ + CThunkObject *self = (CThunkObject *)_self; + Py_CLEAR(self->converters); + Py_CLEAR(self->callable); + Py_CLEAR(self->restype); + return 0; +} + +PyTypeObject CThunk_Type = { + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.CThunkObject", + sizeof(CThunkObject), /* tp_basicsize */ + sizeof(ffi_type), /* tp_itemsize */ + CThunkObject_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + "CThunkObject", /* tp_doc */ + CThunkObject_traverse, /* tp_traverse */ + CThunkObject_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ +}; + +/**************************************************************/ + static void PrintError(char *msg, ...) { @@ -244,32 +311,56 @@ void **args, void *userdata) { - ffi_info *p = userdata; + CThunkObject *p = (CThunkObject *)userdata; _CallPythonObject(resp, - p->restype, + p->ffi_restype, p->setfunc, p->callable, p->converters, args); } -ffi_info *AllocFunctionCallback(PyObject *callable, - PyObject *converters, - PyObject *restype, - int is_cdecl) +static CThunkObject* CThunkObject_new(Py_ssize_t nArgs) +{ + CThunkObject *p; + int i; + + p = PyObject_NewVar(CThunkObject, &CThunk_Type, nArgs); + if (p == NULL) { + PyErr_NoMemory(); + return NULL; + } + + p->pcl = NULL; + memset(&p->cif, 0, sizeof(p->cif)); + p->converters = NULL; + p->callable = NULL; + p->setfunc = NULL; + p->ffi_restype = NULL; + + for (i = 0; i < nArgs + 1; ++i) + p->atypes[i] = NULL; + return p; +} + +CThunkObject *AllocFunctionCallback(PyObject *callable, + PyObject *converters, + PyObject *restype, + int is_cdecl) { int result; - ffi_info *p; + CThunkObject *p; Py_ssize_t nArgs, i; ffi_abi cc; nArgs = PySequence_Size(converters); - p = (ffi_info *)PyMem_Malloc(sizeof(ffi_info) + sizeof(ffi_type) * (nArgs)); - if (p == NULL) { - PyErr_NoMemory(); + p = CThunkObject_new(nArgs); + if (p == NULL) return NULL; - } + + assert(CThunk_CheckExact((PyObject *)p)); + p->pcl = MallocClosure(); if (p->pcl == NULL) { PyErr_NoMemory(); @@ -285,9 +376,11 @@ } p->atypes[i] = NULL; + Py_INCREF(restype); + p->restype = restype; if (restype == Py_None) { p->setfunc = NULL; - p->restype = &ffi_type_void; + p->ffi_restype = &ffi_type_void; } else { StgDictObject *dict = PyType_stgdict(restype); if (dict == NULL || dict->setfunc == NULL) { @@ -296,7 +389,7 @@ goto error; } p->setfunc = dict->setfunc; - p->restype = &dict->ffi_type_pointer; + p->ffi_restype = &dict->ffi_type_pointer; } cc = FFI_DEFAULT_ABI; @@ -320,16 +413,14 @@ goto error; } + Py_INCREF(converters); p->converters = converters; + Py_INCREF(callable); p->callable = callable; return p; error: - if (p) { - if (p->pcl) - FreeClosure(p->pcl); - PyMem_Free(p); - } + Py_XDECREF(p); return NULL; } Modified: python/branches/py3k/Modules/_ctypes/ctypes.h ============================================================================== --- python/branches/py3k/Modules/_ctypes/ctypes.h (original) +++ python/branches/py3k/Modules/_ctypes/ctypes.h Thu Apr 24 20:39:36 2008 @@ -53,14 +53,18 @@ }; typedef struct { + PyObject_VAR_HEAD ffi_closure *pcl; /* the C callable */ ffi_cif cif; PyObject *converters; PyObject *callable; + PyObject *restype; SETFUNC setfunc; - ffi_type *restype; + ffi_type *ffi_restype; ffi_type *atypes[1]; -} ffi_info; +} CThunkObject; +extern PyTypeObject CThunk_Type; +#define CThunk_CheckExact(v) ((v)->ob_type == &CThunk_Type) typedef struct { /* First part identical to tagCDataObject */ @@ -76,7 +80,7 @@ union value b_value; /* end of tagCDataObject, additional fields follow */ - ffi_info *thunk; + CThunkObject *thunk; PyObject *callable; /* These two fields will override the ones in the type's stgdict if @@ -147,10 +151,10 @@ extern PyMethodDef module_methods[]; -extern ffi_info *AllocFunctionCallback(PyObject *callable, - PyObject *converters, - PyObject *restype, - int stdcall); +extern CThunkObject *AllocFunctionCallback(PyObject *callable, + PyObject *converters, + PyObject *restype, + int stdcall); /* a table entry describing a predefined ctypes type */ struct fielddesc { char code; From python-3000-checkins at python.org Thu Apr 24 22:48:13 2008 From: python-3000-checkins at python.org (amaury.forgeotdarc) Date: Thu, 24 Apr 2008 22:48:13 +0200 (CEST) Subject: [Python-3000-checkins] r62488 - in python/branches/py3k: Lib/test/test_pydoc.py Lib/test/test_sundry.py Message-ID: <20080424204813.482201E4012@bag.python.org> Author: amaury.forgeotdarc Date: Thu Apr 24 22:48:12 2008 New Revision: 62488 Log: Merged revisions 62486-62487 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62486 | amaury.forgeotdarc | 2008-04-24 16:22:26 -0400 (Thu, 24 Apr 2008) | 7 lines Add a few tests for pydoc. This is a modified version of a patch proposed by Guilherme Polo in the discussion of issue1883. I will merge manually this change into the py3k branch: the tests must be adapted. ........ r62487 | amaury.forgeotdarc | 2008-04-24 16:41:50 -0400 (Thu, 24 Apr 2008) | 2 lines Use absolute import for test package ........ Added: python/branches/py3k/Lib/test/test_pydoc.py - copied unchanged from r62487, /python/trunk/Lib/test/test_pydoc.py Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_sundry.py Modified: python/branches/py3k/Lib/test/test_sundry.py ============================================================================== --- python/branches/py3k/Lib/test/test_sundry.py (original) +++ python/branches/py3k/Lib/test/test_sundry.py Thu Apr 24 22:48:12 2008 @@ -86,7 +86,6 @@ import pdb import pstats import py_compile - import pydoc import rlcompleter import sched import smtplib From python-3000-checkins at python.org Thu Apr 24 23:00:04 2008 From: python-3000-checkins at python.org (amaury.forgeotdarc) Date: Thu, 24 Apr 2008 23:00:04 +0200 (CEST) Subject: [Python-3000-checkins] r62489 - in python/branches/py3k/Lib: pydoc.py test/test_pydoc.py Message-ID: <20080424210004.73B951E4007@bag.python.org> Author: amaury.forgeotdarc Date: Thu Apr 24 23:00:04 2008 New Revision: 62489 Log: Correct recently merged tests: - two bugs in pydoc.py - remove test about classic classes Modified: python/branches/py3k/Lib/pydoc.py python/branches/py3k/Lib/test/test_pydoc.py Modified: python/branches/py3k/Lib/pydoc.py ============================================================================== --- python/branches/py3k/Lib/pydoc.py (original) +++ python/branches/py3k/Lib/pydoc.py Thu Apr 24 23:00:04 2008 @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: Latin-1 -*- +# -*- coding: latin-1 -*- """Generate Python documentation in HTML or text for interactive use. In the Python interpreter, do "from pydoc import help" to provide online @@ -1074,7 +1074,7 @@ if submodules: submodules.sort() result = result + self.section( - 'SUBMODULES', join(submodules, '\n')) + 'SUBMODULES', '\n'.join(submodules)) if classes: classlist = [value for key, value in classes] @@ -1484,7 +1484,8 @@ desc += ' in ' + name[:name.rfind('.')] elif module and module is not object: desc += ' in module ' + module.__name__ - elif not (inspect.ismodule(object) or + + if not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or inspect.isgetsetdescriptor(object) or Modified: python/branches/py3k/Lib/test/test_pydoc.py ============================================================================== --- python/branches/py3k/Lib/test/test_pydoc.py (original) +++ python/branches/py3k/Lib/test/test_pydoc.py Thu Apr 24 23:00:04 2008 @@ -9,14 +9,6 @@ doc = pydoc.render_doc(pydocfodder) assert "pydocfodder" in doc - def test_classic_class(self): - class C: "Classic class" - c = C() - self.failUnlessEqual(pydoc.describe(C), 'class C') - self.failUnlessEqual(pydoc.describe(c), 'instance of C') - self.failUnless('instance of C in module test.test_pydoc' - in pydoc.render_doc(c)) - def test_class(self): class C(object): "New-style class" c = C() From python-3000-checkins at python.org Fri Apr 25 03:59:12 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Fri, 25 Apr 2008 03:59:12 +0200 (CEST) Subject: [Python-3000-checkins] r62491 - in python/branches/py3k: Doc/library/asynchat.rst Doc/library/asyncore.rst Doc/library/basehttpserver.rst Doc/library/bdb.rst Doc/library/bz2.rst Doc/library/calendar.rst Doc/library/cgihttpserver.rst Doc/library/chunk.rst Doc/library/codecs.rst Doc/library/collections.rst Doc/library/csv.rst Doc/library/ctypes.rst Doc/library/curses.rst Doc/library/decimal.rst Doc/library/difflib.rst Doc/library/doctest.rst Doc/library/email.charset.rst Doc/library/email.generator.rst Doc/library/email.header.rst Doc/library/email.message.rst Doc/library/email.parser.rst Doc/library/filecmp.rst Doc/library/fractions.rst Doc/library/ftplib.rst Doc/library/gettext.rst Doc/library/logging.rst Doc/library/mailbox.rst Doc/library/mmap.rst Doc/library/modulefinder.rst Doc/library/msilib.rst Doc/library/numbers.rst Doc/library/pickle.rst Doc/library/robotparser.rst Doc/library/simplehttpserver.rst Doc/library/smtpd.rst Doc/library/string.rst Doc/library/struct.rst Doc/library/textwrap.rst Doc/library/xml.etree.elementtree.rst Doc/library/zipimport.rst Message-ID: <20080425015912.5421F1E4009@bag.python.org> Author: benjamin.peterson Date: Fri Apr 25 03:59:09 2008 New Revision: 62491 Log: Merged revisions 62490 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62490 | benjamin.peterson | 2008-04-24 20:29:10 -0500 (Thu, 24 Apr 2008) | 2 lines reformat some documentation of classes so methods and attributes are under the class directive ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/asynchat.rst python/branches/py3k/Doc/library/asyncore.rst python/branches/py3k/Doc/library/basehttpserver.rst python/branches/py3k/Doc/library/bdb.rst python/branches/py3k/Doc/library/bz2.rst python/branches/py3k/Doc/library/calendar.rst python/branches/py3k/Doc/library/cgihttpserver.rst python/branches/py3k/Doc/library/chunk.rst python/branches/py3k/Doc/library/codecs.rst python/branches/py3k/Doc/library/collections.rst python/branches/py3k/Doc/library/csv.rst python/branches/py3k/Doc/library/ctypes.rst python/branches/py3k/Doc/library/curses.rst python/branches/py3k/Doc/library/decimal.rst python/branches/py3k/Doc/library/difflib.rst python/branches/py3k/Doc/library/doctest.rst python/branches/py3k/Doc/library/email.charset.rst python/branches/py3k/Doc/library/email.generator.rst python/branches/py3k/Doc/library/email.header.rst python/branches/py3k/Doc/library/email.message.rst python/branches/py3k/Doc/library/email.parser.rst python/branches/py3k/Doc/library/filecmp.rst python/branches/py3k/Doc/library/fractions.rst python/branches/py3k/Doc/library/ftplib.rst python/branches/py3k/Doc/library/gettext.rst python/branches/py3k/Doc/library/logging.rst python/branches/py3k/Doc/library/mailbox.rst python/branches/py3k/Doc/library/mmap.rst python/branches/py3k/Doc/library/modulefinder.rst python/branches/py3k/Doc/library/msilib.rst python/branches/py3k/Doc/library/numbers.rst python/branches/py3k/Doc/library/pickle.rst python/branches/py3k/Doc/library/robotparser.rst python/branches/py3k/Doc/library/simplehttpserver.rst python/branches/py3k/Doc/library/smtpd.rst python/branches/py3k/Doc/library/string.rst python/branches/py3k/Doc/library/struct.rst python/branches/py3k/Doc/library/textwrap.rst python/branches/py3k/Doc/library/xml.etree.elementtree.rst python/branches/py3k/Doc/library/zipimport.rst Modified: python/branches/py3k/Doc/library/asynchat.rst ============================================================================== --- python/branches/py3k/Doc/library/asynchat.rst (original) +++ python/branches/py3k/Doc/library/asynchat.rst Fri Apr 25 03:59:09 2008 @@ -197,10 +197,10 @@ the data no larger than *buffer_size*. -.. method:: simple_producer.more() + .. method:: more() - Produces the next chunk of information from the producer, or returns the - empty string. + Produces the next chunk of information from the producer, or returns the + empty string. .. class:: fifo([list=None]) @@ -212,26 +212,26 @@ producers or data items to be written to the channel. -.. method:: fifo.is_empty() + .. method:: is_empty() - Returns ``True`` if and only if the fifo is empty. + Returns ``True`` if and only if the fifo is empty. -.. method:: fifo.first() + .. method:: first() - Returns the least-recently :meth:`push`\ ed item from the fifo. + Returns the least-recently :meth:`push`\ ed item from the fifo. -.. method:: fifo.push(data) + .. method:: push(data) - Adds the given data (which may be a string or a producer object) to the - producer fifo. + Adds the given data (which may be a string or a producer object) to the + producer fifo. -.. method:: fifo.pop() + .. method:: pop() - If the fifo is not empty, returns ``True, first()``, deleting the popped - item. Returns ``False, None`` for an empty fifo. + If the fifo is not empty, returns ``True, first()``, deleting the popped + item. Returns ``False, None`` for an empty fifo. The :mod:`asynchat` module also defines one utility function, which may be of use in network and textual analysis operations. Modified: python/branches/py3k/Doc/library/asyncore.rst ============================================================================== --- python/branches/py3k/Doc/library/asyncore.rst (original) +++ python/branches/py3k/Doc/library/asyncore.rst Fri Apr 25 03:59:09 2008 @@ -95,132 +95,132 @@ should be added to the list of channels :cfunc:`select`\ ed or :cfunc:`poll`\ ed for read and write events. -Thus, the set of channel events is larger than the basic socket events. The -full set of methods that can be overridden in your subclass follows: + Thus, the set of channel events is larger than the basic socket events. The + full set of methods that can be overridden in your subclass follows: -.. method:: dispatcher.handle_read() + .. method:: handle_read() - Called when the asynchronous loop detects that a :meth:`read` call on the - channel's socket will succeed. + Called when the asynchronous loop detects that a :meth:`read` call on the + channel's socket will succeed. -.. method:: dispatcher.handle_write() + .. method:: handle_write() - Called when the asynchronous loop detects that a writable socket can be - written. Often this method will implement the necessary buffering for - performance. For example:: + Called when the asynchronous loop detects that a writable socket can be + written. Often this method will implement the necessary buffering for + performance. For example:: - def handle_write(self): - sent = self.send(self.buffer) - self.buffer = self.buffer[sent:] + def handle_write(self): + sent = self.send(self.buffer) + self.buffer = self.buffer[sent:] -.. method:: dispatcher.handle_expt() + .. method:: handle_expt() - Called when there is out of band (OOB) data for a socket connection. This - will almost never happen, as OOB is tenuously supported and rarely used. + Called when there is out of band (OOB) data for a socket connection. This + will almost never happen, as OOB is tenuously supported and rarely used. -.. method:: dispatcher.handle_connect() + .. method:: handle_connect() - Called when the active opener's socket actually makes a connection. Might - send a "welcome" banner, or initiate a protocol negotiation with the remote - endpoint, for example. + Called when the active opener's socket actually makes a connection. Might + send a "welcome" banner, or initiate a protocol negotiation with the + remote endpoint, for example. -.. method:: dispatcher.handle_close() + .. method:: handle_close() - Called when the socket is closed. + Called when the socket is closed. -.. method:: dispatcher.handle_error() + .. method:: handle_error() - Called when an exception is raised and not otherwise handled. The default - version prints a condensed traceback. + Called when an exception is raised and not otherwise handled. The default + version prints a condensed traceback. -.. method:: dispatcher.handle_accept() + .. method:: handle_accept() - Called on listening channels (passive openers) when a connection can be - established with a new remote endpoint that has issued a :meth:`connect` - call for the local endpoint. + Called on listening channels (passive openers) when a connection can be + established with a new remote endpoint that has issued a :meth:`connect` + call for the local endpoint. -.. method:: dispatcher.readable() + .. method:: readable() - Called each time around the asynchronous loop to determine whether a - channel's socket should be added to the list on which read events can - occur. The default method simply returns ``True``, indicating that by - default, all channels will be interested in read events. + Called each time around the asynchronous loop to determine whether a + channel's socket should be added to the list on which read events can + occur. The default method simply returns ``True``, indicating that by + default, all channels will be interested in read events. -.. method:: dispatcher.writable() + .. method:: writable() - Called each time around the asynchronous loop to determine whether a - channel's socket should be added to the list on which write events can - occur. The default method simply returns ``True``, indicating that by - default, all channels will be interested in write events. + Called each time around the asynchronous loop to determine whether a + channel's socket should be added to the list on which write events can + occur. The default method simply returns ``True``, indicating that by + default, all channels will be interested in write events. -In addition, each channel delegates or extends many of the socket methods. -Most of these are nearly identical to their socket partners. + In addition, each channel delegates or extends many of the socket methods. + Most of these are nearly identical to their socket partners. -.. method:: dispatcher.create_socket(family, type) - This is identical to the creation of a normal socket, and will use the same - options for creation. Refer to the :mod:`socket` documentation for - information on creating sockets. + .. method:: create_socket(family, type) + This is identical to the creation of a normal socket, and will use the + same options for creation. Refer to the :mod:`socket` documentation for + information on creating sockets. -.. method:: dispatcher.connect(address) - As with the normal socket object, *address* is a tuple with the first - element the host to connect to, and the second the port number. + .. method:: connect(address) + As with the normal socket object, *address* is a tuple with the first + element the host to connect to, and the second the port number. -.. method:: dispatcher.send(data) - Send *data* to the remote end-point of the socket. + .. method:: send(data) + Send *data* to the remote end-point of the socket. -.. method:: dispatcher.recv(buffer_size) - Read at most *buffer_size* bytes from the socket's remote end-point. - An empty string implies that the channel has been closed from the other - end. + .. method:: recv(buffer_size) + Read at most *buffer_size* bytes from the socket's remote end-point. An + empty string implies that the channel has been closed from the other end. -.. method:: dispatcher.listen(backlog) - Listen for connections made to the socket. The *backlog* argument - specifies the maximum number of queued connections and should be at least - 1; the maximum value is system-dependent (usually 5). + .. method:: listen(backlog) + Listen for connections made to the socket. The *backlog* argument + specifies the maximum number of queued connections and should be at least + 1; the maximum value is system-dependent (usually 5). -.. method:: dispatcher.bind(address) - Bind the socket to *address*. The socket must not already be bound. (The - format of *address* depends on the address family --- see above.) To mark - the socket as re-usable (setting the :const:`SO_REUSEADDR` option), call - the :class:`dispatcher` object's :meth:`set_reuse_addr` method. + .. method:: bind(address) + Bind the socket to *address*. The socket must not already be bound. (The + format of *address* depends on the address family --- see above.) To mark + the socket as re-usable (setting the :const:`SO_REUSEADDR` option), call + the :class:`dispatcher` object's :meth:`set_reuse_addr` method. -.. method:: dispatcher.accept() - Accept a connection. The socket must be bound to an address and listening - for connections. The return value is a pair ``(conn, address)`` where - *conn* is a *new* socket object usable to send and receive data on the - connection, and *address* is the address bound to the socket on the other - end of the connection. + .. method:: accept() + Accept a connection. The socket must be bound to an address and listening + for connections. The return value is a pair ``(conn, address)`` where + *conn* is a *new* socket object usable to send and receive data on the + connection, and *address* is the address bound to the socket on the other + end of the connection. -.. method:: dispatcher.close() - Close the socket. All future operations on the socket object will fail. - The remote end-point will receive no more data (after queued data is - flushed). Sockets are automatically closed when they are - garbage-collected. + .. method:: close() + + Close the socket. All future operations on the socket object will fail. + The remote end-point will receive no more data (after queued data is + flushed). Sockets are automatically closed when they are + garbage-collected. .. _asyncore-example: Modified: python/branches/py3k/Doc/library/basehttpserver.rst ============================================================================== --- python/branches/py3k/Doc/library/basehttpserver.rst (original) +++ python/branches/py3k/Doc/library/basehttpserver.rst Fri Apr 25 03:59:09 2008 @@ -34,216 +34,224 @@ .. class:: HTTPServer(server_address, RequestHandlerClass) - This class builds on the :class:`TCPServer` class by storing the server address - as instance variables named :attr:`server_name` and :attr:`server_port`. The - server is accessible by the handler, typically through the handler's - :attr:`server` instance variable. + This class builds on the :class:`TCPServer` class by storing the server + address as instance variables named :attr:`server_name` and + :attr:`server_port`. The server is accessible by the handler, typically + through the handler's :attr:`server` instance variable. .. class:: BaseHTTPRequestHandler(request, client_address, server) This class is used to handle the HTTP requests that arrive at the server. By - itself, it cannot respond to any actual HTTP requests; it must be subclassed to - handle each request method (e.g. GET or POST). :class:`BaseHTTPRequestHandler` - provides a number of class and instance variables, and methods for use by - subclasses. + itself, it cannot respond to any actual HTTP requests; it must be subclassed + to handle each request method (e.g. GET or + POST). :class:`BaseHTTPRequestHandler` provides a number of class and + instance variables, and methods for use by subclasses. - The handler will parse the request and the headers, then call a method specific - to the request type. The method name is constructed from the request. For - example, for the request method ``SPAM``, the :meth:`do_SPAM` method will be - called with no arguments. All of the relevant information is stored in instance - variables of the handler. Subclasses should not need to override or extend the - :meth:`__init__` method. + The handler will parse the request and the headers, then call a method + specific to the request type. The method name is constructed from the + request. For example, for the request method ``SPAM``, the :meth:`do_SPAM` + method will be called with no arguments. All of the relevant information is + stored in instance variables of the handler. Subclasses should not need to + override or extend the :meth:`__init__` method. -:class:`BaseHTTPRequestHandler` has the following instance variables: + :class:`BaseHTTPRequestHandler` has the following instance variables: -.. attribute:: BaseHTTPRequestHandler.client_address + .. attribute:: client_address - Contains a tuple of the form ``(host, port)`` referring to the client's address. + Contains a tuple of the form ``(host, port)`` referring to the client's + address. -.. attribute:: BaseHTTPRequestHandler.command + .. attribute:: command - Contains the command (request type). For example, ``'GET'``. + Contains the command (request type). For example, ``'GET'``. -.. attribute:: BaseHTTPRequestHandler.path + .. attribute:: path - Contains the request path. + Contains the request path. -.. attribute:: BaseHTTPRequestHandler.request_version + .. attribute:: request_version - Contains the version string from the request. For example, ``'HTTP/1.0'``. + Contains the version string from the request. For example, ``'HTTP/1.0'``. -.. attribute:: BaseHTTPRequestHandler.headers + .. attribute:: headers - Holds an instance of the class specified by the :attr:`MessageClass` class - variable. This instance parses and manages the headers in the HTTP request. + Holds an instance of the class specified by the :attr:`MessageClass` class + variable. This instance parses and manages the headers in the HTTP + request. -.. attribute:: BaseHTTPRequestHandler.rfile + .. attribute:: rfile - Contains an input stream, positioned at the start of the optional input data. + Contains an input stream, positioned at the start of the optional input + data. -.. attribute:: BaseHTTPRequestHandler.wfile + .. attribute:: wfile - Contains the output stream for writing a response back to the client. Proper - adherence to the HTTP protocol must be used when writing to this stream. + Contains the output stream for writing a response back to the + client. Proper adherence to the HTTP protocol must be used when writing to + this stream. -:class:`BaseHTTPRequestHandler` has the following class variables: + :class:`BaseHTTPRequestHandler` has the following class variables: -.. attribute:: BaseHTTPRequestHandler.server_version - Specifies the server software version. You may want to override this. The - format is multiple whitespace-separated strings, where each string is of the - form name[/version]. For example, ``'BaseHTTP/0.2'``. + .. attribute:: server_version + Specifies the server software version. You may want to override this. The + format is multiple whitespace-separated strings, where each string is of + the form name[/version]. For example, ``'BaseHTTP/0.2'``. -.. attribute:: BaseHTTPRequestHandler.sys_version - Contains the Python system version, in a form usable by the - :attr:`version_string` method and the :attr:`server_version` class variable. For - example, ``'Python/1.4'``. + .. attribute:: sys_version + Contains the Python system version, in a form usable by the + :attr:`version_string` method and the :attr:`server_version` class + variable. For example, ``'Python/1.4'``. -.. attribute:: BaseHTTPRequestHandler.error_message_format - Specifies a format string for building an error response to the client. It uses - parenthesized, keyed format specifiers, so the format operand must be a - dictionary. The *code* key should be an integer, specifying the numeric HTTP - error code value. *message* should be a string containing a (detailed) error - message of what occurred, and *explain* should be an explanation of the error - code number. Default *message* and *explain* values can found in the *responses* - class variable. + .. attribute:: error_message_format + Specifies a format string for building an error response to the client. It + uses parenthesized, keyed format specifiers, so the format operand must be + a dictionary. The *code* key should be an integer, specifying the numeric + HTTP error code value. *message* should be a string containing a + (detailed) error message of what occurred, and *explain* should be an + explanation of the error code number. Default *message* and *explain* + values can found in the *responses* class variable. -.. attribute:: BaseHTTPRequestHandler.error_content_type - Specifies the Content-Type HTTP header of error responses sent to the client. - The default value is ``'text/html'``. + .. attribute:: error_content_type + Specifies the Content-Type HTTP header of error responses sent to the + client. The default value is ``'text/html'``. -.. attribute:: BaseHTTPRequestHandler.protocol_version - This specifies the HTTP protocol version used in responses. If set to - ``'HTTP/1.1'``, the server will permit HTTP persistent connections; however, - your server *must* then include an accurate ``Content-Length`` header (using - :meth:`send_header`) in all of its responses to clients. For backwards - compatibility, the setting defaults to ``'HTTP/1.0'``. + .. attribute:: protocol_version + This specifies the HTTP protocol version used in responses. If set to + ``'HTTP/1.1'``, the server will permit HTTP persistent connections; + however, your server *must* then include an accurate ``Content-Length`` + header (using :meth:`send_header`) in all of its responses to clients. + For backwards compatibility, the setting defaults to ``'HTTP/1.0'``. -.. attribute:: BaseHTTPRequestHandler.MessageClass - .. index:: single: Message (in module mimetools) + .. attribute:: MessageClass - Specifies a :class:`rfc822.Message`\ -like class to parse HTTP headers. - Typically, this is not overridden, and it defaults to - :class:`mimetools.Message`. + .. index:: single: Message (in module mimetools) + Specifies a :class:`rfc822.Message`\ -like class to parse HTTP headers. + Typically, this is not overridden, and it defaults to + :class:`mimetools.Message`. -.. attribute:: BaseHTTPRequestHandler.responses - This variable contains a mapping of error code integers to two-element tuples - containing a short and long message. For example, ``{code: (shortmessage, - longmessage)}``. The *shortmessage* is usually used as the *message* key in an - error response, and *longmessage* as the *explain* key (see the - :attr:`error_message_format` class variable). + .. attribute:: responses -A :class:`BaseHTTPRequestHandler` instance has the following methods: + This variable contains a mapping of error code integers to two-element tuples + containing a short and long message. For example, ``{code: (shortmessage, + longmessage)}``. The *shortmessage* is usually used as the *message* key in an + error response, and *longmessage* as the *explain* key (see the + :attr:`error_message_format` class variable). -.. method:: BaseHTTPRequestHandler.handle() + A :class:`BaseHTTPRequestHandler` instance has the following methods: - Calls :meth:`handle_one_request` once (or, if persistent connections are - enabled, multiple times) to handle incoming HTTP requests. You should never need - to override it; instead, implement appropriate :meth:`do_\*` methods. + .. method:: handle() -.. method:: BaseHTTPRequestHandler.handle_one_request() + Calls :meth:`handle_one_request` once (or, if persistent connections are + enabled, multiple times) to handle incoming HTTP requests. You should + never need to override it; instead, implement appropriate :meth:`do_\*` + methods. - This method will parse and dispatch the request to the appropriate :meth:`do_\*` - method. You should never need to override it. + .. method:: handle_one_request() -.. method:: BaseHTTPRequestHandler.send_error(code[, message]) + This method will parse and dispatch the request to the appropriate + :meth:`do_\*` method. You should never need to override it. - Sends and logs a complete error reply to the client. The numeric *code* - specifies the HTTP error code, with *message* as optional, more specific text. A - complete set of headers is sent, followed by text composed using the - :attr:`error_message_format` class variable. + .. method:: send_error(code[, message]) -.. method:: BaseHTTPRequestHandler.send_response(code[, message]) + Sends and logs a complete error reply to the client. The numeric *code* + specifies the HTTP error code, with *message* as optional, more specific text. A + complete set of headers is sent, followed by text composed using the + :attr:`error_message_format` class variable. - Sends a response header and logs the accepted request. The HTTP response line is - sent, followed by *Server* and *Date* headers. The values for these two headers - are picked up from the :meth:`version_string` and :meth:`date_time_string` - methods, respectively. + .. method:: send_response(code[, message]) -.. method:: BaseHTTPRequestHandler.send_header(keyword, value) + Sends a response header and logs the accepted request. The HTTP response + line is sent, followed by *Server* and *Date* headers. The values for + these two headers are picked up from the :meth:`version_string` and + :meth:`date_time_string` methods, respectively. - Writes a specific HTTP header to the output stream. *keyword* should specify the - header keyword, with *value* specifying its value. + .. method:: send_header(keyword, value) -.. method:: BaseHTTPRequestHandler.end_headers() + Writes a specific HTTP header to the output stream. *keyword* should + specify the header keyword, with *value* specifying its value. - Sends a blank line, indicating the end of the HTTP headers in the response. + .. method:: end_headers() -.. method:: BaseHTTPRequestHandler.log_request([code[, size]]) + Sends a blank line, indicating the end of the HTTP headers in the + response. - Logs an accepted (successful) request. *code* should specify the numeric HTTP - code associated with the response. If a size of the response is available, then - it should be passed as the *size* parameter. + .. method:: log_request([code[, size]]) -.. method:: BaseHTTPRequestHandler.log_error(...) + Logs an accepted (successful) request. *code* should specify the numeric + HTTP code associated with the response. If a size of the response is + available, then it should be passed as the *size* parameter. - Logs an error when a request cannot be fulfilled. By default, it passes the - message to :meth:`log_message`, so it takes the same arguments (*format* and - additional values). + .. method:: log_error(...) -.. method:: BaseHTTPRequestHandler.log_message(format, ...) + Logs an error when a request cannot be fulfilled. By default, it passes + the message to :meth:`log_message`, so it takes the same arguments + (*format* and additional values). - Logs an arbitrary message to ``sys.stderr``. This is typically overridden to - create custom error logging mechanisms. The *format* argument is a standard - printf-style format string, where the additional arguments to - :meth:`log_message` are applied as inputs to the formatting. The client address - and current date and time are prefixed to every message logged. + .. method:: log_message(format, ...) -.. method:: BaseHTTPRequestHandler.version_string() + Logs an arbitrary message to ``sys.stderr``. This is typically overridden + to create custom error logging mechanisms. The *format* argument is a + standard printf-style format string, where the additional arguments to + :meth:`log_message` are applied as inputs to the formatting. The client + address and current date and time are prefixed to every message logged. - Returns the server software's version string. This is a combination of the - :attr:`server_version` and :attr:`sys_version` class variables. + .. method:: version_string() -.. method:: BaseHTTPRequestHandler.date_time_string([timestamp]) + Returns the server software's version string. This is a combination of the + :attr:`server_version` and :attr:`sys_version` class variables. - Returns the date and time given by *timestamp* (which must be in the format - returned by :func:`time.time`), formatted for a message header. If *timestamp* - is omitted, it uses the current date and time. - The result looks like ``'Sun, 06 Nov 1994 08:49:37 GMT'``. + .. method:: date_time_string([timestamp]) + Returns the date and time given by *timestamp* (which must be in the + format returned by :func:`time.time`), formatted for a message header. If + *timestamp* is omitted, it uses the current date and time. -.. method:: BaseHTTPRequestHandler.log_date_time_string() + The result looks like ``'Sun, 06 Nov 1994 08:49:37 GMT'``. - Returns the current date and time, formatted for logging. + .. method:: log_date_time_string() -.. method:: BaseHTTPRequestHandler.address_string() + Returns the current date and time, formatted for logging. - Returns the client address, formatted for logging. A name lookup is performed on - the client's IP address. + + .. method:: address_string() + + Returns the client address, formatted for logging. A name lookup is + performed on the client's IP address. .. seealso:: Modified: python/branches/py3k/Doc/library/bdb.rst ============================================================================== --- python/branches/py3k/Doc/library/bdb.rst (original) +++ python/branches/py3k/Doc/library/bdb.rst Fri Apr 25 03:59:09 2008 @@ -31,32 +31,35 @@ first line of that function is executed. A conditional breakpoint always counts a hit. -:class:`Breakpoint` instances have the following methods: + :class:`Breakpoint` instances have the following methods: -.. method:: Breakpoint.deleteMe() + .. method:: deleteMe() - Delete the breakpoint from the list associated to a file/line. If it is the - last breakpoint in that position, it also deletes the entry for the - file/line. + Delete the breakpoint from the list associated to a file/line. If it is + the last breakpoint in that position, it also deletes the entry for the + file/line. -.. method:: Breakpoint.enable() - Mark the breakpoint as enabled. + .. method:: enable() -.. method:: Breakpoint.disable() + Mark the breakpoint as enabled. - Mark the breakpoint as disabled. -.. method:: Breakpoint.bpprint([out]) + .. method:: disable() - Print all the information about the breakpoint: + Mark the breakpoint as disabled. - * The breakpoint number. - * If it is temporary or not. - * Its file,line position. - * The condition that causes a break. - * If it must be ignored the next N times. - * The breakpoint hit count. + + .. method:: pprint([out]) + + Print all the information about the breakpoint: + + * The breakpoint number. + * If it is temporary or not. + * Its file,line position. + * The condition that causes a break. + * If it must be ignored the next N times. + * The breakpoint hit count. .. class:: Bdb() @@ -68,247 +71,246 @@ (:class:`pdb.Pdb`) is an example. -The following methods of :class:`Bdb` normally don't need to be overridden. - -.. method:: Bdb.canonic(filename) + The following methods of :class:`Bdb` normally don't need to be overridden. - Auxiliary method for getting a filename in a canonical form, that is, as a - case-normalized (on case-insensitive filesystems) absolute path, stripped - of surrounding angle brackets. + .. method:: canonic(filename) -.. method:: Bdb.reset() + Auxiliary method for getting a filename in a canonical form, that is, as a + case-normalized (on case-insensitive filesystems) absolute path, stripped + of surrounding angle brackets. - Set the :attr:`botframe`, :attr:`stopframe`, :attr:`returnframe` and - :attr:`quitting` attributes with values ready to start debugging. + .. method:: reset() + Set the :attr:`botframe`, :attr:`stopframe`, :attr:`returnframe` and + :attr:`quitting` attributes with values ready to start debugging. -.. method:: Bdb.trace_dispatch(frame, event, arg) + .. method:: trace_dispatch(frame, event, arg) - This function is installed as the trace function of debugged frames. Its - return value is the new trace function (in most cases, that is, itself). + This function is installed as the trace function of debugged frames. Its + return value is the new trace function (in most cases, that is, itself). - The default implementation decides how to dispatch a frame, depending on the - type of event (passed as a string) that is about to be executed. *event* can - be one of the following: + The default implementation decides how to dispatch a frame, depending on + the type of event (passed as a string) that is about to be executed. + *event* can be one of the following: - * ``"line"``: A new line of code is going to be executed. - * ``"call"``: A function is about to be called, or another code block - entered. - * ``"return"``: A function or other code block is about to return. - * ``"exception"``: An exception has occurred. - * ``"c_call"``: A C function is about to be called. - * ``"c_return"``: A C function has returned. - * ``"c_exception"``: A C function has thrown an exception. + * ``"line"``: A new line of code is going to be executed. + * ``"call"``: A function is about to be called, or another code block + entered. + * ``"return"``: A function or other code block is about to return. + * ``"exception"``: An exception has occurred. + * ``"c_call"``: A C function is about to be called. + * ``"c_return"``: A C function has returned. + * ``"c_exception"``: A C function has thrown an exception. - For the Python events, specialized functions (see below) are called. For the - C events, no action is taken. + For the Python events, specialized functions (see below) are called. For + the C events, no action is taken. - The *arg* parameter depends on the previous event. + The *arg* parameter depends on the previous event. - For more information on trace functions, see :ref:`debugger-hooks`. For more - information on code and frame objects, refer to :ref:`types`. + For more information on trace functions, see :ref:`debugger-hooks`. For + more information on code and frame objects, refer to :ref:`types`. -.. method:: Bdb.dispatch_line(frame) + .. method:: dispatch_line(frame) - If the debugger should stop on the current line, invoke the :meth:`user_line` - method (which should be overridden in subclasses). Raise a :exc:`BdbQuit` - exception if the :attr:`Bdb.quitting` flag is set (which can be set from - :meth:`user_line`). Return a reference to the :meth:`trace_dispatch` method - for further tracing in that scope. + If the debugger should stop on the current line, invoke the + :meth:`user_line` method (which should be overridden in subclasses). + Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set + (which can be set from :meth:`user_line`). Return a reference to the + :meth:`trace_dispatch` method for further tracing in that scope. -.. method:: Bdb.dispatch_call(frame, arg) + .. method:: dispatch_call(frame, arg) - If the debugger should stop on this function call, invoke the - :meth:`user_call` method (which should be overridden in subclasses). Raise a - :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set (which can - be set from :meth:`user_call`). Return a reference to the - :meth:`trace_dispatch` method for further tracing in that scope. + If the debugger should stop on this function call, invoke the + :meth:`user_call` method (which should be overridden in subclasses). + Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set + (which can be set from :meth:`user_call`). Return a reference to the + :meth:`trace_dispatch` method for further tracing in that scope. -.. method:: Bdb.dispatch_return(frame, arg) + .. method:: dispatch_return(frame, arg) - If the debugger should stop on this function return, invoke the - :meth:`user_return` method (which should be overridden in subclasses). Raise - a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set (which can - be set from :meth:`user_return`). Return a reference to the - :meth:`trace_dispatch` method for further tracing in that scope. + If the debugger should stop on this function return, invoke the + :meth:`user_return` method (which should be overridden in subclasses). + Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set + (which can be set from :meth:`user_return`). Return a reference to the + :meth:`trace_dispatch` method for further tracing in that scope. -.. method:: Bdb.dispatch_exception(frame, arg) + .. method:: dispatch_exception(frame, arg) - If the debugger should stop at this exception, invokes the - :meth:`user_exception` method (which should be overridden in subclasses). - Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set - (which can be set from :meth:`user_exception`). Return a reference to the - :meth:`trace_dispatch` method for further tracing in that scope. + If the debugger should stop at this exception, invokes the + :meth:`user_exception` method (which should be overridden in subclasses). + Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set + (which can be set from :meth:`user_exception`). Return a reference to the + :meth:`trace_dispatch` method for further tracing in that scope. -Normally derived classes don't override the following methods, but they may if -they want to redefine the definition of stopping and breakpoints. + Normally derived classes don't override the following methods, but they may + if they want to redefine the definition of stopping and breakpoints. -.. method:: Bdb.stop_here(frame) + .. method:: stop_here(frame) - This method checks if the *frame* is somewhere below :attr:`botframe` in the - call stack. :attr:`botframe` is the frame in which debugging started. + This method checks if the *frame* is somewhere below :attr:`botframe` in + the call stack. :attr:`botframe` is the frame in which debugging started. -.. method:: Bdb.break_here(frame) + .. method:: break_here(frame) - This method checks if there is a breakpoint in the filename and line - belonging to *frame* or, at least, in the current function. If the - breakpoint is a temporary one, this method deletes it. + This method checks if there is a breakpoint in the filename and line + belonging to *frame* or, at least, in the current function. If the + breakpoint is a temporary one, this method deletes it. -.. method:: Bdb.break_anywhere(frame) + .. method:: break_anywhere(frame) - This method checks if there is a breakpoint in the filename of the current - frame. + This method checks if there is a breakpoint in the filename of the current + frame. -Derived classes should override these methods to gain control over debugger -operation. + Derived classes should override these methods to gain control over debugger + operation. -.. method:: Bdb.user_call(frame, argument_list) + .. method:: user_call(frame, argument_list) - This method is called from :meth:`dispatch_call` when there is the - possibility that a break might be necessary anywhere inside the called - function. + This method is called from :meth:`dispatch_call` when there is the + possibility that a break might be necessary anywhere inside the called + function. -.. method:: Bdb.user_line(frame) + .. method:: user_line(frame) - This method is called from :meth:`dispatch_line` when either - :meth:`stop_here` or :meth:`break_here` yields True. + This method is called from :meth:`dispatch_line` when either + :meth:`stop_here` or :meth:`break_here` yields True. -.. method:: Bdb.user_return(frame, return_value) + .. method:: user_return(frame, return_value) - This method is called from :meth:`dispatch_return` when :meth:`stop_here` - yields True. + This method is called from :meth:`dispatch_return` when :meth:`stop_here` + yields True. -.. method:: Bdb.user_exception(frame, exc_info) + .. method:: user_exception(frame, exc_info) - This method is called from :meth:`dispatch_exception` when :meth:`stop_here` - yields True. + This method is called from :meth:`dispatch_exception` when + :meth:`stop_here` yields True. -.. method:: Bdb.do_clear(arg) + .. method:: do_clear(arg) - Handle how a breakpoint must be removed when it is a temporary one. + Handle how a breakpoint must be removed when it is a temporary one. - This method must be implemented by derived classes. + This method must be implemented by derived classes. -Derived classes and clients can call the following methods to affect the -stepping state. + Derived classes and clients can call the following methods to affect the + stepping state. -.. method:: Bdb.set_step() + .. method:: set_step() - Stop after one line of code. + Stop after one line of code. -.. method:: Bdb.set_next(frame) + .. method:: set_next(frame) - Stop on the next line in or below the given frame. + Stop on the next line in or below the given frame. -.. method:: Bdb.set_return(frame) + .. method:: set_return(frame) - Stop when returning from the given frame. + Stop when returning from the given frame. -.. method:: Bdb.set_trace([frame]) + .. method:: set_trace([frame]) - Start debugging from *frame*. If *frame* is not specified, debugging starts - from caller's frame. + Start debugging from *frame*. If *frame* is not specified, debugging + starts from caller's frame. -.. method:: Bdb.set_continue() + .. method:: set_continue() - Stop only at breakpoints or when finished. If there are no breakpoints, set - the system trace function to None. + Stop only at breakpoints or when finished. If there are no breakpoints, + set the system trace function to None. -.. method:: Bdb.set_quit() + .. method:: set_quit() - Set the :attr:`quitting` attribute to True. This raises :exc:`BdbQuit` in - the next call to one of the :meth:`dispatch_\*` methods. + Set the :attr:`quitting` attribute to True. This raises :exc:`BdbQuit` in + the next call to one of the :meth:`dispatch_\*` methods. -Derived classes and clients can call the following methods to manipulate -breakpoints. These methods return a string containing an error message if -something went wrong, or ``None`` if all is well. + Derived classes and clients can call the following methods to manipulate + breakpoints. These methods return a string containing an error message if + something went wrong, or ``None`` if all is well. -.. method:: Bdb.set_break(filename, lineno[, temporary=0[, cond[, funcname]]]) + .. method:: set_break(filename, lineno[, temporary=0[, cond[, funcname]]]) - Set a new breakpoint. If the *lineno* line doesn't exist for the *filename* - passed as argument, return an error message. The *filename* should be in - canonical form, as described in the :meth:`canonic` method. + Set a new breakpoint. If the *lineno* line doesn't exist for the + *filename* passed as argument, return an error message. The *filename* + should be in canonical form, as described in the :meth:`canonic` method. -.. method:: Bdb.clear_break(filename, lineno) + .. method:: clear_break(filename, lineno) - Delete the breakpoints in *filename* and *lineno*. If none were set, an - error message is returned. + Delete the breakpoints in *filename* and *lineno*. If none were set, an + error message is returned. -.. method:: Bdb.clear_bpbynumber(arg) + .. method:: clear_bpbynumber(arg) - Delete the breakpoint which has the index *arg* in the - :attr:`Breakpoint.bpbynumber`. If *arg* is not numeric or out of range, - return an error message. + Delete the breakpoint which has the index *arg* in the + :attr:`Breakpoint.bpbynumber`. If *arg* is not numeric or out of range, + return an error message. -.. method:: Bdb.clear_all_file_breaks(filename) + .. method:: clear_all_file_breaks(filename) - Delete all breakpoints in *filename*. If none were set, an error message is - returned. + Delete all breakpoints in *filename*. If none were set, an error message + is returned. -.. method:: Bdb.clear_all_breaks() + .. method:: clear_all_breaks() - Delete all existing breakpoints. + Delete all existing breakpoints. -.. method:: Bdb.get_break(filename, lineno) + .. method:: get_break(filename, lineno) - Check if there is a breakpoint for *lineno* of *filename*. + Check if there is a breakpoint for *lineno* of *filename*. -.. method:: Bdb.get_breaks(filename, lineno) + .. method:: get_breaks(filename, lineno) - Return all breakpoints for *lineno* in *filename*, or an empty list if none - are set. + Return all breakpoints for *lineno* in *filename*, or an empty list if + none are set. -.. method:: Bdb.get_file_breaks(filename) + .. method:: get_file_breaks(filename) - Return all breakpoints in *filename*, or an empty list if none are set. + Return all breakpoints in *filename*, or an empty list if none are set. -.. method:: Bdb.get_all_breaks() + .. method:: get_all_breaks() - Return all breakpoints that are set. + Return all breakpoints that are set. -Derived classes and clients can call the following methods to get a data -structure representing a stack trace. + Derived classes and clients can call the following methods to get a data + structure representing a stack trace. -.. method:: Bdb.get_stack(f, t) + .. method:: get_stack(f, t) - Get a list of records for a frame and all higher (calling) and lower frames, - and the size of the higher part. + Get a list of records for a frame and all higher (calling) and lower + frames, and the size of the higher part. -.. method:: Bdb.format_stack_entry(frame_lineno, [lprefix=': ']) + .. method:: format_stack_entry(frame_lineno, [lprefix=': ']) - Return a string with information about a stack entry, identified by a - ``(frame, lineno)`` tuple: + Return a string with information about a stack entry, identified by a + ``(frame, lineno)`` tuple: - * The canonical form of the filename which contains the frame. - * The function name, or ``""``. - * The input arguments. - * The return value. - * The line of code (if it exists). + * The canonical form of the filename which contains the frame. + * The function name, or ``""``. + * The input arguments. + * The return value. + * The line of code (if it exists). -The following two methods can be called by clients to use a debugger to debug a -:term:`statement`, given as a string. + The following two methods can be called by clients to use a debugger to debug + a :term:`statement`, given as a string. -.. method:: Bdb.run(cmd, [globals, [locals]]) + .. method:: run(cmd, [globals, [locals]]) - Debug a statement executed via the :func:`exec` function. *globals* - defaults to :attr:`__main__.__dict__`, *locals* defaults to *globals*. + Debug a statement executed via the :func:`exec` function. *globals* + defaults to :attr:`__main__.__dict__`, *locals* defaults to *globals*. -.. method:: Bdb.runeval(expr, [globals, [locals]]) + .. method:: runeval(expr, [globals, [locals]]) - Debug an expression executed via the :func:`eval` function. *globals* and - *locals* have the same meaning as in :meth:`run`. + Debug an expression executed via the :func:`eval` function. *globals* and + *locals* have the same meaning as in :meth:`run`. -.. method:: Bdb.runctx(cmd, globals, locals) + .. method:: runctx(cmd, globals, locals) - For backwards compatibility. Calls the :meth:`run` method. + For backwards compatibility. Calls the :meth:`run` method. -.. method:: Bdb.runcall(func, *args, **kwds) + .. method:: runcall(func, *args, **kwds) - Debug a single function call, and return its result. + Debug a single function call, and return its result. Finally, the module defines the following functions: Modified: python/branches/py3k/Doc/library/bz2.rst ============================================================================== --- python/branches/py3k/Doc/library/bz2.rst (original) +++ python/branches/py3k/Doc/library/bz2.rst Fri Apr 25 03:59:09 2008 @@ -44,75 +44,77 @@ .. class:: BZ2File(filename[, mode[, buffering[, compresslevel]]]) - Open a bz2 file. Mode can be either ``'r'`` or ``'w'``, for reading (default) + Open a bz2 file. Mode can be either ``'r'`` or ``'w'``, for reading (default) or writing. When opened for writing, the file will be created if it doesn't - exist, and truncated otherwise. If *buffering* is given, ``0`` means unbuffered, - and larger numbers specify the buffer size; the default is ``0``. If - *compresslevel* is given, it must be a number between ``1`` and ``9``; the - default is ``9``. Add a ``'U'`` to mode to open the file for input with - universal newline support. Any line ending in the input file will be seen as a - ``'\n'`` in Python. Also, a file so opened gains the attribute + exist, and truncated otherwise. If *buffering* is given, ``0`` means + unbuffered, and larger numbers specify the buffer size; the default is + ``0``. If *compresslevel* is given, it must be a number between ``1`` and + ``9``; the default is ``9``. Add a ``'U'`` to mode to open the file for input + with universal newline support. Any line ending in the input file will be + seen as a ``'\n'`` in Python. Also, a file so opened gains the attribute :attr:`newlines`; the value for this attribute is one of ``None`` (no newline - read yet), ``'\r'``, ``'\n'``, ``'\r\n'`` or a tuple containing all the newline - types seen. Universal newlines are available only when reading. Instances - support iteration in the same way as normal :class:`file` instances. + read yet), ``'\r'``, ``'\n'``, ``'\r\n'`` or a tuple containing all the + newline types seen. Universal newlines are available only when + reading. Instances support iteration in the same way as normal :class:`file` + instances. -.. method:: BZ2File.close() + .. method:: close() - Close the file. Sets data attribute :attr:`closed` to true. A closed file cannot - be used for further I/O operations. :meth:`close` may be called more than once - without error. + Close the file. Sets data attribute :attr:`closed` to true. A closed file + cannot be used for further I/O operations. :meth:`close` may be called + more than once without error. -.. method:: BZ2File.read([size]) + .. method:: read([size]) - Read at most *size* uncompressed bytes, returned as a string. If the *size* - argument is negative or omitted, read until EOF is reached. + Read at most *size* uncompressed bytes, returned as a string. If the + *size* argument is negative or omitted, read until EOF is reached. -.. method:: BZ2File.readline([size]) + .. method:: readline([size]) - Return the next line from the file, as a string, retaining newline. A - non-negative *size* argument limits the maximum number of bytes to return (an - incomplete line may be returned then). Return an empty string at EOF. + Return the next line from the file, as a string, retaining newline. A + non-negative *size* argument limits the maximum number of bytes to return + (an incomplete line may be returned then). Return an empty string at EOF. -.. method:: BZ2File.readlines([size]) + .. method:: readlines([size]) - Return a list of lines read. The optional *size* argument, if given, is an - approximate bound on the total number of bytes in the lines returned. + Return a list of lines read. The optional *size* argument, if given, is an + approximate bound on the total number of bytes in the lines returned. -.. method:: BZ2File.seek(offset[, whence]) + .. method:: seek(offset[, whence]) - Move to new file position. Argument *offset* is a byte count. Optional argument - *whence* defaults to ``os.SEEK_SET`` or ``0`` (offset from start of file; offset - should be ``>= 0``); other values are ``os.SEEK_CUR`` or ``1`` (move relative to - current position; offset can be positive or negative), and ``os.SEEK_END`` or - ``2`` (move relative to end of file; offset is usually negative, although many - platforms allow seeking beyond the end of a file). + Move to new file position. Argument *offset* is a byte count. Optional + argument *whence* defaults to ``os.SEEK_SET`` or ``0`` (offset from start + of file; offset should be ``>= 0``); other values are ``os.SEEK_CUR`` or + ``1`` (move relative to current position; offset can be positive or + negative), and ``os.SEEK_END`` or ``2`` (move relative to end of file; + offset is usually negative, although many platforms allow seeking beyond + the end of a file). - Note that seeking of bz2 files is emulated, and depending on the parameters the - operation may be extremely slow. + Note that seeking of bz2 files is emulated, and depending on the + parameters the operation may be extremely slow. -.. method:: BZ2File.tell() + .. method:: tell() - Return the current file position, an integer. + Return the current file position, an integer. -.. method:: BZ2File.write(data) + .. method:: write(data) - Write string *data* to file. Note that due to buffering, :meth:`close` may be - needed before the file on disk reflects the data written. + Write string *data* to file. Note that due to buffering, :meth:`close` may + be needed before the file on disk reflects the data written. -.. method:: BZ2File.writelines(sequence_of_strings) + .. method:: writelines(sequence_of_strings) - Write the sequence of strings to the file. Note that newlines are not added. The - sequence can be any iterable object producing strings. This is equivalent to - calling write() for each string. + Write the sequence of strings to the file. Note that newlines are not + added. The sequence can be any iterable object producing strings. This is + equivalent to calling write() for each string. Sequential (de)compression @@ -125,23 +127,23 @@ .. class:: BZ2Compressor([compresslevel]) Create a new compressor object. This object may be used to compress data - sequentially. If you want to compress data in one shot, use the :func:`compress` - function instead. The *compresslevel* parameter, if given, must be a number - between ``1`` and ``9``; the default is ``9``. + sequentially. If you want to compress data in one shot, use the + :func:`compress` function instead. The *compresslevel* parameter, if given, + must be a number between ``1`` and ``9``; the default is ``9``. -.. method:: BZ2Compressor.compress(data) + .. method:: compress(data) - Provide more data to the compressor object. It will return chunks of compressed - data whenever possible. When you've finished providing data to compress, call - the :meth:`flush` method to finish the compression process, and return what is - left in internal buffers. + Provide more data to the compressor object. It will return chunks of + compressed data whenever possible. When you've finished providing data to + compress, call the :meth:`flush` method to finish the compression process, + and return what is left in internal buffers. -.. method:: BZ2Compressor.flush() + .. method:: flush() - Finish the compression process and return what is left in internal buffers. You - must not use the compressor object after calling this method. + Finish the compression process and return what is left in internal + buffers. You must not use the compressor object after calling this method. .. class:: BZ2Decompressor() @@ -151,12 +153,13 @@ :func:`decompress` function instead. -.. method:: BZ2Decompressor.decompress(data) + .. method:: decompress(data) - Provide more data to the decompressor object. It will return chunks of - decompressed data whenever possible. If you try to decompress data after the end - of stream is found, :exc:`EOFError` will be raised. If any data was found after - the end of stream, it'll be ignored and saved in :attr:`unused_data` attribute. + Provide more data to the decompressor object. It will return chunks of + decompressed data whenever possible. If you try to decompress data after + the end of stream is found, :exc:`EOFError` will be raised. If any data + was found after the end of stream, it'll be ignored and saved in + :attr:`unused_data` attribute. One-shot (de)compression @@ -168,13 +171,13 @@ .. function:: compress(data[, compresslevel]) - Compress *data* in one shot. If you want to compress data sequentially, use an - instance of :class:`BZ2Compressor` instead. The *compresslevel* parameter, if - given, must be a number between ``1`` and ``9``; the default is ``9``. + Compress *data* in one shot. If you want to compress data sequentially, use + an instance of :class:`BZ2Compressor` instead. The *compresslevel* parameter, + if given, must be a number between ``1`` and ``9``; the default is ``9``. .. function:: decompress(data) - Decompress *data* in one shot. If you want to decompress data sequentially, use - an instance of :class:`BZ2Decompressor` instead. + Decompress *data* in one shot. If you want to decompress data sequentially, + use an instance of :class:`BZ2Decompressor` instead. Modified: python/branches/py3k/Doc/library/calendar.rst ============================================================================== --- python/branches/py3k/Doc/library/calendar.rst (original) +++ python/branches/py3k/Doc/library/calendar.rst Fri Apr 25 03:59:09 2008 @@ -33,74 +33,75 @@ itself. This is the job of subclasses. -:class:`Calendar` instances have the following methods: + :class:`Calendar` instances have the following methods: -.. method:: Calendar.iterweekdays(weekday) + .. method:: iterweekdays(weekday) - Return an iterator for the week day numbers that will be used for one week. - The first value from the iterator will be the same as the value of the - :attr:`firstweekday` property. + Return an iterator for the week day numbers that will be used for one + week. The first value from the iterator will be the same as the value of + the :attr:`firstweekday` property. -.. method:: Calendar.itermonthdates(year, month) + .. method:: itermonthdates(year, month) - Return an iterator for the month *month* (1-12) in the year *year*. This - iterator will return all days (as :class:`datetime.date` objects) for the month - and all days before the start of the month or after the end of the month that - are required to get a complete week. + Return an iterator for the month *month* (1-12) in the year *year*. This + iterator will return all days (as :class:`datetime.date` objects) for the + month and all days before the start of the month or after the end of the + month that are required to get a complete week. -.. method:: Calendar.itermonthdays2(year, month) + .. method:: itermonthdays2(year, month) - Return an iterator for the month *month* in the year *year* similar to - :meth:`itermonthdates`. Days returned will be tuples consisting of a day number - and a week day number. + Return an iterator for the month *month* in the year *year* similar to + :meth:`itermonthdates`. Days returned will be tuples consisting of a day + number and a week day number. -.. method:: Calendar.itermonthdays(year, month) + .. method:: itermonthdays(year, month) - Return an iterator for the month *month* in the year *year* similar to - :meth:`itermonthdates`. Days returned will simply be day numbers. + Return an iterator for the month *month* in the year *year* similar to + :meth:`itermonthdates`. Days returned will simply be day numbers. -.. method:: Calendar.monthdatescalendar(year, month) + .. method:: monthdatescalendar(year, month) - Return a list of the weeks in the month *month* of the *year* as full weeks. - Weeks are lists of seven :class:`datetime.date` objects. + Return a list of the weeks in the month *month* of the *year* as full + weeks. Weeks are lists of seven :class:`datetime.date` objects. -.. method:: Calendar.monthdays2calendar(year, month) + .. method:: monthdays2calendar(year, month) - Return a list of the weeks in the month *month* of the *year* as full weeks. - Weeks are lists of seven tuples of day numbers and weekday numbers. + Return a list of the weeks in the month *month* of the *year* as full + weeks. Weeks are lists of seven tuples of day numbers and weekday + numbers. -.. method:: Calendar.monthdayscalendar(year, month) + .. method:: monthdayscalendar(year, month) - Return a list of the weeks in the month *month* of the *year* as full weeks. - Weeks are lists of seven day numbers. + Return a list of the weeks in the month *month* of the *year* as full + weeks. Weeks are lists of seven day numbers. -.. method:: Calendar.yeardatescalendar(year[, width]) + .. method:: yeardatescalendar(year[, width]) - Return the data for the specified year ready for formatting. The return value - is a list of month rows. Each month row contains up to *width* months - (defaulting to 3). Each month contains between 4 and 6 weeks and each week - contains 1--7 days. Days are :class:`datetime.date` objects. + Return the data for the specified year ready for formatting. The return + value is a list of month rows. Each month row contains up to *width* + months (defaulting to 3). Each month contains between 4 and 6 weeks and + each week contains 1--7 days. Days are :class:`datetime.date` objects. -.. method:: Calendar.yeardays2calendar(year[, width]) + .. method:: yeardays2calendar(year[, width]) - Return the data for the specified year ready for formatting (similar to - :meth:`yeardatescalendar`). Entries in the week lists are tuples of day - numbers and weekday numbers. Day numbers outside this month are zero. + Return the data for the specified year ready for formatting (similar to + :meth:`yeardatescalendar`). Entries in the week lists are tuples of day + numbers and weekday numbers. Day numbers outside this month are zero. -.. method:: Calendar.yeardayscalendar(year[, width]) + .. method:: yeardayscalendar(year[, width]) - Return the data for the specified year ready for formatting (similar to - :meth:`yeardatescalendar`). Entries in the week lists are day numbers. Day - numbers outside this month are zero. + Return the data for the specified year ready for formatting (similar to + :meth:`yeardatescalendar`). Entries in the week lists are day numbers. Day + numbers outside this month are zero. .. class:: TextCalendar([firstweekday]) @@ -108,35 +109,35 @@ This class can be used to generate plain text calendars. -:class:`TextCalendar` instances have the following methods: + :class:`TextCalendar` instances have the following methods: -.. method:: TextCalendar.formatmonth(theyear, themonth[, w[, l]]) + .. method:: formatmonth(theyear, themonth[, w[, l]]) - Return a month's calendar in a multi-line string. If *w* is provided, it - specifies the width of the date columns, which are centered. If *l* is given, - it specifies the number of lines that each week will use. Depends on the - first weekday as specified in the constructor or set by the - :meth:`setfirstweekday` method. + Return a month's calendar in a multi-line string. If *w* is provided, it + specifies the width of the date columns, which are centered. If *l* is + given, it specifies the number of lines that each week will use. Depends + on the first weekday as specified in the constructor or set by the + :meth:`setfirstweekday` method. -.. method:: TextCalendar.prmonth(theyear, themonth[, w[, l]]) + .. method:: prmonth(theyear, themonth[, w[, l]]) - Print a month's calendar as returned by :meth:`formatmonth`. + Print a month's calendar as returned by :meth:`formatmonth`. -.. method:: TextCalendar.formatyear(theyear, themonth[, w[, l[, c[, m]]]]) + .. method:: formatyear(theyear, themonth[, w[, l[, c[, m]]]]) - Return a *m*-column calendar for an entire year as a multi-line string. - Optional parameters *w*, *l*, and *c* are for date column width, lines per - week, and number of spaces between month columns, respectively. Depends on - the first weekday as specified in the constructor or set by the - :meth:`setfirstweekday` method. The earliest year for which a calendar can - be generated is platform-dependent. + Return a *m*-column calendar for an entire year as a multi-line string. + Optional parameters *w*, *l*, and *c* are for date column width, lines per + week, and number of spaces between month columns, respectively. Depends on + the first weekday as specified in the constructor or set by the + :meth:`setfirstweekday` method. The earliest year for which a calendar + can be generated is platform-dependent. -.. method:: TextCalendar.pryear(theyear[, w[, l[, c[, m]]]]) + .. method:: pryear(theyear[, w[, l[, c[, m]]]]) - Print the calendar for an entire year as returned by :meth:`formatyear`. + Print the calendar for an entire year as returned by :meth:`formatyear`. .. class:: HTMLCalendar([firstweekday]) @@ -144,43 +145,44 @@ This class can be used to generate HTML calendars. -:class:`HTMLCalendar` instances have the following methods: + :class:`HTMLCalendar` instances have the following methods: -.. method:: HTMLCalendar.formatmonth(theyear, themonth[, withyear]) + .. method:: formatmonth(theyear, themonth[, withyear]) - Return a month's calendar as an HTML table. If *withyear* is true the year will - be included in the header, otherwise just the month name will be used. + Return a month's calendar as an HTML table. If *withyear* is true the year + will be included in the header, otherwise just the month name will be + used. -.. method:: HTMLCalendar.formatyear(theyear, themonth[, width]) + .. method:: formatyear(theyear, themonth[, width]) - Return a year's calendar as an HTML table. *width* (defaulting to 3) specifies - the number of months per row. + Return a year's calendar as an HTML table. *width* (defaulting to 3) + specifies the number of months per row. -.. method:: HTMLCalendar.formatyearpage(theyear[, width[, css[, encoding]]]) + .. method:: formatyearpage(theyear[, width[, css[, encoding]]]) - Return a year's calendar as a complete HTML page. *width* (defaulting to 3) - specifies the number of months per row. *css* is the name for the cascading - style sheet to be used. :const:`None` can be passed if no style sheet should be - used. *encoding* specifies the encoding to be used for the output (defaulting to - the system default encoding). + Return a year's calendar as a complete HTML page. *width* (defaulting to + 3) specifies the number of months per row. *css* is the name for the + cascading style sheet to be used. :const:`None` can be passed if no style + sheet should be used. *encoding* specifies the encoding to be used for the + output (defaulting to the system default encoding). .. class:: LocaleTextCalendar([firstweekday[, locale]]) This subclass of :class:`TextCalendar` can be passed a locale name in the - constructor and will return month and weekday names in the specified locale. If - this locale includes an encoding all strings containing month and weekday names - will be returned as unicode. + constructor and will return month and weekday names in the specified + locale. If this locale includes an encoding all strings containing month and + weekday names will be returned as unicode. .. class:: LocaleHTMLCalendar([firstweekday[, locale]]) This subclass of :class:`HTMLCalendar` can be passed a locale name in the - constructor and will return month and weekday names in the specified locale. If - this locale includes an encoding all strings containing month and weekday names - will be returned as unicode. + constructor and will return month and weekday names in the specified + locale. If this locale includes an encoding all strings containing month and + weekday names will be returned as unicode. For simple text calendars this module provides the following functions. Modified: python/branches/py3k/Doc/library/cgihttpserver.rst ============================================================================== --- python/branches/py3k/Doc/library/cgihttpserver.rst (original) +++ python/branches/py3k/Doc/library/cgihttpserver.rst Fri Apr 25 03:59:09 2008 @@ -43,22 +43,22 @@ and serve the output, instead of serving files, if the request leads to somewhere below the ``cgi_directories`` path. -The :class:`CGIHTTPRequestHandler` defines the following data member: + The :class:`CGIHTTPRequestHandler` defines the following data member: -.. attribute:: CGIHTTPRequestHandler.cgi_directories + .. attribute:: cgi_directories - This defaults to ``['/cgi-bin', '/htbin']`` and describes directories to treat - as containing CGI scripts. + This defaults to ``['/cgi-bin', '/htbin']`` and describes directories to + treat as containing CGI scripts. -The :class:`CGIHTTPRequestHandler` defines the following methods: + The :class:`CGIHTTPRequestHandler` defines the following methods: -.. method:: CGIHTTPRequestHandler.do_POST() + .. method:: do_POST() - This method serves the ``'POST'`` request type, only allowed for CGI scripts. - Error 501, "Can only POST to CGI scripts", is output when trying to POST to a - non-CGI url. + This method serves the ``'POST'`` request type, only allowed for CGI + scripts. Error 501, "Can only POST to CGI scripts", is output when trying + to POST to a non-CGI url. Note that CGI scripts will be run with UID of user nobody, for security reasons. Problems with the CGI script will be translated to error 403. Modified: python/branches/py3k/Doc/library/chunk.rst ============================================================================== --- python/branches/py3k/Doc/library/chunk.rst (original) +++ python/branches/py3k/Doc/library/chunk.rst Fri Apr 25 03:59:09 2008 @@ -66,62 +66,64 @@ optional argument *inclheader* is true, the size given in the chunk header includes the size of the header. The default value is false. -A :class:`Chunk` object supports the following methods: + A :class:`Chunk` object supports the following methods: -.. method:: Chunk.getname() + .. method:: getname() - Returns the name (ID) of the chunk. This is the first 4 bytes of the chunk. + Returns the name (ID) of the chunk. This is the first 4 bytes of the + chunk. -.. method:: Chunk.getsize() + .. method:: getsize() - Returns the size of the chunk. + Returns the size of the chunk. -.. method:: Chunk.close() + .. method:: close() - Close and skip to the end of the chunk. This does not close the underlying - file. + Close and skip to the end of the chunk. This does not close the + underlying file. -The remaining methods will raise :exc:`IOError` if called after the -:meth:`close` method has been called. + The remaining methods will raise :exc:`IOError` if called after the + :meth:`close` method has been called. -.. method:: Chunk.isatty() + .. method:: isatty() - Returns ``False``. + Returns ``False``. -.. method:: Chunk.seek(pos[, whence]) + .. method:: seek(pos[, whence]) - Set the chunk's current position. The *whence* argument is optional and - defaults to ``0`` (absolute file positioning); other values are ``1`` (seek - relative to the current position) and ``2`` (seek relative to the file's end). - There is no return value. If the underlying file does not allow seek, only - forward seeks are allowed. + Set the chunk's current position. The *whence* argument is optional and + defaults to ``0`` (absolute file positioning); other values are ``1`` + (seek relative to the current position) and ``2`` (seek relative to the + file's end). There is no return value. If the underlying file does not + allow seek, only forward seeks are allowed. -.. method:: Chunk.tell() + .. method:: tell() - Return the current position into the chunk. + Return the current position into the chunk. -.. method:: Chunk.read([size]) + .. method:: read([size]) - Read at most *size* bytes from the chunk (less if the read hits the end of the - chunk before obtaining *size* bytes). If the *size* argument is negative or - omitted, read all data until the end of the chunk. The bytes are returned as a - string object. An empty string is returned when the end of the chunk is - encountered immediately. + Read at most *size* bytes from the chunk (less if the read hits the end of + the chunk before obtaining *size* bytes). If the *size* argument is + negative or omitted, read all data until the end of the chunk. The bytes + are returned as a string object. An empty string is returned when the end + of the chunk is encountered immediately. -.. method:: Chunk.skip() + .. method:: skip() + + Skip to the end of the chunk. All further calls to :meth:`read` for the + chunk will return ``''``. If you are not interested in the contents of + the chunk, this method should be called so that the file points to the + start of the next chunk. - Skip to the end of the chunk. All further calls to :meth:`read` for the chunk - will return ``''``. If you are not interested in the contents of the chunk, - this method should be called so that the file points to the start of the next - chunk. .. rubric:: Footnotes Modified: python/branches/py3k/Doc/library/codecs.rst ============================================================================== --- python/branches/py3k/Doc/library/codecs.rst (original) +++ python/branches/py3k/Doc/library/codecs.rst Fri Apr 25 03:59:09 2008 @@ -425,16 +425,16 @@ :func:`register_error`. -.. method:: IncrementalEncoder.encode(object[, final]) + .. method:: encode(object[, final]) - Encodes *object* (taking the current state of the encoder into account) and - returns the resulting encoded object. If this is the last call to :meth:`encode` - *final* must be true (the default is false). + Encodes *object* (taking the current state of the encoder into account) + and returns the resulting encoded object. If this is the last call to + :meth:`encode` *final* must be true (the default is false). -.. method:: IncrementalEncoder.reset() + .. method:: reset() - Reset the encoder to the initial state. + Reset the encoder to the initial state. .. method:: IncrementalEncoder.getstate() @@ -488,41 +488,42 @@ :func:`register_error`. -.. method:: IncrementalDecoder.decode(object[, final]) + .. method:: decode(object[, final]) - Decodes *object* (taking the current state of the decoder into account) and - returns the resulting decoded object. If this is the last call to :meth:`decode` - *final* must be true (the default is false). If *final* is true the decoder must - decode the input completely and must flush all buffers. If this isn't possible - (e.g. because of incomplete byte sequences at the end of the input) it must - initiate error handling just like in the stateless case (which might raise an - exception). + Decodes *object* (taking the current state of the decoder into account) + and returns the resulting decoded object. If this is the last call to + :meth:`decode` *final* must be true (the default is false). If *final* is + true the decoder must decode the input completely and must flush all + buffers. If this isn't possible (e.g. because of incomplete byte sequences + at the end of the input) it must initiate error handling just like in the + stateless case (which might raise an exception). -.. method:: IncrementalDecoder.reset() + .. method:: reset() - Reset the decoder to the initial state. + Reset the decoder to the initial state. -.. method:: IncrementalDecoder.getstate() + .. method:: getstate() - Return the current state of the decoder. This must be a tuple with two items, - the first must be the buffer containing the still undecoded input. The second - must be an integer and can be additional state info. (The implementation should - make sure that ``0`` is the most common additional state info.) If this - additional state info is ``0`` it must be possible to set the decoder to the - state which has no input buffered and ``0`` as the additional state info, so - that feeding the previously buffered input to the decoder returns it to the - previous state without producing any output. (Additional state info that is more - complicated than integers can be converted into an integer by - marshaling/pickling the info and encoding the bytes of the resulting string into - an integer.) + Return the current state of the decoder. This must be a tuple with two + items, the first must be the buffer containing the still undecoded + input. The second must be an integer and can be additional state + info. (The implementation should make sure that ``0`` is the most common + additional state info.) If this additional state info is ``0`` it must be + possible to set the decoder to the state which has no input buffered and + ``0`` as the additional state info, so that feeding the previously + buffered input to the decoder returns it to the previous state without + producing any output. (Additional state info that is more complicated than + integers can be converted into an integer by marshaling/pickling the info + and encoding the bytes of the resulting string into an integer.) -.. method:: IncrementalDecoder.setstate(state) + .. method:: setstate(state) + + Set the state of the encoder to *state*. *state* must be a decoder state + returned by :meth:`getstate`. - Set the state of the encoder to *state*. *state* must be a decoder state - returned by :meth:`getstate`. The :class:`StreamWriter` and :class:`StreamReader` classes provide generic working interfaces which can be used to implement new encoding submodules very @@ -570,24 +571,25 @@ :func:`register_error`. -.. method:: StreamWriter.write(object) + .. method:: write(object) + + Writes the object's contents encoded to the stream. - Writes the object's contents encoded to the stream. + .. method:: writelines(list) -.. method:: StreamWriter.writelines(list) + Writes the concatenated list of strings to the stream (possibly by reusing + the :meth:`write` method). - Writes the concatenated list of strings to the stream (possibly by reusing the - :meth:`write` method). + .. method:: reset() -.. method:: StreamWriter.reset() + Flushes and resets the codec buffers used for keeping state. - Flushes and resets the codec buffers used for keeping state. + Calling this method should ensure that the data on the output is put into + a clean state that allows appending of new fresh data without having to + rescan the whole stream to recover state. - Calling this method should ensure that the data on the output is put into a - clean state that allows appending of new fresh data without having to rescan the - whole stream to recover state. In addition to the above methods, the :class:`StreamWriter` must also inherit all other methods and attributes from the underlying stream. @@ -630,55 +632,59 @@ :func:`register_error`. -.. method:: StreamReader.read([size[, chars, [firstline]]]) + .. method:: read([size[, chars, [firstline]]]) - Decodes data from the stream and returns the resulting object. + Decodes data from the stream and returns the resulting object. - *chars* indicates the number of characters to read from the stream. :func:`read` - will never return more than *chars* characters, but it might return less, if - there are not enough characters available. + *chars* indicates the number of characters to read from the + stream. :func:`read` will never return more than *chars* characters, but + it might return less, if there are not enough characters available. - *size* indicates the approximate maximum number of bytes to read from the stream - for decoding purposes. The decoder can modify this setting as appropriate. The - default value -1 indicates to read and decode as much as possible. *size* is - intended to prevent having to decode huge files in one step. + *size* indicates the approximate maximum number of bytes to read from the + stream for decoding purposes. The decoder can modify this setting as + appropriate. The default value -1 indicates to read and decode as much as + possible. *size* is intended to prevent having to decode huge files in + one step. - *firstline* indicates that it would be sufficient to only return the first line, - if there are decoding errors on later lines. + *firstline* indicates that it would be sufficient to only return the first + line, if there are decoding errors on later lines. - The method should use a greedy read strategy meaning that it should read as much - data as is allowed within the definition of the encoding and the given size, - e.g. if optional encoding endings or state markers are available on the stream, - these should be read too. + The method should use a greedy read strategy meaning that it should read + as much data as is allowed within the definition of the encoding and the + given size, e.g. if optional encoding endings or state markers are + available on the stream, these should be read too. -.. method:: StreamReader.readline([size[, keepends]]) + .. method:: readline([size[, keepends]]) - Read one line from the input stream and return the decoded data. + Read one line from the input stream and return the decoded data. - *size*, if given, is passed as size argument to the stream's :meth:`readline` - method. + *size*, if given, is passed as size argument to the stream's + :meth:`readline` method. - If *keepends* is false line-endings will be stripped from the lines returned. + If *keepends* is false line-endings will be stripped from the lines + returned. -.. method:: StreamReader.readlines([sizehint[, keepends]]) + .. method:: readlines([sizehint[, keepends]]) - Read all lines available on the input stream and return them as a list of lines. + Read all lines available on the input stream and return them as a list of + lines. - Line-endings are implemented using the codec's decoder method and are included - in the list entries if *keepends* is true. + Line-endings are implemented using the codec's decoder method and are + included in the list entries if *keepends* is true. - *sizehint*, if given, is passed as the *size* argument to the stream's - :meth:`read` method. + *sizehint*, if given, is passed as the *size* argument to the stream's + :meth:`read` method. -.. method:: StreamReader.reset() + .. method:: reset() - Resets the codec buffers used for keeping state. + Resets the codec buffers used for keeping state. + + Note that no stream repositioning should take place. This method is + primarily intended to be able to recover from decoding errors. - Note that no stream repositioning should take place. This method is primarily - intended to be able to recover from decoding errors. In addition to the above methods, the :class:`StreamReader` must also inherit all other methods and attributes from the underlying stream. @@ -747,6 +753,7 @@ Error handling is done in the same way as defined for the stream readers and writers. + :class:`StreamRecoder` instances define the combined interfaces of :class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other methods and attributes from the underlying stream. Modified: python/branches/py3k/Doc/library/collections.rst ============================================================================== --- python/branches/py3k/Doc/library/collections.rst (original) +++ python/branches/py3k/Doc/library/collections.rst Fri Apr 25 03:59:09 2008 @@ -166,59 +166,60 @@ where only the most recent activity is of interest. -Deque objects support the following methods: + Deque objects support the following methods: -.. method:: deque.append(x) + .. method:: append(x) - Add *x* to the right side of the deque. + Add *x* to the right side of the deque. -.. method:: deque.appendleft(x) + .. method:: appendleft(x) - Add *x* to the left side of the deque. + Add *x* to the left side of the deque. -.. method:: deque.clear() + .. method:: clear() - Remove all elements from the deque leaving it with length 0. + Remove all elements from the deque leaving it with length 0. -.. method:: deque.extend(iterable) + .. method:: extend(iterable) - Extend the right side of the deque by appending elements from the iterable - argument. + Extend the right side of the deque by appending elements from the iterable + argument. -.. method:: deque.extendleft(iterable) + .. method:: extendleft(iterable) - Extend the left side of the deque by appending elements from *iterable*. Note, - the series of left appends results in reversing the order of elements in the - iterable argument. + Extend the left side of the deque by appending elements from *iterable*. + Note, the series of left appends results in reversing the order of + elements in the iterable argument. -.. method:: deque.pop() + .. method:: pop() - Remove and return an element from the right side of the deque. If no elements - are present, raises an :exc:`IndexError`. + Remove and return an element from the right side of the deque. If no + elements are present, raises an :exc:`IndexError`. -.. method:: deque.popleft() + .. method:: popleft() - Remove and return an element from the left side of the deque. If no elements are - present, raises an :exc:`IndexError`. + Remove and return an element from the left side of the deque. If no + elements are present, raises an :exc:`IndexError`. -.. method:: deque.remove(value) + .. method:: remove(value) - Removed the first occurrence of *value*. If not found, raises a - :exc:`ValueError`. + Removed the first occurrence of *value*. If not found, raises a + :exc:`ValueError`. -.. method:: deque.rotate(n) + .. method:: rotate(n) + + Rotate the deque *n* steps to the right. If *n* is negative, rotate to + the left. Rotating one step to the right is equivalent to: + ``d.appendleft(d.pop())``. - Rotate the deque *n* steps to the right. If *n* is negative, rotate to the - left. Rotating one step to the right is equivalent to: - ``d.appendleft(d.pop())``. In addition to the above, deques support iteration, pickling, ``len(d)``, ``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with @@ -348,32 +349,34 @@ arguments. -:class:`defaultdict` objects support the following method in addition to the -standard :class:`dict` operations: + :class:`defaultdict` objects support the following method in addition to the + standard :class:`dict` operations: + + .. method:: defaultdict.__missing__(key) -.. method:: defaultdict.__missing__(key) + If the :attr:`default_factory` attribute is ``None``, this raises an + :exc:`KeyError` exception with the *key* as argument. - If the :attr:`default_factory` attribute is ``None``, this raises an - :exc:`KeyError` exception with the *key* as argument. + If :attr:`default_factory` is not ``None``, it is called without arguments + to provide a default value for the given *key*, this value is inserted in + the dictionary for the *key*, and returned. - If :attr:`default_factory` is not ``None``, it is called without arguments to - provide a default value for the given *key*, this value is inserted in the - dictionary for the *key*, and returned. + If calling :attr:`default_factory` raises an exception this exception is + propagated unchanged. - If calling :attr:`default_factory` raises an exception this exception is - propagated unchanged. + This method is called by the :meth:`__getitem__` method of the + :class:`dict` class when the requested key is not found; whatever it + returns or raises is then returned or raised by :meth:`__getitem__`. - This method is called by the :meth:`__getitem__` method of the :class:`dict` - class when the requested key is not found; whatever it returns or raises is then - returned or raised by :meth:`__getitem__`. -:class:`defaultdict` objects support the following instance variable: + :class:`defaultdict` objects support the following instance variable: -.. attribute:: defaultdict.default_factory + .. attribute:: defaultdict.default_factory - This attribute is used by the :meth:`__missing__` method; it is initialized from - the first argument to the constructor, if present, or to ``None``, if absent. + This attribute is used by the :meth:`__missing__` method; it is + initialized from the first argument to the constructor, if present, or to + ``None``, if absent. .. _defaultdict-examples: Modified: python/branches/py3k/Doc/library/csv.rst ============================================================================== --- python/branches/py3k/Doc/library/csv.rst (original) +++ python/branches/py3k/Doc/library/csv.rst Fri Apr 25 03:59:09 2008 @@ -209,19 +209,20 @@ The :class:`Sniffer` class is used to deduce the format of a CSV file. -The :class:`Sniffer` class provides two methods: + The :class:`Sniffer` class provides two methods: -.. method:: Sniffer.sniff(sample[, delimiters=None]) + .. method:: sniff(sample[, delimiters=None]) - Analyze the given *sample* and return a :class:`Dialect` subclass reflecting the - parameters found. If the optional *delimiters* parameter is given, it is - interpreted as a string containing possible valid delimiter characters. + Analyze the given *sample* and return a :class:`Dialect` subclass + reflecting the parameters found. If the optional *delimiters* parameter + is given, it is interpreted as a string containing possible valid + delimiter characters. -.. method:: Sniffer.has_header(sample) + .. method:: has_header(sample) - Analyze the sample text (presumed to be in CSV format) and return :const:`True` - if the first row appears to be a series of column headers. + Analyze the sample text (presumed to be in CSV format) and return + :const:`True` if the first row appears to be a series of column headers. An example for :class:`Sniffer` use:: Modified: python/branches/py3k/Doc/library/ctypes.rst ============================================================================== --- python/branches/py3k/Doc/library/ctypes.rst (original) +++ python/branches/py3k/Doc/library/ctypes.rst Fri Apr 25 03:59:09 2008 @@ -1441,10 +1441,10 @@ so repeated attribute accesses return the same library each time. -.. method:: LibraryLoader.LoadLibrary(name) + .. method:: LoadLibrary(name) - Load a shared library into the process and return it. This method always - returns a new instance of the library. + Load a shared library into the process and return it. This method always + returns a new instance of the library. These prefabricated library loaders are available: @@ -1501,50 +1501,51 @@ Base class for C callable foreign functions. -Instances of foreign functions are also C compatible data types; they represent -C function pointers. + Instances of foreign functions are also C compatible data types; they + represent C function pointers. -This behavior can be customized by assigning to special attributes of the -foreign function object. + This behavior can be customized by assigning to special attributes of the + foreign function object. -.. attribute:: _FuncPtr.restype + .. attribute:: restype - Assign a ctypes type to specify the result type of the foreign function. Use - ``None`` for ``void`` a function not returning anything. + Assign a ctypes type to specify the result type of the foreign function. + Use ``None`` for ``void`` a function not returning anything. - It is possible to assign a callable Python object that is not a ctypes type, in - this case the function is assumed to return a C ``int``, and the callable will - be called with this integer, allowing to do further processing or error - checking. Using this is deprecated, for more flexible post processing or error - checking use a ctypes data type as :attr:`restype` and assign a callable to the - :attr:`errcheck` attribute. + It is possible to assign a callable Python object that is not a ctypes + type, in this case the function is assumed to return a C ``int``, and the + callable will be called with this integer, allowing to do further + processing or error checking. Using this is deprecated, for more flexible + post processing or error checking use a ctypes data type as + :attr:`restype` and assign a callable to the :attr:`errcheck` attribute. -.. attribute:: _FuncPtr.argtypes + .. attribute:: argtypes - Assign a tuple of ctypes types to specify the argument types that the function - accepts. Functions using the ``stdcall`` calling convention can only be called - with the same number of arguments as the length of this tuple; functions using - the C calling convention accept additional, unspecified arguments as well. + Assign a tuple of ctypes types to specify the argument types that the + function accepts. Functions using the ``stdcall`` calling convention can + only be called with the same number of arguments as the length of this + tuple; functions using the C calling convention accept additional, + unspecified arguments as well. - When a foreign function is called, each actual argument is passed to the - :meth:`from_param` class method of the items in the :attr:`argtypes` tuple, this - method allows to adapt the actual argument to an object that the foreign - function accepts. For example, a :class:`c_char_p` item in the :attr:`argtypes` - tuple will convert a unicode string passed as argument into an byte string using - ctypes conversion rules. + When a foreign function is called, each actual argument is passed to the + :meth:`from_param` class method of the items in the :attr:`argtypes` + tuple, this method allows to adapt the actual argument to an object that + the foreign function accepts. For example, a :class:`c_char_p` item in + the :attr:`argtypes` tuple will convert a unicode string passed as + argument into an byte string using ctypes conversion rules. - New: It is now possible to put items in argtypes which are not ctypes types, but - each item must have a :meth:`from_param` method which returns a value usable as - argument (integer, string, ctypes instance). This allows to define adapters - that can adapt custom objects as function parameters. + New: It is now possible to put items in argtypes which are not ctypes + types, but each item must have a :meth:`from_param` method which returns a + value usable as argument (integer, string, ctypes instance). This allows + to define adapters that can adapt custom objects as function parameters. -.. attribute:: _FuncPtr.errcheck + .. attribute:: errcheck - Assign a Python function or another callable to this attribute. The callable - will be called with three or more arguments: + Assign a Python function or another callable to this attribute. The + callable will be called with three or more arguments: .. function:: callable(result, func, arguments) @@ -1559,9 +1560,9 @@ ``arguments`` is a tuple containing the parameters originally passed to the function call, this allows to specialize the behavior on the arguments used. - The object that this function returns will be returned from the foreign function - call, but it can also check the result value and raise an exception if the - foreign function call failed. + The object that this function returns will be returned from the foreign + function call, but it can also check the result value and raise an exception + if the foreign function call failed. .. exception:: ArgumentError() @@ -1943,57 +1944,58 @@ :attr:`_objects`; this contains other Python objects that need to be kept alive in case the memory block contains pointers. -Common methods of ctypes data types, these are all class methods (to be exact, -they are methods of the :term:`metaclass`): + Common methods of ctypes data types, these are all class methods (to be + exact, they are methods of the :term:`metaclass`): -.. method:: _CData.from_address(address) + .. method:: from_address(address) - This method returns a ctypes type instance using the memory specified by address - which must be an integer. + This method returns a ctypes type instance using the memory specified by + address which must be an integer. -.. method:: _CData.from_param(obj) + .. method:: from_param(obj) - This method adapts obj to a ctypes type. It is called with the actual object - used in a foreign function call, when the type is present in the foreign - functions :attr:`argtypes` tuple; it must return an object that can be used as - function call parameter. + This method adapts obj to a ctypes type. It is called with the actual + object used in a foreign function call, when the type is present in the + foreign functions :attr:`argtypes` tuple; it must return an object that + can be used as function call parameter. - All ctypes data types have a default implementation of this classmethod, - normally it returns ``obj`` if that is an instance of the type. Some types - accept other objects as well. + All ctypes data types have a default implementation of this classmethod, + normally it returns ``obj`` if that is an instance of the type. Some + types accept other objects as well. -.. method:: _CData.in_dll(library, name) + .. method:: in_dll(library, name) - This method returns a ctypes type instance exported by a shared library. *name* - is the name of the symbol that exports the data, *library* is the loaded shared - library. + This method returns a ctypes type instance exported by a shared + library. *name* is the name of the symbol that exports the data, *library* + is the loaded shared library. -Common instance variables of ctypes data types: + Common instance variables of ctypes data types: -.. attribute:: _CData._b_base_ - Sometimes ctypes data instances do not own the memory block they contain, - instead they share part of the memory block of a base object. The - :attr:`_b_base_` read-only member is the root ctypes object that owns the memory - block. + .. attribute:: _b_base_ + Sometimes ctypes data instances do not own the memory block they contain, + instead they share part of the memory block of a base object. The + :attr:`_b_base_` read-only member is the root ctypes object that owns the + memory block. -.. attribute:: _CData._b_needsfree_ - This read-only variable is true when the ctypes data instance has allocated the - memory block itself, false otherwise. + .. attribute:: _b_needsfree_ + This read-only variable is true when the ctypes data instance has + allocated the memory block itself, false otherwise. -.. attribute:: _CData._objects - This member is either ``None`` or a dictionary containing Python objects that - need to be kept alive so that the memory block contents is kept valid. This - object is only exposed for debugging; never modify the contents of this - dictionary. + .. attribute:: _objects + + This member is either ``None`` or a dictionary containing Python objects + that need to be kept alive so that the memory block contents is kept + valid. This object is only exposed for debugging; never modify the + contents of this dictionary. .. _ctypes-fundamental-data-types-2: @@ -2010,19 +2012,20 @@ so it inherits their methods and attributes. ctypes data types that are not and do not contain pointers can now be pickled. -Instances have a single attribute: + Instances have a single attribute: -.. attribute:: _SimpleCData.value + .. attribute:: value - This attribute contains the actual value of the instance. For integer and - pointer types, it is an integer, for character types, it is a single character - string, for character pointer types it is a Python string or unicode string. + This attribute contains the actual value of the instance. For integer and + pointer types, it is an integer, for character types, it is a single + character string, for character pointer types it is a Python string or + unicode string. - When the ``value`` attribute is retrieved from a ctypes instance, usually a new - object is returned each time. ``ctypes`` does *not* implement original object - return, always a new object is constructed. The same is true for all other - ctypes object instances. + When the ``value`` attribute is retrieved from a ctypes instance, usually + a new object is returned each time. ``ctypes`` does *not* implement + original object return, always a new object is constructed. The same is + true for all other ctypes object instances. Fundamental data types, when returned as foreign function call results, or, for example, by retrieving structure field members or array items, are transparently @@ -2258,90 +2261,92 @@ Abstract base class for structures in *native* byte order. -Concrete structure and union types must be created by subclassing one of these -types, and at least define a :attr:`_fields_` class variable. ``ctypes`` will -create :term:`descriptor`\s which allow reading and writing the fields by direct -attribute accesses. These are the + Concrete structure and union types must be created by subclassing one of these + types, and at least define a :attr:`_fields_` class variable. ``ctypes`` will + create :term:`descriptor`\s which allow reading and writing the fields by direct + attribute accesses. These are the -.. attribute:: Structure._fields_ + .. attribute:: _fields_ - A sequence defining the structure fields. The items must be 2-tuples or - 3-tuples. The first item is the name of the field, the second item specifies - the type of the field; it can be any ctypes data type. + A sequence defining the structure fields. The items must be 2-tuples or + 3-tuples. The first item is the name of the field, the second item + specifies the type of the field; it can be any ctypes data type. - For integer type fields like :class:`c_int`, a third optional item can be given. - It must be a small positive integer defining the bit width of the field. + For integer type fields like :class:`c_int`, a third optional item can be + given. It must be a small positive integer defining the bit width of the + field. - Field names must be unique within one structure or union. This is not checked, - only one field can be accessed when names are repeated. + Field names must be unique within one structure or union. This is not + checked, only one field can be accessed when names are repeated. - It is possible to define the :attr:`_fields_` class variable *after* the class - statement that defines the Structure subclass, this allows to create data types - that directly or indirectly reference themselves:: + It is possible to define the :attr:`_fields_` class variable *after* the + class statement that defines the Structure subclass, this allows to create + data types that directly or indirectly reference themselves:: - class List(Structure): - pass - List._fields_ = [("pnext", POINTER(List)), - ... - ] + class List(Structure): + pass + List._fields_ = [("pnext", POINTER(List)), + ... + ] - The :attr:`_fields_` class variable must, however, be defined before the type is - first used (an instance is created, ``sizeof()`` is called on it, and so on). - Later assignments to the :attr:`_fields_` class variable will raise an - AttributeError. + The :attr:`_fields_` class variable must, however, be defined before the + type is first used (an instance is created, ``sizeof()`` is called on it, + and so on). Later assignments to the :attr:`_fields_` class variable will + raise an AttributeError. - Structure and union subclass constructors accept both positional and named - arguments. Positional arguments are used to initialize the fields in the same - order as they appear in the :attr:`_fields_` definition, named arguments are - used to initialize the fields with the corresponding name. + Structure and union subclass constructors accept both positional and named + arguments. Positional arguments are used to initialize the fields in the + same order as they appear in the :attr:`_fields_` definition, named + arguments are used to initialize the fields with the corresponding name. - It is possible to defined sub-subclasses of structure types, they inherit the - fields of the base class plus the :attr:`_fields_` defined in the sub-subclass, - if any. + It is possible to defined sub-subclasses of structure types, they inherit + the fields of the base class plus the :attr:`_fields_` defined in the + sub-subclass, if any. -.. attribute:: Structure._pack_ + .. attribute:: _pack_ - An optional small integer that allows to override the alignment of structure - fields in the instance. :attr:`_pack_` must already be defined when - :attr:`_fields_` is assigned, otherwise it will have no effect. + An optional small integer that allows to override the alignment of + structure fields in the instance. :attr:`_pack_` must already be defined + when :attr:`_fields_` is assigned, otherwise it will have no effect. -.. attribute:: Structure._anonymous_ + .. attribute:: _anonymous_ - An optional sequence that lists the names of unnamed (anonymous) fields. - ``_anonymous_`` must be already defined when :attr:`_fields_` is assigned, - otherwise it will have no effect. + An optional sequence that lists the names of unnamed (anonymous) fields. + ``_anonymous_`` must be already defined when :attr:`_fields_` is assigned, + otherwise it will have no effect. - The fields listed in this variable must be structure or union type fields. - ``ctypes`` will create descriptors in the structure type that allows to access - the nested fields directly, without the need to create the structure or union - field. + The fields listed in this variable must be structure or union type fields. + ``ctypes`` will create descriptors in the structure type that allows to + access the nested fields directly, without the need to create the + structure or union field. - Here is an example type (Windows):: + Here is an example type (Windows):: - class _U(Union): - _fields_ = [("lptdesc", POINTER(TYPEDESC)), - ("lpadesc", POINTER(ARRAYDESC)), - ("hreftype", HREFTYPE)] + class _U(Union): + _fields_ = [("lptdesc", POINTER(TYPEDESC)), + ("lpadesc", POINTER(ARRAYDESC)), + ("hreftype", HREFTYPE)] - class TYPEDESC(Structure): - _fields_ = [("u", _U), - ("vt", VARTYPE)] + class TYPEDESC(Structure): + _fields_ = [("u", _U), + ("vt", VARTYPE)] - _anonymous_ = ("u",) + _anonymous_ = ("u",) - The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field specifies - which one of the union fields is valid. Since the ``u`` field is defined as - anonymous field, it is now possible to access the members directly off the - TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc`` are equivalent, but the - former is faster since it does not need to create a temporary union instance:: + The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field + specifies which one of the union fields is valid. Since the ``u`` field + is defined as anonymous field, it is now possible to access the members + directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc`` + are equivalent, but the former is faster since it does not need to create + a temporary union instance:: - td = TYPEDESC() - td.vt = VT_PTR - td.lptdesc = POINTER(some_type) - td.u.lptdesc = POINTER(some_type) + td = TYPEDESC() + td.vt = VT_PTR + td.lptdesc = POINTER(some_type) + td.u.lptdesc = POINTER(some_type) It is possible to defined sub-subclasses of structures, they inherit the fields of the base class. If the subclass definition has a separate :attr:`_fields_` Modified: python/branches/py3k/Doc/library/curses.rst ============================================================================== --- python/branches/py3k/Doc/library/curses.rst (original) +++ python/branches/py3k/Doc/library/curses.rst Fri Apr 25 03:59:09 2008 @@ -1567,92 +1567,94 @@ containing window, with coordinates ``(0, 0)``. The instance's :attr:`stripspaces` flag is initially on. -:class:`Textbox` objects have the following methods: + :class:`Textbox` objects have the following methods: -.. method:: Textbox.edit([validator]) + .. method:: edit([validator]) - This is the entry point you will normally use. It accepts editing keystrokes - until one of the termination keystrokes is entered. If *validator* is supplied, - it must be a function. It will be called for each keystroke entered with the - keystroke as a parameter; command dispatch is done on the result. This method - returns the window contents as a string; whether blanks in the window are - included is affected by the :attr:`stripspaces` member. - - -.. method:: Textbox.do_command(ch) - - Process a single command keystroke. Here are the supported special keystrokes: - - +------------------+-------------------------------------------+ - | Keystroke | Action | - +==================+===========================================+ - | :kbd:`Control-A` | Go to left edge of window. | - +------------------+-------------------------------------------+ - | :kbd:`Control-B` | Cursor left, wrapping to previous line if | - | | appropriate. | - +------------------+-------------------------------------------+ - | :kbd:`Control-D` | Delete character under cursor. | - +------------------+-------------------------------------------+ - | :kbd:`Control-E` | Go to right edge (stripspaces off) or end | - | | of line (stripspaces on). | - +------------------+-------------------------------------------+ - | :kbd:`Control-F` | Cursor right, wrapping to next line when | - | | appropriate. | - +------------------+-------------------------------------------+ - | :kbd:`Control-G` | Terminate, returning the window contents. | - +------------------+-------------------------------------------+ - | :kbd:`Control-H` | Delete character backward. | - +------------------+-------------------------------------------+ - | :kbd:`Control-J` | Terminate if the window is 1 line, | - | | otherwise insert newline. | - +------------------+-------------------------------------------+ - | :kbd:`Control-K` | If line is blank, delete it, otherwise | - | | clear to end of line. | - +------------------+-------------------------------------------+ - | :kbd:`Control-L` | Refresh screen. | - +------------------+-------------------------------------------+ - | :kbd:`Control-N` | Cursor down; move down one line. | - +------------------+-------------------------------------------+ - | :kbd:`Control-O` | Insert a blank line at cursor location. | - +------------------+-------------------------------------------+ - | :kbd:`Control-P` | Cursor up; move up one line. | - +------------------+-------------------------------------------+ - - Move operations do nothing if the cursor is at an edge where the movement is not - possible. The following synonyms are supported where possible: - - +------------------------+------------------+ - | Constant | Keystroke | - +========================+==================+ - | :const:`KEY_LEFT` | :kbd:`Control-B` | - +------------------------+------------------+ - | :const:`KEY_RIGHT` | :kbd:`Control-F` | - +------------------------+------------------+ - | :const:`KEY_UP` | :kbd:`Control-P` | - +------------------------+------------------+ - | :const:`KEY_DOWN` | :kbd:`Control-N` | - +------------------------+------------------+ - | :const:`KEY_BACKSPACE` | :kbd:`Control-h` | - +------------------------+------------------+ - - All other keystrokes are treated as a command to insert the given character and - move right (with line wrapping). - - -.. method:: Textbox.gather() - - This method returns the window contents as a string; whether blanks in the - window are included is affected by the :attr:`stripspaces` member. - - -.. attribute:: Textbox.stripspaces - - This data member is a flag which controls the interpretation of blanks in the - window. When it is on, trailing blanks on each line are ignored; any cursor - motion that would land the cursor on a trailing blank goes to the end of that - line instead, and trailing blanks are stripped when the window contents are - gathered. + This is the entry point you will normally use. It accepts editing + keystrokes until one of the termination keystrokes is entered. If + *validator* is supplied, it must be a function. It will be called for + each keystroke entered with the keystroke as a parameter; command dispatch + is done on the result. This method returns the window contents as a + string; whether blanks in the window are included is affected by the + :attr:`stripspaces` member. + + + .. method:: do_command(ch) + + Process a single command keystroke. Here are the supported special + keystrokes: + + +------------------+-------------------------------------------+ + | Keystroke | Action | + +==================+===========================================+ + | :kbd:`Control-A` | Go to left edge of window. | + +------------------+-------------------------------------------+ + | :kbd:`Control-B` | Cursor left, wrapping to previous line if | + | | appropriate. | + +------------------+-------------------------------------------+ + | :kbd:`Control-D` | Delete character under cursor. | + +------------------+-------------------------------------------+ + | :kbd:`Control-E` | Go to right edge (stripspaces off) or end | + | | of line (stripspaces on). | + +------------------+-------------------------------------------+ + | :kbd:`Control-F` | Cursor right, wrapping to next line when | + | | appropriate. | + +------------------+-------------------------------------------+ + | :kbd:`Control-G` | Terminate, returning the window contents. | + +------------------+-------------------------------------------+ + | :kbd:`Control-H` | Delete character backward. | + +------------------+-------------------------------------------+ + | :kbd:`Control-J` | Terminate if the window is 1 line, | + | | otherwise insert newline. | + +------------------+-------------------------------------------+ + | :kbd:`Control-K` | If line is blank, delete it, otherwise | + | | clear to end of line. | + +------------------+-------------------------------------------+ + | :kbd:`Control-L` | Refresh screen. | + +------------------+-------------------------------------------+ + | :kbd:`Control-N` | Cursor down; move down one line. | + +------------------+-------------------------------------------+ + | :kbd:`Control-O` | Insert a blank line at cursor location. | + +------------------+-------------------------------------------+ + | :kbd:`Control-P` | Cursor up; move up one line. | + +------------------+-------------------------------------------+ + + Move operations do nothing if the cursor is at an edge where the movement + is not possible. The following synonyms are supported where possible: + + +------------------------+------------------+ + | Constant | Keystroke | + +========================+==================+ + | :const:`KEY_LEFT` | :kbd:`Control-B` | + +------------------------+------------------+ + | :const:`KEY_RIGHT` | :kbd:`Control-F` | + +------------------------+------------------+ + | :const:`KEY_UP` | :kbd:`Control-P` | + +------------------------+------------------+ + | :const:`KEY_DOWN` | :kbd:`Control-N` | + +------------------------+------------------+ + | :const:`KEY_BACKSPACE` | :kbd:`Control-h` | + +------------------------+------------------+ + + All other keystrokes are treated as a command to insert the given + character and move right (with line wrapping). + + + .. method:: gather() + + This method returns the window contents as a string; whether blanks in the + window are included is affected by the :attr:`stripspaces` member. + + + .. attribute:: stripspaces + + This data member is a flag which controls the interpretation of blanks in + the window. When it is on, trailing blanks on each line are ignored; any + cursor motion that would land the cursor on a trailing blank goes to the + end of that line instead, and trailing blanks are stripped when the window + contents are gathered. :mod:`curses.wrapper` --- Terminal handler for curses programs Modified: python/branches/py3k/Doc/library/decimal.rst ============================================================================== --- python/branches/py3k/Doc/library/decimal.rst (original) +++ python/branches/py3k/Doc/library/decimal.rst Fri Apr 25 03:59:09 2008 @@ -340,442 +340,394 @@ Once constructed, :class:`Decimal` objects are immutable. + Decimal floating point objects share many properties with the other built-in + numeric types such as :class:`float` and :class:`int`. All of the usual math + operations and special methods apply. Likewise, decimal objects can be + copied, pickled, printed, used as dictionary keys, used as set elements, + compared, sorted, and coerced to another type (such as :class:`float` or + :class:`long`). -Decimal floating point objects share many properties with the other built-in -numeric types such as :class:`float` and :class:`int`. All of the usual math -operations and special methods apply. Likewise, decimal objects can be copied, -pickled, printed, used as dictionary keys, used as set elements, compared, -sorted, and converted to another type (such as :class:`float` or :class:`int`). + In addition to the standard numeric properties, decimal floating point + objects also have a number of specialized methods: -In addition to the standard numeric properties, decimal floating point objects -also have a number of specialized methods: + .. method:: adjusted() -.. method:: Decimal.adjusted() + Return the adjusted exponent after shifting out the coefficient's + rightmost digits until only the lead digit remains: + ``Decimal('321e+5').adjusted()`` returns seven. Used for determining the + position of the most significant digit with respect to the decimal point. - Return the adjusted exponent after shifting out the coefficient's rightmost - digits until only the lead digit remains: ``Decimal('321e+5').adjusted()`` - returns seven. Used for determining the position of the most significant digit - with respect to the decimal point. + .. method:: as_tuple() -.. method:: Decimal.as_tuple() + Return a :term:`named tuple` representation of the number: + ``DecimalTuple(sign, digits, exponent)``. - Return a :term:`named tuple` representation of the number: - ``DecimalTuple(sign, digits, exponent)``. + .. method:: canonical() -.. method:: Decimal.canonical() + Return the canonical encoding of the argument. Currently, the encoding of + a :class:`Decimal` instance is always canonical, so this operation returns + its argument unchanged. - Return the canonical encoding of the argument. Currently, the - encoding of a :class:`Decimal` instance is always canonical, so - this operation returns its argument unchanged. + .. method:: compare(other[, context]) + Compare the values of two Decimal instances. This operation behaves in + the same way as the usual comparison method :meth:`__cmp__`, except that + :meth:`compare` returns a Decimal instance rather than an integer, and if + either operand is a NaN then the result is a NaN:: -.. method:: Decimal.compare(other[, context]) + a or b is a NaN ==> Decimal('NaN') + a < b ==> Decimal('-1') + a == b ==> Decimal('0') + a > b ==> Decimal('1') - Compare the values of two Decimal instances. This operation - behaves in the same way as the usual comparison method - :meth:`__cmp__`, except that :meth:`compare` returns a Decimal - instance rather than an integer, and if either operand is a NaN - then the result is a NaN:: + .. method:: compare_signal(other[, context]) - a or b is a NaN ==> Decimal('NaN') - a < b ==> Decimal('-1') - a == b ==> Decimal('0') - a > b ==> Decimal('1') + This operation is identical to the :meth:`compare` method, except that all + NaNs signal. That is, if neither operand is a signaling NaN then any + quiet NaN operand is treated as though it were a signaling NaN. -.. method:: Decimal.compare_signal(other[, context]) + .. method:: compare_total(other) - This operation is identical to the :meth:`compare` method, except - that all NaNs signal. That is, if neither operand is a signaling - NaN then any quiet NaN operand is treated as though it were a - signaling NaN. + Compare two operands using their abstract representation rather than their + numerical value. Similar to the :meth:`compare` method, but the result + gives a total ordering on :class:`Decimal` instances. Two + :class:`Decimal` instances with the same numeric value but different + representations compare unequal in this ordering: + >>> Decimal('12.0').compare_total(Decimal('12')) + Decimal('-1') -.. method:: Decimal.compare_total(other) + Quiet and signaling NaNs are also included in the total ordering. The + result of this function is ``Decimal('0')`` if both operands have the same + representation, ``Decimal('-1')`` if the first operand is lower in the + total order than the second, and ``Decimal('1')`` if the first operand is + higher in the total order than the second operand. See the specification + for details of the total order. - Compare two operands using their abstract representation rather - than their numerical value. Similar to the :meth:`compare` method, - but the result gives a total ordering on :class:`Decimal` - instances. Two :class:`Decimal` instances with the same numeric - value but different representations compare unequal in this - ordering: - - >>> Decimal('12.0').compare_total(Decimal('12')) - Decimal('-1') + .. method:: compare_total_mag(other) - Quiet and signaling NaNs are also included in the total ordering. - The result of this function is ``Decimal('0')`` if both operands - have the same representation, ``Decimal('-1')`` if the first - operand is lower in the total order than the second, and - ``Decimal('1')`` if the first operand is higher in the total order - than the second operand. See the specification for details of the - total order. + Compare two operands using their abstract representation rather than their + value as in :meth:`compare_total`, but ignoring the sign of each operand. + ``x.compare_total_mag(y)`` is equivalent to + ``x.copy_abs().compare_total(y.copy_abs())``. + .. method:: copy_abs() -.. method:: Decimal.compare_total_mag(other) + Return the absolute value of the argument. This operation is unaffected + by the context and is quiet: no flags are changed and no rounding is + performed. - Compare two operands using their abstract representation rather - than their value as in :meth:`compare_total`, but ignoring the sign - of each operand. ``x.compare_total_mag(y)`` is equivalent to - ``x.copy_abs().compare_total(y.copy_abs())``. + .. method:: copy_negate() + Return the negation of the argument. This operation is unaffected by the + context and is quiet: no flags are changed and no rounding is performed. -.. method:: Decimal.copy_abs() + .. method:: copy_sign(other) - Return the absolute value of the argument. This operation is - unaffected by the context and is quiet: no flags are changed and no - rounding is performed. + Return a copy of the first operand with the sign set to be the same as the + sign of the second operand. For example: + >>> Decimal('2.3').copy_sign(Decimal('-1.5')) + Decimal('-2.3') -.. method:: Decimal.copy_negate() + This operation is unaffected by the context and is quiet: no flags are + changed and no rounding is performed. - Return the negation of the argument. This operation is unaffected - by the context and is quiet: no flags are changed and no rounding - is performed. + .. method:: exp([context]) + Return the value of the (natural) exponential function ``e**x`` at the + given number. The result is correctly rounded using the + :const:`ROUND_HALF_EVEN` rounding mode. -.. method:: Decimal.copy_sign(other) + >>> Decimal(1).exp() + Decimal('2.718281828459045235360287471') + >>> Decimal(321).exp() + Decimal('2.561702493119680037517373933E+139') - Return a copy of the first operand with the sign set to be the - same as the sign of the second operand. For example: + .. method:: fma(other, third[, context]) - >>> Decimal('2.3').copy_sign(Decimal('-1.5')) - Decimal('-2.3') - - This operation is unaffected by the context and is quiet: no flags - are changed and no rounding is performed. + Fused multiply-add. Return self*other+third with no rounding of the + intermediate product self*other. + >>> Decimal(2).fma(3, 5) + Decimal('11') -.. method:: Decimal.exp([context]) + .. method:: is_canonical() - Return the value of the (natural) exponential function ``e**x`` at the - given number. The result is correctly rounded using the - :const:`ROUND_HALF_EVEN` rounding mode. + Return :const:`True` if the argument is canonical and :const:`False` + otherwise. Currently, a :class:`Decimal` instance is always canonical, so + this operation always returns :const:`True`. - >>> Decimal(1).exp() - Decimal('2.718281828459045235360287471') - >>> Decimal(321).exp() - Decimal('2.561702493119680037517373933E+139') + .. method:: is_finite() + Return :const:`True` if the argument is a finite number, and + :const:`False` if the argument is an infinity or a NaN. -.. method:: Decimal.fma(other, third[, context]) + .. method:: is_infinite() - Fused multiply-add. Return self*other+third with no rounding of - the intermediate product self*other. + Return :const:`True` if the argument is either positive or negative + infinity and :const:`False` otherwise. - >>> Decimal(2).fma(3, 5) - Decimal('11') + .. method:: is_nan() + Return :const:`True` if the argument is a (quiet or signaling) NaN and + :const:`False` otherwise. -.. method:: Decimal.is_canonical() + .. method:: is_normal() - Return :const:`True` if the argument is canonical and - :const:`False` otherwise. Currently, a :class:`Decimal` instance - is always canonical, so this operation always returns - :const:`True`. + Return :const:`True` if the argument is a *normal* finite number. Return + :const:`False` if the argument is zero, subnormal, infinite or a NaN. + .. method:: is_qnan() -.. method:: is_finite() + Return :const:`True` if the argument is a quiet NaN, and + :const:`False` otherwise. - Return :const:`True` if the argument is a finite number, and - :const:`False` if the argument is an infinity or a NaN. + .. method:: is_signed() + Return :const:`True` if the argument has a negative sign and + :const:`False` otherwise. Note that zeros and NaNs can both carry signs. -.. method:: is_infinite() + .. method:: is_snan() - Return :const:`True` if the argument is either positive or - negative infinity and :const:`False` otherwise. + Return :const:`True` if the argument is a signaling NaN and :const:`False` + otherwise. + .. method:: is_subnormal() -.. method:: is_nan() + Return :const:`True` if the argument is subnormal, and :const:`False` + otherwise. - Return :const:`True` if the argument is a (quiet or signaling) - NaN and :const:`False` otherwise. + .. method:: is_zero() + Return :const:`True` if the argument is a (positive or negative) zero and + :const:`False` otherwise. -.. method:: is_normal() + .. method:: ln([context]) - Return :const:`True` if the argument is a *normal* finite number. - Return :const:`False` if the argument is zero, subnormal, infinite - or a NaN. + Return the natural (base e) logarithm of the operand. The result is + correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode. + .. method:: log10([context]) -.. method:: is_qnan() + Return the base ten logarithm of the operand. The result is correctly + rounded using the :const:`ROUND_HALF_EVEN` rounding mode. - Return :const:`True` if the argument is a quiet NaN, and - :const:`False` otherwise. + .. method:: logb([context]) + For a nonzero number, return the adjusted exponent of its operand as a + :class:`Decimal` instance. If the operand is a zero then + ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag + is raised. If the operand is an infinity then ``Decimal('Infinity')`` is + returned. -.. method:: is_signed() + .. method:: logical_and(other[, context]) - Return :const:`True` if the argument has a negative sign and - :const:`False` otherwise. Note that zeros and NaNs can both carry - signs. + :meth:`logical_and` is a logical operation which takes two *logical + operands* (see :ref:`logical_operands_label`). The result is the + digit-wise ``and`` of the two operands. + .. method:: logical_invert(other[, context]) -.. method:: is_snan() + :meth:`logical_invert` is a logical operation. The argument must + be a *logical operand* (see :ref:`logical_operands_label`). The + result is the digit-wise inversion of the operand. - Return :const:`True` if the argument is a signaling NaN and - :const:`False` otherwise. + .. method:: logical_or(other[, context]) + :meth:`logical_or` is a logical operation which takes two *logical + operands* (see :ref:`logical_operands_label`). The result is the + digit-wise ``or`` of the two operands. -.. method:: is_subnormal() + .. method:: logical_xor(other[, context]) - Return :const:`True` if the argument is subnormal, and - :const:`False` otherwise. + :meth:`logical_xor` is a logical operation which takes two *logical + operands* (see :ref:`logical_operands_label`). The result is the + digit-wise exclusive or of the two operands. + .. method:: max(other[, context]) -.. method:: is_zero() + Like ``max(self, other)`` except that the context rounding rule is applied + before returning and that :const:`NaN` values are either signaled or + ignored (depending on the context and whether they are signaling or + quiet). - Return :const:`True` if the argument is a (positive or negative) - zero and :const:`False` otherwise. + .. method:: max_mag(other[, context]) + Similar to the :meth:`max` method, but the comparison is done using the + absolute values of the operands. -.. method:: Decimal.ln([context]) + .. method:: min(other[, context]) - Return the natural (base e) logarithm of the operand. The result - is correctly rounded using the :const:`ROUND_HALF_EVEN` rounding - mode. + Like ``min(self, other)`` except that the context rounding rule is applied + before returning and that :const:`NaN` values are either signaled or + ignored (depending on the context and whether they are signaling or + quiet). + .. method:: min_mag(other[, context]) -.. method:: Decimal.log10([context]) + Similar to the :meth:`min` method, but the comparison is done using the + absolute values of the operands. - Return the base ten logarithm of the operand. The result is - correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode. + .. method:: next_minus([context]) + Return the largest number representable in the given context (or in the + current thread's context if no context is given) that is smaller than the + given operand. -.. method:: Decimal.logb([context]) + .. method:: next_plus([context]) - For a nonzero number, return the adjusted exponent of its operand - as a :class:`Decimal` instance. If the operand is a zero then - ``Decimal('-Infinity')`` is returned and the - :const:`DivisionByZero` flag is raised. If the operand is an - infinity then ``Decimal('Infinity')`` is returned. + Return the smallest number representable in the given context (or in the + current thread's context if no context is given) that is larger than the + given operand. + .. method:: next_toward(other[, context]) -.. method:: Decimal.logical_and(other[, context]) + If the two operands are unequal, return the number closest to the first + operand in the direction of the second operand. If both operands are + numerically equal, return a copy of the first operand with the sign set to + be the same as the sign of the second operand. - :meth:`logical_and` is a logical operation which takes two - *logical operands* (see :ref:`logical_operands_label`). The result - is the digit-wise ``and`` of the two operands. + .. method:: normalize([context]) + Normalize the number by stripping the rightmost trailing zeros and + converting any result equal to :const:`Decimal('0')` to + :const:`Decimal('0e0')`. Used for producing canonical values for members + of an equivalence class. For example, ``Decimal('32.100')`` and + ``Decimal('0.321000e+2')`` both normalize to the equivalent value + ``Decimal('32.1')``. -.. method:: Decimal.logical_invert(other[, context]) + .. method:: number_class([context]) - :meth:`logical_invert` is a logical operation. The argument must - be a *logical operand* (see :ref:`logical_operands_label`). The - result is the digit-wise inversion of the operand. + Return a string describing the *class* of the operand. The returned value + is one of the following ten strings. + * ``"-Infinity"``, indicating that the operand is negative infinity. + * ``"-Normal"``, indicating that the operand is a negative normal number. + * ``"-Subnormal"``, indicating that the operand is negative and subnormal. + * ``"-Zero"``, indicating that the operand is a negative zero. + * ``"+Zero"``, indicating that the operand is a positive zero. + * ``"+Subnormal"``, indicating that the operand is positive and subnormal. + * ``"+Normal"``, indicating that the operand is a positive normal number. + * ``"+Infinity"``, indicating that the operand is positive infinity. + * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number). + * ``"sNaN"``, indicating that the operand is a signaling NaN. -.. method:: Decimal.logical_or(other[, context]) + .. method:: quantize(exp[, rounding[, context[, watchexp]]]) - :meth:`logical_or` is a logical operation which takes two *logical - operands* (see :ref:`logical_operands_label`). The result is the - digit-wise ``or`` of the two operands. + Return a value equal to the first operand after rounding and having the + exponent of the second operand. + >>> Decimal('1.41421356').quantize(Decimal('1.000')) + Decimal('1.414') -.. method:: Decimal.logical_xor(other[, context]) + Unlike other operations, if the length of the coefficient after the + quantize operation would be greater than precision, then an + :const:`InvalidOperation` is signaled. This guarantees that, unless there + is an error condition, the quantized exponent is always equal to that of + the right-hand operand. - :meth:`logical_xor` is a logical operation which takes two - *logical operands* (see :ref:`logical_operands_label`). The result - is the digit-wise exclusive or of the two operands. + Also unlike other operations, quantize never signals Underflow, even if + the result is subnormal and inexact. + If the exponent of the second operand is larger than that of the first + then rounding may be necessary. In this case, the rounding mode is + determined by the ``rounding`` argument if given, else by the given + ``context`` argument; if neither argument is given the rounding mode of + the current thread's context is used. -.. method:: Decimal.max(other[, context]) + If *watchexp* is set (default), then an error is returned whenever the + resulting exponent is greater than :attr:`Emax` or less than + :attr:`Etiny`. - Like ``max(self, other)`` except that the context rounding rule is applied - before returning and that :const:`NaN` values are either signaled or ignored - (depending on the context and whether they are signaling or quiet). + .. method:: radix() + Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal` + class does all its arithmetic. Included for compatibility with the + specification. -.. method:: Decimal.max_mag(other[, context]) + .. method:: remainder_near(other[, context]) - Similar to the :meth:`max` method, but the comparison is done using - the absolute values of the operands. + Compute the modulo as either a positive or negative value depending on + which is closest to zero. For instance, ``Decimal(10).remainder_near(6)`` + returns ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``. + If both are equally close, the one chosen will have the same sign as + *self*. -.. method:: Decimal.min(other[, context]) + .. method:: rotate(other[, context]) - Like ``min(self, other)`` except that the context rounding rule is applied - before returning and that :const:`NaN` values are either signaled or ignored - (depending on the context and whether they are signaling or quiet). + Return the result of rotating the digits of the first operand by an amount + specified by the second operand. The second operand must be an integer in + the range -precision through precision. The absolute value of the second + operand gives the number of places to rotate. If the second operand is + positive then rotation is to the left; otherwise rotation is to the right. + The coefficient of the first operand is padded on the left with zeros to + length precision if necessary. The sign and exponent of the first operand + are unchanged. -.. method:: Decimal.min_mag(other[, context]) + .. method:: same_quantum(other[, context]) - Similar to the :meth:`min` method, but the comparison is done using - the absolute values of the operands. + Test whether self and other have the same exponent or whether both are + :const:`NaN`. + .. method:: scaleb(other[, context]) -.. method:: Decimal.next_minus([context]) + Return the first operand with exponent adjusted by the second. + Equivalently, return the first operand multiplied by ``10**other``. The + second operand must be an integer. - Return the largest number representable in the given context (or - in the current thread's context if no context is given) that is smaller - than the given operand. + .. method:: shift(other[, context]) + Return the result of shifting the digits of the first operand by an amount + specified by the second operand. The second operand must be an integer in + the range -precision through precision. The absolute value of the second + operand gives the number of places to shift. If the second operand is + positive then the shift is to the left; otherwise the shift is to the + right. Digits shifted into the coefficient are zeros. The sign and + exponent of the first operand are unchanged. -.. method:: Decimal.next_plus([context]) + .. method:: sqrt([context]) - Return the smallest number representable in the given context (or - in the current thread's context if no context is given) that is - larger than the given operand. + Return the square root of the argument to full precision. -.. method:: Decimal.next_toward(other[, context]) + .. method:: to_eng_string([context]) - If the two operands are unequal, return the number closest to the - first operand in the direction of the second operand. If both - operands are numerically equal, return a copy of the first operand - with the sign set to be the same as the sign of the second operand. + Convert to an engineering-type string. + Engineering notation has an exponent which is a multiple of 3, so there + are up to 3 digits left of the decimal place. For example, converts + ``Decimal('123E+1')`` to ``Decimal('1.23E+3')`` -.. method:: Decimal.normalize([context]) + .. method:: to_integral([rounding[, context]]) - Normalize the number by stripping the rightmost trailing zeros and converting - any result equal to :const:`Decimal('0')` to :const:`Decimal('0e0')`. Used for - producing canonical values for members of an equivalence class. For example, - ``Decimal('32.100')`` and ``Decimal('0.321000e+2')`` both normalize to the - equivalent value ``Decimal('32.1')``. + Identical to the :meth:`to_integral_value` method. The ``to_integral`` + name has been kept for compatibility with older versions. + .. method:: to_integral_exact([rounding[, context]]) -.. method:: Decimal.number_class([context]) + Round to the nearest integer, signaling :const:`Inexact` or + :const:`Rounded` as appropriate if rounding occurs. The rounding mode is + determined by the ``rounding`` parameter if given, else by the given + ``context``. If neither parameter is given then the rounding mode of the + current context is used. - Return a string describing the *class* of the operand. The - returned value is one of the following ten strings. + .. method:: to_integral_value([rounding[, context]]) - * ``"-Infinity"``, indicating that the operand is negative infinity. - * ``"-Normal"``, indicating that the operand is a negative normal number. - * ``"-Subnormal"``, indicating that the operand is negative and subnormal. - * ``"-Zero"``, indicating that the operand is a negative zero. - * ``"+Zero"``, indicating that the operand is a positive zero. - * ``"+Subnormal"``, indicating that the operand is positive and subnormal. - * ``"+Normal"``, indicating that the operand is a positive normal number. - * ``"+Infinity"``, indicating that the operand is positive infinity. - * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number). - * ``"sNaN"``, indicating that the operand is a signaling NaN. + Round to the nearest integer without signaling :const:`Inexact` or + :const:`Rounded`. If given, applies *rounding*; otherwise, uses the + rounding method in either the supplied *context* or the current context. + .. method:: trim() -.. method:: Decimal.quantize(exp[, rounding[, context[, watchexp]]]) - - Return a value equal to the first operand after rounding and - having the exponent of the second operand. - - >>> Decimal('1.41421356').quantize(Decimal('1.000')) - Decimal('1.414') - - Unlike other operations, if the length of the coefficient after the - quantize operation would be greater than precision, then an - :const:`InvalidOperation` is signaled. This guarantees that, unless - there is an error condition, the quantized exponent is always equal - to that of the right-hand operand. - - Also unlike other operations, quantize never signals Underflow, - even if the result is subnormal and inexact. - - If the exponent of the second operand is larger than that of the - first then rounding may be necessary. In this case, the rounding - mode is determined by the ``rounding`` argument if given, else by - the given ``context`` argument; if neither argument is given the - rounding mode of the current thread's context is used. - - If *watchexp* is set (default), then an error is returned whenever the - resulting exponent is greater than :attr:`Emax` or less than :attr:`Etiny`. - -.. method:: Decimal.radix() - - Return ``Decimal(10)``, the radix (base) in which the - :class:`Decimal` class does all its arithmetic. Included for - compatibility with the specification. - - -.. method:: Decimal.remainder_near(other[, context]) - - Compute the modulo as either a positive or negative value depending on which is - closest to zero. For instance, ``Decimal(10).remainder_near(6)`` returns - ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``. - - If both are equally close, the one chosen will have the same sign as *self*. - -.. method:: Decimal.rotate(other[, context]) - - Return the result of rotating the digits of the first operand by - an amount specified by the second operand. The second operand - must be an integer in the range -precision through precision. The - absolute value of the second operand gives the number of places to - rotate. If the second operand is positive then rotation is to the - left; otherwise rotation is to the right. The coefficient of the - first operand is padded on the left with zeros to length precision - if necessary. The sign and exponent of the first operand are - unchanged. - - -.. method:: Decimal.same_quantum(other[, context]) - - Test whether self and other have the same exponent or whether both are - :const:`NaN`. - -.. method:: Decimal.scaleb(other[, context]) - - Return the first operand with exponent adjusted by the second. - Equivalently, return the first operand multiplied by ``10**other``. - The second operand must be an integer. - - -.. method:: Decimal.shift(other[, context]) - - Return the result of shifting the digits of the first operand by - an amount specified by the second operand. The second operand must - be an integer in the range -precision through precision. The - absolute value of the second operand gives the number of places to - shift. If the second operand is positive then the shift is to the - left; otherwise the shift is to the right. Digits shifted into the - coefficient are zeros. The sign and exponent of the first operand - are unchanged. - - -.. method:: Decimal.sqrt([context]) - - Return the square root of the argument to full precision. - - -.. method:: Decimal.to_eng_string([context]) - - Convert to an engineering-type string. - - Engineering notation has an exponent which is a multiple of 3, so there are up - to 3 digits left of the decimal place. For example, converts - ``Decimal('123E+1')`` to ``Decimal('1.23E+3')`` - -.. method:: Decimal.to_integral([rounding[, context]]) - - Identical to the :meth:`to_integral_value` method. The ``to_integral`` - name has been kept for compatibility with older versions. - -.. method:: Decimal.to_integral_exact([rounding[, context]]) - - Round to the nearest integer, signaling - :const:`Inexact` or :const:`Rounded` as appropriate if rounding - occurs. The rounding mode is determined by the ``rounding`` - parameter if given, else by the given ``context``. If neither - parameter is given then the rounding mode of the current context is - used. - - -.. method:: Decimal.to_integral_value([rounding[, context]]) - - Round to the nearest integer without signaling :const:`Inexact` or - :const:`Rounded`. If given, applies *rounding*; otherwise, uses the rounding - method in either the supplied *context* or the current context. - - -.. method:: Decimal.trim() - - Return the decimal with *insignificant* trailing zeros removed. - Here, a trailing zero is considered insignificant either if it - follows the decimal point, or if the exponent of the argument (that - is, the last element of the :meth:`as_tuple` representation) is - positive. + Return the decimal with *insignificant* trailing zeros removed. Here, a + trailing zero is considered insignificant either if it follows the decimal + point, or if the exponent of the argument (that is, the last element of + the :meth:`as_tuple` representation) is positive. .. _logical_operands_label: @@ -916,150 +868,147 @@ lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`. -The :class:`Context` class defines several general purpose methods as -well as a large number of methods for doing arithmetic directly in a -given context. In addition, for each of the :class:`Decimal` methods -described above (with the exception of the :meth:`adjusted` and -:meth:`as_tuple` methods) there is a corresponding :class:`Context` -method. For example, ``C.exp(x)`` is equivalent to -``x.exp(context=C)``. - -.. method:: Context.clear_flags() + The :class:`Context` class defines several general purpose methods as well as + a large number of methods for doing arithmetic directly in a given context. + In addition, for each of the :class:`Decimal` methods described above (with + the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is + a corresponding :class:`Context` method. For example, ``C.exp(x)`` is + equivalent to ``x.exp(context=C)``. - Resets all of the flags to :const:`0`. + .. method:: clear_flags() -.. method:: Context.copy() + Resets all of the flags to :const:`0`. - Return a duplicate of the context. + .. method:: copy() -.. method:: Context.copy_decimal(num) + Return a duplicate of the context. - Return a copy of the Decimal instance num. + .. method:: copy_decimal(num) -.. method:: Context.create_decimal(num) + Return a copy of the Decimal instance num. - Creates a new Decimal instance from *num* but using *self* as context. Unlike - the :class:`Decimal` constructor, the context precision, rounding method, flags, - and traps are applied to the conversion. + .. method:: create_decimal(num) - This is useful because constants are often given to a greater precision than is - needed by the application. Another benefit is that rounding immediately - eliminates unintended effects from digits beyond the current precision. In the - following example, using unrounded inputs means that adding zero to a sum can - change the result: + Creates a new Decimal instance from *num* but using *self* as + context. Unlike the :class:`Decimal` constructor, the context precision, + rounding method, flags, and traps are applied to the conversion. - .. doctest:: newcontext + This is useful because constants are often given to a greater precision + than is needed by the application. Another benefit is that rounding + immediately eliminates unintended effects from digits beyond the current + precision. In the following example, using unrounded inputs means that + adding zero to a sum can change the result: - >>> getcontext().prec = 3 - >>> Decimal('3.4445') + Decimal('1.0023') - Decimal('4.45') - >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023') - Decimal('4.44') + .. doctest:: newcontext - This method implements the to-number operation of the IBM - specification. If the argument is a string, no leading or trailing - whitespace is permitted. + >>> getcontext().prec = 3 + >>> Decimal('3.4445') + Decimal('1.0023') + Decimal('4.45') + >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023') + Decimal('4.44') -.. method:: Context.Etiny() + This method implements the to-number operation of the IBM specification. + If the argument is a string, no leading or trailing whitespace is + permitted. - Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent value - for subnormal results. When underflow occurs, the exponent is set to - :const:`Etiny`. + .. method:: Etiny() + Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent + value for subnormal results. When underflow occurs, the exponent is set + to :const:`Etiny`. -.. method:: Context.Etop() - Returns a value equal to ``Emax - prec + 1``. + .. method:: Etop() -The usual approach to working with decimals is to create :class:`Decimal` -instances and then apply arithmetic operations which take place within the -current context for the active thread. An alternative approach is to use context -methods for calculating within a specific context. The methods are similar to -those for the :class:`Decimal` class and are only briefly recounted here. + Returns a value equal to ``Emax - prec + 1``. + The usual approach to working with decimals is to create :class:`Decimal` + instances and then apply arithmetic operations which take place within the + current context for the active thread. An alternative approach is to use + context methods for calculating within a specific context. The methods are + similar to those for the :class:`Decimal` class and are only briefly + recounted here. -.. method:: Context.abs(x) - Returns the absolute value of *x*. + .. method:: abs(x) + Returns the absolute value of *x*. -.. method:: Context.add(x, y) - Return the sum of *x* and *y*. + .. method:: add(x, y) + Return the sum of *x* and *y*. -.. method:: Context.divide(x, y) - Return *x* divided by *y*. + .. method:: divide(x, y) + Return *x* divided by *y*. -.. method:: Context.divide_int(x, y) - Return *x* divided by *y*, truncated to an integer. + .. method:: divide_int(x, y) + Return *x* divided by *y*, truncated to an integer. -.. method:: Context.divmod(x, y) - Divides two numbers and returns the integer part of the result. + .. method:: divmod(x, y) + Divides two numbers and returns the integer part of the result. -.. method:: Context.minus(x) - Minus corresponds to the unary prefix minus operator in Python. + .. method:: minus(x) + Minus corresponds to the unary prefix minus operator in Python. -.. method:: Context.multiply(x, y) - Return the product of *x* and *y*. + .. method:: multiply(x, y) + Return the product of *x* and *y*. -.. method:: Context.plus(x) - Plus corresponds to the unary prefix plus operator in Python. This operation - applies the context precision and rounding, so it is *not* an identity - operation. + .. method:: plus(x) + Plus corresponds to the unary prefix plus operator in Python. This + operation applies the context precision and rounding, so it is *not* an + identity operation. -.. method:: Context.power(x, y[, modulo]) - Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if - given. + .. method:: power(x, y[, modulo]) - With two arguments, compute ``x**y``. If ``x`` is negative then - ``y`` must be integral. The result will be inexact unless ``y`` is - integral and the result is finite and can be expressed exactly in - 'precision' digits. The result should always be correctly rounded, - using the rounding mode of the current thread's context. + Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given. - With three arguments, compute ``(x**y) % modulo``. For the three - argument form, the following restrictions on the arguments hold: + With two arguments, compute ``x**y``. If ``x`` is negative then ``y`` + must be integral. The result will be inexact unless ``y`` is integral and + the result is finite and can be expressed exactly in 'precision' digits. + The result should always be correctly rounded, using the rounding mode of + the current thread's context. - - all three arguments must be integral - - ``y`` must be nonnegative - - at least one of ``x`` or ``y`` must be nonzero - - ``modulo`` must be nonzero and have at most 'precision' digits + With three arguments, compute ``(x**y) % modulo``. For the three argument + form, the following restrictions on the arguments hold: - The result of ``Context.power(x, y, modulo)`` is identical to - the result that would be obtained by computing ``(x**y) % - modulo`` with unbounded precision, but is computed more - efficiently. It is always exact. + - all three arguments must be integral + - ``y`` must be nonnegative + - at least one of ``x`` or ``y`` must be nonzero + - ``modulo`` must be nonzero and have at most 'precision' digits + The result of ``Context.power(x, y, modulo)`` is identical to the result + that would be obtained by computing ``(x**y) % modulo`` with unbounded + precision, but is computed more efficiently. It is always exact. -.. method:: Context.remainder(x, y) + .. method:: remainder(x, y) - Returns the remainder from integer division. + Returns the remainder from integer division. - The sign of the result, if non-zero, is the same as that of the original - dividend. + The sign of the result, if non-zero, is the same as that of the original + dividend. -.. method:: Context.subtract(x, y) + .. method:: subtract(x, y) - Return the difference between *x* and *y*. + Return the difference between *x* and *y*. -.. method:: Context.to_sci_string(x) + .. method:: to_sci_string(x) - Converts a number to a string using scientific notation. + Converts a number to a string using scientific notation. .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -1138,28 +1087,29 @@ Numerical overflow. - Indicates the exponent is larger than :attr:`Emax` after rounding has occurred. - If not trapped, the result depends on the rounding mode, either pulling inward - to the largest representable finite number or rounding outward to - :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded` are - also signaled. + Indicates the exponent is larger than :attr:`Emax` after rounding has + occurred. If not trapped, the result depends on the rounding mode, either + pulling inward to the largest representable finite number or rounding outward + to :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded` + are also signaled. .. class:: Rounded Rounding occurred though possibly no information was lost. - Signaled whenever rounding discards digits; even if those digits are zero (such - as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns the result - unchanged. This signal is used to detect loss of significant digits. + Signaled whenever rounding discards digits; even if those digits are zero + (such as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns + the result unchanged. This signal is used to detect loss of significant + digits. .. class:: Subnormal Exponent was lower than :attr:`Emin` prior to rounding. - Occurs when an operation result is subnormal (the exponent is too small). If not - trapped, returns the result unchanged. + Occurs when an operation result is subnormal (the exponent is too small). If + not trapped, returns the result unchanged. .. class:: Underflow Modified: python/branches/py3k/Doc/library/difflib.rst ============================================================================== --- python/branches/py3k/Doc/library/difflib.rst (original) +++ python/branches/py3k/Doc/library/difflib.rst Fri Apr 25 03:59:09 2008 @@ -343,166 +343,171 @@ The optional arguments *a* and *b* are sequences to be compared; both default to empty strings. The elements of both sequences must be :term:`hashable`. -:class:`SequenceMatcher` objects have the following methods: + :class:`SequenceMatcher` objects have the following methods: -.. method:: SequenceMatcher.set_seqs(a, b) + .. method:: set_seqs(a, b) - Set the two sequences to be compared. + Set the two sequences to be compared. -:class:`SequenceMatcher` computes and caches detailed information about the -second sequence, so if you want to compare one sequence against many sequences, -use :meth:`set_seq2` to set the commonly used sequence once and call -:meth:`set_seq1` repeatedly, once for each of the other sequences. + :class:`SequenceMatcher` computes and caches detailed information about the + second sequence, so if you want to compare one sequence against many + sequences, use :meth:`set_seq2` to set the commonly used sequence once and + call :meth:`set_seq1` repeatedly, once for each of the other sequences. -.. method:: SequenceMatcher.set_seq1(a) + .. method:: set_seq1(a) - Set the first sequence to be compared. The second sequence to be compared is - not changed. + Set the first sequence to be compared. The second sequence to be compared + is not changed. -.. method:: SequenceMatcher.set_seq2(b) + .. method:: set_seq2(b) - Set the second sequence to be compared. The first sequence to be compared is - not changed. + Set the second sequence to be compared. The first sequence to be compared + is not changed. -.. method:: SequenceMatcher.find_longest_match(alo, ahi, blo, bhi) + .. method:: find_longest_match(alo, ahi, blo, bhi) - Find longest matching block in ``a[alo:ahi]`` and ``b[blo:bhi]``. + Find longest matching block in ``a[alo:ahi]`` and ``b[blo:bhi]``. - If *isjunk* was omitted or ``None``, :meth:`find_longest_match` returns ``(i, j, - k)`` such that ``a[i:i+k]`` is equal to ``b[j:j+k]``, where ``alo <= i <= i+k <= - ahi`` and ``blo <= j <= j+k <= bhi``. For all ``(i', j', k')`` meeting those - conditions, the additional conditions ``k >= k'``, ``i <= i'``, and if ``i == - i'``, ``j <= j'`` are also met. In other words, of all maximal matching blocks, - return one that starts earliest in *a*, and of all those maximal matching blocks - that start earliest in *a*, return the one that starts earliest in *b*. + If *isjunk* was omitted or ``None``, :meth:`find_longest_match` returns + ``(i, j, k)`` such that ``a[i:i+k]`` is equal to ``b[j:j+k]``, where ``alo + <= i <= i+k <= ahi`` and ``blo <= j <= j+k <= bhi``. For all ``(i', j', + k')`` meeting those conditions, the additional conditions ``k >= k'``, ``i + <= i'``, and if ``i == i'``, ``j <= j'`` are also met. In other words, of + all maximal matching blocks, return one that starts earliest in *a*, and + of all those maximal matching blocks that start earliest in *a*, return + the one that starts earliest in *b*. - >>> s = SequenceMatcher(None, " abcd", "abcd abcd") - >>> s.find_longest_match(0, 5, 0, 9) - Match(a=0, b=4, size=5) + >>> s = SequenceMatcher(None, " abcd", "abcd abcd") + >>> s.find_longest_match(0, 5, 0, 9) + Match(a=0, b=4, size=5) - If *isjunk* was provided, first the longest matching block is determined as - above, but with the additional restriction that no junk element appears in the - block. Then that block is extended as far as possible by matching (only) junk - elements on both sides. So the resulting block never matches on junk except as - identical junk happens to be adjacent to an interesting match. + If *isjunk* was provided, first the longest matching block is determined + as above, but with the additional restriction that no junk element appears + in the block. Then that block is extended as far as possible by matching + (only) junk elements on both sides. So the resulting block never matches + on junk except as identical junk happens to be adjacent to an interesting + match. - Here's the same example as before, but considering blanks to be junk. That - prevents ``' abcd'`` from matching the ``' abcd'`` at the tail end of the second - sequence directly. Instead only the ``'abcd'`` can match, and matches the - leftmost ``'abcd'`` in the second sequence: + Here's the same example as before, but considering blanks to be junk. That + prevents ``' abcd'`` from matching the ``' abcd'`` at the tail end of the + second sequence directly. Instead only the ``'abcd'`` can match, and + matches the leftmost ``'abcd'`` in the second sequence: - >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd") - >>> s.find_longest_match(0, 5, 0, 9) - Match(a=1, b=0, size=4) + >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd") + >>> s.find_longest_match(0, 5, 0, 9) + Match(a=1, b=0, size=4) - If no blocks match, this returns ``(alo, blo, 0)``. + If no blocks match, this returns ``(alo, blo, 0)``. - This method returns a :term:`named tuple` ``Match(a, b, size)``. + This method returns a :term:`named tuple` ``Match(a, b, size)``. -.. method:: SequenceMatcher.get_matching_blocks() + .. method:: get_matching_blocks() - Return list of triples describing matching subsequences. Each triple is of the - form ``(i, j, n)``, and means that ``a[i:i+n] == b[j:j+n]``. The triples are - monotonically increasing in *i* and *j*. + Return list of triples describing matching subsequences. Each triple is of + the form ``(i, j, n)``, and means that ``a[i:i+n] == b[j:j+n]``. The + triples are monotonically increasing in *i* and *j*. - The last triple is a dummy, and has the value ``(len(a), len(b), 0)``. It is - the only triple with ``n == 0``. If ``(i, j, n)`` and ``(i', j', n')`` are - adjacent triples in the list, and the second is not the last triple in the list, - then ``i+n != i'`` or ``j+n != j'``; in other words, adjacent triples always - describe non-adjacent equal blocks. + The last triple is a dummy, and has the value ``(len(a), len(b), 0)``. It + is the only triple with ``n == 0``. If ``(i, j, n)`` and ``(i', j', n')`` + are adjacent triples in the list, and the second is not the last triple in + the list, then ``i+n != i'`` or ``j+n != j'``; in other words, adjacent + triples always describe non-adjacent equal blocks. - .. XXX Explain why a dummy is used! + .. XXX Explain why a dummy is used! - .. doctest:: + .. doctest:: - >>> s = SequenceMatcher(None, "abxcd", "abcd") - >>> s.get_matching_blocks() - [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)] + >>> s = SequenceMatcher(None, "abxcd", "abcd") + >>> s.get_matching_blocks() + [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)] -.. method:: SequenceMatcher.get_opcodes() + .. method:: get_opcodes() - Return list of 5-tuples describing how to turn *a* into *b*. Each tuple is of - the form ``(tag, i1, i2, j1, j2)``. The first tuple has ``i1 == j1 == 0``, and - remaining tuples have *i1* equal to the *i2* from the preceding tuple, and, - likewise, *j1* equal to the previous *j2*. + Return list of 5-tuples describing how to turn *a* into *b*. Each tuple is + of the form ``(tag, i1, i2, j1, j2)``. The first tuple has ``i1 == j1 == + 0``, and remaining tuples have *i1* equal to the *i2* from the preceding + tuple, and, likewise, *j1* equal to the previous *j2*. - The *tag* values are strings, with these meanings: + The *tag* values are strings, with these meanings: - +---------------+---------------------------------------------+ - | Value | Meaning | - +===============+=============================================+ - | ``'replace'`` | ``a[i1:i2]`` should be replaced by | - | | ``b[j1:j2]``. | - +---------------+---------------------------------------------+ - | ``'delete'`` | ``a[i1:i2]`` should be deleted. Note that | - | | ``j1 == j2`` in this case. | - +---------------+---------------------------------------------+ - | ``'insert'`` | ``b[j1:j2]`` should be inserted at | - | | ``a[i1:i1]``. Note that ``i1 == i2`` in | - | | this case. | - +---------------+---------------------------------------------+ - | ``'equal'`` | ``a[i1:i2] == b[j1:j2]`` (the sub-sequences | - | | are equal). | - +---------------+---------------------------------------------+ + +---------------+---------------------------------------------+ + | Value | Meaning | + +===============+=============================================+ + | ``'replace'`` | ``a[i1:i2]`` should be replaced by | + | | ``b[j1:j2]``. | + +---------------+---------------------------------------------+ + | ``'delete'`` | ``a[i1:i2]`` should be deleted. Note that | + | | ``j1 == j2`` in this case. | + +---------------+---------------------------------------------+ + | ``'insert'`` | ``b[j1:j2]`` should be inserted at | + | | ``a[i1:i1]``. Note that ``i1 == i2`` in | + | | this case. | + +---------------+---------------------------------------------+ + | ``'equal'`` | ``a[i1:i2] == b[j1:j2]`` (the sub-sequences | + | | are equal). | + +---------------+---------------------------------------------+ - For example: + For example: - >>> a = "qabxcd" - >>> b = "abycdf" - >>> s = SequenceMatcher(None, a, b) - >>> for tag, i1, i2, j1, j2 in s.get_opcodes(): - ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % - ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))) - delete a[0:1] (q) b[0:0] () - equal a[1:3] (ab) b[0:2] (ab) - replace a[3:4] (x) b[2:3] (y) - equal a[4:6] (cd) b[3:5] (cd) - insert a[6:6] () b[5:6] (f) + >>> a = "qabxcd" + >>> b = "abycdf" + >>> s = SequenceMatcher(None, a, b) + >>> for tag, i1, i2, j1, j2 in s.get_opcodes(): + ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % + ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))) + delete a[0:1] (q) b[0:0] () + equal a[1:3] (ab) b[0:2] (ab) + replace a[3:4] (x) b[2:3] (y) + equal a[4:6] (cd) b[3:5] (cd) + insert a[6:6] () b[5:6] (f) -.. method:: SequenceMatcher.get_grouped_opcodes([n]) + .. method:: get_grouped_opcodes([n]) - Return a :term:`generator` of groups with up to *n* lines of context. + Return a :term:`generator` of groups with up to *n* lines of context. - Starting with the groups returned by :meth:`get_opcodes`, this method splits out - smaller change clusters and eliminates intervening ranges which have no changes. + Starting with the groups returned by :meth:`get_opcodes`, this method + splits out smaller change clusters and eliminates intervening ranges which + have no changes. - The groups are returned in the same format as :meth:`get_opcodes`. + The groups are returned in the same format as :meth:`get_opcodes`. -.. method:: SequenceMatcher.ratio() + .. method:: ratio() - Return a measure of the sequences' similarity as a float in the range [0, 1]. + Return a measure of the sequences' similarity as a float in the range [0, + 1]. - Where T is the total number of elements in both sequences, and M is the number - of matches, this is 2.0\*M / T. Note that this is ``1.0`` if the sequences are - identical, and ``0.0`` if they have nothing in common. + Where T is the total number of elements in both sequences, and M is the + number of matches, this is 2.0\*M / T. Note that this is ``1.0`` if the + sequences are identical, and ``0.0`` if they have nothing in common. - This is expensive to compute if :meth:`get_matching_blocks` or - :meth:`get_opcodes` hasn't already been called, in which case you may want to - try :meth:`quick_ratio` or :meth:`real_quick_ratio` first to get an upper bound. + This is expensive to compute if :meth:`get_matching_blocks` or + :meth:`get_opcodes` hasn't already been called, in which case you may want + to try :meth:`quick_ratio` or :meth:`real_quick_ratio` first to get an + upper bound. -.. method:: SequenceMatcher.quick_ratio() + .. method:: quick_ratio() - Return an upper bound on :meth:`ratio` relatively quickly. + Return an upper bound on :meth:`ratio` relatively quickly. - This isn't defined beyond that it is an upper bound on :meth:`ratio`, and is - faster to compute. + This isn't defined beyond that it is an upper bound on :meth:`ratio`, and + is faster to compute. -.. method:: SequenceMatcher.real_quick_ratio() + .. method:: real_quick_ratio() - Return an upper bound on :meth:`ratio` very quickly. + Return an upper bound on :meth:`ratio` very quickly. - This isn't defined beyond that it is an upper bound on :meth:`ratio`, and is - faster to compute than either :meth:`ratio` or :meth:`quick_ratio`. + This isn't defined beyond that it is an upper bound on :meth:`ratio`, and + is faster to compute than either :meth:`ratio` or :meth:`quick_ratio`. The three methods that return the ratio of matching to total characters can give different results due to differing levels of approximation, although @@ -589,17 +594,17 @@ length 1), and returns true if the character is junk. The default is ``None``, meaning that no character is considered junk. -:class:`Differ` objects are used (deltas generated) via a single method: + :class:`Differ` objects are used (deltas generated) via a single method: -.. method:: Differ.compare(a, b) + .. method:: Differ.compare(a, b) - Compare two sequences of lines, and generate the delta (a sequence of lines). + Compare two sequences of lines, and generate the delta (a sequence of lines). - Each sequence must contain individual single-line strings ending with newlines. - Such sequences can be obtained from the :meth:`readlines` method of file-like - objects. The delta generated also consists of newline-terminated strings, ready - to be printed as-is via the :meth:`writelines` method of a file-like object. + Each sequence must contain individual single-line strings ending with newlines. + Such sequences can be obtained from the :meth:`readlines` method of file-like + objects. The delta generated also consists of newline-terminated strings, ready + to be printed as-is via the :meth:`writelines` method of a file-like object. .. _differ-examples: Modified: python/branches/py3k/Doc/library/doctest.rst ============================================================================== --- python/branches/py3k/Doc/library/doctest.rst (original) +++ python/branches/py3k/Doc/library/doctest.rst Fri Apr 25 03:59:09 2008 @@ -1113,48 +1113,48 @@ names. -:class:`DocTest` defines the following member variables. They are initialized -by the constructor, and should not be modified directly. + :class:`DocTest` defines the following member variables. They are initialized by + the constructor, and should not be modified directly. -.. attribute:: DocTest.examples + .. attribute:: examples - A list of :class:`Example` objects encoding the individual interactive Python - examples that should be run by this test. + A list of :class:`Example` objects encoding the individual interactive Python + examples that should be run by this test. -.. attribute:: DocTest.globs + .. attribute:: globs - The namespace (aka globals) that the examples should be run in. This is a - dictionary mapping names to values. Any changes to the namespace made by the - examples (such as binding new variables) will be reflected in :attr:`globs` - after the test is run. + The namespace (aka globals) that the examples should be run in. This is a + dictionary mapping names to values. Any changes to the namespace made by the + examples (such as binding new variables) will be reflected in :attr:`globs` + after the test is run. -.. attribute:: DocTest.name + .. attribute:: name - A string name identifying the :class:`DocTest`. Typically, this is the name of - the object or file that the test was extracted from. + A string name identifying the :class:`DocTest`. Typically, this is the name + of the object or file that the test was extracted from. -.. attribute:: DocTest.filename + .. attribute:: filename - The name of the file that this :class:`DocTest` was extracted from; or ``None`` - if the filename is unknown, or if the :class:`DocTest` was not extracted from a - file. + The name of the file that this :class:`DocTest` was extracted from; or + ``None`` if the filename is unknown, or if the :class:`DocTest` was not + extracted from a file. -.. attribute:: DocTest.lineno + .. attribute:: lineno - The line number within :attr:`filename` where this :class:`DocTest` begins, or - ``None`` if the line number is unavailable. This line number is zero-based with - respect to the beginning of the file. + The line number within :attr:`filename` where this :class:`DocTest` begins, or + ``None`` if the line number is unavailable. This line number is zero-based + with respect to the beginning of the file. -.. attribute:: DocTest.docstring + .. attribute:: docstring - The string that the test was extracted from, or 'None' if the string is - unavailable, or if the test was not extracted from a string. + The string that the test was extracted from, or 'None' if the string is + unavailable, or if the test was not extracted from a string. .. _doctest-example: @@ -1170,53 +1170,53 @@ of the same names. -:class:`Example` defines the following member variables. They are initialized -by the constructor, and should not be modified directly. + :class:`Example` defines the following member variables. They are initialized by + the constructor, and should not be modified directly. -.. attribute:: Example.source + .. attribute:: source - A string containing the example's source code. This source code consists of a - single Python statement, and always ends with a newline; the constructor adds a - newline when necessary. + A string containing the example's source code. This source code consists of a + single Python statement, and always ends with a newline; the constructor adds + a newline when necessary. -.. attribute:: Example.want + .. attribute:: want - The expected output from running the example's source code (either from stdout, - or a traceback in case of exception). :attr:`want` ends with a newline unless - no output is expected, in which case it's an empty string. The constructor adds - a newline when necessary. + The expected output from running the example's source code (either from + stdout, or a traceback in case of exception). :attr:`want` ends with a + newline unless no output is expected, in which case it's an empty string. The + constructor adds a newline when necessary. -.. attribute:: Example.exc_msg + .. attribute:: exc_msg - The exception message generated by the example, if the example is expected to - generate an exception; or ``None`` if it is not expected to generate an - exception. This exception message is compared against the return value of - :func:`traceback.format_exception_only`. :attr:`exc_msg` ends with a newline - unless it's ``None``. The constructor adds a newline if needed. + The exception message generated by the example, if the example is expected to + generate an exception; or ``None`` if it is not expected to generate an + exception. This exception message is compared against the return value of + :func:`traceback.format_exception_only`. :attr:`exc_msg` ends with a newline + unless it's ``None``. The constructor adds a newline if needed. -.. attribute:: Example.lineno + .. attribute:: lineno - The line number within the string containing this example where the example - begins. This line number is zero-based with respect to the beginning of the - containing string. + The line number within the string containing this example where the example + begins. This line number is zero-based with respect to the beginning of the + containing string. -.. attribute:: Example.indent + .. attribute:: indent - The example's indentation in the containing string, i.e., the number of space - characters that precede the example's first prompt. + The example's indentation in the containing string, i.e., the number of space + characters that precede the example's first prompt. -.. attribute:: Example.options + .. attribute:: options - A dictionary mapping from option flags to ``True`` or ``False``, which is used - to override default options for this example. Any option flags not contained in - this dictionary are left at their default value (as specified by the - :class:`DocTestRunner`'s :attr:`optionflags`). By default, no options are set. + A dictionary mapping from option flags to ``True`` or ``False``, which is used + to override default options for this example. Any option flags not contained + in this dictionary are left at their default value (as specified by the + :class:`DocTestRunner`'s :attr:`optionflags`). By default, no options are set. .. _doctest-doctestfinder: @@ -1246,44 +1246,44 @@ :meth:`DocTestFinder.find` will include tests for objects with empty docstrings. -:class:`DocTestFinder` defines the following method: + :class:`DocTestFinder` defines the following method: -.. method:: DocTestFinder.find(obj[, name][, module][, globs][, extraglobs]) + .. method:: find(obj[, name][, module][, globs][, extraglobs]) - Return a list of the :class:`DocTest`\ s that are defined by *obj*'s docstring, - or by any of its contained objects' docstrings. + Return a list of the :class:`DocTest`\ s that are defined by *obj*'s + docstring, or by any of its contained objects' docstrings. - The optional argument *name* specifies the object's name; this name will be used - to construct names for the returned :class:`DocTest`\ s. If *name* is not - specified, then ``obj.__name__`` is used. + The optional argument *name* specifies the object's name; this name will be + used to construct names for the returned :class:`DocTest`\ s. If *name* is + not specified, then ``obj.__name__`` is used. - The optional parameter *module* is the module that contains the given object. - If the module is not specified or is None, then the test finder will attempt to - automatically determine the correct module. The object's module is used: + The optional parameter *module* is the module that contains the given object. + If the module is not specified or is None, then the test finder will attempt + to automatically determine the correct module. The object's module is used: - * As a default namespace, if *globs* is not specified. + * As a default namespace, if *globs* is not specified. - * To prevent the DocTestFinder from extracting DocTests from objects that are - imported from other modules. (Contained objects with modules other than - *module* are ignored.) + * To prevent the DocTestFinder from extracting DocTests from objects that are + imported from other modules. (Contained objects with modules other than + *module* are ignored.) - * To find the name of the file containing the object. + * To find the name of the file containing the object. - * To help find the line number of the object within its file. + * To help find the line number of the object within its file. - If *module* is ``False``, no attempt to find the module will be made. This is - obscure, of use mostly in testing doctest itself: if *module* is ``False``, or - is ``None`` but cannot be found automatically, then all objects are considered - to belong to the (non-existent) module, so all contained objects will - (recursively) be searched for doctests. + If *module* is ``False``, no attempt to find the module will be made. This is + obscure, of use mostly in testing doctest itself: if *module* is ``False``, or + is ``None`` but cannot be found automatically, then all objects are considered + to belong to the (non-existent) module, so all contained objects will + (recursively) be searched for doctests. - The globals for each :class:`DocTest` is formed by combining *globs* and - *extraglobs* (bindings in *extraglobs* override bindings in *globs*). A new - shallow copy of the globals dictionary is created for each :class:`DocTest`. If - *globs* is not specified, then it defaults to the module's *__dict__*, if - specified, or ``{}`` otherwise. If *extraglobs* is not specified, then it - defaults to ``{}``. + The globals for each :class:`DocTest` is formed by combining *globs* and + *extraglobs* (bindings in *extraglobs* override bindings in *globs*). A new + shallow copy of the globals dictionary is created for each :class:`DocTest`. + If *globs* is not specified, then it defaults to the module's *__dict__*, if + specified, or ``{}`` otherwise. If *extraglobs* is not specified, then it + defaults to ``{}``. .. _doctest-doctestparser: @@ -1298,32 +1298,32 @@ them to create a :class:`DocTest` object. -:class:`DocTestParser` defines the following methods: + :class:`DocTestParser` defines the following methods: -.. method:: DocTestParser.get_doctest(string, globs, name, filename, lineno) + .. method:: get_doctest(string, globs, name, filename, lineno) - Extract all doctest examples from the given string, and collect them into a - :class:`DocTest` object. + Extract all doctest examples from the given string, and collect them into a + :class:`DocTest` object. - *globs*, *name*, *filename*, and *lineno* are attributes for the new - :class:`DocTest` object. See the documentation for :class:`DocTest` for more - information. + *globs*, *name*, *filename*, and *lineno* are attributes for the new + :class:`DocTest` object. See the documentation for :class:`DocTest` for more + information. -.. method:: DocTestParser.get_examples(string[, name]) + .. method:: get_examples(string[, name]) - Extract all doctest examples from the given string, and return them as a list of - :class:`Example` objects. Line numbers are 0-based. The optional argument - *name* is a name identifying this string, and is only used for error messages. + Extract all doctest examples from the given string, and return them as a list + of :class:`Example` objects. Line numbers are 0-based. The optional argument + *name* is a name identifying this string, and is only used for error messages. -.. method:: DocTestParser.parse(string[, name]) + .. method:: parse(string[, name]) - Divide the given string into examples and intervening text, and return them as a - list of alternating :class:`Example`\ s and strings. Line numbers for the - :class:`Example`\ s are 0-based. The optional argument *name* is a name - identifying this string, and is only used for error messages. + Divide the given string into examples and intervening text, and return them as + a list of alternating :class:`Example`\ s and strings. Line numbers for the + :class:`Example`\ s are 0-based. The optional argument *name* is a name + identifying this string, and is only used for error messages. .. _doctest-doctestrunner: @@ -1366,81 +1366,81 @@ For more information, see section :ref:`doctest-options`. -:class:`DocTestParser` defines the following methods: + :class:`DocTestParser` defines the following methods: -.. method:: DocTestRunner.report_start(out, test, example) + .. method:: report_start(out, test, example) - Report that the test runner is about to process the given example. This method - is provided to allow subclasses of :class:`DocTestRunner` to customize their - output; it should not be called directly. + Report that the test runner is about to process the given example. This method + is provided to allow subclasses of :class:`DocTestRunner` to customize their + output; it should not be called directly. - *example* is the example about to be processed. *test* is the test containing - *example*. *out* is the output function that was passed to - :meth:`DocTestRunner.run`. + *example* is the example about to be processed. *test* is the test + *containing example*. *out* is the output function that was passed to + :meth:`DocTestRunner.run`. -.. method:: DocTestRunner.report_success(out, test, example, got) + .. method:: report_success(out, test, example, got) - Report that the given example ran successfully. This method is provided to - allow subclasses of :class:`DocTestRunner` to customize their output; it should - not be called directly. + Report that the given example ran successfully. This method is provided to + allow subclasses of :class:`DocTestRunner` to customize their output; it + should not be called directly. - *example* is the example about to be processed. *got* is the actual output from - the example. *test* is the test containing *example*. *out* is the output - function that was passed to :meth:`DocTestRunner.run`. + *example* is the example about to be processed. *got* is the actual output + from the example. *test* is the test containing *example*. *out* is the + output function that was passed to :meth:`DocTestRunner.run`. -.. method:: DocTestRunner.report_failure(out, test, example, got) + .. method:: report_failure(out, test, example, got) - Report that the given example failed. This method is provided to allow - subclasses of :class:`DocTestRunner` to customize their output; it should not be - called directly. + Report that the given example failed. This method is provided to allow + subclasses of :class:`DocTestRunner` to customize their output; it should not + be called directly. - *example* is the example about to be processed. *got* is the actual output from - the example. *test* is the test containing *example*. *out* is the output - function that was passed to :meth:`DocTestRunner.run`. + *example* is the example about to be processed. *got* is the actual output + from the example. *test* is the test containing *example*. *out* is the + output function that was passed to :meth:`DocTestRunner.run`. -.. method:: DocTestRunner.report_unexpected_exception(out, test, example, exc_info) + .. method:: report_unexpected_exception(out, test, example, exc_info) - Report that the given example raised an unexpected exception. This method is - provided to allow subclasses of :class:`DocTestRunner` to customize their - output; it should not be called directly. + Report that the given example raised an unexpected exception. This method is + provided to allow subclasses of :class:`DocTestRunner` to customize their + output; it should not be called directly. - *example* is the example about to be processed. *exc_info* is a tuple containing - information about the unexpected exception (as returned by - :func:`sys.exc_info`). *test* is the test containing *example*. *out* is the - output function that was passed to :meth:`DocTestRunner.run`. + *example* is the example about to be processed. *exc_info* is a tuple + containing information about the unexpected exception (as returned by + :func:`sys.exc_info`). *test* is the test containing *example*. *out* is the + output function that was passed to :meth:`DocTestRunner.run`. -.. method:: DocTestRunner.run(test[, compileflags][, out][, clear_globs]) + .. method:: run(test[, compileflags][, out][, clear_globs]) - Run the examples in *test* (a :class:`DocTest` object), and display the results - using the writer function *out*. + Run the examples in *test* (a :class:`DocTest` object), and display the + results using the writer function *out*. - The examples are run in the namespace ``test.globs``. If *clear_globs* is true - (the default), then this namespace will be cleared after the test runs, to help - with garbage collection. If you would like to examine the namespace after the - test completes, then use *clear_globs=False*. + The examples are run in the namespace ``test.globs``. If *clear_globs* is + true (the default), then this namespace will be cleared after the test runs, + to help with garbage collection. If you would like to examine the namespace + after the test completes, then use *clear_globs=False*. - *compileflags* gives the set of flags that should be used by the Python compiler - when running the examples. If not specified, then it will default to the set of - future-import flags that apply to *globs*. + *compileflags* gives the set of flags that should be used by the Python + compiler when running the examples. If not specified, then it will default to + the set of future-import flags that apply to *globs*. - The output of each example is checked using the :class:`DocTestRunner`'s output - checker, and the results are formatted by the :meth:`DocTestRunner.report_\*` - methods. + The output of each example is checked using the :class:`DocTestRunner`'s + output checker, and the results are formatted by the + :meth:`DocTestRunner.report_\*` methods. -.. method:: DocTestRunner.summarize([verbose]) + .. method:: summarize([verbose]) - Print a summary of all the test cases that have been run by this DocTestRunner, - and return a :term:`named tuple` ``TestResults(failed, attempted)``. - - The optional *verbose* argument controls how detailed the summary is. If the - verbosity is not specified, then the :class:`DocTestRunner`'s verbosity is used. + Print a summary of all the test cases that have been run by this DocTestRunner, + and return a :term:`named tuple` ``TestResults(failed, attempted)``. + The optional *verbose* argument controls how detailed the summary is. If the + verbosity is not specified, then the :class:`DocTestRunner`'s verbosity is + used. .. _doctest-outputchecker: @@ -1457,22 +1457,22 @@ the differences between two outputs. -:class:`OutputChecker` defines the following methods: + :class:`OutputChecker` defines the following methods: -.. method:: OutputChecker.check_output(want, got, optionflags) + .. method:: check_output(want, got, optionflags) - Return ``True`` iff the actual output from an example (*got*) matches the - expected output (*want*). These strings are always considered to match if they - are identical; but depending on what option flags the test runner is using, - several non-exact match types are also possible. See section - :ref:`doctest-options` for more information about option flags. + Return ``True`` iff the actual output from an example (*got*) matches the + expected output (*want*). These strings are always considered to match if + they are identical; but depending on what option flags the test runner is + using, several non-exact match types are also possible. See section + :ref:`doctest-options` for more information about option flags. -.. method:: OutputChecker.output_difference(example, got, optionflags) + .. method:: output_difference(example, got, optionflags) - Return a string describing the differences between the expected output for a - given example (*example*) and the actual output (*got*). *optionflags* is the - set of option flags used to compare *want* and *got*. + Return a string describing the differences between the expected output for a + given example (*example*) and the actual output (*got*). *optionflags* is the + set of option flags used to compare *want* and *got*. .. _doctest-debugging: Modified: python/branches/py3k/Doc/library/email.charset.rst ============================================================================== --- python/branches/py3k/Doc/library/email.charset.rst (original) +++ python/branches/py3k/Doc/library/email.charset.rst Fri Apr 25 03:59:09 2008 @@ -38,164 +38,168 @@ will not be encoded, but output text will be converted from the ``euc-jp`` character set to the ``iso-2022-jp`` character set. -:class:`Charset` instances have the following data attributes: + :class:`Charset` instances have the following data attributes: -.. data:: input_charset + .. attribute:: input_charset - The initial character set specified. Common aliases are converted to their - *official* email names (e.g. ``latin_1`` is converted to ``iso-8859-1``). - Defaults to 7-bit ``us-ascii``. + The initial character set specified. Common aliases are converted to + their *official* email names (e.g. ``latin_1`` is converted to + ``iso-8859-1``). Defaults to 7-bit ``us-ascii``. -.. data:: header_encoding + .. attribute:: header_encoding - If the character set must be encoded before it can be used in an email header, - this attribute will be set to ``Charset.QP`` (for quoted-printable), - ``Charset.BASE64`` (for base64 encoding), or ``Charset.SHORTEST`` for the - shortest of QP or BASE64 encoding. Otherwise, it will be ``None``. + If the character set must be encoded before it can be used in an email + header, this attribute will be set to ``Charset.QP`` (for + quoted-printable), ``Charset.BASE64`` (for base64 encoding), or + ``Charset.SHORTEST`` for the shortest of QP or BASE64 encoding. Otherwise, + it will be ``None``. -.. data:: body_encoding + .. attribute:: body_encoding - Same as *header_encoding*, but describes the encoding for the mail message's - body, which indeed may be different than the header encoding. - ``Charset.SHORTEST`` is not allowed for *body_encoding*. + Same as *header_encoding*, but describes the encoding for the mail + message's body, which indeed may be different than the header encoding. + ``Charset.SHORTEST`` is not allowed for *body_encoding*. -.. data:: output_charset + .. attribute:: output_charset - Some character sets must be converted before they can be used in email headers - or bodies. If the *input_charset* is one of them, this attribute will contain - the name of the character set output will be converted to. Otherwise, it will - be ``None``. + Some character sets must be converted before they can be used in email headers + or bodies. If the *input_charset* is one of them, this attribute will + contain the name of the character set output will be converted to. Otherwise, it will + be ``None``. -.. data:: input_codec + .. attribute:: input_codec - The name of the Python codec used to convert the *input_charset* to Unicode. If - no conversion codec is necessary, this attribute will be ``None``. + The name of the Python codec used to convert the *input_charset* to + Unicode. If no conversion codec is necessary, this attribute will be + ``None``. -.. data:: output_codec + .. attribute:: output_codec - The name of the Python codec used to convert Unicode to the *output_charset*. - If no conversion codec is necessary, this attribute will have the same value as - the *input_codec*. + The name of the Python codec used to convert Unicode to the + *output_charset*. If no conversion codec is necessary, this attribute + will have the same value as the *input_codec*. -:class:`Charset` instances also have the following methods: + :class:`Charset` instances also have the following methods: -.. method:: Charset.get_body_encoding() + .. method:: get_body_encoding() - Return the content transfer encoding used for body encoding. + Return the content transfer encoding used for body encoding. - This is either the string ``quoted-printable`` or ``base64`` depending on the - encoding used, or it is a function, in which case you should call the function - with a single argument, the Message object being encoded. The function should - then set the :mailheader:`Content-Transfer-Encoding` header itself to whatever - is appropriate. + This is either the string ``quoted-printable`` or ``base64`` depending on + the encoding used, or it is a function, in which case you should call the + function with a single argument, the Message object being encoded. The + function should then set the :mailheader:`Content-Transfer-Encoding` + header itself to whatever is appropriate. - Returns the string ``quoted-printable`` if *body_encoding* is ``QP``, returns - the string ``base64`` if *body_encoding* is ``BASE64``, and returns the string - ``7bit`` otherwise. + Returns the string ``quoted-printable`` if *body_encoding* is ``QP``, + returns the string ``base64`` if *body_encoding* is ``BASE64``, and + returns the string ``7bit`` otherwise. -.. method:: Charset.convert(s) + .. method:: convert(s) - Convert the string *s* from the *input_codec* to the *output_codec*. + Convert the string *s* from the *input_codec* to the *output_codec*. -.. method:: Charset.to_splittable(s) + .. method:: to_splittable(s) - Convert a possibly multibyte string to a safely splittable format. *s* is the - string to split. + Convert a possibly multibyte string to a safely splittable format. *s* is + the string to split. - Uses the *input_codec* to try and convert the string to Unicode, so it can be - safely split on character boundaries (even for multibyte characters). + Uses the *input_codec* to try and convert the string to Unicode, so it can + be safely split on character boundaries (even for multibyte characters). - Returns the string as-is if it isn't known how to convert *s* to Unicode with - the *input_charset*. + Returns the string as-is if it isn't known how to convert *s* to Unicode + with the *input_charset*. - Characters that could not be converted to Unicode will be replaced with the - Unicode replacement character ``'U+FFFD'``. + Characters that could not be converted to Unicode will be replaced with + the Unicode replacement character ``'U+FFFD'``. -.. method:: Charset.from_splittable(ustr[, to_output]) + .. method:: from_splittable(ustr[, to_output]) - Convert a splittable string back into an encoded string. *ustr* is a Unicode - string to "unsplit". + Convert a splittable string back into an encoded string. *ustr* is a + Unicode string to "unsplit". - This method uses the proper codec to try and convert the string from Unicode - back into an encoded format. Return the string as-is if it is not Unicode, or - if it could not be converted from Unicode. + This method uses the proper codec to try and convert the string from + Unicode back into an encoded format. Return the string as-is if it is not + Unicode, or if it could not be converted from Unicode. - Characters that could not be converted from Unicode will be replaced with an - appropriate character (usually ``'?'``). + Characters that could not be converted from Unicode will be replaced with + an appropriate character (usually ``'?'``). - If *to_output* is ``True`` (the default), uses *output_codec* to convert to an - encoded format. If *to_output* is ``False``, it uses *input_codec*. + If *to_output* is ``True`` (the default), uses *output_codec* to convert + to an encoded format. If *to_output* is ``False``, it uses *input_codec*. -.. method:: Charset.get_output_charset() + .. method:: get_output_charset() - Return the output character set. + Return the output character set. - This is the *output_charset* attribute if that is not ``None``, otherwise it is - *input_charset*. + This is the *output_charset* attribute if that is not ``None``, otherwise + it is *input_charset*. -.. method:: Charset.encoded_header_len() + .. method:: encoded_header_len() - Return the length of the encoded header string, properly calculating for - quoted-printable or base64 encoding. + Return the length of the encoded header string, properly calculating for + quoted-printable or base64 encoding. -.. method:: Charset.header_encode(s[, convert]) + .. method:: header_encode(s[, convert]) - Header-encode the string *s*. + Header-encode the string *s*. - If *convert* is ``True``, the string will be converted from the input charset to - the output charset automatically. This is not useful for multibyte character - sets, which have line length issues (multibyte characters must be split on a - character, not a byte boundary); use the higher-level :class:`Header` class to - deal with these issues (see :mod:`email.header`). *convert* defaults to - ``False``. + If *convert* is ``True``, the string will be converted from the input + charset to the output charset automatically. This is not useful for + multibyte character sets, which have line length issues (multibyte + characters must be split on a character, not a byte boundary); use the + higher-level :class:`Header` class to deal with these issues (see + :mod:`email.header`). *convert* defaults to ``False``. - The type of encoding (base64 or quoted-printable) will be based on the - *header_encoding* attribute. + The type of encoding (base64 or quoted-printable) will be based on the + *header_encoding* attribute. -.. method:: Charset.body_encode(s[, convert]) + .. method:: body_encode(s[, convert]) - Body-encode the string *s*. + Body-encode the string *s*. - If *convert* is ``True`` (the default), the string will be converted from the - input charset to output charset automatically. Unlike :meth:`header_encode`, - there are no issues with byte boundaries and multibyte charsets in email bodies, - so this is usually pretty safe. + If *convert* is ``True`` (the default), the string will be converted from + the input charset to output charset automatically. Unlike + :meth:`header_encode`, there are no issues with byte boundaries and + multibyte charsets in email bodies, so this is usually pretty safe. - The type of encoding (base64 or quoted-printable) will be based on the - *body_encoding* attribute. + The type of encoding (base64 or quoted-printable) will be based on the + *body_encoding* attribute. -The :class:`Charset` class also provides a number of methods to support standard -operations and built-in functions. + The :class:`Charset` class also provides a number of methods to support + standard operations and built-in functions. -.. method:: Charset.__str__() + .. method:: __str__() - Returns *input_charset* as a string coerced to lower case. :meth:`__repr__` is - an alias for :meth:`__str__`. + Returns *input_charset* as a string coerced to lower + case. :meth:`__repr__` is an alias for :meth:`__str__`. -.. method:: Charset.__eq__(other) + .. method:: __eq__(other) - This method allows you to compare two :class:`Charset` instances for equality. + This method allows you to compare two :class:`Charset` instances for + equality. -.. method:: Header.__ne__(other) + .. method:: __ne__(other) - This method allows you to compare two :class:`Charset` instances for inequality. + This method allows you to compare two :class:`Charset` instances for + inequality. The :mod:`email.charset` module also provides the following functions for adding new entries to the global character set, alias, and codec registries: Modified: python/branches/py3k/Doc/library/email.generator.rst ============================================================================== --- python/branches/py3k/Doc/library/email.generator.rst (original) +++ python/branches/py3k/Doc/library/email.generator.rst Fri Apr 25 03:59:09 2008 @@ -44,35 +44,34 @@ :mod:`email.header.Header` class. Set to zero to disable header wrapping. The default is 78, as recommended (but not required) by :rfc:`2822`. -The other public :class:`Generator` methods are: + The other public :class:`Generator` methods are: -.. method:: Generator.flatten(msg[, unixfrom]) + .. method:: flatten(msg[, unixfrom]) - Print the textual representation of the message object structure rooted at *msg* - to the output file specified when the :class:`Generator` instance was created. - Subparts are visited depth-first and the resulting text will be properly MIME - encoded. + Print the textual representation of the message object structure rooted at + *msg* to the output file specified when the :class:`Generator` instance + was created. Subparts are visited depth-first and the resulting text will + be properly MIME encoded. - Optional *unixfrom* is a flag that forces the printing of the envelope header - delimiter before the first :rfc:`2822` header of the root message object. If - the root object has no envelope header, a standard one is crafted. By default, - this is set to ``False`` to inhibit the printing of the envelope delimiter. + Optional *unixfrom* is a flag that forces the printing of the envelope + header delimiter before the first :rfc:`2822` header of the root message + object. If the root object has no envelope header, a standard one is + crafted. By default, this is set to ``False`` to inhibit the printing of + the envelope delimiter. - Note that for subparts, no envelope header is ever printed. + Note that for subparts, no envelope header is ever printed. + .. method:: clone(fp) -.. method:: Generator.clone(fp) + Return an independent clone of this :class:`Generator` instance with the + exact same options. - Return an independent clone of this :class:`Generator` instance with the exact - same options. + .. method:: write(s) - -.. method:: Generator.write(s) - - Write the string *s* to the underlying file object, i.e. *outfp* passed to - :class:`Generator`'s constructor. This provides just enough file-like API for - :class:`Generator` instances to be used in the :func:`print` function. + Write the string *s* to the underlying file object, i.e. *outfp* passed to + :class:`Generator`'s constructor. This provides just enough file-like API + for :class:`Generator` instances to be used in the :func:`print` function. As a convenience, see the methods :meth:`Message.as_string` and ``str(aMessage)``, a.k.a. :meth:`Message.__str__`, which simplify the generation Modified: python/branches/py3k/Doc/library/email.header.rst ============================================================================== --- python/branches/py3k/Doc/library/email.header.rst (original) +++ python/branches/py3k/Doc/library/email.header.rst Fri Apr 25 03:59:09 2008 @@ -74,65 +74,66 @@ and is usually either a space or a hard tab character. This character will be prepended to continuation lines. -Optional *errors* is passed straight through to the :meth:`append` method. + Optional *errors* is passed straight through to the :meth:`append` method. -.. method:: Header.append(s[, charset[, errors]]) + .. method:: append(s[, charset[, errors]]) - Append the string *s* to the MIME header. + Append the string *s* to the MIME header. - Optional *charset*, if given, should be a :class:`Charset` instance (see - :mod:`email.charset`) or the name of a character set, which will be converted to - a :class:`Charset` instance. A value of ``None`` (the default) means that the - *charset* given in the constructor is used. + Optional *charset*, if given, should be a :class:`Charset` instance (see + :mod:`email.charset`) or the name of a character set, which will be + converted to a :class:`Charset` instance. A value of ``None`` (the + default) means that the *charset* given in the constructor is used. - *s* may be an instance of :class:`bytes` or :class:`str`. If it is an instance - of :class:`bytes`, then *charset* is the encoding of that byte string, and a - :exc:`UnicodeError` will be raised if the string cannot be decoded with that - character set. + *s* may be an instance of :class:`bytes` or :class:`str`. If it is an + instance of :class:`bytes`, then *charset* is the encoding of that byte + string, and a :exc:`UnicodeError` will be raised if the string cannot be + decoded with that character set. - If *s* is an instance of :class:`str`, then *charset* is a hint specifying the - character set of the characters in the string. In this case, when producing an - :rfc:`2822`\ -compliant header using :rfc:`2047` rules, the Unicode string will - be encoded using the following charsets in order: ``us-ascii``, the *charset* - hint, ``utf-8``. The first character set to not provoke a :exc:`UnicodeError` - is used. + If *s* is an instance of :class:`str`, then *charset* is a hint specifying + the character set of the characters in the string. In this case, when + producing an :rfc:`2822`\ -compliant header using :rfc:`2047` rules, the + Unicode string will be encoded using the following charsets in order: + ``us-ascii``, the *charset* hint, ``utf-8``. The first character set to + not provoke a :exc:`UnicodeError` is used. - Optional *errors* is passed through to any :func:`encode` or - :func:`ustr.encode` call, and defaults to "strict". + Optional *errors* is passed through to any :func:`encode` or + :func:`ustr.encode` call, and defaults to "strict". -.. method:: Header.encode([splitchars]) + .. method:: encode([splitchars]) - Encode a message header into an RFC-compliant format, possibly wrapping long - lines and encapsulating non-ASCII parts in base64 or quoted-printable encodings. - Optional *splitchars* is a string containing characters to split long ASCII - lines on, in rough support of :rfc:`2822`'s *highest level syntactic breaks*. - This doesn't affect :rfc:`2047` encoded lines. + Encode a message header into an RFC-compliant format, possibly wrapping + long lines and encapsulating non-ASCII parts in base64 or quoted-printable + encodings. Optional *splitchars* is a string containing characters to + split long ASCII lines on, in rough support of :rfc:`2822`'s *highest + level syntactic breaks*. This doesn't affect :rfc:`2047` encoded lines. -The :class:`Header` class also provides a number of methods to support standard -operators and built-in functions. + The :class:`Header` class also provides a number of methods to support + standard operators and built-in functions. -.. method:: Header.__str__() + .. method:: __str__() - A synonym for :meth:`Header.encode`. Useful for ``str(aHeader)``. + A synonym for :meth:`Header.encode`. Useful for ``str(aHeader)``. -.. method:: Header.__unicode__() + .. method:: __unicode__() - A helper for :class:`str`'s :func:`encode` method. Returns the header as a - Unicode string. + A helper for :class:`str`'s :func:`encode` method. Returns the header as + a Unicode string. + .. method:: __eq__(other) -.. method:: Header.__eq__(other) + This method allows you to compare two :class:`Header` instances for + equality. - This method allows you to compare two :class:`Header` instances for equality. + .. method:: __ne__(other) -.. method:: Header.__ne__(other) - - This method allows you to compare two :class:`Header` instances for inequality. + This method allows you to compare two :class:`Header` instances for + inequality. The :mod:`email.header` module also provides the following convenient functions. Modified: python/branches/py3k/Doc/library/email.message.rst ============================================================================== --- python/branches/py3k/Doc/library/email.message.rst (original) +++ python/branches/py3k/Doc/library/email.message.rst Fri Apr 25 03:59:09 2008 @@ -36,472 +36,489 @@ The constructor takes no arguments. -.. method:: Message.as_string([unixfrom]) + .. method:: as_string([unixfrom]) - Return the entire message flattened as a string. When optional *unixfrom* is - ``True``, the envelope header is included in the returned string. *unixfrom* - defaults to ``False``. + Return the entire message flattened as a string. When optional *unixfrom* + is ``True``, the envelope header is included in the returned string. + *unixfrom* defaults to ``False``. - Note that this method is provided as a convenience and may not always format the - message the way you want. For example, by default it mangles lines that begin - with ``From``. For more flexibility, instantiate a :class:`Generator` instance - and use its :meth:`flatten` method directly. For example:: + Note that this method is provided as a convenience and may not always + format the message the way you want. For example, by default it mangles + lines that begin with ``From``. For more flexibility, instantiate a + :class:`Generator` instance and use its :meth:`flatten` method directly. + For example:: - from cStringIO import StringIO - from email.generator import Generator - fp = StringIO() - g = Generator(fp, mangle_from_=False, maxheaderlen=60) - g.flatten(msg) - text = fp.getvalue() + from cStringIO import StringIO + from email.generator import Generator + fp = StringIO() + g = Generator(fp, mangle_from_=False, maxheaderlen=60) + g.flatten(msg) + text = fp.getvalue() -.. method:: Message.__str__() + .. method:: __str__() - Equivalent to ``as_string(unixfrom=True)``. + Equivalent to ``as_string(unixfrom=True)``. -.. method:: Message.is_multipart() + .. method:: is_multipart() - Return ``True`` if the message's payload is a list of sub-\ :class:`Message` - objects, otherwise return ``False``. When :meth:`is_multipart` returns False, - the payload should be a string object. + Return ``True`` if the message's payload is a list of sub-\ + :class:`Message` objects, otherwise return ``False``. When + :meth:`is_multipart` returns False, the payload should be a string object. -.. method:: Message.set_unixfrom(unixfrom) + .. method:: set_unixfrom(unixfrom) - Set the message's envelope header to *unixfrom*, which should be a string. + Set the message's envelope header to *unixfrom*, which should be a string. -.. method:: Message.get_unixfrom() + .. method:: get_unixfrom() - Return the message's envelope header. Defaults to ``None`` if the envelope - header was never set. + Return the message's envelope header. Defaults to ``None`` if the + envelope header was never set. -.. method:: Message.attach(payload) + .. method:: attach(payload) - Add the given *payload* to the current payload, which must be ``None`` or a list - of :class:`Message` objects before the call. After the call, the payload will - always be a list of :class:`Message` objects. If you want to set the payload to - a scalar object (e.g. a string), use :meth:`set_payload` instead. + Add the given *payload* to the current payload, which must be ``None`` or + a list of :class:`Message` objects before the call. After the call, the + payload will always be a list of :class:`Message` objects. If you want to + set the payload to a scalar object (e.g. a string), use + :meth:`set_payload` instead. -.. method:: Message.get_payload([i[, decode]]) + .. method:: get_payload([i[, decode]]) - Return a reference the current payload, which will be a list of :class:`Message` - objects when :meth:`is_multipart` is ``True``, or a string when - :meth:`is_multipart` is ``False``. If the payload is a list and you mutate the - list object, you modify the message's payload in place. + Return a reference the current payload, which will be a list of + :class:`Message` objects when :meth:`is_multipart` is ``True``, or a + string when :meth:`is_multipart` is ``False``. If the payload is a list + and you mutate the list object, you modify the message's payload in place. - With optional argument *i*, :meth:`get_payload` will return the *i*-th element - of the payload, counting from zero, if :meth:`is_multipart` is ``True``. An - :exc:`IndexError` will be raised if *i* is less than 0 or greater than or equal - to the number of items in the payload. If the payload is a string (i.e. - :meth:`is_multipart` is ``False``) and *i* is given, a :exc:`TypeError` is - raised. + With optional argument *i*, :meth:`get_payload` will return the *i*-th + element of the payload, counting from zero, if :meth:`is_multipart` is + ``True``. An :exc:`IndexError` will be raised if *i* is less than 0 or + greater than or equal to the number of items in the payload. If the + payload is a string (i.e. :meth:`is_multipart` is ``False``) and *i* is + given, a :exc:`TypeError` is raised. - Optional *decode* is a flag indicating whether the payload should be decoded or - not, according to the :mailheader:`Content-Transfer-Encoding` header. When - ``True`` and the message is not a multipart, the payload will be decoded if this - header's value is ``quoted-printable`` or ``base64``. If some other encoding is - used, or :mailheader:`Content-Transfer-Encoding` header is missing, or if the - payload has bogus base64 data, the payload is returned as-is (undecoded). If - the message is a multipart and the *decode* flag is ``True``, then ``None`` is - returned. The default for *decode* is ``False``. + Optional *decode* is a flag indicating whether the payload should be + decoded or not, according to the :mailheader:`Content-Transfer-Encoding` + header. When ``True`` and the message is not a multipart, the payload will + be decoded if this header's value is ``quoted-printable`` or ``base64``. + If some other encoding is used, or :mailheader:`Content-Transfer-Encoding` + header is missing, or if the payload has bogus base64 data, the payload is + returned as-is (undecoded). If the message is a multipart and the + *decode* flag is ``True``, then ``None`` is returned. The default for + *decode* is ``False``. -.. method:: Message.set_payload(payload[, charset]) + .. method:: set_payload(payload[, charset]) - Set the entire message object's payload to *payload*. It is the client's - responsibility to ensure the payload invariants. Optional *charset* sets the - message's default character set; see :meth:`set_charset` for details. + Set the entire message object's payload to *payload*. It is the client's + responsibility to ensure the payload invariants. Optional *charset* sets + the message's default character set; see :meth:`set_charset` for details. + .. method:: set_charset(charset) -.. method:: Message.set_charset(charset) + Set the character set of the payload to *charset*, which can either be a + :class:`Charset` instance (see :mod:`email.charset`), a string naming a + character set, or ``None``. If it is a string, it will be converted to a + :class:`Charset` instance. If *charset* is ``None``, the ``charset`` + parameter will be removed from the :mailheader:`Content-Type` + header. Anything else will generate a :exc:`TypeError`. - Set the character set of the payload to *charset*, which can either be a - :class:`Charset` instance (see :mod:`email.charset`), a string naming a - character set, or ``None``. If it is a string, it will be converted to a - :class:`Charset` instance. If *charset* is ``None``, the ``charset`` parameter - will be removed from the :mailheader:`Content-Type` header. Anything else will - generate a :exc:`TypeError`. + The message will be assumed to be of type :mimetype:`text/\*` encoded with + *charset.input_charset*. It will be converted to *charset.output_charset* + and encoded properly, if needed, when generating the plain text + representation of the message. MIME headers (:mailheader:`MIME-Version`, + :mailheader:`Content-Type`, :mailheader:`Content-Transfer-Encoding`) will + be added as needed. - The message will be assumed to be of type :mimetype:`text/\*` encoded with - *charset.input_charset*. It will be converted to *charset.output_charset* and - encoded properly, if needed, when generating the plain text representation of - the message. MIME headers (:mailheader:`MIME-Version`, - :mailheader:`Content-Type`, :mailheader:`Content-Transfer-Encoding`) will be - added as needed. + .. method:: get_charset() + Return the :class:`Charset` instance associated with the message's + payload. -.. method:: Message.get_charset() + The following methods implement a mapping-like interface for accessing the + message's :rfc:`2822` headers. Note that there are some semantic differences + between these methods and a normal mapping (i.e. dictionary) interface. For + example, in a dictionary there are no duplicate keys, but here there may be + duplicate message headers. Also, in dictionaries there is no guaranteed + order to the keys returned by :meth:`keys`, but in a :class:`Message` object, + headers are always returned in the order they appeared in the original + message, or were added to the message later. Any header deleted and then + re-added are always appended to the end of the header list. - Return the :class:`Charset` instance associated with the message's payload. + These semantic differences are intentional and are biased toward maximal + convenience. -The following methods implement a mapping-like interface for accessing the -message's :rfc:`2822` headers. Note that there are some semantic differences -between these methods and a normal mapping (i.e. dictionary) interface. For -example, in a dictionary there are no duplicate keys, but here there may be -duplicate message headers. Also, in dictionaries there is no guaranteed order -to the keys returned by :meth:`keys`, but in a :class:`Message` object, headers -are always returned in the order they appeared in the original message, or were -added to the message later. Any header deleted and then re-added are always -appended to the end of the header list. + Note that in all cases, any envelope header present in the message is not + included in the mapping interface. -These semantic differences are intentional and are biased toward maximal -convenience. -Note that in all cases, any envelope header present in the message is not -included in the mapping interface. + .. method:: __len__() + Return the total number of headers, including duplicates. -.. method:: Message.__len__() - Return the total number of headers, including duplicates. + .. method:: __contains__(name) + Return true if the message object has a field named *name*. Matching is + done case-insensitively and *name* should not include the trailing colon. + Used for the ``in`` operator, e.g.:: -.. method:: Message.__contains__(name) + if 'message-id' in myMessage: + print('Message-ID:', myMessage['message-id']) - Return true if the message object has a field named *name*. Matching is done - case-insensitively and *name* should not include the trailing colon. Used for - the ``in`` operator, e.g.:: - if 'message-id' in myMessage: - print('Message-ID:', myMessage['message-id']) + .. method:: __getitem__(name) + Return the value of the named header field. *name* should not include the + colon field separator. If the header is missing, ``None`` is returned; a + :exc:`KeyError` is never raised. -.. method:: Message.__getitem__(name) + Note that if the named field appears more than once in the message's + headers, exactly which of those field values will be returned is + undefined. Use the :meth:`get_all` method to get the values of all the + extant named headers. - Return the value of the named header field. *name* should not include the colon - field separator. If the header is missing, ``None`` is returned; a - :exc:`KeyError` is never raised. - Note that if the named field appears more than once in the message's headers, - exactly which of those field values will be returned is undefined. Use the - :meth:`get_all` method to get the values of all the extant named headers. + .. method:: __setitem__(name, val) + Add a header to the message with field name *name* and value *val*. The + field is appended to the end of the message's existing fields. -.. method:: Message.__setitem__(name, val) + Note that this does *not* overwrite or delete any existing header with the same + name. If you want to ensure that the new header is the only one present in the + message with field name *name*, delete the field first, e.g.:: - Add a header to the message with field name *name* and value *val*. The field - is appended to the end of the message's existing fields. + del msg['subject'] + msg['subject'] = 'Python roolz!' - Note that this does *not* overwrite or delete any existing header with the same - name. If you want to ensure that the new header is the only one present in the - message with field name *name*, delete the field first, e.g.:: - del msg['subject'] - msg['subject'] = 'Python roolz!' + .. method:: __delitem__(name) + Delete all occurrences of the field with name *name* from the message's + headers. No exception is raised if the named field isn't present in the headers. -.. method:: Message.__delitem__(name) - Delete all occurrences of the field with name *name* from the message's headers. - No exception is raised if the named field isn't present in the headers. + .. method:: Message.__contains__(name) + Return true if the message contains a header field named *name*, otherwise + return false. -.. method:: Message.__contains__(name) - Return true if the message contains a header field named *name*, otherwise - return false. + .. method:: keys() + Return a list of all the message's header field names. -.. method:: Message.keys() - Return a list of all the message's header field names. + .. method:: values() + Return a list of all the message's field values. -.. method:: Message.values() - Return a list of all the message's field values. + .. method:: items() + Return a list of 2-tuples containing all the message's field headers and + values. -.. method:: Message.items() - Return a list of 2-tuples containing all the message's field headers and values. + .. method:: get(name[, failobj]) + Return the value of the named header field. This is identical to + :meth:`__getitem__` except that optional *failobj* is returned if the + named header is missing (defaults to ``None``). -.. method:: Message.get(name[, failobj]) + Here are some additional useful methods: - Return the value of the named header field. This is identical to - :meth:`__getitem__` except that optional *failobj* is returned if the named - header is missing (defaults to ``None``). -Here are some additional useful methods: + .. method:: get_all(name[, failobj]) + Return a list of all the values for the field named *name*. If there are + no such named headers in the message, *failobj* is returned (defaults to + ``None``). -.. method:: Message.get_all(name[, failobj]) - Return a list of all the values for the field named *name*. If there are no such - named headers in the message, *failobj* is returned (defaults to ``None``). + .. method:: add_header(_name, _value, **_params) + Extended header setting. This method is similar to :meth:`__setitem__` + except that additional header parameters can be provided as keyword + arguments. *_name* is the header field to add and *_value* is the + *primary* value for the header. -.. method:: Message.add_header(_name, _value, **_params) + For each item in the keyword argument dictionary *_params*, the key is + taken as the parameter name, with underscores converted to dashes (since + dashes are illegal in Python identifiers). Normally, the parameter will + be added as ``key="value"`` unless the value is ``None``, in which case + only the key will be added. - Extended header setting. This method is similar to :meth:`__setitem__` except - that additional header parameters can be provided as keyword arguments. *_name* - is the header field to add and *_value* is the *primary* value for the header. + Here's an example:: - For each item in the keyword argument dictionary *_params*, the key is taken as - the parameter name, with underscores converted to dashes (since dashes are - illegal in Python identifiers). Normally, the parameter will be added as - ``key="value"`` unless the value is ``None``, in which case only the key will be - added. + msg.add_header('Content-Disposition', 'attachment', filename='bud.gif') - Here's an example:: + This will add a header that looks like :: - msg.add_header('Content-Disposition', 'attachment', filename='bud.gif') + Content-Disposition: attachment; filename="bud.gif" - This will add a header that looks like :: - Content-Disposition: attachment; filename="bud.gif" + .. method:: replace_header(_name, _value) + Replace a header. Replace the first header found in the message that + matches *_name*, retaining header order and field name case. If no + matching header was found, a :exc:`KeyError` is raised. -.. method:: Message.replace_header(_name, _value) - Replace a header. Replace the first header found in the message that matches - *_name*, retaining header order and field name case. If no matching header was - found, a :exc:`KeyError` is raised. + .. method:: get_content_type() + Return the message's content type. The returned string is coerced to + lower case of the form :mimetype:`maintype/subtype`. If there was no + :mailheader:`Content-Type` header in the message the default type as given + by :meth:`get_default_type` will be returned. Since according to + :rfc:`2045`, messages always have a default type, :meth:`get_content_type` + will always return a value. -.. method:: Message.get_content_type() + :rfc:`2045` defines a message's default type to be :mimetype:`text/plain` + unless it appears inside a :mimetype:`multipart/digest` container, in + which case it would be :mimetype:`message/rfc822`. If the + :mailheader:`Content-Type` header has an invalid type specification, + :rfc:`2045` mandates that the default type be :mimetype:`text/plain`. - Return the message's content type. The returned string is coerced to lower case - of the form :mimetype:`maintype/subtype`. If there was no - :mailheader:`Content-Type` header in the message the default type as given by - :meth:`get_default_type` will be returned. Since according to :rfc:`2045`, - messages always have a default type, :meth:`get_content_type` will always return - a value. - :rfc:`2045` defines a message's default type to be :mimetype:`text/plain` unless - it appears inside a :mimetype:`multipart/digest` container, in which case it - would be :mimetype:`message/rfc822`. If the :mailheader:`Content-Type` header - has an invalid type specification, :rfc:`2045` mandates that the default type be - :mimetype:`text/plain`. + .. method:: get_content_maintype() + Return the message's main content type. This is the :mimetype:`maintype` + part of the string returned by :meth:`get_content_type`. -.. method:: Message.get_content_maintype() - Return the message's main content type. This is the :mimetype:`maintype` part - of the string returned by :meth:`get_content_type`. + .. method:: get_content_subtype() + Return the message's sub-content type. This is the :mimetype:`subtype` + part of the string returned by :meth:`get_content_type`. -.. method:: Message.get_content_subtype() - Return the message's sub-content type. This is the :mimetype:`subtype` part of - the string returned by :meth:`get_content_type`. + .. method:: get_default_type() + Return the default content type. Most messages have a default content + type of :mimetype:`text/plain`, except for messages that are subparts of + :mimetype:`multipart/digest` containers. Such subparts have a default + content type of :mimetype:`message/rfc822`. -.. method:: Message.get_default_type() - Return the default content type. Most messages have a default content type of - :mimetype:`text/plain`, except for messages that are subparts of - :mimetype:`multipart/digest` containers. Such subparts have a default content - type of :mimetype:`message/rfc822`. + .. method:: set_default_type(ctype) + Set the default content type. *ctype* should either be + :mimetype:`text/plain` or :mimetype:`message/rfc822`, although this is not + enforced. The default content type is not stored in the + :mailheader:`Content-Type` header. -.. method:: Message.set_default_type(ctype) - Set the default content type. *ctype* should either be :mimetype:`text/plain` - or :mimetype:`message/rfc822`, although this is not enforced. The default - content type is not stored in the :mailheader:`Content-Type` header. + .. method:: get_params([failobj[, header[, unquote]]]) + Return the message's :mailheader:`Content-Type` parameters, as a list. + The elements of the returned list are 2-tuples of key/value pairs, as + split on the ``'='`` sign. The left hand side of the ``'='`` is the key, + while the right hand side is the value. If there is no ``'='`` sign in + the parameter the value is the empty string, otherwise the value is as + described in :meth:`get_param` and is unquoted if optional *unquote* is + ``True`` (the default). -.. method:: Message.get_params([failobj[, header[, unquote]]]) + Optional *failobj* is the object to return if there is no + :mailheader:`Content-Type` header. Optional *header* is the header to + search instead of :mailheader:`Content-Type`. - Return the message's :mailheader:`Content-Type` parameters, as a list. The - elements of the returned list are 2-tuples of key/value pairs, as split on the - ``'='`` sign. The left hand side of the ``'='`` is the key, while the right - hand side is the value. If there is no ``'='`` sign in the parameter the value - is the empty string, otherwise the value is as described in :meth:`get_param` - and is unquoted if optional *unquote* is ``True`` (the default). - Optional *failobj* is the object to return if there is no - :mailheader:`Content-Type` header. Optional *header* is the header to search - instead of :mailheader:`Content-Type`. + .. method:: get_param(param[, failobj[, header[, unquote]]]) + Return the value of the :mailheader:`Content-Type` header's parameter + *param* as a string. If the message has no :mailheader:`Content-Type` + header or if there is no such parameter, then *failobj* is returned + (defaults to ``None``). -.. method:: Message.get_param(param[, failobj[, header[, unquote]]]) + Optional *header* if given, specifies the message header to use instead of + :mailheader:`Content-Type`. - Return the value of the :mailheader:`Content-Type` header's parameter *param* as - a string. If the message has no :mailheader:`Content-Type` header or if there - is no such parameter, then *failobj* is returned (defaults to ``None``). + Parameter keys are always compared case insensitively. The return value + can either be a string, or a 3-tuple if the parameter was :rfc:`2231` + encoded. When it's a 3-tuple, the elements of the value are of the form + ``(CHARSET, LANGUAGE, VALUE)``. Note that both ``CHARSET`` and + ``LANGUAGE`` can be ``None``, in which case you should consider ``VALUE`` + to be encoded in the ``us-ascii`` charset. You can usually ignore + ``LANGUAGE``. - Optional *header* if given, specifies the message header to use instead of - :mailheader:`Content-Type`. + If your application doesn't care whether the parameter was encoded as in + :rfc:`2231`, you can collapse the parameter value by calling + :func:`email.Utils.collapse_rfc2231_value`, passing in the return value + from :meth:`get_param`. This will return a suitably decoded Unicode + string whn the value is a tuple, or the original string unquoted if it + isn't. For example:: - Parameter keys are always compared case insensitively. The return value can - either be a string, or a 3-tuple if the parameter was :rfc:`2231` encoded. When - it's a 3-tuple, the elements of the value are of the form ``(CHARSET, LANGUAGE, - VALUE)``. Note that both ``CHARSET`` and ``LANGUAGE`` can be ``None``, in which - case you should consider ``VALUE`` to be encoded in the ``us-ascii`` charset. - You can usually ignore ``LANGUAGE``. + rawparam = msg.get_param('foo') + param = email.Utils.collapse_rfc2231_value(rawparam) - If your application doesn't care whether the parameter was encoded as in - :rfc:`2231`, you can collapse the parameter value by calling - :func:`email.Utils.collapse_rfc2231_value`, passing in the return value from - :meth:`get_param`. This will return a suitably decoded Unicode string whn the - value is a tuple, or the original string unquoted if it isn't. For example:: + In any case, the parameter value (either the returned string, or the + ``VALUE`` item in the 3-tuple) is always unquoted, unless *unquote* is set + to ``False``. - rawparam = msg.get_param('foo') - param = email.Utils.collapse_rfc2231_value(rawparam) - In any case, the parameter value (either the returned string, or the ``VALUE`` - item in the 3-tuple) is always unquoted, unless *unquote* is set to ``False``. + .. method:: set_param(param, value[, header[, requote[, charset[, language]]]]) + Set a parameter in the :mailheader:`Content-Type` header. If the + parameter already exists in the header, its value will be replaced with + *value*. If the :mailheader:`Content-Type` header as not yet been defined + for this message, it will be set to :mimetype:`text/plain` and the new + parameter value will be appended as per :rfc:`2045`. -.. method:: Message.set_param(param, value[, header[, requote[, charset[, language]]]]) + Optional *header* specifies an alternative header to + :mailheader:`Content-Type`, and all parameters will be quoted as necessary + unless optional *requote* is ``False`` (the default is ``True``). - Set a parameter in the :mailheader:`Content-Type` header. If the parameter - already exists in the header, its value will be replaced with *value*. If the - :mailheader:`Content-Type` header as not yet been defined for this message, it - will be set to :mimetype:`text/plain` and the new parameter value will be - appended as per :rfc:`2045`. + If optional *charset* is specified, the parameter will be encoded + according to :rfc:`2231`. Optional *language* specifies the RFC 2231 + language, defaulting to the empty string. Both *charset* and *language* + should be strings. - Optional *header* specifies an alternative header to :mailheader:`Content-Type`, - and all parameters will be quoted as necessary unless optional *requote* is - ``False`` (the default is ``True``). - If optional *charset* is specified, the parameter will be encoded according to - :rfc:`2231`. Optional *language* specifies the RFC 2231 language, defaulting to - the empty string. Both *charset* and *language* should be strings. + .. method:: del_param(param[, header[, requote]]) + Remove the given parameter completely from the :mailheader:`Content-Type` + header. The header will be re-written in place without the parameter or + its value. All values will be quoted as necessary unless *requote* is + ``False`` (the default is ``True``). Optional *header* specifies an + alternative to :mailheader:`Content-Type`. -.. method:: Message.del_param(param[, header[, requote]]) - Remove the given parameter completely from the :mailheader:`Content-Type` - header. The header will be re-written in place without the parameter or its - value. All values will be quoted as necessary unless *requote* is ``False`` - (the default is ``True``). Optional *header* specifies an alternative to - :mailheader:`Content-Type`. + .. method:: set_type(type[, header][, requote]) + Set the main type and subtype for the :mailheader:`Content-Type` + header. *type* must be a string in the form :mimetype:`maintype/subtype`, + otherwise a :exc:`ValueError` is raised. -.. method:: Message.set_type(type[, header][, requote]) + This method replaces the :mailheader:`Content-Type` header, keeping all + the parameters in place. If *requote* is ``False``, this leaves the + existing header's quoting as is, otherwise the parameters will be quoted + (the default). - Set the main type and subtype for the :mailheader:`Content-Type` header. *type* - must be a string in the form :mimetype:`maintype/subtype`, otherwise a - :exc:`ValueError` is raised. + An alternative header can be specified in the *header* argument. When the + :mailheader:`Content-Type` header is set a :mailheader:`MIME-Version` + header is also added. - This method replaces the :mailheader:`Content-Type` header, keeping all the - parameters in place. If *requote* is ``False``, this leaves the existing - header's quoting as is, otherwise the parameters will be quoted (the default). - An alternative header can be specified in the *header* argument. When the - :mailheader:`Content-Type` header is set a :mailheader:`MIME-Version` header is - also added. + .. method:: get_filename([failobj]) + Return the value of the ``filename`` parameter of the + :mailheader:`Content-Disposition` header of the message. If the header + does not have a ``filename`` parameter, this method falls back to looking + for the ``name`` parameter. If neither is found, or the header is + missing, then *failobj* is returned. The returned string will always be + unquoted as per :meth:`Utils.unquote`. -.. method:: Message.get_filename([failobj]) - Return the value of the ``filename`` parameter of the - :mailheader:`Content-Disposition` header of the message. If the header does not - have a ``filename`` parameter, this method falls back to looking for the - ``name`` parameter. If neither is found, or the header is missing, then - *failobj* is returned. The returned string will always be unquoted as per - :meth:`Utils.unquote`. + .. method:: get_boundary([failobj]) + Return the value of the ``boundary`` parameter of the + :mailheader:`Content-Type` header of the message, or *failobj* if either + the header is missing, or has no ``boundary`` parameter. The returned + string will always be unquoted as per :meth:`Utils.unquote`. -.. method:: Message.get_boundary([failobj]) - Return the value of the ``boundary`` parameter of the :mailheader:`Content-Type` - header of the message, or *failobj* if either the header is missing, or has no - ``boundary`` parameter. The returned string will always be unquoted as per - :meth:`Utils.unquote`. + .. method:: set_boundary(boundary) + Set the ``boundary`` parameter of the :mailheader:`Content-Type` header to + *boundary*. :meth:`set_boundary` will always quote *boundary* if + necessary. A :exc:`HeaderParseError` is raised if the message object has + no :mailheader:`Content-Type` header. -.. method:: Message.set_boundary(boundary) + Note that using this method is subtly different than deleting the old + :mailheader:`Content-Type` header and adding a new one with the new + boundary via :meth:`add_header`, because :meth:`set_boundary` preserves + the order of the :mailheader:`Content-Type` header in the list of + headers. However, it does *not* preserve any continuation lines which may + have been present in the original :mailheader:`Content-Type` header. - Set the ``boundary`` parameter of the :mailheader:`Content-Type` header to - *boundary*. :meth:`set_boundary` will always quote *boundary* if necessary. A - :exc:`HeaderParseError` is raised if the message object has no - :mailheader:`Content-Type` header. - Note that using this method is subtly different than deleting the old - :mailheader:`Content-Type` header and adding a new one with the new boundary via - :meth:`add_header`, because :meth:`set_boundary` preserves the order of the - :mailheader:`Content-Type` header in the list of headers. However, it does *not* - preserve any continuation lines which may have been present in the original - :mailheader:`Content-Type` header. + .. method:: get_content_charset([failobj]) + Return the ``charset`` parameter of the :mailheader:`Content-Type` header, + coerced to lower case. If there is no :mailheader:`Content-Type` header, or if + that header has no ``charset`` parameter, *failobj* is returned. -.. method:: Message.get_content_charset([failobj]) + Note that this method differs from :meth:`get_charset` which returns the + :class:`Charset` instance for the default encoding of the message body. - Return the ``charset`` parameter of the :mailheader:`Content-Type` header, - coerced to lower case. If there is no :mailheader:`Content-Type` header, or if - that header has no ``charset`` parameter, *failobj* is returned. - Note that this method differs from :meth:`get_charset` which returns the - :class:`Charset` instance for the default encoding of the message body. + .. method:: get_charsets([failobj]) + Return a list containing the character set names in the message. If the + message is a :mimetype:`multipart`, then the list will contain one element + for each subpart in the payload, otherwise, it will be a list of length 1. -.. method:: Message.get_charsets([failobj]) + Each item in the list will be a string which is the value of the + ``charset`` parameter in the :mailheader:`Content-Type` header for the + represented subpart. However, if the subpart has no + :mailheader:`Content-Type` header, no ``charset`` parameter, or is not of + the :mimetype:`text` main MIME type, then that item in the returned list + will be *failobj*. - Return a list containing the character set names in the message. If the message - is a :mimetype:`multipart`, then the list will contain one element for each - subpart in the payload, otherwise, it will be a list of length 1. - Each item in the list will be a string which is the value of the ``charset`` - parameter in the :mailheader:`Content-Type` header for the represented subpart. - However, if the subpart has no :mailheader:`Content-Type` header, no ``charset`` - parameter, or is not of the :mimetype:`text` main MIME type, then that item in - the returned list will be *failobj*. + .. method:: walk() + The :meth:`walk` method is an all-purpose generator which can be used to + iterate over all the parts and subparts of a message object tree, in + depth-first traversal order. You will typically use :meth:`walk` as the + iterator in a ``for`` loop; each iteration returns the next subpart. -.. method:: Message.walk() + Here's an example that prints the MIME type of every part of a multipart + message structure:: - The :meth:`walk` method is an all-purpose generator which can be used to iterate - over all the parts and subparts of a message object tree, in depth-first - traversal order. You will typically use :meth:`walk` as the iterator in a - ``for`` loop; each iteration returns the next subpart. + >>> for part in msg.walk(): + ... print(part.get_content_type()) + multipart/report + text/plain + message/delivery-status + text/plain + text/plain + message/rfc822 - Here's an example that prints the MIME type of every part of a multipart message - structure:: + :class:`Message` objects can also optionally contain two instance attributes, + which can be used when generating the plain text of a MIME message. - >>> for part in msg.walk(): - ... print(part.get_content_type()) - multipart/report - text/plain - message/delivery-status - text/plain - text/plain - message/rfc822 -:class:`Message` objects can also optionally contain two instance attributes, -which can be used when generating the plain text of a MIME message. + .. attribute:: preamble + The format of a MIME document allows for some text between the blank line + following the headers, and the first multipart boundary string. Normally, + this text is never visible in a MIME-aware mail reader because it falls + outside the standard MIME armor. However, when viewing the raw text of + the message, or when viewing the message in a non-MIME aware reader, this + text can become visible. -.. data:: preamble + The *preamble* attribute contains this leading extra-armor text for MIME + documents. When the :class:`Parser` discovers some text after the headers + but before the first boundary string, it assigns this text to the + message's *preamble* attribute. When the :class:`Generator` is writing + out the plain text representation of a MIME message, and it finds the + message has a *preamble* attribute, it will write this text in the area + between the headers and the first boundary. See :mod:`email.parser` and + :mod:`email.generator` for details. - The format of a MIME document allows for some text between the blank line - following the headers, and the first multipart boundary string. Normally, this - text is never visible in a MIME-aware mail reader because it falls outside the - standard MIME armor. However, when viewing the raw text of the message, or when - viewing the message in a non-MIME aware reader, this text can become visible. + Note that if the message object has no preamble, the *preamble* attribute + will be ``None``. - The *preamble* attribute contains this leading extra-armor text for MIME - documents. When the :class:`Parser` discovers some text after the headers but - before the first boundary string, it assigns this text to the message's - *preamble* attribute. When the :class:`Generator` is writing out the plain text - representation of a MIME message, and it finds the message has a *preamble* - attribute, it will write this text in the area between the headers and the first - boundary. See :mod:`email.parser` and :mod:`email.generator` for details. - Note that if the message object has no preamble, the *preamble* attribute will - be ``None``. + .. attribute:: epilogue + The *epilogue* attribute acts the same way as the *preamble* attribute, + except that it contains text that appears between the last boundary and + the end of the message. -.. data:: epilogue + You do not need to set the epilogue to the empty string in order for the + :class:`Generator` to print a newline at the end of the file. - The *epilogue* attribute acts the same way as the *preamble* attribute, except - that it contains text that appears between the last boundary and the end of the - message. - You do not need to set the epilogue to the empty string in order for the - :class:`Generator` to print a newline at the end of the file. + .. attribute:: defects - -.. data:: defects - - The *defects* attribute contains a list of all the problems found when parsing - this message. See :mod:`email.errors` for a detailed description of the - possible parsing defects. + The *defects* attribute contains a list of all the problems found when + parsing this message. See :mod:`email.errors` for a detailed description + of the possible parsing defects. Modified: python/branches/py3k/Doc/library/email.parser.rst ============================================================================== --- python/branches/py3k/Doc/library/email.parser.rst (original) +++ python/branches/py3k/Doc/library/email.parser.rst Fri Apr 25 03:59:09 2008 @@ -65,20 +65,21 @@ defaults to the :class:`email.message.Message` class. -.. method:: FeedParser.feed(data) + .. method:: feed(data) - Feed the :class:`FeedParser` some more data. *data* should be a string - containing one or more lines. The lines can be partial and the - :class:`FeedParser` will stitch such partial lines together properly. The lines - in the string can have any of the common three line endings, carriage return, - newline, or carriage return and newline (they can even be mixed). + Feed the :class:`FeedParser` some more data. *data* should be a string + containing one or more lines. The lines can be partial and the + :class:`FeedParser` will stitch such partial lines together properly. The + lines in the string can have any of the common three line endings, + carriage return, newline, or carriage return and newline (they can even be + mixed). -.. method:: FeedParser.close() + .. method:: close() - Closing a :class:`FeedParser` completes the parsing of all previously fed data, - and returns the root message object. It is undefined what happens if you feed - more data to a closed :class:`FeedParser`. + Closing a :class:`FeedParser` completes the parsing of all previously fed + data, and returns the root message object. It is undefined what happens + if you feed more data to a closed :class:`FeedParser`. Parser class API @@ -111,33 +112,33 @@ effectively non-strict. You should simply stop passing a *strict* flag to the :class:`Parser` constructor. -The other public :class:`Parser` methods are: + The other public :class:`Parser` methods are: -.. method:: Parser.parse(fp[, headersonly]) + .. method:: parse(fp[, headersonly]) - Read all the data from the file-like object *fp*, parse the resulting text, and - return the root message object. *fp* must support both the :meth:`readline` and - the :meth:`read` methods on file-like objects. + Read all the data from the file-like object *fp*, parse the resulting + text, and return the root message object. *fp* must support both the + :meth:`readline` and the :meth:`read` methods on file-like objects. - The text contained in *fp* must be formatted as a block of :rfc:`2822` style - headers and header continuation lines, optionally preceded by a envelope - header. The header block is terminated either by the end of the data or by a - blank line. Following the header block is the body of the message (which may - contain MIME-encoded subparts). + The text contained in *fp* must be formatted as a block of :rfc:`2822` + style headers and header continuation lines, optionally preceded by a + envelope header. The header block is terminated either by the end of the + data or by a blank line. Following the header block is the body of the + message (which may contain MIME-encoded subparts). - Optional *headersonly* is as with the :meth:`parse` method. + Optional *headersonly* is as with the :meth:`parse` method. + .. method:: parsestr(text[, headersonly]) -.. method:: Parser.parsestr(text[, headersonly]) + Similar to the :meth:`parse` method, except it takes a string object + instead of a file-like object. Calling this method on a string is exactly + equivalent to wrapping *text* in a :class:`StringIO` instance first and + calling :meth:`parse`. - Similar to the :meth:`parse` method, except it takes a string object instead of - a file-like object. Calling this method on a string is exactly equivalent to - wrapping *text* in a :class:`StringIO` instance first and calling :meth:`parse`. - - Optional *headersonly* is a flag specifying whether to stop parsing after - reading the headers or not. The default is ``False``, meaning it parses the - entire contents of the file. + Optional *headersonly* is a flag specifying whether to stop parsing after + reading the headers or not. The default is ``False``, meaning it parses + the entire contents of the file. Since creating a message object structure from a string or a file object is such Modified: python/branches/py3k/Doc/library/filecmp.rst ============================================================================== --- python/branches/py3k/Doc/library/filecmp.rst (original) +++ python/branches/py3k/Doc/library/filecmp.rst Fri Apr 25 03:59:09 2008 @@ -66,88 +66,91 @@ 'tags']``. *hide* is a list of names to hide, and defaults to ``[os.curdir, os.pardir]``. -The :class:`dircmp` class provides the following methods: + The :class:`dircmp` class provides the following methods: -.. method:: dircmp.report() + .. method:: report() - Print (to ``sys.stdout``) a comparison between *a* and *b*. + Print (to ``sys.stdout``) a comparison between *a* and *b*. -.. method:: dircmp.report_partial_closure() + .. method:: report_partial_closure() - Print a comparison between *a* and *b* and common immediate subdirectories. + Print a comparison between *a* and *b* and common immediate + subdirectories. -.. method:: dircmp.report_full_closure() + .. method:: report_full_closure() - Print a comparison between *a* and *b* and common subdirectories (recursively). + Print a comparison between *a* and *b* and common subdirectories + (recursively). -The :class:`dircmp` offers a number of interesting attributes that may be used -to get various bits of information about the directory trees being compared. + The :class:`dircmp` offers a number of interesting attributes that may be + used to get various bits of information about the directory trees being + compared. -Note that via :meth:`__getattr__` hooks, all attributes are computed lazily, so -there is no speed penalty if only those attributes which are lightweight to -compute are used. + Note that via :meth:`__getattr__` hooks, all attributes are computed lazily, + so there is no speed penalty if only those attributes which are lightweight + to compute are used. -.. attribute:: dircmp.left_list + .. attribute:: left_list - Files and subdirectories in *a*, filtered by *hide* and *ignore*. + Files and subdirectories in *a*, filtered by *hide* and *ignore*. -.. attribute:: dircmp.right_list + .. attribute:: right_list - Files and subdirectories in *b*, filtered by *hide* and *ignore*. + Files and subdirectories in *b*, filtered by *hide* and *ignore*. -.. attribute:: dircmp.common + .. attribute:: common - Files and subdirectories in both *a* and *b*. + Files and subdirectories in both *a* and *b*. -.. attribute:: dircmp.left_only + .. attribute:: left_only - Files and subdirectories only in *a*. + Files and subdirectories only in *a*. -.. attribute:: dircmp.right_only + .. attribute:: right_only - Files and subdirectories only in *b*. + Files and subdirectories only in *b*. -.. attribute:: dircmp.common_dirs + .. attribute:: common_dirs - Subdirectories in both *a* and *b*. + Subdirectories in both *a* and *b*. -.. attribute:: dircmp.common_files + .. attribute:: common_files - Files in both *a* and *b* + Files in both *a* and *b* -.. attribute:: dircmp.common_funny + .. attribute:: common_funny - Names in both *a* and *b*, such that the type differs between the directories, - or names for which :func:`os.stat` reports an error. + Names in both *a* and *b*, such that the type differs between the + directories, or names for which :func:`os.stat` reports an error. -.. attribute:: dircmp.same_files + .. attribute:: same_files - Files which are identical in both *a* and *b*. + Files which are identical in both *a* and *b*. -.. attribute:: dircmp.diff_files + .. attribute:: diff_files - Files which are in both *a* and *b*, whose contents differ. + Files which are in both *a* and *b*, whose contents differ. -.. attribute:: dircmp.funny_files + .. attribute:: funny_files - Files which are in both *a* and *b*, but could not be compared. + Files which are in both *a* and *b*, but could not be compared. -.. attribute:: dircmp.subdirs + .. attribute:: subdirs - A dictionary mapping names in :attr:`common_dirs` to :class:`dircmp` objects. + A dictionary mapping names in :attr:`common_dirs` to :class:`dircmp` objects. Modified: python/branches/py3k/Doc/library/fractions.rst ============================================================================== --- python/branches/py3k/Doc/library/fractions.rst (original) +++ python/branches/py3k/Doc/library/fractions.rst Fri Apr 25 03:59:09 2008 @@ -30,60 +30,58 @@ :class:`numbers.Rational` and is immutable and hashable. -.. method:: Fraction.from_float(flt) + .. method:: from_float(flt) - This classmethod constructs a :class:`Fraction` representing the - exact value of *flt*, which must be a :class:`float`. Beware that - ``Fraction.from_float(0.3)`` is not the same value as ``Rational(3, - 10)`` + This classmethod constructs a :class:`Fraction` representing the exact + value of *flt*, which must be a :class:`float`. Beware that + ``Fraction.from_float(0.3)`` is not the same value as ``Rational(3, 10)`` -.. method:: Fraction.from_decimal(dec) + .. method:: from_decimal(dec) - This classmethod constructs a :class:`Fraction` representing the - exact value of *dec*, which must be a - :class:`decimal.Decimal`. + This classmethod constructs a :class:`Fraction` representing the exact + value of *dec*, which must be a :class:`decimal.Decimal`. -.. method:: Fraction.limit_denominator(max_denominator=1000000) + .. method:: limit_denominator(max_denominator=1000000) - Finds and returns the closest :class:`Fraction` to ``self`` that - has denominator at most max_denominator. This method is useful for - finding rational approximations to a given floating-point number: + Finds and returns the closest :class:`Fraction` to ``self`` that has + denominator at most max_denominator. This method is useful for finding + rational approximations to a given floating-point number: - >>> from fractions import Fraction - >>> Fraction('3.1415926535897932').limit_denominator(1000) - Fraction(355L, 113L) + >>> from fractions import Fraction + >>> Fraction('3.1415926535897932').limit_denominator(1000) + Fraction(355L, 113L) - or for recovering a rational number that's represented as a float: + or for recovering a rational number that's represented as a float: - >>> from math import pi, cos - >>> Fraction.from_float(cos(pi/3)) - Fraction(4503599627370497L, 9007199254740992L) - >>> Fraction.from_float(cos(pi/3)).limit_denominator() - Fraction(1L, 2L) + >>> from math import pi, cos + >>> Fraction.from_float(cos(pi/3)) + Fraction(4503599627370497L, 9007199254740992L) + >>> Fraction.from_float(cos(pi/3)).limit_denominator() + Fraction(1L, 2L) -.. method:: Fraction.__floor__() + .. method:: __floor__() - Returns the greatest :class:`int` ``<= self``. Will be accessible - through :func:`math.floor` in Py3k. + Returns the greatest :class:`int` ``<= self``. Will be accessible through + :func:`math.floor` in Py3k. -.. method:: Fraction.__ceil__() + .. method:: __ceil__() - Returns the least :class:`int` ``>= self``. Will be accessible - through :func:`math.ceil` in Py3k. + Returns the least :class:`int` ``>= self``. Will be accessible through + :func:`math.ceil` in Py3k. -.. method:: Fraction.__round__() - Fraction.__round__(ndigits) + .. method:: __round__() + __round__(ndigits) - The first version returns the nearest :class:`int` to ``self``, - rounding half to even. The second version rounds ``self`` to the - nearest multiple of ``Fraction(1, 10**ndigits)`` (logically, if - ``ndigits`` is negative), again rounding half toward even. Will be - accessible through :func:`round` in Py3k. + The first version returns the nearest :class:`int` to ``self``, rounding + half to even. The second version rounds ``self`` to the nearest multiple + of ``Fraction(1, 10**ndigits)`` (logically, if ``ndigits`` is negative), + again rounding half toward even. Will be accessible through :func:`round` + in Py3k. .. seealso:: Modified: python/branches/py3k/Doc/library/ftplib.rst ============================================================================== --- python/branches/py3k/Doc/library/ftplib.rst (original) +++ python/branches/py3k/Doc/library/ftplib.rst Fri Apr 25 03:59:09 2008 @@ -47,33 +47,34 @@ or passed as None, the global default timeout setting will be used). -.. data:: all_errors + .. attribute:: all_errors - The set of all exceptions (as a tuple) that methods of :class:`FTP` instances - may raise as a result of problems with the FTP connection (as opposed to - programming errors made by the caller). This set includes the four exceptions - listed below as well as :exc:`socket.error` and :exc:`IOError`. + The set of all exceptions (as a tuple) that methods of :class:`FTP` + instances may raise as a result of problems with the FTP connection (as + opposed to programming errors made by the caller). This set includes the + four exceptions listed below as well as :exc:`socket.error` and + :exc:`IOError`. -.. exception:: error_reply + .. exception:: error_reply - Exception raised when an unexpected reply is received from the server. + Exception raised when an unexpected reply is received from the server. -.. exception:: error_temp + .. exception:: error_temp - Exception raised when an error code in the range 400--499 is received. + Exception raised when an error code in the range 400--499 is received. -.. exception:: error_perm + .. exception:: error_perm - Exception raised when an error code in the range 500--599 is received. + Exception raised when an error code in the range 500--599 is received. -.. exception:: error_proto + .. exception:: error_proto - Exception raised when a reply is received from the server that does not begin - with a digit in the range 1--5. + Exception raised when a reply is received from the server that does not + begin with a digit in the range 1--5. .. seealso:: Modified: python/branches/py3k/Doc/library/gettext.rst ============================================================================== --- python/branches/py3k/Doc/library/gettext.rst (original) +++ python/branches/py3k/Doc/library/gettext.rst Fri Apr 25 03:59:09 2008 @@ -218,7 +218,7 @@ are the methods of :class:`NullTranslations`: -.. method:: NullTranslations.__init__([fp]) +.. class:: NullTranslations([fp]) Takes an optional file object *fp*, which is ignored by the base class. Initializes "protected" instance variables *_info* and *_charset* which are set @@ -227,105 +227,107 @@ ``None``. -.. method:: NullTranslations._parse(fp) + .. method:: _parse(fp) - No-op'd in the base class, this method takes file object *fp*, and reads the - data from the file, initializing its message catalog. If you have an - unsupported message catalog file format, you should override this method to - parse your format. + No-op'd in the base class, this method takes file object *fp*, and reads + the data from the file, initializing its message catalog. If you have an + unsupported message catalog file format, you should override this method + to parse your format. -.. method:: NullTranslations.add_fallback(fallback) + .. method:: add_fallback(fallback) - Add *fallback* as the fallback object for the current translation object. A - translation object should consult the fallback if it cannot provide a - translation for a given message. + Add *fallback* as the fallback object for the current translation + object. A translation object should consult the fallback if it cannot provide a + translation for a given message. -.. method:: NullTranslations.gettext(message) + .. method:: gettext(message) - If a fallback has been set, forward :meth:`gettext` to the fallback. Otherwise, - return the translated message. Overridden in derived classes. + If a fallback has been set, forward :meth:`gettext` to the + fallback. Otherwise, return the translated message. Overridden in derived + classes. -.. method:: NullTranslations.lgettext(message) + .. method:: lgettext(message) - If a fallback has been set, forward :meth:`lgettext` to the fallback. Otherwise, - return the translated message. Overridden in derived classes. + If a fallback has been set, forward :meth:`lgettext` to the + fallback. Otherwise, return the translated message. Overridden in derived + classes. + .. method:: ugettext(message) -.. method:: NullTranslations.ugettext(message) + If a fallback has been set, forward :meth:`ugettext` to the + fallback. Otherwise, return the translated message as a string. Overridden + in derived classes. - If a fallback has been set, forward :meth:`ugettext` to the fallback. Otherwise, - return the translated message as a string. Overridden in derived classes. + .. method:: ngettext(singular, plural, n) -.. method:: NullTranslations.ngettext(singular, plural, n) + If a fallback has been set, forward :meth:`ngettext` to the + fallback. Otherwise, return the translated message. Overridden in derived + classes. - If a fallback has been set, forward :meth:`ngettext` to the fallback. Otherwise, - return the translated message. Overridden in derived classes. + .. method:: lngettext(singular, plural, n) + If a fallback has been set, forward :meth:`ngettext` to the + fallback. Otherwise, return the translated message. Overridden in derived + classes. -.. method:: NullTranslations.lngettext(singular, plural, n) + .. method:: ungettext(singular, plural, n) - If a fallback has been set, forward :meth:`ngettext` to the fallback. Otherwise, - return the translated message. Overridden in derived classes. + If a fallback has been set, forward :meth:`ungettext` to the fallback. + Otherwise, return the translated message as a string. Overridden in + derived classes. + .. method:: info() -.. method:: NullTranslations.ungettext(singular, plural, n) + Return the "protected" :attr:`_info` variable. - If a fallback has been set, forward :meth:`ungettext` to the fallback. - Otherwise, return the translated message as a string. Overridden in - derived classes. + .. method:: charset() -.. method:: NullTranslations.info() + Return the "protected" :attr:`_charset` variable. - Return the "protected" :attr:`_info` variable. + .. method:: output_charset() -.. method:: NullTranslations.charset() + Return the "protected" :attr:`_output_charset` variable, which defines the + encoding used to return translated messages. - Return the "protected" :attr:`_charset` variable. + .. method:: set_output_charset(charset) -.. method:: NullTranslations.output_charset() + Change the "protected" :attr:`_output_charset` variable, which defines the + encoding used to return translated messages. - Return the "protected" :attr:`_output_charset` variable, which defines the - encoding used to return translated messages. + .. method:: install([unicode [, names]]) -.. method:: NullTranslations.set_output_charset(charset) + If the *unicode* flag is false, this method installs :meth:`self.gettext` + into the built-in namespace, binding it to ``_``. If *unicode* is true, + it binds :meth:`self.ugettext` instead. By default, *unicode* is false. - Change the "protected" :attr:`_output_charset` variable, which defines the - encoding used to return translated messages. + If the *names* parameter is given, it must be a sequence containing the + names of functions you want to install in the builtin namespace in + addition to :func:`_`. Supported names are ``'gettext'`` (bound to + :meth:`self.gettext` or :meth:`self.ugettext` according to the *unicode* + flag), ``'ngettext'`` (bound to :meth:`self.ngettext` or + :meth:`self.ungettext` according to the *unicode* flag), ``'lgettext'`` + and ``'lngettext'``. + Note that this is only one way, albeit the most convenient way, to make + the :func:`_` function available to your application. Because it affects + the entire application globally, and specifically the built-in namespace, + localized modules should never install :func:`_`. Instead, they should use + this code to make :func:`_` available to their module:: -.. method:: NullTranslations.install([unicode [, names]]) + import gettext + t = gettext.translation('mymodule', ...) + _ = t.gettext - If the *unicode* flag is false, this method installs :meth:`self.gettext` into - the built-in namespace, binding it to ``_``. If *unicode* is true, it binds - :meth:`self.ugettext` instead. By default, *unicode* is false. - - If the *names* parameter is given, it must be a sequence containing the names of - functions you want to install in the builtin namespace in addition to :func:`_`. - Supported names are ``'gettext'`` (bound to :meth:`self.gettext` or - :meth:`self.ugettext` according to the *unicode* flag), ``'ngettext'`` (bound to - :meth:`self.ngettext` or :meth:`self.ungettext` according to the *unicode* - flag), ``'lgettext'`` and ``'lngettext'``. - - Note that this is only one way, albeit the most convenient way, to make the - :func:`_` function available to your application. Because it affects the entire - application globally, and specifically the built-in namespace, localized modules - should never install :func:`_`. Instead, they should use this code to make - :func:`_` available to their module:: - - import gettext - t = gettext.translation('mymodule', ...) - _ = t.gettext - - This puts :func:`_` only in the module's global namespace and so only affects - calls within this module. + This puts :func:`_` only in the module's global namespace and so only + affects calls within this module. The :class:`GNUTranslations` class Modified: python/branches/py3k/Doc/library/logging.rst ============================================================================== --- python/branches/py3k/Doc/library/logging.rst (original) +++ python/branches/py3k/Doc/library/logging.rst Fri Apr 25 03:59:09 2008 @@ -1491,19 +1491,19 @@ will be used. -.. method:: StreamHandler.emit(record) + .. method:: emit(record) - If a formatter is specified, it is used to format the record. The record is then - written to the stream with a trailing newline. If exception information is - present, it is formatted using :func:`traceback.print_exception` and appended to - the stream. + If a formatter is specified, it is used to format the record. The record + is then written to the stream with a trailing newline. If exception + information is present, it is formatted using + :func:`traceback.print_exception` and appended to the stream. -.. method:: StreamHandler.flush() + .. method:: flush() - Flushes the stream by calling its :meth:`flush` method. Note that the - :meth:`close` method is inherited from :class:`Handler` and so does nothing, so - an explicit :meth:`flush` call may be needed at times. + Flushes the stream by calling its :meth:`flush` method. Note that the + :meth:`close` method is inherited from :class:`Handler` and so does + nothing, so an explicit :meth:`flush` call may be needed at times. FileHandler @@ -1523,14 +1523,14 @@ first call to :meth:`emit`. By default, the file grows indefinitely. -.. method:: FileHandler.close() + .. method:: close() - Closes the file. + Closes the file. -.. method:: FileHandler.emit(record) + .. method:: emit(record) - Outputs the record to the file. + Outputs the record to the file. WatchedFileHandler @@ -1563,11 +1563,11 @@ first call to :meth:`emit`. By default, the file grows indefinitely. -.. method:: WatchedFileHandler.emit(record) + .. method:: emit(record) - Outputs the record to the file, but first checks to see if the file has changed. - If it has, the existing stream is flushed and closed and the file opened again, - before outputting the record to the file. + Outputs the record to the file, but first checks to see if the file has + changed. If it has, the existing stream is flushed and closed and the + file opened again, before outputting the record to the file. RotatingFileHandler @@ -1599,14 +1599,15 @@ :file:`app.log.2`, :file:`app.log.3` etc. respectively. -.. method:: RotatingFileHandler.doRollover() + .. method:: doRollover() - Does a rollover, as described above. + Does a rollover, as described above. -.. method:: RotatingFileHandler.emit(record) + .. method:: emit(record) - Outputs the record to the file, catering for rollover as described previously. + Outputs the record to the file, catering for rollover as described + previously. TimedRotatingFileHandler @@ -1652,14 +1653,14 @@ files to delete, so changing the interval may leave old files lying around. -.. method:: TimedRotatingFileHandler.doRollover() + .. method:: doRollover() - Does a rollover, as described above. + Does a rollover, as described above. -.. method:: TimedRotatingFileHandler.emit(record) + .. method:: emit(record) - Outputs the record to the file, catering for rollover as described above. + Outputs the record to the file, catering for rollover as described above. SocketHandler @@ -1675,43 +1676,44 @@ communicate with a remote machine whose address is given by *host* and *port*. -.. method:: SocketHandler.close() + .. method:: close() - Closes the socket. + Closes the socket. -.. method:: SocketHandler.emit() + .. method:: emit() - Pickles the record's attribute dictionary and writes it to the socket in binary - format. If there is an error with the socket, silently drops the packet. If the - connection was previously lost, re-establishes the connection. To unpickle the - record at the receiving end into a :class:`LogRecord`, use the - :func:`makeLogRecord` function. + Pickles the record's attribute dictionary and writes it to the socket in + binary format. If there is an error with the socket, silently drops the + packet. If the connection was previously lost, re-establishes the + connection. To unpickle the record at the receiving end into a + :class:`LogRecord`, use the :func:`makeLogRecord` function. -.. method:: SocketHandler.handleError() + .. method:: handleError() - Handles an error which has occurred during :meth:`emit`. The most likely cause - is a lost connection. Closes the socket so that we can retry on the next event. + Handles an error which has occurred during :meth:`emit`. The most likely + cause is a lost connection. Closes the socket so that we can retry on the + next event. -.. method:: SocketHandler.makeSocket() + .. method:: makeSocket() - This is a factory method which allows subclasses to define the precise type of - socket they want. The default implementation creates a TCP socket - (:const:`socket.SOCK_STREAM`). + This is a factory method which allows subclasses to define the precise + type of socket they want. The default implementation creates a TCP socket + (:const:`socket.SOCK_STREAM`). -.. method:: SocketHandler.makePickle(record) + .. method:: makePickle(record) - Pickles the record's attribute dictionary in binary format with a length prefix, - and returns it ready for transmission across the socket. + Pickles the record's attribute dictionary in binary format with a length + prefix, and returns it ready for transmission across the socket. -.. method:: SocketHandler.send(packet) + .. method:: send(packet) - Send a pickled string *packet* to the socket. This function allows for partial - sends which can happen when the network is busy. + Send a pickled string *packet* to the socket. This function allows for + partial sends which can happen when the network is busy. DatagramHandler @@ -1728,23 +1730,23 @@ communicate with a remote machine whose address is given by *host* and *port*. -.. method:: DatagramHandler.emit() + .. method:: emit() - Pickles the record's attribute dictionary and writes it to the socket in binary - format. If there is an error with the socket, silently drops the packet. To - unpickle the record at the receiving end into a :class:`LogRecord`, use the - :func:`makeLogRecord` function. + Pickles the record's attribute dictionary and writes it to the socket in + binary format. If there is an error with the socket, silently drops the + packet. To unpickle the record at the receiving end into a + :class:`LogRecord`, use the :func:`makeLogRecord` function. -.. method:: DatagramHandler.makeSocket() + .. method:: makeSocket() - The factory method of :class:`SocketHandler` is here overridden to create a UDP - socket (:const:`socket.SOCK_DGRAM`). + The factory method of :class:`SocketHandler` is here overridden to create + a UDP socket (:const:`socket.SOCK_DGRAM`). -.. method:: DatagramHandler.send(s) + .. method:: send(s) - Send a pickled string to a socket. + Send a pickled string to a socket. SysLogHandler @@ -1766,22 +1768,22 @@ :const:`LOG_USER` is used. -.. method:: SysLogHandler.close() + .. method:: close() - Closes the socket to the remote host. + Closes the socket to the remote host. -.. method:: SysLogHandler.emit(record) + .. method:: emit(record) - The record is formatted, and then sent to the syslog server. If exception - information is present, it is *not* sent to the server. + The record is formatted, and then sent to the syslog server. If exception + information is present, it is *not* sent to the server. -.. method:: SysLogHandler.encodePriority(facility, priority) + .. method:: encodePriority(facility, priority) - Encodes the facility and priority into an integer. You can pass in strings or - integers - if strings are passed, internal mapping dictionaries are used to - convert them to integers. + Encodes the facility and priority into an integer. You can pass in strings + or integers - if strings are passed, internal mapping dictionaries are + used to convert them to integers. NTEventLogHandler @@ -1809,45 +1811,45 @@ defaults to ``'Application'``. -.. method:: NTEventLogHandler.close() + .. method:: close() - At this point, you can remove the application name from the registry as a source - of event log entries. However, if you do this, you will not be able to see the - events as you intended in the Event Log Viewer - it needs to be able to access - the registry to get the .dll name. The current version does not do this (in fact - it doesn't do anything). + At this point, you can remove the application name from the registry as a + source of event log entries. However, if you do this, you will not be able + to see the events as you intended in the Event Log Viewer - it needs to be + able to access the registry to get the .dll name. The current version does + not do this (in fact it doesn't do anything). -.. method:: NTEventLogHandler.emit(record) + .. method:: emit(record) - Determines the message ID, event category and event type, and then logs the - message in the NT event log. + Determines the message ID, event category and event type, and then logs + the message in the NT event log. -.. method:: NTEventLogHandler.getEventCategory(record) + .. method:: getEventCategory(record) - Returns the event category for the record. Override this if you want to specify - your own categories. This version returns 0. + Returns the event category for the record. Override this if you want to + specify your own categories. This version returns 0. -.. method:: NTEventLogHandler.getEventType(record) + .. method:: getEventType(record) - Returns the event type for the record. Override this if you want to specify your - own types. This version does a mapping using the handler's typemap attribute, - which is set up in :meth:`__init__` to a dictionary which contains mappings for - :const:`DEBUG`, :const:`INFO`, :const:`WARNING`, :const:`ERROR` and - :const:`CRITICAL`. If you are using your own levels, you will either need to - override this method or place a suitable dictionary in the handler's *typemap* - attribute. + Returns the event type for the record. Override this if you want to + specify your own types. This version does a mapping using the handler's + typemap attribute, which is set up in :meth:`__init__` to a dictionary + which contains mappings for :const:`DEBUG`, :const:`INFO`, + :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using + your own levels, you will either need to override this method or place a + suitable dictionary in the handler's *typemap* attribute. -.. method:: NTEventLogHandler.getMessageID(record) + .. method:: getMessageID(record) - Returns the message ID for the record. If you are using your own messages, you - could do this by having the *msg* passed to the logger being an ID rather than a - format string. Then, in here, you could use a dictionary lookup to get the - message ID. This version returns 1, which is the base message ID in - :file:`win32service.pyd`. + Returns the message ID for the record. If you are using your own messages, + you could do this by having the *msg* passed to the logger being an ID + rather than a format string. Then, in here, you could use a dictionary + lookup to get the message ID. This version returns 1, which is the base + message ID in :file:`win32service.pyd`. SMTPHandler @@ -1867,15 +1869,15 @@ can specify a (username, password) tuple for the *credentials* argument. -.. method:: SMTPHandler.emit(record) + .. method:: emit(record) - Formats the record and sends it to the specified addressees. + Formats the record and sends it to the specified addressees. -.. method:: SMTPHandler.getSubject(record) + .. method:: getSubject(record) - If you want to specify a subject line which is record-dependent, override this - method. + If you want to specify a subject line which is record-dependent, override + this method. MemoryHandler @@ -1898,22 +1900,22 @@ Initializes the handler with a buffer of the specified capacity. -.. method:: BufferingHandler.emit(record) + .. method:: emit(record) - Appends the record to the buffer. If :meth:`shouldFlush` returns true, calls - :meth:`flush` to process the buffer. + Appends the record to the buffer. If :meth:`shouldFlush` returns true, + calls :meth:`flush` to process the buffer. -.. method:: BufferingHandler.flush() + .. method:: flush() - You can override this to implement custom flushing behavior. This version just - zaps the buffer to empty. + You can override this to implement custom flushing behavior. This version + just zaps the buffer to empty. -.. method:: BufferingHandler.shouldFlush(record) + .. method:: shouldFlush(record) - Returns true if the buffer is up to capacity. This method can be overridden to - implement custom flushing strategies. + Returns true if the buffer is up to capacity. This method can be + overridden to implement custom flushing strategies. .. class:: MemoryHandler(capacity[, flushLevel [, target]]) @@ -1924,25 +1926,27 @@ set using :meth:`setTarget` before this handler does anything useful. -.. method:: MemoryHandler.close() + .. method:: close() - Calls :meth:`flush`, sets the target to :const:`None` and clears the buffer. + Calls :meth:`flush`, sets the target to :const:`None` and clears the + buffer. -.. method:: MemoryHandler.flush() + .. method:: flush() - For a :class:`MemoryHandler`, flushing means just sending the buffered records - to the target, if there is one. Override if you want different behavior. + For a :class:`MemoryHandler`, flushing means just sending the buffered + records to the target, if there is one. Override if you want different + behavior. -.. method:: MemoryHandler.setTarget(target) + .. method:: setTarget(target) - Sets the target handler for this handler. + Sets the target handler for this handler. -.. method:: MemoryHandler.shouldFlush(record) + .. method:: shouldFlush(record) - Checks for buffer full or a record at the *flushLevel* or higher. + Checks for buffer full or a record at the *flushLevel* or higher. HTTPHandler @@ -1961,9 +1965,9 @@ *method* is specified, ``GET`` is used. -.. method:: HTTPHandler.emit(record) + .. method:: emit(record) - Sends the record to the Web server as an URL-encoded dictionary. + Sends the record to the Web server as an URL-encoded dictionary. .. _formatter-objects: @@ -2048,38 +2052,42 @@ is used. -.. method:: Formatter.format(record) + .. method:: format(record) - The record's attribute dictionary is used as the operand to a string formatting - operation. Returns the resulting string. Before formatting the dictionary, a - couple of preparatory steps are carried out. The *message* attribute of the - record is computed using *msg* % *args*. If the formatting string contains - ``'(asctime)'``, :meth:`formatTime` is called to format the event time. If there - is exception information, it is formatted using :meth:`formatException` and - appended to the message. Note that the formatted exception information is cached - in attribute *exc_text*. This is useful because the exception information can - be pickled and sent across the wire, but you should be careful if you have more - than one :class:`Formatter` subclass which customizes the formatting of exception - information. In this case, you will have to clear the cached value after a - formatter has done its formatting, so that the next formatter to handle the event - doesn't use the cached value but recalculates it afresh. - - -.. method:: Formatter.formatTime(record[, datefmt]) - - This method should be called from :meth:`format` by a formatter which wants to - make use of a formatted time. This method can be overridden in formatters to - provide for any specific requirement, but the basic behavior is as follows: if - *datefmt* (a string) is specified, it is used with :func:`time.strftime` to - format the creation time of the record. Otherwise, the ISO8601 format is used. - The resulting string is returned. - - -.. method:: Formatter.formatException(exc_info) - - Formats the specified exception information (a standard exception tuple as - returned by :func:`sys.exc_info`) as a string. This default implementation just - uses :func:`traceback.print_exception`. The resulting string is returned. + The record's attribute dictionary is used as the operand to a string + formatting operation. Returns the resulting string. Before formatting the + dictionary, a couple of preparatory steps are carried out. The *message* + attribute of the record is computed using *msg* % *args*. If the + formatting string contains ``'(asctime)'``, :meth:`formatTime` is called + to format the event time. If there is exception information, it is + formatted using :meth:`formatException` and appended to the message. Note + that the formatted exception information is cached in attribute + *exc_text*. This is useful because the exception information can be + pickled and sent across the wire, but you should be careful if you have + more than one :class:`Formatter` subclass which customizes the formatting + of exception information. In this case, you will have to clear the cached + value after a formatter has done its formatting, so that the next + formatter to handle the event doesn't use the cached value but + recalculates it afresh. + + + .. method:: formatTime(record[, datefmt]) + + This method should be called from :meth:`format` by a formatter which + wants to make use of a formatted time. This method can be overridden in + formatters to provide for any specific requirement, but the basic behavior + is as follows: if *datefmt* (a string) is specified, it is used with + :func:`time.strftime` to format the creation time of the + record. Otherwise, the ISO8601 format is used. The resulting string is + returned. + + + .. method:: formatException(exc_info) + + Formats the specified exception information (a standard exception tuple as + returned by :func:`sys.exc_info`) as a string. This default implementation + just uses :func:`traceback.print_exception`. The resulting string is + returned. Filter Objects @@ -2100,10 +2108,11 @@ through the filter. If no name is specified, allows every event. -.. method:: Filter.filter(record) + .. method:: filter(record) - Is the specified record to be logged? Returns zero for no, nonzero for yes. If - deemed appropriate, the record may be modified in-place by this method. + Is the specified record to be logged? Returns zero for no, nonzero for + yes. If deemed appropriate, the record may be modified in-place by this + method. LogRecord Objects @@ -2131,10 +2140,11 @@ specified, it defaults to ``None``. -.. method:: LogRecord.getMessage() + .. method:: getMessage() + + Returns the message for this :class:`LogRecord` instance after merging any + user-supplied arguments with the message. - Returns the message for this :class:`LogRecord` instance after merging any - user-supplied arguments with the message. LoggerAdapter Objects --------------------- @@ -2150,13 +2160,13 @@ Returns an instance of :class:`LoggerAdapter` initialized with an underlying :class:`Logger` instance and a dict-like object. -.. method:: LoggerAdapter.process(msg, kwargs) + .. method:: process(msg, kwargs) - Modifies the message and/or keyword arguments passed to a logging call in - order to insert contextual information. This implementation takes the - object passed as *extra* to the constructor and adds it to *kwargs* using - key 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the - (possibly modified) versions of the arguments passed in. + Modifies the message and/or keyword arguments passed to a logging call in + order to insert contextual information. This implementation takes the object + passed as *extra* to the constructor and adds it to *kwargs* using key + 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the + (possibly modified) versions of the arguments passed in. In addition to the above, :class:`LoggerAdapter` supports all the logging methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`, Modified: python/branches/py3k/Doc/library/mailbox.rst ============================================================================== --- python/branches/py3k/Doc/library/mailbox.rst (original) +++ python/branches/py3k/Doc/library/mailbox.rst Fri Apr 25 03:59:09 2008 @@ -32,237 +32,243 @@ A mailbox, which may be inspected and modified. -The :class:`Mailbox` class defines an interface and is not intended to be -instantiated. Instead, format-specific subclasses should inherit from -:class:`Mailbox` and your code should instantiate a particular subclass. + The :class:`Mailbox` class defines an interface and is not intended to be + instantiated. Instead, format-specific subclasses should inherit from + :class:`Mailbox` and your code should instantiate a particular subclass. + + The :class:`Mailbox` interface is dictionary-like, with small keys + corresponding to messages. Keys are issued by the :class:`Mailbox` instance + with which they will be used and are only meaningful to that :class:`Mailbox` + instance. A key continues to identify a message even if the corresponding + message is modified, such as by replacing it with another message. + + Messages may be added to a :class:`Mailbox` instance using the set-like + method :meth:`add` and removed using a ``del`` statement or the set-like + methods :meth:`remove` and :meth:`discard`. + + :class:`Mailbox` interface semantics differ from dictionary semantics in some + noteworthy ways. Each time a message is requested, a new representation + (typically a :class:`Message` instance) is generated based upon the current + state of the mailbox. Similarly, when a message is added to a + :class:`Mailbox` instance, the provided message representation's contents are + copied. In neither case is a reference to the message representation kept by + the :class:`Mailbox` instance. + + The default :class:`Mailbox` iterator iterates over message representations, + not keys as the default dictionary iterator does. Moreover, modification of a + mailbox during iteration is safe and well-defined. Messages added to the + mailbox after an iterator is created will not be seen by the + iterator. Messages removed from the mailbox before the iterator yields them + will be silently skipped, though using a key from an iterator may result in a + :exc:`KeyError` exception if the corresponding message is subsequently + removed. -The :class:`Mailbox` interface is dictionary-like, with small keys corresponding -to messages. Keys are issued by the :class:`Mailbox` instance with which they -will be used and are only meaningful to that :class:`Mailbox` instance. A key -continues to identify a message even if the corresponding message is modified, -such as by replacing it with another message. - -Messages may be added to a :class:`Mailbox` instance using the set-like method -:meth:`add` and removed using a ``del`` statement or the set-like methods -:meth:`remove` and :meth:`discard`. - -:class:`Mailbox` interface semantics differ from dictionary semantics in some -noteworthy ways. Each time a message is requested, a new representation -(typically a :class:`Message` instance) is generated based upon the current -state of the mailbox. Similarly, when a message is added to a :class:`Mailbox` -instance, the provided message representation's contents are copied. In neither -case is a reference to the message representation kept by the :class:`Mailbox` -instance. + .. warning:: -The default :class:`Mailbox` iterator iterates over message representations, not -keys as the default dictionary iterator does. Moreover, modification of a -mailbox during iteration is safe and well-defined. Messages added to the mailbox -after an iterator is created will not be seen by the iterator. Messages removed -from the mailbox before the iterator yields them will be silently skipped, -though using a key from an iterator may result in a :exc:`KeyError` exception if -the corresponding message is subsequently removed. + Be very cautious when modifying mailboxes that might be simultaneously + changed by some other process. The safest mailbox format to use for such + tasks is Maildir; try to avoid using single-file formats such as mbox for + concurrent writing. If you're modifying a mailbox, you *must* lock it by + calling the :meth:`lock` and :meth:`unlock` methods *before* reading any + messages in the file or making any changes by adding or deleting a + message. Failing to lock the mailbox runs the risk of losing messages or + corrupting the entire mailbox. -.. warning:: + :class:`Mailbox` instances have the following methods: - Be very cautious when modifying mailboxes that might be simultaneously changed - by some other process. The safest mailbox format to use for such tasks is - Maildir; try to avoid using single-file formats such as mbox for concurrent - writing. If you're modifying a mailbox, you *must* lock it by calling the - :meth:`lock` and :meth:`unlock` methods *before* reading any messages in the - file or making any changes by adding or deleting a message. Failing to lock the - mailbox runs the risk of losing messages or corrupting the entire mailbox. -:class:`Mailbox` instances have the following methods: + .. method:: add(message) + Add *message* to the mailbox and return the key that has been assigned to + it. -.. method:: Mailbox.add(message) + Parameter *message* may be a :class:`Message` instance, an + :class:`email.Message.Message` instance, a string, or a file-like object + (which should be open in text mode). If *message* is an instance of the + appropriate format-specific :class:`Message` subclass (e.g., if it's an + :class:`mboxMessage` instance and this is an :class:`mbox` instance), its + format-specific information is used. Otherwise, reasonable defaults for + format-specific information are used. - Add *message* to the mailbox and return the key that has been assigned to it. - Parameter *message* may be a :class:`Message` instance, an - :class:`email.Message.Message` instance, a string, or a file-like object (which - should be open in text mode). If *message* is an instance of the appropriate - format-specific :class:`Message` subclass (e.g., if it's an :class:`mboxMessage` - instance and this is an :class:`mbox` instance), its format-specific information - is used. Otherwise, reasonable defaults for format-specific information are - used. + .. method:: remove(key) + __delitem__(key) + discard(key) + Delete the message corresponding to *key* from the mailbox. -.. method:: Mailbox.remove(key) - Mailbox.__delitem__(key) - Mailbox.discard(key) + If no such message exists, a :exc:`KeyError` exception is raised if the + method was called as :meth:`remove` or :meth:`__delitem__` but no + exception is raised if the method was called as :meth:`discard`. The + behavior of :meth:`discard` may be preferred if the underlying mailbox + format supports concurrent modification by other processes. - Delete the message corresponding to *key* from the mailbox. - If no such message exists, a :exc:`KeyError` exception is raised if the method - was called as :meth:`remove` or :meth:`__delitem__` but no exception is raised - if the method was called as :meth:`discard`. The behavior of :meth:`discard` may - be preferred if the underlying mailbox format supports concurrent modification - by other processes. + .. method:: __setitem__(key, message) + Replace the message corresponding to *key* with *message*. Raise a + :exc:`KeyError` exception if no message already corresponds to *key*. -.. method:: Mailbox.__setitem__(key, message) + As with :meth:`add`, parameter *message* may be a :class:`Message` + instance, an :class:`email.Message.Message` instance, a string, or a + file-like object (which should be open in text mode). If *message* is an + instance of the appropriate format-specific :class:`Message` subclass + (e.g., if it's an :class:`mboxMessage` instance and this is an + :class:`mbox` instance), its format-specific information is + used. Otherwise, the format-specific information of the message that + currently corresponds to *key* is left unchanged. - Replace the message corresponding to *key* with *message*. Raise a - :exc:`KeyError` exception if no message already corresponds to *key*. - As with :meth:`add`, parameter *message* may be a :class:`Message` instance, an - :class:`email.Message.Message` instance, a string, or a file-like object (which - should be open in text mode). If *message* is an instance of the appropriate - format-specific :class:`Message` subclass (e.g., if it's an :class:`mboxMessage` - instance and this is an :class:`mbox` instance), its format-specific information - is used. Otherwise, the format-specific information of the message that - currently corresponds to *key* is left unchanged. + .. method:: iterkeys() + keys() + Return an iterator over all keys if called as :meth:`iterkeys` or return a + list of keys if called as :meth:`keys`. -.. method:: Mailbox.iterkeys() - Mailbox.keys() - Return an iterator over all keys if called as :meth:`iterkeys` or return a list - of keys if called as :meth:`keys`. + .. method:: itervalues() + __iter__() + values() + Return an iterator over representations of all messages if called as + :meth:`itervalues` or :meth:`__iter__` or return a list of such + representations if called as :meth:`values`. The messages are represented + as instances of the appropriate format-specific :class:`Message` subclass + unless a custom message factory was specified when the :class:`Mailbox` + instance was initialized. -.. method:: Mailbox.itervalues() - Mailbox.__iter__() - Mailbox.values() + .. note:: - Return an iterator over representations of all messages if called as - :meth:`itervalues` or :meth:`__iter__` or return a list of such representations - if called as :meth:`values`. The messages are represented as instances of the - appropriate format-specific :class:`Message` subclass unless a custom message - factory was specified when the :class:`Mailbox` instance was initialized. + The behavior of :meth:`__iter__` is unlike that of dictionaries, which + iterate over keys. - .. note:: - The behavior of :meth:`__iter__` is unlike that of dictionaries, which iterate - over keys. + .. method:: iteritems() + items() + Return an iterator over (*key*, *message*) pairs, where *key* is a key and + *message* is a message representation, if called as :meth:`iteritems` or + return a list of such pairs if called as :meth:`items`. The messages are + represented as instances of the appropriate format-specific + :class:`Message` subclass unless a custom message factory was specified + when the :class:`Mailbox` instance was initialized. -.. method:: Mailbox.iteritems() - Mailbox.items() - Return an iterator over (*key*, *message*) pairs, where *key* is a key and - *message* is a message representation, if called as :meth:`iteritems` or return - a list of such pairs if called as :meth:`items`. The messages are represented as - instances of the appropriate format-specific :class:`Message` subclass unless a - custom message factory was specified when the :class:`Mailbox` instance was - initialized. + .. method:: get(key[, default=None]) + __getitem__(key) + Return a representation of the message corresponding to *key*. If no such + message exists, *default* is returned if the method was called as + :meth:`get` and a :exc:`KeyError` exception is raised if the method was + called as :meth:`__getitem__`. The message is represented as an instance + of the appropriate format-specific :class:`Message` subclass unless a + custom message factory was specified when the :class:`Mailbox` instance + was initialized. -.. method:: Mailbox.get(key[, default=None]) - Mailbox.__getitem__(key) - Return a representation of the message corresponding to *key*. If no such - message exists, *default* is returned if the method was called as :meth:`get` - and a :exc:`KeyError` exception is raised if the method was called as - :meth:`__getitem__`. The message is represented as an instance of the - appropriate format-specific :class:`Message` subclass unless a custom message - factory was specified when the :class:`Mailbox` instance was initialized. + .. method:: get_message(key) + Return a representation of the message corresponding to *key* as an + instance of the appropriate format-specific :class:`Message` subclass, or + raise a :exc:`KeyError` exception if no such message exists. -.. method:: Mailbox.get_message(key) - Return a representation of the message corresponding to *key* as an instance of - the appropriate format-specific :class:`Message` subclass, or raise a - :exc:`KeyError` exception if no such message exists. + .. method:: get_string(key) + Return a string representation of the message corresponding to *key*, or + raise a :exc:`KeyError` exception if no such message exists. -.. method:: Mailbox.get_string(key) - Return a string representation of the message corresponding to *key*, or raise a - :exc:`KeyError` exception if no such message exists. + .. method:: get_file(key) + Return a file-like representation of the message corresponding to *key*, + or raise a :exc:`KeyError` exception if no such message exists. The + file-like object behaves as if open in binary mode. This file should be + closed once it is no longer needed. -.. method:: Mailbox.get_file(key) + .. note:: - Return a file-like representation of the message corresponding to *key*, or - raise a :exc:`KeyError` exception if no such message exists. The file-like - object behaves as if open in binary mode. This file should be closed once it is - no longer needed. + Unlike other representations of messages, file-like representations are + not necessarily independent of the :class:`Mailbox` instance that + created them or of the underlying mailbox. More specific documentation + is provided by each subclass. - .. note:: - Unlike other representations of messages, file-like representations are not - necessarily independent of the :class:`Mailbox` instance that created them or of - the underlying mailbox. More specific documentation is provided by each - subclass. + .. method:: __contains__(key) + Return ``True`` if *key* corresponds to a message, ``False`` otherwise. -.. method:: Mailbox.__contains__(key) - Return ``True`` if *key* corresponds to a message, ``False`` otherwise. + .. method:: __len__() + Return a count of messages in the mailbox. -.. method:: Mailbox.__len__() - Return a count of messages in the mailbox. + .. method:: clear() + Delete all messages from the mailbox. -.. method:: Mailbox.clear() - Delete all messages from the mailbox. + .. method:: pop(key[, default]) + Return a representation of the message corresponding to *key* and delete + the message. If no such message exists, return *default* if it was + supplied or else raise a :exc:`KeyError` exception. The message is + represented as an instance of the appropriate format-specific + :class:`Message` subclass unless a custom message factory was specified + when the :class:`Mailbox` instance was initialized. -.. method:: Mailbox.pop(key[, default]) - Return a representation of the message corresponding to *key* and delete the - message. If no such message exists, return *default* if it was supplied or else - raise a :exc:`KeyError` exception. The message is represented as an instance of - the appropriate format-specific :class:`Message` subclass unless a custom - message factory was specified when the :class:`Mailbox` instance was - initialized. + .. method:: popitem() + Return an arbitrary (*key*, *message*) pair, where *key* is a key and + *message* is a message representation, and delete the corresponding + message. If the mailbox is empty, raise a :exc:`KeyError` exception. The + message is represented as an instance of the appropriate format-specific + :class:`Message` subclass unless a custom message factory was specified + when the :class:`Mailbox` instance was initialized. -.. method:: Mailbox.popitem() - Return an arbitrary (*key*, *message*) pair, where *key* is a key and *message* - is a message representation, and delete the corresponding message. If the - mailbox is empty, raise a :exc:`KeyError` exception. The message is represented - as an instance of the appropriate format-specific :class:`Message` subclass - unless a custom message factory was specified when the :class:`Mailbox` instance - was initialized. + .. method:: update(arg) + Parameter *arg* should be a *key*-to-*message* mapping or an iterable of + (*key*, *message*) pairs. Updates the mailbox so that, for each given + *key* and *message*, the message corresponding to *key* is set to + *message* as if by using :meth:`__setitem__`. As with :meth:`__setitem__`, + each *key* must already correspond to a message in the mailbox or else a + :exc:`KeyError` exception will be raised, so in general it is incorrect + for *arg* to be a :class:`Mailbox` instance. -.. method:: Mailbox.update(arg) + .. note:: - Parameter *arg* should be a *key*-to-*message* mapping or an iterable of (*key*, - *message*) pairs. Updates the mailbox so that, for each given *key* and - *message*, the message corresponding to *key* is set to *message* as if by using - :meth:`__setitem__`. As with :meth:`__setitem__`, each *key* must already - correspond to a message in the mailbox or else a :exc:`KeyError` exception will - be raised, so in general it is incorrect for *arg* to be a :class:`Mailbox` - instance. + Unlike with dictionaries, keyword arguments are not supported. - .. note:: - Unlike with dictionaries, keyword arguments are not supported. + .. method:: flush() + Write any pending changes to the filesystem. For some :class:`Mailbox` + subclasses, changes are always written immediately and :meth:`flush` does + nothing, but you should still make a habit of calling this method. -.. method:: Mailbox.flush() - Write any pending changes to the filesystem. For some :class:`Mailbox` - subclasses, changes are always written immediately and :meth:`flush` does - nothing, but you should still make a habit of calling this method. + .. method:: lock() + Acquire an exclusive advisory lock on the mailbox so that other processes + know not to modify it. An :exc:`ExternalClashError` is raised if the lock + is not available. The particular locking mechanisms used depend upon the + mailbox format. You should *always* lock the mailbox before making any + modifications to its contents. -.. method:: Mailbox.lock() - Acquire an exclusive advisory lock on the mailbox so that other processes know - not to modify it. An :exc:`ExternalClashError` is raised if the lock is not - available. The particular locking mechanisms used depend upon the mailbox - format. You should *always* lock the mailbox before making any modifications - to its contents. + .. method:: unlock() + Release the lock on the mailbox, if any. -.. method:: Mailbox.unlock() - Release the lock on the mailbox, if any. + .. method:: close() - -.. method:: Mailbox.close() - - Flush the mailbox, unlock it if necessary, and close any open files. For some - :class:`Mailbox` subclasses, this method does nothing. + Flush the mailbox, unlock it if necessary, and close any open files. For + some :class:`Mailbox` subclasses, this method does nothing. .. _mailbox-maildir: @@ -285,113 +291,115 @@ instance that behaves like instances of other :class:`Mailbox` subclasses, set *factory* to ``None``. -Maildir is a directory-based mailbox format invented for the qmail mail transfer -agent and now widely supported by other programs. Messages in a Maildir mailbox -are stored in separate files within a common directory structure. This design -allows Maildir mailboxes to be accessed and modified by multiple unrelated -programs without data corruption, so file locking is unnecessary. - -Maildir mailboxes contain three subdirectories, namely: :file:`tmp`, -:file:`new`, and :file:`cur`. Messages are created momentarily in the -:file:`tmp` subdirectory and then moved to the :file:`new` subdirectory to -finalize delivery. A mail user agent may subsequently move the message to the -:file:`cur` subdirectory and store information about the state of the message in -a special "info" section appended to its file name. + Maildir is a directory-based mailbox format invented for the qmail mail + transfer agent and now widely supported by other programs. Messages in a + Maildir mailbox are stored in separate files within a common directory + structure. This design allows Maildir mailboxes to be accessed and modified + by multiple unrelated programs without data corruption, so file locking is + unnecessary. + + Maildir mailboxes contain three subdirectories, namely: :file:`tmp`, + :file:`new`, and :file:`cur`. Messages are created momentarily in the + :file:`tmp` subdirectory and then moved to the :file:`new` subdirectory to + finalize delivery. A mail user agent may subsequently move the message to the + :file:`cur` subdirectory and store information about the state of the message + in a special "info" section appended to its file name. + + Folders of the style introduced by the Courier mail transfer agent are also + supported. Any subdirectory of the main mailbox is considered a folder if + ``'.'`` is the first character in its name. Folder names are represented by + :class:`Maildir` without the leading ``'.'``. Each folder is itself a Maildir + mailbox but should not contain other folders. Instead, a logical nesting is + indicated using ``'.'`` to delimit levels, e.g., "Archived.2005.07". -Folders of the style introduced by the Courier mail transfer agent are also -supported. Any subdirectory of the main mailbox is considered a folder if -``'.'`` is the first character in its name. Folder names are represented by -:class:`Maildir` without the leading ``'.'``. Each folder is itself a Maildir -mailbox but should not contain other folders. Instead, a logical nesting is -indicated using ``'.'`` to delimit levels, e.g., "Archived.2005.07". - -.. note:: + .. note:: - The Maildir specification requires the use of a colon (``':'``) in certain - message file names. However, some operating systems do not permit this character - in file names, If you wish to use a Maildir-like format on such an operating - system, you should specify another character to use instead. The exclamation - point (``'!'``) is a popular choice. For example:: + The Maildir specification requires the use of a colon (``':'``) in certain + message file names. However, some operating systems do not permit this + character in file names, If you wish to use a Maildir-like format on such + an operating system, you should specify another character to use + instead. The exclamation point (``'!'``) is a popular choice. For + example:: - import mailbox - mailbox.Maildir.colon = '!' + import mailbox + mailbox.Maildir.colon = '!' - The :attr:`colon` attribute may also be set on a per-instance basis. + The :attr:`colon` attribute may also be set on a per-instance basis. -:class:`Maildir` instances have all of the methods of :class:`Mailbox` in -addition to the following: + :class:`Maildir` instances have all of the methods of :class:`Mailbox` in + addition to the following: -.. method:: Maildir.list_folders() + .. method:: list_folders() - Return a list of the names of all folders. + Return a list of the names of all folders. -.. method:: Maildir.get_folder(folder) + .. method:: .et_folder(folder) - Return a :class:`Maildir` instance representing the folder whose name is - *folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder does not - exist. + Return a :class:`Maildir` instance representing the folder whose name is + *folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder + does not exist. -.. method:: Maildir.add_folder(folder) + .. method:: add_folder(folder) - Create a folder whose name is *folder* and return a :class:`Maildir` instance - representing it. + Create a folder whose name is *folder* and return a :class:`Maildir` + instance representing it. -.. method:: Maildir.remove_folder(folder) + .. method:: remove_folder(folder) - Delete the folder whose name is *folder*. If the folder contains any messages, a - :exc:`NotEmptyError` exception will be raised and the folder will not be - deleted. + Delete the folder whose name is *folder*. If the folder contains any + messages, a :exc:`NotEmptyError` exception will be raised and the folder + will not be deleted. -.. method:: Maildir.clean() + .. method:: clean() - Delete temporary files from the mailbox that have not been accessed in the last - 36 hours. The Maildir specification says that mail-reading programs should do - this occasionally. + Delete temporary files from the mailbox that have not been accessed in the + last 36 hours. The Maildir specification says that mail-reading programs + should do this occasionally. -Some :class:`Mailbox` methods implemented by :class:`Maildir` deserve special -remarks: + Some :class:`Mailbox` methods implemented by :class:`Maildir` deserve special + remarks: -.. method:: Maildir.add(message) - Maildir.__setitem__(key, message) - Maildir.update(arg) + .. method:: add(message) + __setitem__(key, message) + update(arg) - .. warning:: + .. warning:: - These methods generate unique file names based upon the current process ID. When - using multiple threads, undetected name clashes may occur and cause corruption - of the mailbox unless threads are coordinated to avoid using these methods to - manipulate the same mailbox simultaneously. + These methods generate unique file names based upon the current process + ID. When using multiple threads, undetected name clashes may occur and + cause corruption of the mailbox unless threads are coordinated to avoid + using these methods to manipulate the same mailbox simultaneously. -.. method:: Maildir.flush() + .. method:: flush() - All changes to Maildir mailboxes are immediately applied, so this method does - nothing. + All changes to Maildir mailboxes are immediately applied, so this method + does nothing. -.. method:: Maildir.lock() - Maildir.unlock() + .. method:: lock() + unlock() - Maildir mailboxes do not support (or require) locking, so these methods do - nothing. + Maildir mailboxes do not support (or require) locking, so these methods do + nothing. -.. method:: Maildir.close() + .. method:: close() - :class:`Maildir` instances do not keep any open files and the underlying - mailboxes do not support locking, so this method does nothing. + :class:`Maildir` instances do not keep any open files and the underlying + mailboxes do not support locking, so this method does nothing. -.. method:: Maildir.get_file(key) + .. method:: get_file(key) - Depending upon the host platform, it may not be possible to modify or remove the - underlying message while the returned file remains open. + Depending upon the host platform, it may not be possible to modify or + remove the underlying message while the returned file remains open. .. seealso:: @@ -423,33 +431,34 @@ representation. If *create* is ``True``, the mailbox is created if it does not exist. -The mbox format is the classic format for storing mail on Unix systems. All -messages in an mbox mailbox are stored in a single file with the beginning of -each message indicated by a line whose first five characters are "From ". + The mbox format is the classic format for storing mail on Unix systems. All + messages in an mbox mailbox are stored in a single file with the beginning of + each message indicated by a line whose first five characters are "From ". -Several variations of the mbox format exist to address perceived shortcomings in -the original. In the interest of compatibility, :class:`mbox` implements the -original format, which is sometimes referred to as :dfn:`mboxo`. This means that -the :mailheader:`Content-Length` header, if present, is ignored and that any -occurrences of "From " at the beginning of a line in a message body are -transformed to ">From " when storing the message, although occurrences of ">From -" are not transformed to "From " when reading the message. + Several variations of the mbox format exist to address perceived shortcomings in + the original. In the interest of compatibility, :class:`mbox` implements the + original format, which is sometimes referred to as :dfn:`mboxo`. This means that + the :mailheader:`Content-Length` header, if present, is ignored and that any + occurrences of "From " at the beginning of a line in a message body are + transformed to ">From " when storing the message, although occurrences of ">From + " are not transformed to "From " when reading the message. -Some :class:`Mailbox` methods implemented by :class:`mbox` deserve special -remarks: + Some :class:`Mailbox` methods implemented by :class:`mbox` deserve special + remarks: -.. method:: mbox.get_file(key) + .. method:: get_file(key) - Using the file after calling :meth:`flush` or :meth:`close` on the :class:`mbox` - instance may yield unpredictable results or raise an exception. + Using the file after calling :meth:`flush` or :meth:`close` on the + :class:`mbox` instance may yield unpredictable results or raise an + exception. -.. method:: mbox.lock() - mbox.unlock() + .. method:: lock() + unlock() - Three locking mechanisms are used---dot locking and, if available, the - :cfunc:`flock` and :cfunc:`lockf` system calls. + Three locking mechanisms are used---dot locking and, if available, the + :cfunc:`flock` and :cfunc:`lockf` system calls. .. seealso:: @@ -482,106 +491,109 @@ representation. If *create* is ``True``, the mailbox is created if it does not exist. -MH is a directory-based mailbox format invented for the MH Message Handling -System, a mail user agent. Each message in an MH mailbox resides in its own -file. An MH mailbox may contain other MH mailboxes (called :dfn:`folders`) in -addition to messages. Folders may be nested indefinitely. MH mailboxes also -support :dfn:`sequences`, which are named lists used to logically group messages -without moving them to sub-folders. Sequences are defined in a file called -:file:`.mh_sequences` in each folder. + MH is a directory-based mailbox format invented for the MH Message Handling + System, a mail user agent. Each message in an MH mailbox resides in its own + file. An MH mailbox may contain other MH mailboxes (called :dfn:`folders`) in + addition to messages. Folders may be nested indefinitely. MH mailboxes also + support :dfn:`sequences`, which are named lists used to logically group + messages without moving them to sub-folders. Sequences are defined in a file + called :file:`.mh_sequences` in each folder. -The :class:`MH` class manipulates MH mailboxes, but it does not attempt to -emulate all of :program:`mh`'s behaviors. In particular, it does not modify and -is not affected by the :file:`context` or :file:`.mh_profile` files that are -used by :program:`mh` to store its state and configuration. + The :class:`MH` class manipulates MH mailboxes, but it does not attempt to + emulate all of :program:`mh`'s behaviors. In particular, it does not modify + and is not affected by the :file:`context` or :file:`.mh_profile` files that + are used by :program:`mh` to store its state and configuration. -:class:`MH` instances have all of the methods of :class:`Mailbox` in addition to -the following: + :class:`MH` instances have all of the methods of :class:`Mailbox` in addition + to the following: -.. method:: MH.list_folders() + .. method:: list_folders() - Return a list of the names of all folders. + Return a list of the names of all folders. -.. method:: MH.get_folder(folder) + .. method:: get_folder(folder) - Return an :class:`MH` instance representing the folder whose name is *folder*. A - :exc:`NoSuchMailboxError` exception is raised if the folder does not exist. + Return an :class:`MH` instance representing the folder whose name is + *folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder + does not exist. -.. method:: MH.add_folder(folder) + .. method:: add_folder(folder) - Create a folder whose name is *folder* and return an :class:`MH` instance - representing it. + Create a folder whose name is *folder* and return an :class:`MH` instance + representing it. -.. method:: MH.remove_folder(folder) + .. method:: remove_folder(folder) - Delete the folder whose name is *folder*. If the folder contains any messages, a - :exc:`NotEmptyError` exception will be raised and the folder will not be - deleted. + Delete the folder whose name is *folder*. If the folder contains any + messages, a :exc:`NotEmptyError` exception will be raised and the folder + will not be deleted. -.. method:: MH.get_sequences() + .. method:: get_sequences() - Return a dictionary of sequence names mapped to key lists. If there are no - sequences, the empty dictionary is returned. + Return a dictionary of sequence names mapped to key lists. If there are no + sequences, the empty dictionary is returned. -.. method:: MH.set_sequences(sequences) + .. method:: set_sequences(sequences) - Re-define the sequences that exist in the mailbox based upon *sequences*, a - dictionary of names mapped to key lists, like returned by :meth:`get_sequences`. + Re-define the sequences that exist in the mailbox based upon *sequences*, + a dictionary of names mapped to key lists, like returned by + :meth:`get_sequences`. -.. method:: MH.pack() + .. method:: pack() - Rename messages in the mailbox as necessary to eliminate gaps in numbering. - Entries in the sequences list are updated correspondingly. + Rename messages in the mailbox as necessary to eliminate gaps in + numbering. Entries in the sequences list are updated correspondingly. - .. note:: + .. note:: - Already-issued keys are invalidated by this operation and should not be - subsequently used. + Already-issued keys are invalidated by this operation and should not be + subsequently used. -Some :class:`Mailbox` methods implemented by :class:`MH` deserve special -remarks: + Some :class:`Mailbox` methods implemented by :class:`MH` deserve special + remarks: -.. method:: MH.remove(key) - MH.__delitem__(key) - MH.discard(key) + .. method:: remove(key) + __delitem__(key) + discard(key) - These methods immediately delete the message. The MH convention of marking a - message for deletion by prepending a comma to its name is not used. + These methods immediately delete the message. The MH convention of marking + a message for deletion by prepending a comma to its name is not used. -.. method:: MH.lock() - MH.unlock() + .. method:: lock() + unlock() - Three locking mechanisms are used---dot locking and, if available, the - :cfunc:`flock` and :cfunc:`lockf` system calls. For MH mailboxes, locking the - mailbox means locking the :file:`.mh_sequences` file and, only for the duration - of any operations that affect them, locking individual message files. + Three locking mechanisms are used---dot locking and, if available, the + :cfunc:`flock` and :cfunc:`lockf` system calls. For MH mailboxes, locking + the mailbox means locking the :file:`.mh_sequences` file and, only for the + duration of any operations that affect them, locking individual message + files. -.. method:: MH.get_file(key) + .. method:: get_file(key) - Depending upon the host platform, it may not be possible to remove the - underlying message while the returned file remains open. + Depending upon the host platform, it may not be possible to remove the + underlying message while the returned file remains open. -.. method:: MH.flush() + .. method:: flush() - All changes to MH mailboxes are immediately applied, so this method does - nothing. + All changes to MH mailboxes are immediately applied, so this method does + nothing. -.. method:: MH.close() + .. method:: close() - :class:`MH` instances do not keep any open files, so this method is equivalent - to :meth:`unlock`. + :class:`MH` instances do not keep any open files, so this method is + equivalent to :meth:`unlock`. .. seealso:: @@ -609,54 +621,56 @@ representation. If *create* is ``True``, the mailbox is created if it does not exist. -Babyl is a single-file mailbox format used by the Rmail mail user agent included -with Emacs. The beginning of a message is indicated by a line containing the two -characters Control-Underscore (``'\037'``) and Control-L (``'\014'``). The end -of a message is indicated by the start of the next message or, in the case of -the last message, a line containing a Control-Underscore (``'\037'``) -character. - -Messages in a Babyl mailbox have two sets of headers, original headers and -so-called visible headers. Visible headers are typically a subset of the -original headers that have been reformatted or abridged to be more -attractive. Each message in a Babyl mailbox also has an accompanying list of -:dfn:`labels`, or short strings that record extra information about the message, -and a list of all user-defined labels found in the mailbox is kept in the Babyl -options section. + Babyl is a single-file mailbox format used by the Rmail mail user agent + included with Emacs. The beginning of a message is indicated by a line + containing the two characters Control-Underscore (``'\037'``) and Control-L + (``'\014'``). The end of a message is indicated by the start of the next + message or, in the case of the last message, a line containing a + Control-Underscore (``'\037'``) character. -:class:`Babyl` instances have all of the methods of :class:`Mailbox` in addition -to the following: + Messages in a Babyl mailbox have two sets of headers, original headers and + so-called visible headers. Visible headers are typically a subset of the + original headers that have been reformatted or abridged to be more + attractive. Each message in a Babyl mailbox also has an accompanying list of + :dfn:`labels`, or short strings that record extra information about the + message, and a list of all user-defined labels found in the mailbox is kept + in the Babyl options section. + :class:`Babyl` instances have all of the methods of :class:`Mailbox` in + addition to the following: -.. method:: Babyl.get_labels() - Return a list of the names of all user-defined labels used in the mailbox. + .. method:: get_labels() - .. note:: + Return a list of the names of all user-defined labels used in the mailbox. + + .. note:: - The actual messages are inspected to determine which labels exist in the mailbox - rather than consulting the list of labels in the Babyl options section, but the - Babyl section is updated whenever the mailbox is modified. + The actual messages are inspected to determine which labels exist in + the mailbox rather than consulting the list of labels in the Babyl + options section, but the Babyl section is updated whenever the mailbox + is modified. -Some :class:`Mailbox` methods implemented by :class:`Babyl` deserve special -remarks: + Some :class:`Mailbox` methods implemented by :class:`Babyl` deserve special + remarks: -.. method:: Babyl.get_file(key) + .. method:: get_file(key) - In Babyl mailboxes, the headers of a message are not stored contiguously with - the body of the message. To generate a file-like representation, the headers and - body are copied together into a :class:`StringIO` instance (from the - :mod:`StringIO` module), which has an API identical to that of a file. As a - result, the file-like object is truly independent of the underlying mailbox but - does not save memory compared to a string representation. + In Babyl mailboxes, the headers of a message are not stored contiguously + with the body of the message. To generate a file-like representation, the + headers and body are copied together into a :class:`StringIO` instance + (from the :mod:`StringIO` module), which has an API identical to that of a + file. As a result, the file-like object is truly independent of the + underlying mailbox but does not save memory compared to a string + representation. -.. method:: Babyl.lock() - Babyl.unlock() + .. method:: lock() + unlock() - Three locking mechanisms are used---dot locking and, if available, the - :cfunc:`flock` and :cfunc:`lockf` system calls. + Three locking mechanisms are used---dot locking and, if available, the + :cfunc:`flock` and :cfunc:`lockf` system calls. .. seealso:: @@ -683,30 +697,31 @@ representation. If *create* is ``True``, the mailbox is created if it does not exist. -MMDF is a single-file mailbox format invented for the Multichannel Memorandum -Distribution Facility, a mail transfer agent. Each message is in the same form -as an mbox message but is bracketed before and after by lines containing four -Control-A (``'\001'``) characters. As with the mbox format, the beginning of -each message is indicated by a line whose first five characters are "From ", but -additional occurrences of "From " are not transformed to ">From " when storing -messages because the extra message separator lines prevent mistaking such -occurrences for the starts of subsequent messages. + MMDF is a single-file mailbox format invented for the Multichannel Memorandum + Distribution Facility, a mail transfer agent. Each message is in the same + form as an mbox message but is bracketed before and after by lines containing + four Control-A (``'\001'``) characters. As with the mbox format, the + beginning of each message is indicated by a line whose first five characters + are "From ", but additional occurrences of "From " are not transformed to + ">From " when storing messages because the extra message separator lines + prevent mistaking such occurrences for the starts of subsequent messages. -Some :class:`Mailbox` methods implemented by :class:`MMDF` deserve special -remarks: + Some :class:`Mailbox` methods implemented by :class:`MMDF` deserve special + remarks: -.. method:: MMDF.get_file(key) + .. method:: get_file(key) - Using the file after calling :meth:`flush` or :meth:`close` on the :class:`MMDF` - instance may yield unpredictable results or raise an exception. + Using the file after calling :meth:`flush` or :meth:`close` on the + :class:`MMDF` instance may yield unpredictable results or raise an + exception. -.. method:: MMDF.lock() - MMDF.unlock() + .. method:: lock() + unlock() - Three locking mechanisms are used---dot locking and, if available, the - :cfunc:`flock` and :cfunc:`lockf` system calls. + Three locking mechanisms are used---dot locking and, if available, the + :cfunc:`flock` and :cfunc:`lockf` system calls. .. seealso:: @@ -737,21 +752,21 @@ or a file, it should contain an :rfc:`2822`\ -compliant message, which is read and parsed. -The format-specific state and behaviors offered by subclasses vary, but in -general it is only the properties that are not specific to a particular mailbox -that are supported (although presumably the properties are specific to a -particular mailbox format). For example, file offsets for single-file mailbox -formats and file names for directory-based mailbox formats are not retained, -because they are only applicable to the original mailbox. But state such as -whether a message has been read by the user or marked as important is retained, -because it applies to the message itself. - -There is no requirement that :class:`Message` instances be used to represent -messages retrieved using :class:`Mailbox` instances. In some situations, the -time and memory required to generate :class:`Message` representations might not -not acceptable. For such situations, :class:`Mailbox` instances also offer -string and file-like representations, and a custom message factory may be -specified when a :class:`Mailbox` instance is initialized. + The format-specific state and behaviors offered by subclasses vary, but in + general it is only the properties that are not specific to a particular + mailbox that are supported (although presumably the properties are specific + to a particular mailbox format). For example, file offsets for single-file + mailbox formats and file names for directory-based mailbox formats are not + retained, because they are only applicable to the original mailbox. But state + such as whether a message has been read by the user or marked as important is + retained, because it applies to the message itself. + + There is no requirement that :class:`Message` instances be used to represent + messages retrieved using :class:`Mailbox` instances. In some situations, the + time and memory required to generate :class:`Message` representations might + not not acceptable. For such situations, :class:`Mailbox` instances also + offer string and file-like representations, and a custom message factory may + be specified when a :class:`Mailbox` instance is initialized. .. _mailbox-maildirmessage: @@ -765,106 +780,109 @@ A message with Maildir-specific behaviors. Parameter *message* has the same meaning as with the :class:`Message` constructor. -Typically, a mail user agent application moves all of the messages in the -:file:`new` subdirectory to the :file:`cur` subdirectory after the first time -the user opens and closes the mailbox, recording that the messages are old -whether or not they've actually been read. Each message in :file:`cur` has an -"info" section added to its file name to store information about its state. -(Some mail readers may also add an "info" section to messages in :file:`new`.) -The "info" section may take one of two forms: it may contain "2," followed by a -list of standardized flags (e.g., "2,FR") or it may contain "1," followed by -so-called experimental information. Standard flags for Maildir messages are as -follows: - -+------+---------+--------------------------------+ -| Flag | Meaning | Explanation | -+======+=========+================================+ -| D | Draft | Under composition | -+------+---------+--------------------------------+ -| F | Flagged | Marked as important | -+------+---------+--------------------------------+ -| P | Passed | Forwarded, resent, or bounced | -+------+---------+--------------------------------+ -| R | Replied | Replied to | -+------+---------+--------------------------------+ -| S | Seen | Read | -+------+---------+--------------------------------+ -| T | Trashed | Marked for subsequent deletion | -+------+---------+--------------------------------+ - -:class:`MaildirMessage` instances offer the following methods: - - -.. method:: MaildirMessage.get_subdir() - - Return either "new" (if the message should be stored in the :file:`new` - subdirectory) or "cur" (if the message should be stored in the :file:`cur` - subdirectory). + Typically, a mail user agent application moves all of the messages in the + :file:`new` subdirectory to the :file:`cur` subdirectory after the first time + the user opens and closes the mailbox, recording that the messages are old + whether or not they've actually been read. Each message in :file:`cur` has an + "info" section added to its file name to store information about its state. + (Some mail readers may also add an "info" section to messages in + :file:`new`.) The "info" section may take one of two forms: it may contain + "2," followed by a list of standardized flags (e.g., "2,FR") or it may + contain "1," followed by so-called experimental information. Standard flags + for Maildir messages are as follows: - .. note:: + +------+---------+--------------------------------+ + | Flag | Meaning | Explanation | + +======+=========+================================+ + | D | Draft | Under composition | + +------+---------+--------------------------------+ + | F | Flagged | Marked as important | + +------+---------+--------------------------------+ + | P | Passed | Forwarded, resent, or bounced | + +------+---------+--------------------------------+ + | R | Replied | Replied to | + +------+---------+--------------------------------+ + | S | Seen | Read | + +------+---------+--------------------------------+ + | T | Trashed | Marked for subsequent deletion | + +------+---------+--------------------------------+ + + :class:`MaildirMessage` instances offer the following methods: + + + .. method:: get_subdir() + + Return either "new" (if the message should be stored in the :file:`new` + subdirectory) or "cur" (if the message should be stored in the :file:`cur` + subdirectory). + + .. note:: - A message is typically moved from :file:`new` to :file:`cur` after its mailbox - has been accessed, whether or not the message is has been read. A message - ``msg`` has been read if ``"S" in msg.get_flags()`` is ``True``. + A message is typically moved from :file:`new` to :file:`cur` after its + mailbox has been accessed, whether or not the message is has been + read. A message ``msg`` has been read if ``"S" in msg.get_flags()`` is + ``True``. -.. method:: MaildirMessage.set_subdir(subdir) + .. method:: set_subdir(subdir) - Set the subdirectory the message should be stored in. Parameter *subdir* must be - either "new" or "cur". + Set the subdirectory the message should be stored in. Parameter *subdir* + must be either "new" or "cur". -.. method:: MaildirMessage.get_flags() + .. method:: get_flags() - Return a string specifying the flags that are currently set. If the message - complies with the standard Maildir format, the result is the concatenation in - alphabetical order of zero or one occurrence of each of ``'D'``, ``'F'``, - ``'P'``, ``'R'``, ``'S'``, and ``'T'``. The empty string is returned if no flags - are set or if "info" contains experimental semantics. + Return a string specifying the flags that are currently set. If the + message complies with the standard Maildir format, the result is the + concatenation in alphabetical order of zero or one occurrence of each of + ``'D'``, ``'F'``, ``'P'``, ``'R'``, ``'S'``, and ``'T'``. The empty string + is returned if no flags are set or if "info" contains experimental + semantics. -.. method:: MaildirMessage.set_flags(flags) + .. method:: set_flags(flags) - Set the flags specified by *flags* and unset all others. + Set the flags specified by *flags* and unset all others. -.. method:: MaildirMessage.add_flag(flag) + .. method:: add_flag(flag) - Set the flag(s) specified by *flag* without changing other flags. To add more - than one flag at a time, *flag* may be a string of more than one character. The - current "info" is overwritten whether or not it contains experimental - information rather than flags. + Set the flag(s) specified by *flag* without changing other flags. To add + more than one flag at a time, *flag* may be a string of more than one + character. The current "info" is overwritten whether or not it contains + experimental information rather than flags. -.. method:: MaildirMessage.remove_flag(flag) + .. method:: remove_flag(flag) - Unset the flag(s) specified by *flag* without changing other flags. To remove - more than one flag at a time, *flag* maybe a string of more than one character. - If "info" contains experimental information rather than flags, the current - "info" is not modified. + Unset the flag(s) specified by *flag* without changing other flags. To + remove more than one flag at a time, *flag* maybe a string of more than + one character. If "info" contains experimental information rather than + flags, the current "info" is not modified. -.. method:: MaildirMessage.get_date() + .. method:: get_date() - Return the delivery date of the message as a floating-point number representing - seconds since the epoch. + Return the delivery date of the message as a floating-point number + representing seconds since the epoch. -.. method:: MaildirMessage.set_date(date) + .. method:: set_date(date) - Set the delivery date of the message to *date*, a floating-point number - representing seconds since the epoch. + Set the delivery date of the message to *date*, a floating-point number + representing seconds since the epoch. -.. method:: MaildirMessage.get_info() + .. method:: get_info() - Return a string containing the "info" for a message. This is useful for - accessing and modifying "info" that is experimental (i.e., not a list of flags). + Return a string containing the "info" for a message. This is useful for + accessing and modifying "info" that is experimental (i.e., not a list of + flags). -.. method:: MaildirMessage.set_info(info) + .. method:: set_info(info) - Set "info" to *info*, which should be a string. + Set "info" to *info*, which should be a string. When a :class:`MaildirMessage` instance is created based upon an :class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status` @@ -930,78 +948,81 @@ A message with mbox-specific behaviors. Parameter *message* has the same meaning as with the :class:`Message` constructor. -Messages in an mbox mailbox are stored together in a single file. The sender's -envelope address and the time of delivery are typically stored in a line -beginning with "From " that is used to indicate the start of a message, though -there is considerable variation in the exact format of this data among mbox -implementations. Flags that indicate the state of the message, such as whether -it has been read or marked as important, are typically stored in -:mailheader:`Status` and :mailheader:`X-Status` headers. + Messages in an mbox mailbox are stored together in a single file. The + sender's envelope address and the time of delivery are typically stored in a + line beginning with "From " that is used to indicate the start of a message, + though there is considerable variation in the exact format of this data among + mbox implementations. Flags that indicate the state of the message, such as + whether it has been read or marked as important, are typically stored in + :mailheader:`Status` and :mailheader:`X-Status` headers. -Conventional flags for mbox messages are as follows: + Conventional flags for mbox messages are as follows: -+------+----------+--------------------------------+ -| Flag | Meaning | Explanation | -+======+==========+================================+ -| R | Read | Read | -+------+----------+--------------------------------+ -| O | Old | Previously detected by MUA | -+------+----------+--------------------------------+ -| D | Deleted | Marked for subsequent deletion | -+------+----------+--------------------------------+ -| F | Flagged | Marked as important | -+------+----------+--------------------------------+ -| A | Answered | Replied to | -+------+----------+--------------------------------+ + +------+----------+--------------------------------+ + | Flag | Meaning | Explanation | + +======+==========+================================+ + | R | Read | Read | + +------+----------+--------------------------------+ + | O | Old | Previously detected by MUA | + +------+----------+--------------------------------+ + | D | Deleted | Marked for subsequent deletion | + +------+----------+--------------------------------+ + | F | Flagged | Marked as important | + +------+----------+--------------------------------+ + | A | Answered | Replied to | + +------+----------+--------------------------------+ -The "R" and "O" flags are stored in the :mailheader:`Status` header, and the -"D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The -flags and headers typically appear in the order mentioned. + The "R" and "O" flags are stored in the :mailheader:`Status` header, and the + "D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The + flags and headers typically appear in the order mentioned. -:class:`mboxMessage` instances offer the following methods: + :class:`mboxMessage` instances offer the following methods: -.. method:: mboxMessage.get_from() + .. method:: get_from() - Return a string representing the "From " line that marks the start of the - message in an mbox mailbox. The leading "From " and the trailing newline are - excluded. + Return a string representing the "From " line that marks the start of the + message in an mbox mailbox. The leading "From " and the trailing newline + are excluded. -.. method:: mboxMessage.set_from(from_[, time_=None]) + .. method:: set_from(from_[, time_=None]) - Set the "From " line to *from_*, which should be specified without a leading - "From " or trailing newline. For convenience, *time_* may be specified and will - be formatted appropriately and appended to *from_*. If *time_* is specified, it - should be a :class:`struct_time` instance, a tuple suitable for passing to - :meth:`time.strftime`, or ``True`` (to use :meth:`time.gmtime`). + Set the "From " line to *from_*, which should be specified without a + leading "From " or trailing newline. For convenience, *time_* may be + specified and will be formatted appropriately and appended to *from_*. If + *time_* is specified, it should be a :class:`struct_time` instance, a + tuple suitable for passing to :meth:`time.strftime`, or ``True`` (to use + :meth:`time.gmtime`). -.. method:: mboxMessage.get_flags() + .. method:: get_flags() - Return a string specifying the flags that are currently set. If the message - complies with the conventional format, the result is the concatenation in the - following order of zero or one occurrence of each of ``'R'``, ``'O'``, ``'D'``, - ``'F'``, and ``'A'``. + Return a string specifying the flags that are currently set. If the + message complies with the conventional format, the result is the + concatenation in the following order of zero or one occurrence of each of + ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. -.. method:: mboxMessage.set_flags(flags) + .. method:: set_flags(flags) - Set the flags specified by *flags* and unset all others. Parameter *flags* - should be the concatenation in any order of zero or more occurrences of each of - ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. + Set the flags specified by *flags* and unset all others. Parameter *flags* + should be the concatenation in any order of zero or more occurrences of + each of ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. -.. method:: mboxMessage.add_flag(flag) + .. method:: add_flag(flag) - Set the flag(s) specified by *flag* without changing other flags. To add more - than one flag at a time, *flag* may be a string of more than one character. + Set the flag(s) specified by *flag* without changing other flags. To add + more than one flag at a time, *flag* may be a string of more than one + character. -.. method:: mboxMessage.remove_flag(flag) + .. method:: remove_flag(flag) - Unset the flag(s) specified by *flag* without changing other flags. To remove - more than one flag at a time, *flag* maybe a string of more than one character. + Unset the flag(s) specified by *flag* without changing other flags. To + remove more than one flag at a time, *flag* maybe a string of more than + one character. When an :class:`mboxMessage` instance is created based upon a :class:`MaildirMessage` instance, a "From " line is generated based upon the @@ -1081,43 +1102,43 @@ A message with MH-specific behaviors. Parameter *message* has the same meaning as with the :class:`Message` constructor. -MH messages do not support marks or flags in the traditional sense, but they do -support sequences, which are logical groupings of arbitrary messages. Some mail -reading programs (although not the standard :program:`mh` and :program:`nmh`) -use sequences in much the same way flags are used with other formats, as -follows: + MH messages do not support marks or flags in the traditional sense, but they + do support sequences, which are logical groupings of arbitrary messages. Some + mail reading programs (although not the standard :program:`mh` and + :program:`nmh`) use sequences in much the same way flags are used with other + formats, as follows: -+----------+------------------------------------------+ -| Sequence | Explanation | -+==========+==========================================+ -| unseen | Not read, but previously detected by MUA | -+----------+------------------------------------------+ -| replied | Replied to | -+----------+------------------------------------------+ -| flagged | Marked as important | -+----------+------------------------------------------+ + +----------+------------------------------------------+ + | Sequence | Explanation | + +==========+==========================================+ + | unseen | Not read, but previously detected by MUA | + +----------+------------------------------------------+ + | replied | Replied to | + +----------+------------------------------------------+ + | flagged | Marked as important | + +----------+------------------------------------------+ -:class:`MHMessage` instances offer the following methods: + :class:`MHMessage` instances offer the following methods: -.. method:: MHMessage.get_sequences() + .. method:: get_sequences() - Return a list of the names of sequences that include this message. + Return a list of the names of sequences that include this message. -.. method:: MHMessage.set_sequences(sequences) + .. method:: set_sequences(sequences) - Set the list of sequences that include this message. + Set the list of sequences that include this message. -.. method:: MHMessage.add_sequence(sequence) + .. method:: add_sequence(sequence) - Add *sequence* to the list of sequences that include this message. + Add *sequence* to the list of sequences that include this message. -.. method:: MHMessage.remove_sequence(sequence) + .. method:: remove_sequence(sequence) - Remove *sequence* from the list of sequences that include this message. + Remove *sequence* from the list of sequences that include this message. When an :class:`MHMessage` instance is created based upon a :class:`MaildirMessage` instance, the following conversions take place: @@ -1171,79 +1192,79 @@ A message with Babyl-specific behaviors. Parameter *message* has the same meaning as with the :class:`Message` constructor. -Certain message labels, called :dfn:`attributes`, are defined by convention to -have special meanings. The attributes are as follows: + Certain message labels, called :dfn:`attributes`, are defined by convention + to have special meanings. The attributes are as follows: -+-----------+------------------------------------------+ -| Label | Explanation | -+===========+==========================================+ -| unseen | Not read, but previously detected by MUA | -+-----------+------------------------------------------+ -| deleted | Marked for subsequent deletion | -+-----------+------------------------------------------+ -| filed | Copied to another file or mailbox | -+-----------+------------------------------------------+ -| answered | Replied to | -+-----------+------------------------------------------+ -| forwarded | Forwarded | -+-----------+------------------------------------------+ -| edited | Modified by the user | -+-----------+------------------------------------------+ -| resent | Resent | -+-----------+------------------------------------------+ + +-----------+------------------------------------------+ + | Label | Explanation | + +===========+==========================================+ + | unseen | Not read, but previously detected by MUA | + +-----------+------------------------------------------+ + | deleted | Marked for subsequent deletion | + +-----------+------------------------------------------+ + | filed | Copied to another file or mailbox | + +-----------+------------------------------------------+ + | answered | Replied to | + +-----------+------------------------------------------+ + | forwarded | Forwarded | + +-----------+------------------------------------------+ + | edited | Modified by the user | + +-----------+------------------------------------------+ + | resent | Resent | + +-----------+------------------------------------------+ -By default, Rmail displays only visible headers. The :class:`BabylMessage` -class, though, uses the original headers because they are more complete. Visible -headers may be accessed explicitly if desired. + By default, Rmail displays only visible headers. The :class:`BabylMessage` + class, though, uses the original headers because they are more + complete. Visible headers may be accessed explicitly if desired. -:class:`BabylMessage` instances offer the following methods: + :class:`BabylMessage` instances offer the following methods: -.. method:: BabylMessage.get_labels() + .. method:: get_labels() - Return a list of labels on the message. + Return a list of labels on the message. -.. method:: BabylMessage.set_labels(labels) + .. method:: set_labels(labels) - Set the list of labels on the message to *labels*. + Set the list of labels on the message to *labels*. -.. method:: BabylMessage.add_label(label) + .. method:: add_label(label) - Add *label* to the list of labels on the message. + Add *label* to the list of labels on the message. -.. method:: BabylMessage.remove_label(label) + .. method:: remove_label(label) - Remove *label* from the list of labels on the message. + Remove *label* from the list of labels on the message. -.. method:: BabylMessage.get_visible() + .. method:: get_visible() - Return an :class:`Message` instance whose headers are the message's visible - headers and whose body is empty. + Return an :class:`Message` instance whose headers are the message's + visible headers and whose body is empty. -.. method:: BabylMessage.set_visible(visible) + .. method:: set_visible(visible) - Set the message's visible headers to be the same as the headers in *message*. - Parameter *visible* should be a :class:`Message` instance, an - :class:`email.Message.Message` instance, a string, or a file-like object (which - should be open in text mode). + Set the message's visible headers to be the same as the headers in + *message*. Parameter *visible* should be a :class:`Message` instance, an + :class:`email.Message.Message` instance, a string, or a file-like object + (which should be open in text mode). -.. method:: BabylMessage.update_visible() + .. method:: update_visible() - When a :class:`BabylMessage` instance's original headers are modified, the - visible headers are not automatically modified to correspond. This method - updates the visible headers as follows: each visible header with a corresponding - original header is set to the value of the original header, each visible header - without a corresponding original header is removed, and any of - :mailheader:`Date`, :mailheader:`From`, :mailheader:`Reply-To`, - :mailheader:`To`, :mailheader:`CC`, and :mailheader:`Subject` that are present - in the original headers but not the visible headers are added to the visible - headers. + When a :class:`BabylMessage` instance's original headers are modified, the + visible headers are not automatically modified to correspond. This method + updates the visible headers as follows: each visible header with a + corresponding original header is set to the value of the original header, + each visible header without a corresponding original header is removed, + and any of :mailheader:`Date`, :mailheader:`From`, :mailheader:`Reply-To`, + :mailheader:`To`, :mailheader:`CC`, and :mailheader:`Subject` that are + present in the original headers but not the visible headers are added to + the visible headers. When a :class:`BabylMessage` instance is created based upon a :class:`MaildirMessage` instance, the following conversions take place: @@ -1299,77 +1320,80 @@ A message with MMDF-specific behaviors. Parameter *message* has the same meaning as with the :class:`Message` constructor. -As with message in an mbox mailbox, MMDF messages are stored with the sender's -address and the delivery date in an initial line beginning with "From ". -Likewise, flags that indicate the state of the message are typically stored in -:mailheader:`Status` and :mailheader:`X-Status` headers. + As with message in an mbox mailbox, MMDF messages are stored with the + sender's address and the delivery date in an initial line beginning with + "From ". Likewise, flags that indicate the state of the message are + typically stored in :mailheader:`Status` and :mailheader:`X-Status` headers. -Conventional flags for MMDF messages are identical to those of mbox message and -are as follows: + Conventional flags for MMDF messages are identical to those of mbox message + and are as follows: -+------+----------+--------------------------------+ -| Flag | Meaning | Explanation | -+======+==========+================================+ -| R | Read | Read | -+------+----------+--------------------------------+ -| O | Old | Previously detected by MUA | -+------+----------+--------------------------------+ -| D | Deleted | Marked for subsequent deletion | -+------+----------+--------------------------------+ -| F | Flagged | Marked as important | -+------+----------+--------------------------------+ -| A | Answered | Replied to | -+------+----------+--------------------------------+ + +------+----------+--------------------------------+ + | Flag | Meaning | Explanation | + +======+==========+================================+ + | R | Read | Read | + +------+----------+--------------------------------+ + | O | Old | Previously detected by MUA | + +------+----------+--------------------------------+ + | D | Deleted | Marked for subsequent deletion | + +------+----------+--------------------------------+ + | F | Flagged | Marked as important | + +------+----------+--------------------------------+ + | A | Answered | Replied to | + +------+----------+--------------------------------+ -The "R" and "O" flags are stored in the :mailheader:`Status` header, and the -"D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The -flags and headers typically appear in the order mentioned. + The "R" and "O" flags are stored in the :mailheader:`Status` header, and the + "D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The + flags and headers typically appear in the order mentioned. -:class:`MMDFMessage` instances offer the following methods, which are identical -to those offered by :class:`mboxMessage`: + :class:`MMDFMessage` instances offer the following methods, which are + identical to those offered by :class:`mboxMessage`: -.. method:: MMDFMessage.get_from() + .. method:: get_from() - Return a string representing the "From " line that marks the start of the - message in an mbox mailbox. The leading "From " and the trailing newline are - excluded. + Return a string representing the "From " line that marks the start of the + message in an mbox mailbox. The leading "From " and the trailing newline + are excluded. -.. method:: MMDFMessage.set_from(from_[, time_=None]) + .. method:: set_from(from_[, time_=None]) - Set the "From " line to *from_*, which should be specified without a leading - "From " or trailing newline. For convenience, *time_* may be specified and will - be formatted appropriately and appended to *from_*. If *time_* is specified, it - should be a :class:`struct_time` instance, a tuple suitable for passing to - :meth:`time.strftime`, or ``True`` (to use :meth:`time.gmtime`). + Set the "From " line to *from_*, which should be specified without a + leading "From " or trailing newline. For convenience, *time_* may be + specified and will be formatted appropriately and appended to *from_*. If + *time_* is specified, it should be a :class:`struct_time` instance, a + tuple suitable for passing to :meth:`time.strftime`, or ``True`` (to use + :meth:`time.gmtime`). -.. method:: MMDFMessage.get_flags() + .. method:: get_flags() - Return a string specifying the flags that are currently set. If the message - complies with the conventional format, the result is the concatenation in the - following order of zero or one occurrence of each of ``'R'``, ``'O'``, ``'D'``, - ``'F'``, and ``'A'``. + Return a string specifying the flags that are currently set. If the + message complies with the conventional format, the result is the + concatenation in the following order of zero or one occurrence of each of + ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. -.. method:: MMDFMessage.set_flags(flags) + .. method:: set_flags(flags) - Set the flags specified by *flags* and unset all others. Parameter *flags* - should be the concatenation in any order of zero or more occurrences of each of - ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. + Set the flags specified by *flags* and unset all others. Parameter *flags* + should be the concatenation in any order of zero or more occurrences of + each of ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. -.. method:: MMDFMessage.add_flag(flag) + .. method:: add_flag(flag) - Set the flag(s) specified by *flag* without changing other flags. To add more - than one flag at a time, *flag* may be a string of more than one character. + Set the flag(s) specified by *flag* without changing other flags. To add + more than one flag at a time, *flag* may be a string of more than one + character. -.. method:: MMDFMessage.remove_flag(flag) + .. method:: remove_flag(flag) - Unset the flag(s) specified by *flag* without changing other flags. To remove - more than one flag at a time, *flag* maybe a string of more than one character. + Unset the flag(s) specified by *flag* without changing other flags. To + remove more than one flag at a time, *flag* maybe a string of more than + one character. When an :class:`MMDFMessage` instance is created based upon a :class:`MaildirMessage` instance, a "From " line is generated based upon the @@ -1445,25 +1469,25 @@ The following exception classes are defined in the :mod:`mailbox` module: -.. class:: Error() +.. exception:: Error() The based class for all other module-specific exceptions. -.. class:: NoSuchMailboxError() +.. exception:: NoSuchMailboxError() Raised when a mailbox is expected but is not found, such as when instantiating a :class:`Mailbox` subclass with a path that does not exist (and with the *create* parameter set to ``False``), or when opening a folder that does not exist. -.. class:: NotEmptyErrorError() +.. exception:: NotEmptyErrorError() Raised when a mailbox is not empty but is expected to be, such as when deleting a folder that contains messages. -.. class:: ExternalClashError() +.. exception:: ExternalClashError() Raised when some mailbox-related condition beyond the control of the program causes it to be unable to proceed, such as when failing to acquire a lock that @@ -1471,7 +1495,7 @@ already exists. -.. class:: FormatError() +.. exception:: FormatError() Raised when the data in a file cannot be parsed, such as when an :class:`MH` instance attempts to read a corrupted :file:`.mh_sequences` file. Modified: python/branches/py3k/Doc/library/mmap.rst ============================================================================== --- python/branches/py3k/Doc/library/mmap.rst (original) +++ python/branches/py3k/Doc/library/mmap.rst Fri Apr 25 03:59:09 2008 @@ -131,111 +131,111 @@ map.close() -Memory-mapped file objects support the following methods: + Memory-mapped file objects support the following methods: -.. method:: mmap.close() + .. method:: close() - Close the file. Subsequent calls to other methods of the object will - result in an exception being raised. + Close the file. Subsequent calls to other methods of the object will + result in an exception being raised. -.. method:: mmap.find(string[, start[, end]]) + .. method:: find(string[, start[, end]]) - Returns the lowest index in the object where the substring *string* is - found, such that *string* is contained in the range [*start*, *end*]. - Optional arguments *start* and *end* are interpreted as in slice notation. - Returns ``-1`` on failure. + Returns the lowest index in the object where the substring *string* is + found, such that *string* is contained in the range [*start*, *end*]. + Optional arguments *start* and *end* are interpreted as in slice notation. + Returns ``-1`` on failure. -.. method:: mmap.flush([offset, size]) + .. method:: flush([offset, size]) - Flushes changes made to the in-memory copy of a file back to disk. Without - use of this call there is no guarantee that changes are written back before - the object is destroyed. If *offset* and *size* are specified, only - changes to the given range of bytes will be flushed to disk; otherwise, the - whole extent of the mapping is flushed. + Flushes changes made to the in-memory copy of a file back to disk. Without + use of this call there is no guarantee that changes are written back before + the object is destroyed. If *offset* and *size* are specified, only + changes to the given range of bytes will be flushed to disk; otherwise, the + whole extent of the mapping is flushed. - **(Windows version)** A nonzero value returned indicates success; zero - indicates failure. + **(Windows version)** A nonzero value returned indicates success; zero + indicates failure. - **(Unix version)** A zero value is returned to indicate success. An - exception is raised when the call failed. + **(Unix version)** A zero value is returned to indicate success. An + exception is raised when the call failed. -.. method:: mmap.move(dest, src, count) + .. method:: move(dest, src, count) - Copy the *count* bytes starting at offset *src* to the destination index - *dest*. If the mmap was created with :const:`ACCESS_READ`, then calls to - move will throw a :exc:`TypeError` exception. + Copy the *count* bytes starting at offset *src* to the destination index + *dest*. If the mmap was created with :const:`ACCESS_READ`, then calls to + move will throw a :exc:`TypeError` exception. -.. method:: mmap.read(num) + .. method:: read(num) - Return a string containing up to *num* bytes starting from the current file - position; the file position is updated to point after the bytes that were - returned. + Return a string containing up to *num* bytes starting from the current + file position; the file position is updated to point after the bytes that + were returned. -.. method:: mmap.read_byte() + .. method:: read_byte() - Returns a string of length 1 containing the character at the current file - position, and advances the file position by 1. + Returns a string of length 1 containing the character at the current file + position, and advances the file position by 1. -.. method:: mmap.readline() + .. method:: readline() - Returns a single line, starting at the current file position and up to the - next newline. + Returns a single line, starting at the current file position and up to the + next newline. -.. method:: mmap.resize(newsize) + .. method:: resize(newsize) - Resizes the map and the underlying file, if any. If the mmap was created - with :const:`ACCESS_READ` or :const:`ACCESS_COPY`, resizing the map will - throw a :exc:`TypeError` exception. + Resizes the map and the underlying file, if any. If the mmap was created + with :const:`ACCESS_READ` or :const:`ACCESS_COPY`, resizing the map will + throw a :exc:`TypeError` exception. -.. method:: mmap.rfind(string[, start[, end]]) + .. method:: rfind(string[, start[, end]]) - Returns the highest index in the object where the substring *string* is - found, such that *string* is contained in the range [*start*, *end*]. - Optional arguments *start* and *end* are interpreted as in slice notation. - Returns ``-1`` on failure. + Returns the highest index in the object where the substring *string* is + found, such that *string* is contained in the range [*start*, *end*]. + Optional arguments *start* and *end* are interpreted as in slice notation. + Returns ``-1`` on failure. -.. method:: mmap.seek(pos[, whence]) + .. method:: seek(pos[, whence]) - Set the file's current position. *whence* argument is optional and - defaults to ``os.SEEK_SET`` or ``0`` (absolute file positioning); other - values are ``os.SEEK_CUR`` or ``1`` (seek relative to the current position) - and ``os.SEEK_END`` or ``2`` (seek relative to the file's end). + Set the file's current position. *whence* argument is optional and + defaults to ``os.SEEK_SET`` or ``0`` (absolute file positioning); other + values are ``os.SEEK_CUR`` or ``1`` (seek relative to the current + position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's end). -.. method:: mmap.size() + .. method:: size() - Return the length of the file, which can be larger than the size of the - memory-mapped area. + Return the length of the file, which can be larger than the size of the + memory-mapped area. -.. method:: mmap.tell() + .. method:: tell() - Returns the current position of the file pointer. + Returns the current position of the file pointer. -.. method:: mmap.write(string) + .. method:: write(string) - Write the bytes in *string* into memory at the current position of the file - pointer; the file position is updated to point after the bytes that were - written. If the mmap was created with :const:`ACCESS_READ`, then writing to - it will throw a :exc:`TypeError` exception. + Write the bytes in *string* into memory at the current position of the + file pointer; the file position is updated to point after the bytes that + were written. If the mmap was created with :const:`ACCESS_READ`, then + writing to it will throw a :exc:`TypeError` exception. -.. method:: mmap.write_byte(byte) + .. method:: write_byte(byte) - Write the single-character string *byte* into memory at the current - position of the file pointer; the file position is advanced by ``1``. If - the mmap was created with :const:`ACCESS_READ`, then writing to it will - throw a :exc:`TypeError` exception. + Write the single-character string *byte* into memory at the current + position of the file pointer; the file position is advanced by ``1``. If + the mmap was created with :const:`ACCESS_READ`, then writing to it will + throw a :exc:`TypeError` exception. Modified: python/branches/py3k/Doc/library/modulefinder.rst ============================================================================== --- python/branches/py3k/Doc/library/modulefinder.rst (original) +++ python/branches/py3k/Doc/library/modulefinder.rst Fri Apr 25 03:59:09 2008 @@ -38,19 +38,21 @@ be replaced in module paths. -.. method:: ModuleFinder.report() + .. method:: report() - Print a report to standard output that lists the modules imported by the script - and their paths, as well as modules that are missing or seem to be missing. + Print a report to standard output that lists the modules imported by the + script and their paths, as well as modules that are missing or seem to be + missing. + .. method:: run_script(pathname) -.. method:: ModuleFinder.run_script(pathname) + Analyze the contents of the *pathname* file, which must contain Python + code. - Analyze the contents of the *pathname* file, which must contain Python code. + .. attribute:: modules -.. attribute:: ModuleFinder.modules - - A dictionary mapping module names to modules. See :ref:`modulefinder-example` + A dictionary mapping module names to modules. See + :ref:`modulefinder-example` .. _modulefinder-example: Modified: python/branches/py3k/Doc/library/msilib.rst ============================================================================== --- python/branches/py3k/Doc/library/msilib.rst (original) +++ python/branches/py3k/Doc/library/msilib.rst Fri Apr 25 03:59:09 2008 @@ -318,19 +318,20 @@ *name* is the name of the CAB file in the MSI file. -.. method:: CAB.append(full, file, logical) + .. method:: append(full, file, logical) - Add the file with the pathname *full* to the CAB file, under the name *logical*. - If there is already a file named *logical*, a new file name is created. + Add the file with the pathname *full* to the CAB file, under the name + *logical*. If there is already a file named *logical*, a new file name is + created. - Return the index of the file in the CAB file, and the new name of the file - inside the CAB file. + Return the index of the file in the CAB file, and the new name of the file + inside the CAB file. -.. method:: CAB.commit(database) + .. method:: commit(database) - Generate a CAB file, add it as a stream to the MSI file, put it into the - ``Media`` table, and remove the generated file from the disk. + Generate a CAB file, add it as a stream to the MSI file, put it into the + ``Media`` table, and remove the generated file from the disk. .. _msi-directory: @@ -351,33 +352,33 @@ the default flags that new components get. -.. method:: Directory.start_component([component[, feature[, flags[, keyfile[, uuid]]]]]) + .. method:: start_component([component[, feature[, flags[, keyfile[, uuid]]]]]) - Add an entry to the Component table, and make this component the current - component for this directory. If no component name is given, the directory name - is used. If no *feature* is given, the current feature is used. If no *flags* - are given, the directory's default flags are used. If no *keyfile* is given, the - KeyPath is left null in the Component table. + Add an entry to the Component table, and make this component the current + component for this directory. If no component name is given, the directory + name is used. If no *feature* is given, the current feature is used. If no + *flags* are given, the directory's default flags are used. If no *keyfile* + is given, the KeyPath is left null in the Component table. -.. method:: Directory.add_file(file[, src[, version[, language]]]) + .. method:: add_file(file[, src[, version[, language]]]) - Add a file to the current component of the directory, starting a new one if - there is no current component. By default, the file name in the source and the - file table will be identical. If the *src* file is specified, it is interpreted - relative to the current directory. Optionally, a *version* and a *language* can - be specified for the entry in the File table. + Add a file to the current component of the directory, starting a new one + if there is no current component. By default, the file name in the source + and the file table will be identical. If the *src* file is specified, it + is interpreted relative to the current directory. Optionally, a *version* + and a *language* can be specified for the entry in the File table. -.. method:: Directory.glob(pattern[, exclude]) + .. method:: glob(pattern[, exclude]) - Add a list of files to the current component as specified in the glob pattern. - Individual files can be excluded in the *exclude* list. + Add a list of files to the current component as specified in the glob + pattern. Individual files can be excluded in the *exclude* list. -.. method:: Directory.remove_pyc() + .. method:: remove_pyc() - Remove ``.pyc``/``.pyo`` files on uninstall. + Remove ``.pyc``/``.pyo`` files on uninstall. .. seealso:: @@ -401,11 +402,11 @@ :class:`Directory`. -.. method:: Feature.set_current() + .. method:: set_current() - Make this feature the current feature of :mod:`msilib`. New components are - automatically added to the default feature, unless a feature is explicitly - specified. + Make this feature the current feature of :mod:`msilib`. New components are + automatically added to the default feature, unless a feature is explicitly + specified. .. seealso:: @@ -428,19 +429,19 @@ belongs to, and *name* is the control's name. -.. method:: Control.event(event, argument[, condition=1[, ordering]]) + .. method:: event(event, argument[, condition=1[, ordering]]) - Make an entry into the ``ControlEvent`` table for this control. + Make an entry into the ``ControlEvent`` table for this control. -.. method:: Control.mapping(event, attribute) + .. method:: mapping(event, attribute) - Make an entry into the ``EventMapping`` table for this control. + Make an entry into the ``EventMapping`` table for this control. -.. method:: Control.condition(action, condition) + .. method:: condition(action, condition) - Make an entry into the ``ControlCondition`` table for this control. + Make an entry into the ``ControlCondition`` table for this control. .. class:: RadioButtonGroup(dlg, name, property) @@ -449,11 +450,11 @@ that gets set when a radio button is selected. -.. method:: RadioButtonGroup.add(name, x, y, width, height, text [, value]) + .. method:: add(name, x, y, width, height, text [, value]) - Add a radio button named *name* to the group, at the coordinates *x*, *y*, - *width*, *height*, and with the label *text*. If *value* is omitted, it defaults - to *name*. + Add a radio button named *name* to the group, at the coordinates *x*, *y*, + *width*, *height*, and with the label *text*. If *value* is omitted, it + defaults to *name*. .. class:: Dialog(db, name, x, y, w, h, attr, title, first, default, cancel) @@ -463,42 +464,43 @@ default, and cancel controls. -.. method:: Dialog.control(name, type, x, y, width, height, attributes, property, text, control_next, help) + .. method:: control(name, type, x, y, width, height, attributes, property, text, control_next, help) - Return a new :class:`Control` object. An entry in the ``Control`` table is made - with the specified parameters. + Return a new :class:`Control` object. An entry in the ``Control`` table is + made with the specified parameters. - This is a generic method; for specific types, specialized methods are provided. + This is a generic method; for specific types, specialized methods are + provided. -.. method:: Dialog.text(name, x, y, width, height, attributes, text) + .. method:: text(name, x, y, width, height, attributes, text) - Add and return a ``Text`` control. + Add and return a ``Text`` control. -.. method:: Dialog.bitmap(name, x, y, width, height, text) + .. method:: bitmap(name, x, y, width, height, text) - Add and return a ``Bitmap`` control. + Add and return a ``Bitmap`` control. -.. method:: Dialog.line(name, x, y, width, height) + .. method:: line(name, x, y, width, height) - Add and return a ``Line`` control. + Add and return a ``Line`` control. -.. method:: Dialog.pushbutton(name, x, y, width, height, attributes, text, next_control) + .. method:: pushbutton(name, x, y, width, height, attributes, text, next_control) - Add and return a ``PushButton`` control. + Add and return a ``PushButton`` control. -.. method:: Dialog.radiogroup(name, x, y, width, height, attributes, property, text, next_control) + .. method:: radiogroup(name, x, y, width, height, attributes, property, text, next_control) - Add and return a ``RadioButtonGroup`` control. + Add and return a ``RadioButtonGroup`` control. -.. method:: Dialog.checkbox(name, x, y, width, height, attributes, property, text, next_control) + .. method:: checkbox(name, x, y, width, height, attributes, property, text, next_control) - Add and return a ``CheckBox`` control. + Add and return a ``CheckBox`` control. .. seealso:: Modified: python/branches/py3k/Doc/library/numbers.rst ============================================================================== --- python/branches/py3k/Doc/library/numbers.rst (original) +++ python/branches/py3k/Doc/library/numbers.rst Fri Apr 25 03:59:09 2008 @@ -27,18 +27,18 @@ ``-``, ``*``, ``/``, :func:`abs`, :meth:`conjugate`, ``==``, and ``!=``. All except ``-`` and ``!=`` are abstract. -.. attribute:: Complex.real + .. attribute:: real - Abstract. Retrieves the :class:`Real` component of this number. + Abstract. Retrieves the :class:`Real` component of this number. -.. attribute:: Complex.imag + .. attribute:: imag - Abstract. Retrieves the :class:`Real` component of this number. + Abstract. Retrieves the :class:`Real` component of this number. -.. method:: Complex.conjugate() + .. method:: conjugate() - Abstract. Returns the complex conjugate. For example, ``(1+3j).conjugate() == - (1-3j)``. + Abstract. Returns the complex conjugate. For example, ``(1+3j).conjugate() + == (1-3j)``. .. class:: Real @@ -60,13 +60,13 @@ should be in lowest terms. With these, it provides a default for :func:`float`. -.. attribute:: Rational.numerator + .. attribute:: numerator - Abstract. + Abstract. -.. attribute:: Rational.denominator + .. attribute:: denominator - Abstract. + Abstract. .. class:: Integral Modified: python/branches/py3k/Doc/library/pickle.rst ============================================================================== --- python/branches/py3k/Doc/library/pickle.rst (original) +++ python/branches/py3k/Doc/library/pickle.rst Fri Apr 25 03:59:09 2008 @@ -245,34 +245,34 @@ It can thus be an open file object, a :mod:`StringIO` object, or any other custom object that meets this interface. -:class:`Pickler` objects define one (or two) public methods: + :class:`Pickler` objects define one (or two) public methods: -.. method:: Pickler.dump(obj) + .. method:: dump(obj) - Write a pickled representation of *obj* to the open file object given in the - constructor. Either the binary or ASCII format will be used, depending on the - value of the *protocol* argument passed to the constructor. + Write a pickled representation of *obj* to the open file object given in the + constructor. Either the binary or ASCII format will be used, depending on the + value of the *protocol* argument passed to the constructor. -.. method:: Pickler.clear_memo() + .. method:: clear_memo() - Clears the pickler's "memo". The memo is the data structure that remembers - which objects the pickler has already seen, so that shared or recursive objects - pickled by reference and not by value. This method is useful when re-using - picklers. + Clears the pickler's "memo". The memo is the data structure that remembers + which objects the pickler has already seen, so that shared or recursive objects + pickled by reference and not by value. This method is useful when re-using + picklers. - .. note:: + .. note:: - Prior to Python 2.3, :meth:`clear_memo` was only available on the picklers - created by :mod:`cPickle`. In the :mod:`pickle` module, picklers have an - instance variable called :attr:`memo` which is a Python dictionary. So to clear - the memo for a :mod:`pickle` module pickler, you could do the following:: + Prior to Python 2.3, :meth:`clear_memo` was only available on the picklers + created by :mod:`cPickle`. In the :mod:`pickle` module, picklers have an + instance variable called :attr:`memo` which is a Python dictionary. So to clear + the memo for a :mod:`pickle` module pickler, you could do the following:: - mypickler.memo.clear() + mypickler.memo.clear() - Code that does not need to support older versions of Python should simply use - :meth:`clear_memo`. + Code that does not need to support older versions of Python should simply use + :meth:`clear_memo`. It is possible to make multiple calls to the :meth:`dump` method of the same :class:`Pickler` instance. These must then be matched to the same number of @@ -296,29 +296,30 @@ reading, a :mod:`StringIO` object, or any other custom object that meets this interface. -:class:`Unpickler` objects have one (or two) public methods: + :class:`Unpickler` objects have one (or two) public methods: -.. method:: Unpickler.load() + .. method:: load() - Read a pickled object representation from the open file object given in the - constructor, and return the reconstituted object hierarchy specified therein. + Read a pickled object representation from the open file object given in + the constructor, and return the reconstituted object hierarchy specified + therein. - This method automatically determines whether the data stream was written in - binary mode or not. + This method automatically determines whether the data stream was written + in binary mode or not. -.. method:: Unpickler.noload() + .. method:: noload() - This is just like :meth:`load` except that it doesn't actually create any - objects. This is useful primarily for finding what's called "persistent ids" - that may be referenced in a pickle data stream. See section - :ref:`pickle-protocol` below for more details. + This is just like :meth:`load` except that it doesn't actually create any + objects. This is useful primarily for finding what's called "persistent + ids" that may be referenced in a pickle data stream. See section + :ref:`pickle-protocol` below for more details. - **Note:** the :meth:`noload` method is currently only available on - :class:`Unpickler` objects created with the :mod:`cPickle` module. - :mod:`pickle` module :class:`Unpickler`\ s do not have the :meth:`noload` - method. + **Note:** the :meth:`noload` method is currently only available on + :class:`Unpickler` objects created with the :mod:`cPickle` module. + :mod:`pickle` module :class:`Unpickler`\ s do not have the :meth:`noload` + method. What can be pickled and unpickled? Modified: python/branches/py3k/Doc/library/robotparser.rst ============================================================================== --- python/branches/py3k/Doc/library/robotparser.rst (original) +++ python/branches/py3k/Doc/library/robotparser.rst Fri Apr 25 03:59:09 2008 @@ -25,35 +25,35 @@ single :file:`robots.txt` file. - .. method:: RobotFileParser.set_url(url) + .. method:: set_url(url) Sets the URL referring to a :file:`robots.txt` file. - .. method:: RobotFileParser.read() + .. method:: read() Reads the :file:`robots.txt` URL and feeds it to the parser. - .. method:: RobotFileParser.parse(lines) + .. method:: parse(lines) Parses the lines argument. - .. method:: RobotFileParser.can_fetch(useragent, url) + .. method:: can_fetch(useragent, url) Returns ``True`` if the *useragent* is allowed to fetch the *url* according to the rules contained in the parsed :file:`robots.txt` file. - .. method:: RobotFileParser.mtime() + .. method:: mtime() Returns the time the ``robots.txt`` file was last fetched. This is useful for long-running web spiders that need to check for new ``robots.txt`` files periodically. - .. method:: RobotFileParser.modified() + .. method:: modified() Sets the time the ``robots.txt`` file was last fetched to the current time. Modified: python/branches/py3k/Doc/library/simplehttpserver.rst ============================================================================== --- python/branches/py3k/Doc/library/simplehttpserver.rst (original) +++ python/branches/py3k/Doc/library/simplehttpserver.rst Fri Apr 25 03:59:09 2008 @@ -23,57 +23,59 @@ :class:`BaseHTTPServer.BaseHTTPRequestHandler`. This class implements the :func:`do_GET` and :func:`do_HEAD` functions. -The :class:`SimpleHTTPRequestHandler` defines the following member variables: + The :class:`SimpleHTTPRequestHandler` defines the following member variables: -.. attribute:: SimpleHTTPRequestHandler.server_version + .. attribute:: server_version - This will be ``"SimpleHTTP/" + __version__``, where ``__version__`` is defined - in the module. + This will be ``"SimpleHTTP/" + __version__``, where ``__version__`` is + defined in the module. -.. attribute:: SimpleHTTPRequestHandler.extensions_map + .. attribute:: extensions_map - A dictionary mapping suffixes into MIME types. The default is signified by an - empty string, and is considered to be ``application/octet-stream``. The mapping - is used case-insensitively, and so should contain only lower-cased keys. + A dictionary mapping suffixes into MIME types. The default is signified by + an empty string, and is considered to be ``application/octet-stream``. The + mapping is used case-insensitively, and so should contain only lower-cased + keys. -The :class:`SimpleHTTPRequestHandler` defines the following methods: + The :class:`SimpleHTTPRequestHandler` defines the following methods: -.. method:: SimpleHTTPRequestHandler.do_HEAD() + .. method:: do_HEAD() - This method serves the ``'HEAD'`` request type: it sends the headers it would - send for the equivalent ``GET`` request. See the :meth:`do_GET` method for a - more complete explanation of the possible headers. + This method serves the ``'HEAD'`` request type: it sends the headers it + would send for the equivalent ``GET`` request. See the :meth:`do_GET` + method for a more complete explanation of the possible headers. -.. method:: SimpleHTTPRequestHandler.do_GET() + .. method:: do_GET() - The request is mapped to a local file by interpreting the request as a path - relative to the current working directory. + The request is mapped to a local file by interpreting the request as a + path relative to the current working directory. - If the request was mapped to a directory, the directory is checked for a file - named ``index.html`` or ``index.htm`` (in that order). If found, the file's - contents are returned; otherwise a directory listing is generated by calling the - :meth:`list_directory` method. This method uses :func:`os.listdir` to scan the - directory, and returns a ``404`` error response if the :func:`listdir` fails. + If the request was mapped to a directory, the directory is checked for a + file named ``index.html`` or ``index.htm`` (in that order). If found, the + file's contents are returned; otherwise a directory listing is generated + by calling the :meth:`list_directory` method. This method uses + :func:`os.listdir` to scan the directory, and returns a ``404`` error + response if the :func:`listdir` fails. - If the request was mapped to a file, it is opened and the contents are returned. - Any :exc:`IOError` exception in opening the requested file is mapped to a - ``404``, ``'File not found'`` error. Otherwise, the content type is guessed by - calling the :meth:`guess_type` method, which in turn uses the *extensions_map* - variable. + If the request was mapped to a file, it is opened and the contents are + returned. Any :exc:`IOError` exception in opening the requested file is + mapped to a ``404``, ``'File not found'`` error. Otherwise, the content + type is guessed by calling the :meth:`guess_type` method, which in turn + uses the *extensions_map* variable. - A ``'Content-type:'`` header with the guessed content type is output, followed - by a ``'Content-Length:'`` header with the file's size and a - ``'Last-Modified:'`` header with the file's modification time. + A ``'Content-type:'`` header with the guessed content type is output, + followed by a ``'Content-Length:'`` header with the file's size and a + ``'Last-Modified:'`` header with the file's modification time. - Then follows a blank line signifying the end of the headers, and then the - contents of the file are output. If the file's MIME type starts with ``text/`` - the file is opened in text mode; otherwise binary mode is used. + Then follows a blank line signifying the end of the headers, and then the + contents of the file are output. If the file's MIME type starts with + ``text/`` the file is opened in text mode; otherwise binary mode is used. - For example usage, see the implementation of the :func:`test` function. + For example usage, see the implementation of the :func:`test` function. .. seealso:: Modified: python/branches/py3k/Doc/library/smtpd.rst ============================================================================== --- python/branches/py3k/Doc/library/smtpd.rst (original) +++ python/branches/py3k/Doc/library/smtpd.rst Fri Apr 25 03:59:09 2008 @@ -27,14 +27,15 @@ :mod:`asyncore`'s event loop on instantiation. -.. method:: SMTPServer.process_message(peer, mailfrom, rcpttos, data) + .. method:: process_message(peer, mailfrom, rcpttos, data) - Raise :exc:`NotImplementedError` exception. Override this in subclasses to do - something useful with this message. Whatever was passed in the constructor as - *remoteaddr* will be available as the :attr:`_remoteaddr` attribute. *peer* is - the remote host's address, *mailfrom* is the envelope originator, *rcpttos* are - the envelope recipients and *data* is a string containing the contents of the - e-mail (which should be in :rfc:`2822` format). + Raise :exc:`NotImplementedError` exception. Override this in subclasses to + do something useful with this message. Whatever was passed in the + constructor as *remoteaddr* will be available as the :attr:`_remoteaddr` + attribute. *peer* is the remote host's address, *mailfrom* is the envelope + originator, *rcpttos* are the envelope recipients and *data* is a string + containing the contents of the e-mail (which should be in :rfc:`2822` + format). DebuggingServer Objects Modified: python/branches/py3k/Doc/library/string.rst ============================================================================== --- python/branches/py3k/Doc/library/string.rst (original) +++ python/branches/py3k/Doc/library/string.rst Fri Apr 25 03:59:09 2008 @@ -452,29 +452,29 @@ The constructor takes a single argument which is the template string. -.. method:: Template.substitute(mapping[, **kws]) + .. method:: substitute(mapping[, **kws]) - Performs the template substitution, returning a new string. *mapping* is any - dictionary-like object with keys that match the placeholders in the template. - Alternatively, you can provide keyword arguments, where the keywords are the - placeholders. When both *mapping* and *kws* are given and there are duplicates, - the placeholders from *kws* take precedence. - - -.. method:: Template.safe_substitute(mapping[, **kws]) - - Like :meth:`substitute`, except that if placeholders are missing from *mapping* - and *kws*, instead of raising a :exc:`KeyError` exception, the original - placeholder will appear in the resulting string intact. Also, unlike with - :meth:`substitute`, any other appearances of the ``$`` will simply return ``$`` - instead of raising :exc:`ValueError`. - - While other exceptions may still occur, this method is called "safe" because - substitutions always tries to return a usable string instead of raising an - exception. In another sense, :meth:`safe_substitute` may be anything other than - safe, since it will silently ignore malformed templates containing dangling - delimiters, unmatched braces, or placeholders that are not valid Python - identifiers. + Performs the template substitution, returning a new string. *mapping* is + any dictionary-like object with keys that match the placeholders in the + template. Alternatively, you can provide keyword arguments, where the + keywords are the placeholders. When both *mapping* and *kws* are given + and there are duplicates, the placeholders from *kws* take precedence. + + + .. method:: safe_substitute(mapping[, **kws]) + + Like :meth:`substitute`, except that if placeholders are missing from + *mapping* and *kws*, instead of raising a :exc:`KeyError` exception, the + original placeholder will appear in the resulting string intact. Also, + unlike with :meth:`substitute`, any other appearances of the ``$`` will + simply return ``$`` instead of raising :exc:`ValueError`. + + While other exceptions may still occur, this method is called "safe" + because substitutions always tries to return a usable string instead of + raising an exception. In another sense, :meth:`safe_substitute` may be + anything other than safe, since it will silently ignore malformed + templates containing dangling delimiters, unmatched braces, or + placeholders that are not valid Python identifiers. :class:`Template` instances also provide one public data attribute: Modified: python/branches/py3k/Doc/library/struct.rst ============================================================================== --- python/branches/py3k/Doc/library/struct.rst (original) +++ python/branches/py3k/Doc/library/struct.rst Fri Apr 25 03:59:09 2008 @@ -242,37 +242,37 @@ since the format string only needs to be compiled once. -Compiled Struct objects support the following methods and attributes: + Compiled Struct objects support the following methods and attributes: -.. method:: Struct.pack(v1, v2, ...) + .. method:: pack(v1, v2, ...) - Identical to the :func:`pack` function, using the compiled format. - (``len(result)`` will equal :attr:`self.size`.) + Identical to the :func:`pack` function, using the compiled format. + (``len(result)`` will equal :attr:`self.size`.) -.. method:: Struct.pack_into(buffer, offset, v1, v2, ...) + .. method:: pack_into(buffer, offset, v1, v2, ...) - Identical to the :func:`pack_into` function, using the compiled format. + Identical to the :func:`pack_into` function, using the compiled format. -.. method:: Struct.unpack(string) + .. method:: unpack(string) - Identical to the :func:`unpack` function, using the compiled format. - (``len(string)`` must equal :attr:`self.size`). + Identical to the :func:`unpack` function, using the compiled format. + (``len(string)`` must equal :attr:`self.size`). -.. method:: Struct.unpack_from(buffer[, offset=0]) + .. method:: unpack_from(buffer[, offset=0]) - Identical to the :func:`unpack_from` function, using the compiled format. - (``len(buffer[offset:])`` must be at least :attr:`self.size`). + Identical to the :func:`unpack_from` function, using the compiled format. + (``len(buffer[offset:])`` must be at least :attr:`self.size`). -.. attribute:: Struct.format + .. attribute:: format - The format string used to construct this Struct object. + The format string used to construct this Struct object. -.. attribute:: Struct.size + .. attribute:: size - The calculated size of the struct (and hence of the string) corresponding - to :attr:`format`. + The calculated size of the struct (and hence of the string) corresponding + to :attr:`format`. Modified: python/branches/py3k/Doc/library/textwrap.rst ============================================================================== --- python/branches/py3k/Doc/library/textwrap.rst (original) +++ python/branches/py3k/Doc/library/textwrap.rst Fri Apr 25 03:59:09 2008 @@ -85,103 +85,104 @@ change any of its options through direct assignment to instance attributes between uses. -The :class:`TextWrapper` instance attributes (and keyword arguments to the -constructor) are as follows: + The :class:`TextWrapper` instance attributes (and keyword arguments to the + constructor) are as follows: -.. attribute:: TextWrapper.width + .. attribute:: width - (default: ``70``) The maximum length of wrapped lines. As long as there are no - individual words in the input text longer than :attr:`width`, - :class:`TextWrapper` guarantees that no output line will be longer than - :attr:`width` characters. + (default: ``70``) The maximum length of wrapped lines. As long as there + are no individual words in the input text longer than :attr:`width`, + :class:`TextWrapper` guarantees that no output line will be longer than + :attr:`width` characters. -.. attribute:: TextWrapper.expand_tabs + .. attribute:: expand_tabs - (default: ``True``) If true, then all tab characters in *text* will be expanded - to spaces using the :meth:`expandtabs` method of *text*. + (default: ``True``) If true, then all tab characters in *text* will be + expanded to spaces using the :meth:`expandtabs` method of *text*. -.. attribute:: TextWrapper.replace_whitespace + .. attribute:: replace_whitespace - (default: ``True``) If true, each whitespace character (as defined by - ``string.whitespace``) remaining after tab expansion will be replaced by a - single space. + (default: ``True``) If true, each whitespace character (as defined by + ``string.whitespace``) remaining after tab expansion will be replaced by a + single space. - .. note:: + .. note:: - If :attr:`expand_tabs` is false and :attr:`replace_whitespace` is true, each tab - character will be replaced by a single space, which is *not* the same as tab - expansion. + If :attr:`expand_tabs` is false and :attr:`replace_whitespace` is true, + each tab character will be replaced by a single space, which is *not* + the same as tab expansion. -.. attribute:: TextWrapper.drop_whitespace + .. attribute:: drop_whitespace - (default: ``True``) If true, whitespace that, after wrapping, happens to end up - at the beginning or end of a line is dropped (leading whitespace in the first - line is always preserved, though). + (default: ``True``) If true, whitespace that, after wrapping, happens to + end up at the beginning or end of a line is dropped (leading whitespace in + the first line is always preserved, though). -.. attribute:: TextWrapper.initial_indent + .. attribute:: initial_indent - (default: ``''``) String that will be prepended to the first line of wrapped - output. Counts towards the length of the first line. + (default: ``''``) String that will be prepended to the first line of + wrapped output. Counts towards the length of the first line. -.. attribute:: TextWrapper.subsequent_indent + .. attribute:: subsequent_indent - (default: ``''``) String that will be prepended to all lines of wrapped output - except the first. Counts towards the length of each line except the first. + (default: ``''``) String that will be prepended to all lines of wrapped + output except the first. Counts towards the length of each line except + the first. -.. attribute:: TextWrapper.fix_sentence_endings + .. attribute:: fix_sentence_endings - (default: ``False``) If true, :class:`TextWrapper` attempts to detect sentence - endings and ensure that sentences are always separated by exactly two spaces. - This is generally desired for text in a monospaced font. However, the sentence - detection algorithm is imperfect: it assumes that a sentence ending consists of - a lowercase letter followed by one of ``'.'``, ``'!'``, or ``'?'``, possibly - followed by one of ``'"'`` or ``"'"``, followed by a space. One problem with - this is algorithm is that it is unable to detect the difference between "Dr." in - :: + (default: ``False``) If true, :class:`TextWrapper` attempts to detect + sentence endings and ensure that sentences are always separated by exactly + two spaces. This is generally desired for text in a monospaced font. + However, the sentence detection algorithm is imperfect: it assumes that a + sentence ending consists of a lowercase letter followed by one of ``'.'``, + ``'!'``, or ``'?'``, possibly followed by one of ``'"'`` or ``"'"``, + followed by a space. One problem with this is algorithm is that it is + unable to detect the difference between "Dr." in :: - [...] Dr. Frankenstein's monster [...] + [...] Dr. Frankenstein's monster [...] - and "Spot." in :: + and "Spot." in :: - [...] See Spot. See Spot run [...] + [...] See Spot. See Spot run [...] - :attr:`fix_sentence_endings` is false by default. + :attr:`fix_sentence_endings` is false by default. - Since the sentence detection algorithm relies on ``string.lowercase`` for the - definition of "lowercase letter," and a convention of using two spaces after - a period to separate sentences on the same line, it is specific to - English-language texts. + Since the sentence detection algorithm relies on ``string.lowercase`` for + the definition of "lowercase letter," and a convention of using two spaces + after a period to separate sentences on the same line, it is specific to + English-language texts. -.. attribute:: TextWrapper.break_long_words + .. attribute:: break_long_words - (default: ``True``) If true, then words longer than :attr:`width` will be broken - in order to ensure that no lines are longer than :attr:`width`. If it is false, - long words will not be broken, and some lines may be longer than :attr:`width`. - (Long words will be put on a line by themselves, in order to minimize the amount - by which :attr:`width` is exceeded.) + (default: ``True``) If true, then words longer than :attr:`width` will be + broken in order to ensure that no lines are longer than :attr:`width`. If + it is false, long words will not be broken, and some lines may be longer + than :attr:`width`. (Long words will be put on a line by themselves, in + order to minimize the amount by which :attr:`width` is exceeded.) -:class:`TextWrapper` also provides two public methods, analogous to the -module-level convenience functions: + :class:`TextWrapper` also provides two public methods, analogous to the + module-level convenience functions: -.. method:: TextWrapper.wrap(text) + .. method:: wrap(text) - Wraps the single paragraph in *text* (a string) so every line is at most - :attr:`width` characters long. All wrapping options are taken from instance - attributes of the :class:`TextWrapper` instance. Returns a list of output lines, - without final newlines. + Wraps the single paragraph in *text* (a string) so every line is at most + :attr:`width` characters long. All wrapping options are taken from + instance attributes of the :class:`TextWrapper` instance. Returns a list + of output lines, without final newlines. -.. method:: TextWrapper.fill(text) + .. method:: fill(text) - Wraps the single paragraph in *text*, and returns a single string containing the - wrapped paragraph. + Wraps the single paragraph in *text*, and returns a single string + containing the wrapped paragraph. Modified: python/branches/py3k/Doc/library/xml.etree.elementtree.rst ============================================================================== --- python/branches/py3k/Doc/library/xml.etree.elementtree.rst (original) +++ python/branches/py3k/Doc/library/xml.etree.elementtree.rst Fri Apr 25 03:59:09 2008 @@ -304,61 +304,63 @@ XML *file* if given. -.. method:: ElementTree._setroot(element) + .. method:: _setroot(element) - Replaces the root element for this tree. This discards the current contents of - the tree, and replaces it with the given element. Use with care. *element* is - an element instance. + Replaces the root element for this tree. This discards the current + contents of the tree, and replaces it with the given element. Use with + care. *element* is an element instance. -.. method:: ElementTree.find(path) + .. method:: find(path) - Finds the first toplevel element with given tag. Same as getroot().find(path). - *path* is the element to look for. Returns the first matching element, or - ``None`` if no element was found. + Finds the first toplevel element with given tag. Same as + getroot().find(path). *path* is the element to look for. Returns the + first matching element, or ``None`` if no element was found. -.. method:: ElementTree.findall(path) + .. method:: findall(path) - Finds all toplevel elements with the given tag. Same as getroot().findall(path). - *path* is the element to look for. Returns a list or :term:`iterator` containing all - matching elements, in document order. + Finds all toplevel elements with the given tag. Same as + getroot().findall(path). *path* is the element to look for. Returns a + list or :term:`iterator` containing all matching elements, in document + order. -.. method:: ElementTree.findtext(path[, default]) + .. method:: findtext(path[, default]) - Finds the element text for the first toplevel element with given tag. Same as - getroot().findtext(path). *path* is the toplevel element to look for. *default* - is the value to return if the element was not found. Returns the text content of - the first matching element, or the default value no element was found. Note - that if the element has is found, but has no text content, this method returns - an empty string. + Finds the element text for the first toplevel element with given tag. + Same as getroot().findtext(path). *path* is the toplevel element to look + for. *default* is the value to return if the element was not + found. Returns the text content of the first matching element, or the + default value no element was found. Note that if the element has is + found, but has no text content, this method returns an empty string. -.. method:: ElementTree.getiterator([tag]) + .. method:: getiterator([tag]) - Creates and returns a tree iterator for the root element. The iterator loops - over all elements in this tree, in section order. *tag* is the tag to look for - (default is to return all elements) + Creates and returns a tree iterator for the root element. The iterator + loops over all elements in this tree, in section order. *tag* is the tag + to look for (default is to return all elements) -.. method:: ElementTree.getroot() + .. method:: getroot() - Returns the root element for this tree. + Returns the root element for this tree. -.. method:: ElementTree.parse(source[, parser]) + .. method:: parse(source[, parser]) - Loads an external XML section into this element tree. *source* is a file name or - file object. *parser* is an optional parser instance. If not given, the - standard XMLTreeBuilder parser is used. Returns the section root element. + Loads an external XML section into this element tree. *source* is a file + name or file object. *parser* is an optional parser instance. If not + given, the standard XMLTreeBuilder parser is used. Returns the section + root element. -.. method:: ElementTree.write(file[, encoding]) + .. method:: write(file[, encoding]) - Writes the element tree to a file, as XML. *file* is a file name, or a file - object opened for writing. *encoding* [1]_ is the output encoding (default is - US-ASCII). + Writes the element tree to a file, as XML. *file* is a file name, or a + file object opened for writing. *encoding* [1]_ is the output encoding + (default is US-ASCII). This is the XML file that is going to be manipulated:: @@ -419,28 +421,28 @@ Element instances when given. -.. method:: TreeBuilder.close() + .. method:: close() - Flushes the parser buffers, and returns the toplevel document element. Returns an - Element instance. + Flushes the parser buffers, and returns the toplevel document + element. Returns an Element instance. -.. method:: TreeBuilder.data(data) + .. method:: data(data) - Adds text to the current element. *data* is a string. This should be either an - ASCII-only :class:`bytes` object or a :class:`str` object. + Adds text to the current element. *data* is a string. This should be + either an ASCII-only :class:`bytes` object or a :class:`str` object. -.. method:: TreeBuilder.end(tag) + .. method:: end(tag) - Closes the current element. *tag* is the element name. Returns the closed - element. + Closes the current element. *tag* is the element name. Returns the closed + element. -.. method:: TreeBuilder.start(tag, attrs) + .. method:: start(tag, attrs) - Opens a new element. *tag* is the element name. *attrs* is a dictionary - containing element attributes. Returns the opened element. + Opens a new element. *tag* is the element name. *attrs* is a dictionary + containing element attributes. Returns the opened element. .. _elementtree-xmltreebuilder-objects: @@ -457,20 +459,20 @@ instance of the standard TreeBuilder class. -.. method:: XMLTreeBuilder.close() + .. method:: close() - Finishes feeding data to the parser. Returns an element structure. + Finishes feeding data to the parser. Returns an element structure. -.. method:: XMLTreeBuilder.doctype(name, pubid, system) + .. method:: doctype(name, pubid, system) - Handles a doctype declaration. *name* is the doctype name. *pubid* is the public - identifier. *system* is the system identifier. + Handles a doctype declaration. *name* is the doctype name. *pubid* is the + public identifier. *system* is the system identifier. -.. method:: XMLTreeBuilder.feed(data) + .. method:: feed(data) - Feeds data to the parser. *data* is encoded data. + Feeds data to the parser. *data* is encoded data. :meth:`XMLTreeBuilder.feed` calls *target*\'s :meth:`start` method for each opening tag, its :meth:`end` method for each closing tag, Modified: python/branches/py3k/Doc/library/zipimport.rst ============================================================================== --- python/branches/py3k/Doc/library/zipimport.rst (original) +++ python/branches/py3k/Doc/library/zipimport.rst Fri Apr 25 03:59:09 2008 @@ -70,55 +70,57 @@ (provided that it exists). -.. method:: zipimporter.find_module(fullname[, path]) + .. method:: find_module(fullname[, path]) - Search for a module specified by *fullname*. *fullname* must be the fully - qualified (dotted) module name. It returns the zipimporter instance itself if - the module was found, or :const:`None` if it wasn't. The optional *path* - argument is ignored---it's there for compatibility with the importer protocol. + Search for a module specified by *fullname*. *fullname* must be the fully + qualified (dotted) module name. It returns the zipimporter instance itself + if the module was found, or :const:`None` if it wasn't. The optional + *path* argument is ignored---it's there for compatibility with the + importer protocol. -.. method:: zipimporter.get_code(fullname) + .. method:: get_code(fullname) - Return the code object for the specified module. Raise :exc:`ZipImportError` if - the module couldn't be found. + Return the code object for the specified module. Raise + :exc:`ZipImportError` if the module couldn't be found. -.. method:: zipimporter.get_data(pathname) + .. method:: get_data(pathname) - Return the data associated with *pathname*. Raise :exc:`IOError` if the file - wasn't found. + Return the data associated with *pathname*. Raise :exc:`IOError` if the + file wasn't found. -.. method:: zipimporter.get_source(fullname) + .. method:: get_source(fullname) - Return the source code for the specified module. Raise :exc:`ZipImportError` if - the module couldn't be found, return :const:`None` if the archive does contain - the module, but has no source for it. + Return the source code for the specified module. Raise + :exc:`ZipImportError` if the module couldn't be found, return + :const:`None` if the archive does contain the module, but has no source + for it. -.. method:: zipimporter.is_package(fullname) + .. method:: is_package(fullname) - Return True if the module specified by *fullname* is a package. Raise - :exc:`ZipImportError` if the module couldn't be found. + Return True if the module specified by *fullname* is a package. Raise + :exc:`ZipImportError` if the module couldn't be found. -.. method:: zipimporter.load_module(fullname) + .. method:: load_module(fullname) - Load the module specified by *fullname*. *fullname* must be the fully qualified - (dotted) module name. It returns the imported module, or raises - :exc:`ZipImportError` if it wasn't found. + Load the module specified by *fullname*. *fullname* must be the fully + qualified (dotted) module name. It returns the imported module, or raises + :exc:`ZipImportError` if it wasn't found. -.. attribute:: zipimporter.archive + .. attribute:: archive - The file name of the importer's associated ZIP file. + The file name of the importer's associated ZIP file. -.. attribute:: zipimporter.prefix + .. attribute:: prefix - The path within the ZIP file where modules are searched; see - :class:`zipimporter` for details. + The path within the ZIP file where modules are searched; see + :class:`zipimporter` for details. .. _zipimport-examples: From python-3000-checkins at python.org Fri Apr 25 22:47:52 2008 From: python-3000-checkins at python.org (amaury.forgeotdarc) Date: Fri, 25 Apr 2008 22:47:52 +0200 (CEST) Subject: [Python-3000-checkins] r62505 - python/branches/py3k/Lib/pydoc.py Message-ID: <20080425204752.5091E1E401F@bag.python.org> Author: amaury.forgeotdarc Date: Fri Apr 25 22:47:52 2008 New Revision: 62505 Log: Remove duplicated code in pydoc.py, probably a merge conflict some months ago. Spotted by Humberto Diogenes. Modified: python/branches/py3k/Lib/pydoc.py Modified: python/branches/py3k/Lib/pydoc.py ============================================================================== --- python/branches/py3k/Lib/pydoc.py (original) +++ python/branches/py3k/Lib/pydoc.py Fri Apr 25 22:47:52 2008 @@ -1500,23 +1500,6 @@ def doc(thing, title='Python Library Documentation: %s', forceload=0): """Display text documentation, given an object or a path to an object.""" try: - object, name = resolve(thing, forceload) - desc = describe(object) - module = inspect.getmodule(object) - if name and '.' in name: - desc += ' in ' + name[:name.rfind('.')] - elif module and module is not object: - desc += ' in module ' + module.__name__ - elif not (inspect.ismodule(object) or - inspect.isclass(object) or - inspect.isroutine(object) or - inspect.isgetsetdescriptor(object) or - inspect.ismemberdescriptor(object) or - isinstance(object, property)): - # If the passed object is a piece of data or an instance, - # document its available methods instead of its value. - object = type(object) - desc += ' object' pager(render_doc(thing, title, forceload)) except (ImportError, ErrorDuringImport) as value: print(value) From python-3000-checkins at python.org Fri Apr 25 23:15:37 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Fri, 25 Apr 2008 23:15:37 +0200 (CEST) Subject: [Python-3000-checkins] r62506 - python/branches/py3k/Objects/rangeobject.c Message-ID: <20080425211537.C7F591E4009@bag.python.org> Author: benjamin.peterson Date: Fri Apr 25 23:15:37 2008 New Revision: 62506 Log: #2689 Fix indentation in Objects/rangeobject.c Modified: python/branches/py3k/Objects/rangeobject.c Modified: python/branches/py3k/Objects/rangeobject.c ============================================================================== --- python/branches/py3k/Objects/rangeobject.c (original) +++ python/branches/py3k/Objects/rangeobject.c Fri Apr 25 23:15:37 2008 @@ -216,8 +216,8 @@ if (!PyErr_Occurred()) PyErr_SetString(PyExc_IndexError, "range object index out of range"); - return NULL; - } + return NULL; + } /* XXX(nnorwitz): optimize for short ints. */ rem = PyLong_FromSsize_t(i); From python-3000-checkins at python.org Sat Apr 26 20:28:23 2008 From: python-3000-checkins at python.org (georg.brandl) Date: Sat, 26 Apr 2008 20:28:23 +0200 (CEST) Subject: [Python-3000-checkins] r62512 - python/branches/py3k Message-ID: <20080426182823.660C21E400B@bag.python.org> Author: georg.brandl Date: Sat Apr 26 20:28:08 2008 New Revision: 62512 Log: Block 2.6-only doc change. Modified: python/branches/py3k/ (props changed) From python-3000-checkins at python.org Sat Apr 26 22:48:57 2008 From: python-3000-checkins at python.org (mark.dickinson) Date: Sat, 26 Apr 2008 22:48:57 +0200 (CEST) Subject: [Python-3000-checkins] r62515 - in python/branches/py3k: Misc/NEWS configure configure.in Message-ID: <20080426204857.3D82E1E4002@bag.python.org> Author: mark.dickinson Date: Sat Apr 26 22:48:56 2008 New Revision: 62515 Log: Merged revisions 62499 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62499 | mark.dickinson | 2008-04-25 12:11:04 -0400 (Fri, 25 Apr 2008) | 7 lines Issue #1496032. Add -mieee to BASECFLAGS on alpha, when gcc is the compiler. This should(?) help to fix failures in test_math and test_cmath on Linux/alpha. Also add configure message reporting the result of uname -m, as a debugging aid. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Misc/NEWS python/branches/py3k/configure python/branches/py3k/configure.in Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sat Apr 26 22:48:56 2008 @@ -47,6 +47,8 @@ Build ----- +- Issue #1496032: On alpha, use -mieee when gcc is the compiler. + - "make install" is now an alias for "make altinstall", to prevent accidentally overwriting a Python 2.x installation. Use "make fullinstall" to force Python 3.0 to be installed as Modified: python/branches/py3k/configure ============================================================================== --- python/branches/py3k/configure (original) +++ python/branches/py3k/configure Sat Apr 26 22:48:56 2008 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 62146 . +# From configure.in Revision: 62451 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.61 for python 3.0. # @@ -2153,6 +2153,12 @@ CONFIGURE_MACOSX_DEPLOYMENT_TARGET= EXPORT_MACOSX_DEPLOYMENT_TARGET='#' +{ echo "$as_me:$LINENO: checking machine type as reported by uname -m" >&5 +echo $ECHO_N "checking machine type as reported by uname -m... $ECHO_C" >&6; } +ac_sys_machine=`uname -m` +{ echo "$as_me:$LINENO: result: $ac_sys_machine" >&5 +echo "${ECHO_T}$ac_sys_machine" >&6; } + # checks for alternative programs # compiler flags are generated in two sets, BASECFLAGS and OPT. OPT is just @@ -4503,6 +4509,16 @@ then BASECFLAGS="$BASECFLAGS -fno-strict-aliasing" fi + + # if using gcc on alpha, use -mieee to get (near) full IEEE 754 + # support. Without this, treatment of subnormals doesn't follow + # the standard. + case $ac_sys_machine in + alpha*) + BASECFLAGS="$BASECFLAGS -mieee" + ;; + esac + case $ac_sys_system in SCO_SV*) BASECFLAGS="$BASECFLAGS -m486 -DSCO5" Modified: python/branches/py3k/configure.in ============================================================================== --- python/branches/py3k/configure.in (original) +++ python/branches/py3k/configure.in Sat Apr 26 22:48:56 2008 @@ -333,6 +333,10 @@ CONFIGURE_MACOSX_DEPLOYMENT_TARGET= EXPORT_MACOSX_DEPLOYMENT_TARGET='#' +AC_MSG_CHECKING(machine type as reported by uname -m) +ac_sys_machine=`uname -m` +AC_MSG_RESULT($ac_sys_machine) + # checks for alternative programs # compiler flags are generated in two sets, BASECFLAGS and OPT. OPT is just @@ -792,6 +796,16 @@ then BASECFLAGS="$BASECFLAGS -fno-strict-aliasing" fi + + # if using gcc on alpha, use -mieee to get (near) full IEEE 754 + # support. Without this, treatment of subnormals doesn't follow + # the standard. + case $ac_sys_machine in + alpha*) + BASECFLAGS="$BASECFLAGS -mieee" + ;; + esac + case $ac_sys_system in SCO_SV*) BASECFLAGS="$BASECFLAGS -m486 -DSCO5" From python-3000-checkins at python.org Sun Apr 27 05:02:57 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Sun, 27 Apr 2008 05:02:57 +0200 (CEST) Subject: [Python-3000-checkins] r62519 - python/branches/py3k Message-ID: <20080427030257.EF5CE1E400B@bag.python.org> Author: benjamin.peterson Date: Sun Apr 27 05:02:57 2008 New Revision: 62519 Log: Blocked revisions 62517-62518 via svnmerge ........ r62517 | benjamin.peterson | 2008-04-26 21:28:02 -0500 (Sat, 26 Apr 2008) | 2 lines Added PyErr_WarnPy3k function. (issue 2671) I will be converting current Py3k warnings to the use of this function soon. ........ r62518 | benjamin.peterson | 2008-04-26 22:01:45 -0500 (Sat, 26 Apr 2008) | 2 lines Use PyErr_WarnPy3k throughout ........ Modified: python/branches/py3k/ (props changed) From python-3000-checkins at python.org Sun Apr 27 20:44:04 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Sun, 27 Apr 2008 20:44:04 +0200 (CEST) Subject: [Python-3000-checkins] r62537 - python/branches/py3k Message-ID: <20080427184404.664A01E400B@bag.python.org> Author: benjamin.peterson Date: Sun Apr 27 20:44:04 2008 New Revision: 62537 Log: Blocked revisions 62536 via svnmerge ........ r62536 | benjamin.peterson | 2008-04-27 13:40:21 -0500 (Sun, 27 Apr 2008) | 2 lines A little reformating of Py3k warnings ........ Modified: python/branches/py3k/ (props changed) From python-3000-checkins at python.org Mon Apr 28 23:05:10 2008 From: python-3000-checkins at python.org (benjamin.peterson) Date: Mon, 28 Apr 2008 23:05:10 +0200 (CEST) Subject: [Python-3000-checkins] r62568 - in python/branches/py3k: Doc/reference/lexical_analysis.rst Doc/whatsnew/3.0.rst Misc/NEWS Message-ID: <20080428210510.625261E400D@bag.python.org> Author: benjamin.peterson Date: Mon Apr 28 23:05:10 2008 New Revision: 62568 Log: Document the fact that '\U' and '\u' escapes are not treated specially in 3.0 (see issue 2541) Modified: python/branches/py3k/Doc/reference/lexical_analysis.rst python/branches/py3k/Doc/whatsnew/3.0.rst python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Doc/reference/lexical_analysis.rst ============================================================================== --- python/branches/py3k/Doc/reference/lexical_analysis.rst (original) +++ python/branches/py3k/Doc/reference/lexical_analysis.rst Mon Apr 28 23:05:10 2008 @@ -423,8 +423,9 @@ itself, or the quote character. String literals may optionally be prefixed with a letter ``'r'`` or ``'R'``; -such strings are called :dfn:`raw strings` and use different rules for -interpreting backslash escape sequences. +such strings are called :dfn:`raw strings` and treat backslashes as literal +characters. As a result, ``'\U'`` and ``'\u'`` escapes in raw strings are not +treated specially. Bytes literals are always prefixed with ``'b'`` or ``'B'``; they produce an instance of the :class:`bytes` type instead of the :class:`str` type. They @@ -520,15 +521,6 @@ escape sequences only recognized in string literals fall into the category of unrecognized escapes for bytes literals. -When an ``'r'`` or ``'R'`` prefix is used in a string literal, then the -``\uXXXX`` and ``\UXXXXXXXX`` escape sequences are processed while *all other -backslashes are left in the string*. For example, the string literal -``r"\u0062\n"`` consists of three Unicode characters: 'LATIN SMALL LETTER B', -'REVERSE SOLIDUS', and 'LATIN SMALL LETTER N'. Backslashes can be escaped with a -preceding backslash; however, both remain in the string. As a result, -``\uXXXX`` escape sequences are only recognized when there is an odd number of -backslashes. - Even in a raw string, string quotes can be escaped with a backslash, but the backslash remains in the string; for example, ``r"\""`` is a valid string literal consisting of two characters: a backslash and a double quote; ``r"\"`` Modified: python/branches/py3k/Doc/whatsnew/3.0.rst ============================================================================== --- python/branches/py3k/Doc/whatsnew/3.0.rst (original) +++ python/branches/py3k/Doc/whatsnew/3.0.rst Mon Apr 28 23:05:10 2008 @@ -167,6 +167,9 @@ explicitly convert between them, using the :meth:`str.encode` (str -> bytes) or :meth:`bytes.decode` (bytes -> str) methods. +* All backslashes in raw strings are interpreted literally. This means that + Unicode escapes are not treated specially. + .. XXX add bytearray * PEP 3112: Bytes literals, e.g. ``b"abc"``, create :class:`bytes` instances. @@ -183,6 +186,8 @@ * The :mod:`StringIO` and :mod:`cStringIO` modules are gone. Instead, import :class:`io.StringIO` or :class:`io.BytesIO`. +* ``'\U'`` and ``'\u'`` escapes in raw strings are not treated specially. + PEP 3101: A New Approach to String Formatting ============================================= Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Mon Apr 28 23:05:10 2008 @@ -26,6 +26,9 @@ through as unmodified as possible; as a consequence, the C API related to command line arguments was changed to use wchar_t. +- All backslashes in raw strings are interpreted literally. This means that + '\u' and '\U' escapes are not treated specially. + Extension Modules ----------------- From python-3000-checkins at python.org Tue Apr 29 13:14:08 2008 From: python-3000-checkins at python.org (marc-andre.lemburg) Date: Tue, 29 Apr 2008 13:14:08 +0200 (CEST) Subject: [Python-3000-checkins] r62580 - python/branches/py3k/Include/unicodeobject.h Message-ID: <20080429111408.E42A91E400D@bag.python.org> Author: marc-andre.lemburg Date: Tue Apr 29 13:14:08 2008 New Revision: 62580 Log: Cleanup the Unicode header documentation and formatting a bit. Modified: python/branches/py3k/Include/unicodeobject.h Modified: python/branches/py3k/Include/unicodeobject.h ============================================================================== --- python/branches/py3k/Include/unicodeobject.h (original) +++ python/branches/py3k/Include/unicodeobject.h Tue Apr 29 13:14:08 2008 @@ -660,7 +660,8 @@ */ PyAPI_FUNC(PyObject *) _PyUnicode_AsDefaultEncodedString( - PyObject *, const char *); + PyObject *unicode, + const char *errors); /* Decode a null-terminated string using Py_FileSystemDefaultEncoding. @@ -681,26 +682,36 @@ Py_ssize_t size /* size */ ); +/* Returns a pointer to the default encoding (normally, UTF-8) of the + Unicode object unicode and the size of the encoded representation + in bytes stored in *size. -/* Return a char* holding the UTF-8 encoded value of the - Unicode object. + In case of an error, no *size is set. - DEPRECATED: use PyUnicode_AsStringAndSize() instead. */ -PyAPI_FUNC(char *) PyUnicode_AsStringAndSize(PyObject*, Py_ssize_t *); +PyAPI_FUNC(char *) PyUnicode_AsStringAndSize( + PyObject *unicode, + Py_ssize_t *size); -/* Returns the UTF-8 encoding, and its size. +/* Returns a pointer to the default encoding (normally, UTf-8) of the + Unicode object unicode. - If the output argument is NULL, no size is stored. - */ + Use of this API is DEPRECATED since no size information can be + extracted from the returned data. Use PyUnicode_AsStringAndSize() + instead. -PyAPI_FUNC(char *) PyUnicode_AsString(PyObject*); +*/ -/* Returns the UTF-8 encoding. +PyAPI_FUNC(char *) PyUnicode_AsString(PyObject *unicode); - This is equivalent to PyUnicode_AsStringAndSize(x, NULL). +/* Returns the currently active default encoding. + The default encoding is currently implemented as run-time settable + process global. This may change in future versions of the + interpreter to become a parameter which is managed on a per-thread + basis. + */ PyAPI_FUNC(const char*) PyUnicode_GetDefaultEncoding(void); From python-3000-checkins at python.org Tue Apr 29 23:00:18 2008 From: python-3000-checkins at python.org (georg.brandl) Date: Tue, 29 Apr 2008 23:00:18 +0200 (CEST) Subject: [Python-3000-checkins] r62583 - python/branches/py3k/Doc/library/functions.rst Message-ID: <20080429210019.0351B1E4019@bag.python.org> Author: georg.brandl Date: Tue Apr 29 23:00:18 2008 New Revision: 62583 Log: Fix var name. Modified: python/branches/py3k/Doc/library/functions.rst Modified: python/branches/py3k/Doc/library/functions.rst ============================================================================== --- python/branches/py3k/Doc/library/functions.rst (original) +++ python/branches/py3k/Doc/library/functions.rst Tue Apr 29 23:00:18 2008 @@ -671,7 +671,7 @@ .. function:: next(iterator[, default]) - Retrieve the next item from the *iterable* by calling its :meth:`__next__` + Retrieve the next item from the *iterator* by calling its :meth:`__next__` method. If *default* is given, it is returned if the iterator is exhausted, otherwise :exc:`StopIteration` is raised. From python-3000-checkins at python.org Wed Apr 30 04:12:09 2008 From: python-3000-checkins at python.org (eric.smith) Date: Wed, 30 Apr 2008 04:12:09 +0200 (CEST) Subject: [Python-3000-checkins] r62587 - in python/branches/py3k: Lib/test/test_types.py Python/pystrtod.c Message-ID: <20080430021209.EEA721E4006@bag.python.org> Author: eric.smith Date: Wed Apr 30 04:12:09 2008 New Revision: 62587 Log: Merged revisions 62586 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62586 | eric.smith | 2008-04-29 21:09:30 -0400 (Tue, 29 Apr 2008) | 5 lines Issue 2526, float.__format__ 'n' specifier does not support thousands grouping. Implemented grouping, with tests. Cleaned up PyOS_ascii_formatd by breaking reformatting into smaller functions. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_types.py python/branches/py3k/Python/pystrtod.c Modified: python/branches/py3k/Lib/test/test_types.py ============================================================================== --- python/branches/py3k/Lib/test/test_types.py (original) +++ python/branches/py3k/Lib/test/test_types.py Wed Apr 30 04:12:09 2008 @@ -1,8 +1,9 @@ # Python test set -- part 6, built-in types -from test.test_support import run_unittest +from test.test_support import run_unittest, run_with_locale import unittest import sys +import locale class TypesTests(unittest.TestCase): @@ -407,6 +408,15 @@ self.assertEqual(value.__format__(format_spec), float(value).__format__(format_spec)) + @run_with_locale('LC_NUMERIC', 'en_US.UTF8') + def test_float__format__locale(self): + # test locale support for __format__ code 'n' + + for i in range(-10, 10): + x = 1234567890.0 * (10.0 ** i) + self.assertEqual(locale.format('%g', x, grouping=True), format(x, 'n')) + self.assertEqual(locale.format('%.10g', x, grouping=True), format(x, '.10n')) + def test_float__format__(self): # these should be rewritten to use both format(x, spec) and # x.__format__(spec) Modified: python/branches/py3k/Python/pystrtod.c ============================================================================== --- python/branches/py3k/Python/pystrtod.c (original) +++ python/branches/py3k/Python/pystrtod.c Wed Apr 30 04:12:09 2008 @@ -187,6 +187,38 @@ return val; } +/* Given a string that may have a decimal point in the current + locale, change it back to a dot. Since the string cannot get + longer, no need for a maximum buffer size parameter. */ +Py_LOCAL_INLINE(void) +change_decimal_from_locale_to_dot(char* buffer) +{ + struct lconv *locale_data = localeconv(); + const char *decimal_point = locale_data->decimal_point; + + if (decimal_point[0] != '.' || decimal_point[1] != 0) { + size_t decimal_point_len = strlen(decimal_point); + + if (*buffer == '+' || *buffer == '-') + buffer++; + while (isdigit(Py_CHARMASK(*buffer))) + buffer++; + if (strncmp(buffer, decimal_point, decimal_point_len) == 0) { + *buffer = '.'; + buffer++; + if (decimal_point_len > 1) { + /* buffer needs to get smaller */ + size_t rest_len = strlen(buffer + + (decimal_point_len - 1)); + memmove(buffer, + buffer + (decimal_point_len - 1), + rest_len); + buffer[rest_len] = 0; + } + } + } +} + /* From the C99 standard, section 7.19.6: The exponent always contains at least two digits, and only as many more digits @@ -194,6 +226,189 @@ */ #define MIN_EXPONENT_DIGITS 2 +/* Ensure that any exponent, if present, is at least MIN_EXPONENT_DIGITS + in length. */ +Py_LOCAL_INLINE(void) +ensure_minumim_exponent_length(char* buffer, size_t buf_size) +{ + char *p = strpbrk(buffer, "eE"); + if (p && (*(p + 1) == '-' || *(p + 1) == '+')) { + char *start = p + 2; + int exponent_digit_cnt = 0; + int leading_zero_cnt = 0; + int in_leading_zeros = 1; + int significant_digit_cnt; + + /* Skip over the exponent and the sign. */ + p += 2; + + /* Find the end of the exponent, keeping track of leading + zeros. */ + while (*p && isdigit(Py_CHARMASK(*p))) { + if (in_leading_zeros && *p == '0') + ++leading_zero_cnt; + if (*p != '0') + in_leading_zeros = 0; + ++p; + ++exponent_digit_cnt; + } + + significant_digit_cnt = exponent_digit_cnt - leading_zero_cnt; + if (exponent_digit_cnt == MIN_EXPONENT_DIGITS) { + /* If there are 2 exactly digits, we're done, + regardless of what they contain */ + } + else if (exponent_digit_cnt > MIN_EXPONENT_DIGITS) { + int extra_zeros_cnt; + + /* There are more than 2 digits in the exponent. See + if we can delete some of the leading zeros */ + if (significant_digit_cnt < MIN_EXPONENT_DIGITS) + significant_digit_cnt = MIN_EXPONENT_DIGITS; + extra_zeros_cnt = exponent_digit_cnt - + significant_digit_cnt; + + /* Delete extra_zeros_cnt worth of characters from the + front of the exponent */ + assert(extra_zeros_cnt >= 0); + + /* Add one to significant_digit_cnt to copy the + trailing 0 byte, thus setting the length */ + memmove(start, + start + extra_zeros_cnt, + significant_digit_cnt + 1); + } + else { + /* If there are fewer than 2 digits, add zeros + until there are 2, if there's enough room */ + int zeros = MIN_EXPONENT_DIGITS - exponent_digit_cnt; + if (start + zeros + exponent_digit_cnt + 1 + < buffer + buf_size) { + memmove(start + zeros, start, + exponent_digit_cnt + 1); + memset(start, '0', zeros); + } + } + } +} + +/* Ensure that buffer has a decimal point in it. The decimal point + will not be in the current locale, it will always be '.' */ +Py_LOCAL_INLINE(void) +ensure_decimal_point(char* buffer, size_t buf_size) +{ + int insert_count = 0; + char* chars_to_insert; + + /* search for the first non-digit character */ + char *p = buffer; + while (*p && isdigit(Py_CHARMASK(*p))) + ++p; + + if (*p == '.') { + if (isdigit(Py_CHARMASK(*(p+1)))) { + /* Nothing to do, we already have a decimal + point and a digit after it */ + } + else { + /* We have a decimal point, but no following + digit. Insert a zero after the decimal. */ + ++p; + chars_to_insert = "0"; + insert_count = 1; + } + } + else { + chars_to_insert = ".0"; + insert_count = 2; + } + if (insert_count) { + size_t buf_len = strlen(buffer); + if (buf_len + insert_count + 1 >= buf_size) { + /* If there is not enough room in the buffer + for the additional text, just skip it. It's + not worth generating an error over. */ + } + else { + memmove(p + insert_count, p, + buffer + strlen(buffer) - p + 1); + memcpy(p, chars_to_insert, insert_count); + } + } +} + +/* Add the locale specific grouping characters to buffer. Note + that any decimal point (if it's present) in buffer is already + locale-specific. Return 0 on error, else 1. */ +Py_LOCAL_INLINE(int) +add_thousands_grouping(char* buffer, size_t buf_size) +{ + struct lconv *locale_data = localeconv(); + const char *grouping = locale_data->grouping; + const char *thousands_sep = locale_data->thousands_sep; + size_t thousands_sep_len = strlen(thousands_sep); + const char *decimal_point = locale_data->decimal_point; + char *pend = buffer + strlen(buffer); /* current end of buffer */ + char *pmax = buffer + buf_size; /* max of buffer */ + char current_grouping; + + /* Find the decimal point, if any. We're only concerned + about the characters to the left of the decimal when + adding grouping. */ + char *p = strstr(buffer, decimal_point); + if (!p) { + /* No decimal, use the entire string. */ + + /* If any exponent, adjust p. */ + p = strpbrk(buffer, "eE"); + if (!p) + /* No exponent and no decimal. Use the entire + string. */ + p = pend; + } + /* At this point, p points just past the right-most character we + want to format. We need to add the grouping string for the + characters between buffer and p. */ + + /* Starting at p and working right-to-left, keep track of + what grouping needs to be added and insert that. */ + current_grouping = *grouping++; + + /* If the first character is 0, perform no grouping at all. */ + if (current_grouping == 0) + return 1; + + while (p - buffer > current_grouping) { + /* Always leave buffer and pend valid at the end of this + loop, since we might leave with a return statement. */ + + /* Is there room to insert thousands_sep_len chars?. */ + if (pmax - pend <= thousands_sep_len) + /* No room. */ + return 0; + + /* Move the rest of the string down. */ + p -= current_grouping; + memmove(p + thousands_sep_len, + p, + pend - p + 1); + /* Adjust end pointer. */ + pend += thousands_sep_len; + /* Copy the thousands_sep chars into the buffer. */ + memcpy(p, thousands_sep, thousands_sep_len); + + /* Move to the next grouping character, unless we're + repeating (which is designated by a grouping of 0). */ + if (*grouping != 0) { + current_grouping = *grouping++; + if (current_grouping == CHAR_MAX) + /* We're done. */ + return 1; + } + } + return 1; +} + /* see FORMATBUFLEN in unicodeobject.c */ #define FLOAT_FORMATBUFLEN 120 @@ -222,7 +437,6 @@ const char *format, double d) { - char *p; char format_char; size_t format_len = strlen(format); @@ -277,144 +491,31 @@ /* Have PyOS_snprintf do the hard work */ PyOS_snprintf(buffer, buf_size, format, d); - /* Get the current local, and find the decimal point character (or - string?). Convert that string back to a dot. Do not do this if - using the 'n' (number) format code. */ - if (format_char != 'n') { - struct lconv *locale_data = localeconv(); - const char *decimal_point = locale_data->decimal_point; - size_t decimal_point_len = strlen(decimal_point); - size_t rest_len; - - assert(decimal_point_len != 0); + /* Do various fixups on the return string */ - if (decimal_point[0] != '.' || decimal_point[1] != 0) { - p = buffer; - - if (*p == '+' || *p == '-') - p++; - - while (isdigit(Py_CHARMASK(*p))) - p++; - - if (strncmp(p, decimal_point, - decimal_point_len) == 0) { - *p = '.'; - p++; - if (decimal_point_len > 1) { - rest_len = strlen(p + - (decimal_point_len - 1)); - memmove(p, p + (decimal_point_len - 1), - rest_len); - p[rest_len] = 0; - } - } - } - } + /* Get the current locale, and find the decimal point string. + Convert that string back to a dot. Do not do this if using the + 'n' (number) format code, since we want to keep the localized + decimal point in that case. */ + if (format_char != 'n') + change_decimal_from_locale_to_dot(buffer); /* If an exponent exists, ensure that the exponent is at least MIN_EXPONENT_DIGITS digits, providing the buffer is large enough for the extra zeros. Also, if there are more than MIN_EXPONENT_DIGITS, remove as many zeros as possible until we get back to MIN_EXPONENT_DIGITS */ - p = strpbrk(buffer, "eE"); - if (p && (*(p + 1) == '-' || *(p + 1) == '+')) { - char *start = p + 2; - int exponent_digit_cnt = 0; - int leading_zero_cnt = 0; - int in_leading_zeros = 1; - int significant_digit_cnt; - - p += 2; - while (*p && isdigit(Py_CHARMASK(*p))) { - if (in_leading_zeros && *p == '0') - ++leading_zero_cnt; - if (*p != '0') - in_leading_zeros = 0; - ++p; - ++exponent_digit_cnt; - } - - significant_digit_cnt = exponent_digit_cnt - leading_zero_cnt; - if (exponent_digit_cnt == MIN_EXPONENT_DIGITS) { - /* If there are 2 exactly digits, we're done, - regardless of what they contain */ - } - else if (exponent_digit_cnt > MIN_EXPONENT_DIGITS) { - int extra_zeros_cnt; - - /* There are more than 2 digits in the exponent. See - if we can delete some of the leading zeros */ - if (significant_digit_cnt < MIN_EXPONENT_DIGITS) - significant_digit_cnt = MIN_EXPONENT_DIGITS; - extra_zeros_cnt = exponent_digit_cnt - - significant_digit_cnt; - - /* Delete extra_zeros_cnt worth of characters from the - front of the exponent */ - assert(extra_zeros_cnt >= 0); - - /* Add one to significant_digit_cnt to copy the - trailing 0 byte, thus setting the length */ - memmove(start, - start + extra_zeros_cnt, - significant_digit_cnt + 1); - } - else { - /* If there are fewer than 2 digits, add zeros - until there are 2, if there's enough room */ - int zeros = MIN_EXPONENT_DIGITS - exponent_digit_cnt; - if (start + zeros + exponent_digit_cnt + 1 - < buffer + buf_size) { - memmove(start + zeros, start, - exponent_digit_cnt + 1); - memset(start, '0', zeros); - } - } - } + ensure_minumim_exponent_length(buffer, buf_size); /* If format_char is 'Z', make sure we have at least one character after the decimal point (and make sure we have a decimal point). */ - if (format_char == 'Z') { - int insert_count = 0; - char* chars_to_insert; - - /* search for the first non-digit character */ - p = buffer; - while (*p && isdigit(Py_CHARMASK(*p))) - ++p; + if (format_char == 'Z') + ensure_decimal_point(buffer, buf_size); - if (*p == '.') { - if (isdigit(Py_CHARMASK(*(p+1)))) { - /* Nothing to do, we already have a decimal - point and a digit after it */ - } - else { - /* We have a decimal point, but no following - digit. Insert a zero after the decimal. */ - ++p; - chars_to_insert = "0"; - insert_count = 1; - } - } - else { - chars_to_insert = ".0"; - insert_count = 2; - } - if (insert_count) { - size_t buf_len = strlen(buffer); - if (buf_len + insert_count + 1 >= buf_size) { - /* If there is not enough room in the buffer - for the additional text, just skip it. It's - not worth generating an error over. */ - } - else { - memmove(p + insert_count, p, - buffer + strlen(buffer) - p + 1); - memcpy(p, chars_to_insert, insert_count); - } - } - } + /* If format_char is 'n', add the thousands grouping. */ + if (format_char == 'n') + if (!add_thousands_grouping(buffer, buf_size)) + return NULL; return buffer; } From python-3000-checkins at python.org Wed Apr 30 13:49:46 2008 From: python-3000-checkins at python.org (thomas.heller) Date: Wed, 30 Apr 2008 13:49:46 +0200 (CEST) Subject: [Python-3000-checkins] r62589 - in python/branches/py3k-ctypes-pep3118/Modules/_ctypes: _ctypes.c ctypes.h Message-ID: <20080430114946.A4CDE1E4007@bag.python.org> Author: thomas.heller Date: Wed Apr 30 13:49:46 2008 New Revision: 62589 Log: Fix compiler warnings. Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/_ctypes.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/ctypes.h Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/_ctypes.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/_ctypes.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/_ctypes.c Wed Apr 30 13:49:46 2008 @@ -1173,10 +1173,10 @@ assert(itemdict->format); if (itemdict->format[0] == '(') { - sprintf(buf, "(%d,", length); + sprintf(buf, "(%ld,", length); stgdict->format = alloc_format_string(buf, itemdict->format+1); } else { - sprintf(buf, "(%d)", length); + sprintf(buf, "(%ld)", length); stgdict->format = alloc_format_string(buf, itemdict->format); } if (stgdict->format == NULL) { Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/ctypes.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/ctypes.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/ctypes.h Wed Apr 30 13:49:46 2008 @@ -205,8 +205,8 @@ char *format; int ndim; Py_ssize_t *shape; -/* Py_ssize_t *strides; /* unused in ctypes */ -/* Py_ssize_t *suboffsets; /* unused in ctypes */ +/* Py_ssize_t *strides; */ /* unused in ctypes */ +/* Py_ssize_t *suboffsets; */ /* unused in ctypes */ } StgDictObject; From python-3000-checkins at python.org Wed Apr 30 15:57:56 2008 From: python-3000-checkins at python.org (thomas.heller) Date: Wed, 30 Apr 2008 15:57:56 +0200 (CEST) Subject: [Python-3000-checkins] r62590 - in python/branches/py3k-ctypes-pep3118: .bzrignore Demo/classes/Dbm.py Demo/classes/README Demo/curses/ncurses.py Demo/rpc/mountclient.py Demo/rpc/nfsclient.py Demo/rpc/rpc.py Demo/tkinter/guido/ShellWindow.py Demo/tkinter/guido/paint.py Doc/ACKS.txt Doc/Makefile Doc/README.txt Doc/bugs.rst Doc/builddoc.bat Doc/c-api/arg.rst Doc/c-api/float.rst Doc/c-api/import.rst Doc/c-api/init.rst Doc/c-api/intro.rst Doc/c-api/long.rst Doc/c-api/method.rst Doc/c-api/module.rst Doc/c-api/objbuffer.rst Doc/c-api/set.rst Doc/c-api/structures.rst Doc/c-api/sys.rst Doc/c-api/tuple.rst Doc/c-api/type.rst Doc/c-api/typeobj.rst Doc/c-api/unicode.rst Doc/c-api/veryhigh.rst Doc/conf.py Doc/copyright.rst Doc/distutils/apiref.rst Doc/distutils/builtdist.rst Doc/distutils/examples.rst Doc/distutils/packageindex.rst Doc/distutils/setupscript.rst Doc/distutils/sourcedist.rst Doc/documenting/markup.rst Doc/documenting/style.rst Doc/extending/extending.rst Doc/extending/newtypes.rst Doc/extending/windows.rst Doc/glossary.rst Doc/howto/advocacy.rst Doc/howto/curses.rst Doc/howto/doanddont.rst Doc/howto/functional.rst Doc/howto/regex.rst Doc/howto/sockets.rst Doc/howto/unicode.rst Doc/howto/urllib2.rst Doc/includes/email-alternative.py Doc/includes/sqlite3/ctx_manager.py Doc/includes/tzinfo-examples.py Doc/install/index.rst Doc/library/__future__.rst Doc/library/_ast.rst Doc/library/_winreg.rst Doc/library/aepack.rst Doc/library/allos.rst Doc/library/array.rst Doc/library/asynchat.rst Doc/library/asyncore.rst Doc/library/audioop.rst Doc/library/base64.rst Doc/library/basehttpserver.rst Doc/library/bdb.rst Doc/library/bisect.rst Doc/library/bz2.rst Doc/library/calendar.rst Doc/library/cgihttpserver.rst Doc/library/chunk.rst Doc/library/cmath.rst Doc/library/codecs.rst Doc/library/collections.rst Doc/library/configparser.rst Doc/library/cookie.rst Doc/library/cookielib.rst Doc/library/copy_reg.rst Doc/library/csv.rst Doc/library/ctypes.rst Doc/library/curses.rst Doc/library/datatypes.rst Doc/library/datetime.rst Doc/library/decimal.rst Doc/library/difflib.rst Doc/library/dis.rst Doc/library/dl.rst Doc/library/doctest.rst Doc/library/easydialogs.rst Doc/library/email-examples.rst Doc/library/email.charset.rst Doc/library/email.generator.rst Doc/library/email.header.rst Doc/library/email.message.rst Doc/library/email.parser.rst Doc/library/email.util.rst Doc/library/fcntl.rst Doc/library/filecmp.rst Doc/library/fileinput.rst Doc/library/fnmatch.rst Doc/library/fractions.rst Doc/library/ftplib.rst Doc/library/functions.rst Doc/library/functools.rst Doc/library/getopt.rst Doc/library/gettext.rst Doc/library/gzip.rst Doc/library/hashlib.rst Doc/library/heapq.rst Doc/library/imaplib.rst Doc/library/imp.rst Doc/library/index.rst Doc/library/inspect.rst Doc/library/io.rst Doc/library/itertools.rst Doc/library/logging.rst Doc/library/mailbox.rst Doc/library/marshal.rst Doc/library/math.rst Doc/library/mimetools.rst Doc/library/mimetypes.rst Doc/library/mmap.rst Doc/library/modulefinder.rst Doc/library/msilib.rst Doc/library/numbers.rst Doc/library/numeric.rst Doc/library/operator.rst Doc/library/optparse.rst Doc/library/os.path.rst Doc/library/os.rst Doc/library/othergui.rst Doc/library/pdb.rst Doc/library/pickle.rst Doc/library/pickletools.rst Doc/library/pkgutil.rst Doc/library/platform.rst Doc/library/plistlib.rst Doc/library/pprint.rst Doc/library/profile.rst Doc/library/py_compile.rst Doc/library/pyexpat.rst Doc/library/queue.rst Doc/library/random.rst Doc/library/rational.rst Doc/library/re.rst Doc/library/robotparser.rst Doc/library/sched.rst Doc/library/select.rst Doc/library/shutil.rst Doc/library/signal.rst Doc/library/simplehttpserver.rst Doc/library/simplexmlrpcserver.rst Doc/library/smtpd.rst Doc/library/smtplib.rst Doc/library/socket.rst Doc/library/socketserver.rst Doc/library/sqlite3.rst Doc/library/ssl.rst Doc/library/stdtypes.rst Doc/library/string.rst Doc/library/stringio.rst Doc/library/struct.rst Doc/library/subprocess.rst Doc/library/sys.rst Doc/library/tempfile.rst Doc/library/textwrap.rst Doc/library/threading.rst Doc/library/time.rst Doc/library/tix.rst Doc/library/tkinter.rst Doc/library/tokenize.rst Doc/library/trace.rst Doc/library/traceback.rst Doc/library/types.rst Doc/library/undoc.rst Doc/library/unicodedata.rst Doc/library/unittest.rst Doc/library/unix.rst Doc/library/urllib.rst Doc/library/urllib2.rst Doc/library/urlparse.rst Doc/library/userdict.rst Doc/library/warnings.rst Doc/library/weakref.rst Doc/library/wsgiref.rst Doc/library/xml.dom.minidom.rst Doc/library/xml.dom.rst Doc/library/xml.etree.elementtree.rst Doc/library/xml.sax.handler.rst Doc/library/xml.sax.reader.rst Doc/library/xmlrpclib.rst Doc/library/zipfile.rst Doc/library/zipimport.rst Doc/library/zlib.rst Doc/license.rst Doc/make.bat Doc/reference/compound_stmts.rst Doc/reference/datamodel.rst Doc/reference/expressions.rst Doc/reference/index.rst Doc/reference/lexical_analysis.rst Doc/reference/simple_stmts.rst Doc/tools/sphinxext Doc/tools/sphinxext/download.html Doc/tools/sphinxext/indexcontent.html Doc/tools/sphinxext/patchlevel.py Doc/tools/sphinxext/pyspecific.py Doc/tutorial/appetite.rst Doc/tutorial/classes.rst Doc/tutorial/controlflow.rst Doc/tutorial/datastructures.rst Doc/tutorial/errors.rst Doc/tutorial/inputoutput.rst Doc/tutorial/stdlib.rst Doc/tutorial/stdlib2.rst Doc/tutorial/whatnow.rst Doc/using/cmdline.rst Doc/using/unix.rst Doc/using/windows.rst Doc/whatsnew/2.6.rst Doc/whatsnew/3.0.rst Include/Python-ast.h Include/Python.h Include/abstract.h Include/ceval.h Include/classobject.h Include/code.h Include/compile.h Include/complexobject.h Include/floatobject.h Include/frameobject.h Include/genobject.h Include/graminit.h Include/iterobject.h Include/methodobject.h Include/object.h Include/osdefs.h Include/parsetok.h Include/patchlevel.h Include/pyerrors.h Include/pygetopt.h Include/pymath.h Include/pyport.h Include/pythonrun.h Include/setobject.h Include/sysmodule.h Include/traceback.h Include/tupleobject.h Include/unicodeobject.h Include/warnings.h LICENSE Lib/BaseHTTPServer.py Lib/ConfigParser.py Lib/DocXMLRPCServer.py Lib/SimpleHTTPServer.py Lib/SocketServer.py Lib/UserDict.py Lib/UserList.py Lib/UserString.py Lib/__future__.py Lib/_abcoll.py Lib/_strptime.py Lib/_weakrefset.py Lib/abc.py Lib/bdb.py Lib/bsddb/__init__.py Lib/bsddb/dbobj.py Lib/bsddb/dbshelve.py Lib/bsddb/dbtables.py Lib/bsddb/test/test_1413192.py Lib/bsddb/test/test_associate.py Lib/bsddb/test/test_basics.py Lib/bsddb/test/test_compare.py Lib/bsddb/test/test_cursor_pget_bug.py Lib/bsddb/test/test_dbobj.py Lib/bsddb/test/test_dbshelve.py Lib/bsddb/test/test_dbtables.py Lib/bsddb/test/test_env_close.py Lib/bsddb/test/test_join.py Lib/bsddb/test/test_lock.py Lib/bsddb/test/test_misc.py Lib/bsddb/test/test_pickle.py Lib/bsddb/test/test_recno.py Lib/bsddb/test/test_sequence.py Lib/bsddb/test/test_thread.py Lib/calendar.py Lib/cgi.py Lib/codecs.py Lib/collections.py Lib/compileall.py Lib/cookielib.py Lib/copy.py Lib/csv.py Lib/ctypes/__init__.py Lib/ctypes/test/__init__.py Lib/ctypes/test/test_arrays.py Lib/ctypes/test/test_checkretval.py Lib/ctypes/test/test_find.py Lib/ctypes/test/test_funcptr.py Lib/ctypes/test/test_libc.py Lib/ctypes/test/test_numbers.py Lib/ctypes/test/test_pep3118.py Lib/ctypes/test/test_pickling.py Lib/ctypes/test/test_slicing.py Lib/ctypes/test/test_structures.py Lib/ctypes/util.py Lib/curses/__init__.py Lib/curses/wrapper.py Lib/decimal.py Lib/distutils/__init__.py Lib/distutils/bcppcompiler.py Lib/distutils/ccompiler.py Lib/distutils/command/bdist.py Lib/distutils/command/bdist_dumb.py Lib/distutils/command/bdist_msi.py Lib/distutils/command/bdist_rpm.py Lib/distutils/command/bdist_wininst.py Lib/distutils/command/build.py Lib/distutils/command/build_ext.py Lib/distutils/command/build_py.py Lib/distutils/command/build_scripts.py Lib/distutils/command/install.py Lib/distutils/command/install_headers.py Lib/distutils/command/register.py Lib/distutils/command/sdist.py Lib/distutils/command/wininst-9.0-amd64.exe Lib/distutils/core.py Lib/distutils/filelist.py Lib/distutils/msvc9compiler.py Lib/distutils/msvccompiler.py Lib/distutils/sysconfig.py Lib/distutils/tests/test_core.py Lib/distutils/tests/test_dist.py Lib/distutils/tests/test_sysconfig.py Lib/distutils/unixccompiler.py Lib/distutils/util.py Lib/dumbdbm.py Lib/email/base64mime.py Lib/filecmp.py Lib/fractions.py Lib/ftplib.py Lib/glob.py Lib/gzip.py Lib/hashlib.py Lib/heapq.py Lib/hmac.py Lib/httplib.py Lib/idlelib/AutoComplete.py Lib/idlelib/EditorWindow.py Lib/idlelib/MultiCall.py Lib/idlelib/NEWS.txt Lib/idlelib/PyShell.py Lib/idlelib/RemoteDebugger.py Lib/idlelib/ScriptBinding.py Lib/idlelib/TreeWidget.py Lib/idlelib/UndoDelegator.py Lib/idlelib/configDialog.py Lib/idlelib/configHandler.py Lib/idlelib/idlever.py Lib/idlelib/keybindingDialog.py Lib/idlelib/run.py Lib/imaplib.py Lib/inspect.py Lib/io.py Lib/lib-tk/Tkinter.py Lib/lib-tk/tkSimpleDialog.py Lib/lib-tk/turtle.py Lib/lib2to3 Lib/lib2to3/fixes Lib/lib2to3/pgen2 Lib/lib2to3/tests Lib/locale.py Lib/logging/__init__.py Lib/logging/handlers.py Lib/mailbox.py Lib/ntpath.py Lib/numbers.py Lib/opcode.py Lib/pdb.py Lib/pickle.py Lib/pickletools.py Lib/pkgutil.py Lib/plat-mac/EasyDialogs.py Lib/plat-mac/FrameWork.py Lib/plat-mac/MiniAEFrame.py Lib/plat-mac/PixMapWrapper.py Lib/plat-mac/aepack.py Lib/plat-mac/bgenlocations.py Lib/plat-mac/buildtools.py Lib/plat-mac/findertools.py Lib/plat-mac/gensuitemodule.py Lib/plat-mac/ic.py Lib/plat-mac/lib-scriptpackages/CodeWarrior/CodeWarrior_suite.py Lib/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py Lib/plat-mac/lib-scriptpackages/CodeWarrior/Standard_Suite.py Lib/plat-mac/lib-scriptpackages/Explorer/Required_Suite.py Lib/plat-mac/lib-scriptpackages/Explorer/Web_Browser_Suite.py Lib/plat-mac/lib-scriptpackages/Finder/Finder_Basics.py Lib/plat-mac/lib-scriptpackages/Finder/Legacy_suite.py Lib/plat-mac/lib-scriptpackages/Finder/Standard_Suite.py Lib/plat-mac/lib-scriptpackages/Netscape/Mozilla_suite.py Lib/plat-mac/lib-scriptpackages/Netscape/PowerPlant.py Lib/plat-mac/lib-scriptpackages/Netscape/Required_suite.py Lib/plat-mac/lib-scriptpackages/Netscape/WorldWideWeb_suite.py Lib/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py Lib/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py Lib/plat-mac/lib-scriptpackages/SystemEvents/Standard_Suite.py Lib/plat-mac/lib-scriptpackages/Terminal/Standard_Suite.py Lib/plat-mac/lib-scriptpackages/_builtinSuites/builtin_Suite.py Lib/plat-mac/macostools.py Lib/plat-mac/videoreader.py Lib/plat-os2emx/grp.py Lib/plat-os2emx/pwd.py Lib/platform.py Lib/plistlib.py Lib/pprint.py Lib/pstats.py Lib/py_compile.py Lib/pyclbr.py Lib/pydoc.py Lib/random.py Lib/rational.py Lib/re.py Lib/rlcompleter.py Lib/runpy.py Lib/shelve.py Lib/shutil.py Lib/smtplib.py Lib/sqlite3/dump.py Lib/sqlite3/test/dbapi.py Lib/sqlite3/test/dump.py Lib/sqlite3/test/factory.py Lib/sqlite3/test/hooks.py Lib/sqlite3/test/regression.py Lib/sqlite3/test/transactions.py Lib/sqlite3/test/types.py Lib/sqlite3/test/userfunctions.py Lib/sre_compile.py Lib/sre_parse.py Lib/ssl.py Lib/stat.py Lib/subprocess.py Lib/tarfile.py Lib/tempfile.py Lib/test/cjkencodings_test.py Lib/test/cmath_testcases.txt Lib/test/fork_wait.py Lib/test/ieee754.txt Lib/test/list_tests.py Lib/test/mapping_tests.py Lib/test/output Lib/test/outstanding_bugs.py Lib/test/pickletester.py Lib/test/profilee.py Lib/test/regrtest.py Lib/test/relimport.py Lib/test/seq_tests.py Lib/test/string_tests.py Lib/test/test_SimpleHTTPServer.py Lib/test/test___all__.py Lib/test/test__locale.py Lib/test/test_abc.py Lib/test/test_abstract_numbers.py Lib/test/test_applesingle.py Lib/test/test_array.py Lib/test/test_ast.py Lib/test/test_asynchat.py Lib/test/test_asyncore.py Lib/test/test_audioop.py Lib/test/test_bisect.py Lib/test/test_bsddb3.py Lib/test/test_builtin.py Lib/test/test_bytes.py Lib/test/test_cProfile.py Lib/test/test_capi.py Lib/test/test_cfgparser.py Lib/test/test_class.py Lib/test/test_cmath.py Lib/test/test_cmd.py Lib/test/test_cmd_line.py Lib/test/test_code.py Lib/test/test_codecmaps_hk.py Lib/test/test_coding.py Lib/test/test_collections.py Lib/test/test_compare.py Lib/test/test_compile.py Lib/test/test_complex.py Lib/test/test_contains.py Lib/test/test_copy.py Lib/test/test_crypt.py Lib/test/test_curses.py Lib/test/test_datetime.py Lib/test/test_dbm.py Lib/test/test_decimal.py Lib/test/test_defaultdict.py Lib/test/test_deque.py Lib/test/test_descr.py Lib/test/test_descrtut.py Lib/test/test_dict.py Lib/test/test_dis.py Lib/test/test_dl.py Lib/test/test_doctest3.txt Lib/test/test_docxmlrpc.py Lib/test/test_dummy_threading.py Lib/test/test_email.py Lib/test/test_eof.py Lib/test/test_epoll.py Lib/test/test_errno.py Lib/test/test_extcall.py Lib/test/test_fcntl.py Lib/test/test_file.py Lib/test/test_fileinput.py Lib/test/test_fileio.py Lib/test/test_float.py Lib/test/test_format.py Lib/test/test_fractions.py Lib/test/test_frozen.py Lib/test/test_ftplib.py Lib/test/test_funcattrs.py Lib/test/test_future4.py Lib/test/test_gc.py Lib/test/test_gdbm.py Lib/test/test_generators.py Lib/test/test_genexps.py Lib/test/test_getargs2.py Lib/test/test_grammar.py Lib/test/test_gzip.py Lib/test/test_heapq.py Lib/test/test_hexoct.py Lib/test/test_hmac.py Lib/test/test_htmlparser.py Lib/test/test_httplib.py Lib/test/test_imaplib.py Lib/test/test_imp.py Lib/test/test_import.py Lib/test/test_index.py Lib/test/test_inspect.py Lib/test/test_int_literal.py Lib/test/test_io.py Lib/test/test_ioctl.py Lib/test/test_iterlen.py Lib/test/test_itertools.py Lib/test/test_kqueue.py Lib/test/test_largefile.py Lib/test/test_lib2to3.py Lib/test/test_list.py Lib/test/test_logging.py Lib/test/test_long.py Lib/test/test_mailbox.py Lib/test/test_math.py Lib/test/test_metaclass.py Lib/test/test_minidom.py Lib/test/test_mmap.py Lib/test/test_module.py Lib/test/test_modulefinder.py Lib/test/test_multibytecodec_support.py Lib/test/test_mutex.py Lib/test/test_nis.py Lib/test/test_ntpath.py Lib/test/test_operator.py Lib/test/test_optparse.py Lib/test/test_os.py Lib/test/test_ossaudiodev.py Lib/test/test_parser.py Lib/test/test_pep247.py Lib/test/test_pep263.py Lib/test/test_pickle.py Lib/test/test_pickletools.py Lib/test/test_pkg.py Lib/test/test_pkgutil.py Lib/test/test_plistlib.py Lib/test/test_poll.py Lib/test/test_poplib.py Lib/test/test_posix.py Lib/test/test_pprint.py Lib/test/test_print.py Lib/test/test_profile.py Lib/test/test_pty.py Lib/test/test_pyclbr.py Lib/test/test_pydoc.py Lib/test/test_queue.py Lib/test/test_random.py Lib/test/test_rational.py Lib/test/test_re.py Lib/test/test_resource.py Lib/test/test_rfc822.py Lib/test/test_richcmp.py Lib/test/test_sax.py Lib/test/test_scope.py Lib/test/test_scriptpackages.py Lib/test/test_select.py Lib/test/test_set.py Lib/test/test_sgmllib.py Lib/test/test_shelve.py Lib/test/test_shutil.py Lib/test/test_signal.py Lib/test/test_site.py Lib/test/test_smtplib.py Lib/test/test_socket.py Lib/test/test_socketserver.py Lib/test/test_sort.py Lib/test/test_sqlite.py Lib/test/test_ssl.py Lib/test/test_strftime.py Lib/test/test_strptime.py Lib/test/test_struct.py Lib/test/test_structmembers.py Lib/test/test_subprocess.py Lib/test/test_sundry.py Lib/test/test_support.py Lib/test/test_sys.py Lib/test/test_tarfile.py Lib/test/test_telnetlib.py Lib/test/test_tempfile.py Lib/test/test_thread.py Lib/test/test_threading.py Lib/test/test_timeout.py Lib/test/test_tokenize.py Lib/test/test_trace.py Lib/test/test_tuple.py Lib/test/test_types.py Lib/test/test_unicode.py Lib/test/test_unicode_file.py Lib/test/test_unpack.py Lib/test/test_unpack_ex.py Lib/test/test_urllib.py Lib/test/test_urllib2.py Lib/test/test_urllib2_localnet.py Lib/test/test_urllib2net.py Lib/test/test_urllibnet.py Lib/test/test_userdict.py Lib/test/test_userlist.py Lib/test/test_userstring.py Lib/test/test_uu.py Lib/test/test_warnings.py Lib/test/test_wave.py Lib/test/test_weakref.py Lib/test/test_whichdb.py Lib/test/test_winsound.py Lib/test/test_wsgiref.py Lib/test/test_xml_etree.py Lib/test/test_xml_etree_c.py Lib/test/test_xmlrpc.py Lib/test/test_xmlrpc_net.py Lib/test/test_zipfile.py Lib/test/test_zlib.py Lib/test/testall.py Lib/test/testtar.tar Lib/test/tokenize_tests-latin1-coding-cookie-and-utf8-bom-sig.txt Lib/test/tokenize_tests-no-coding-cookie-and-utf8-bom-sig-only.txt Lib/test/tokenize_tests-utf8-coding-cookie-and-no-utf8-bom-sig.txt Lib/test/tokenize_tests-utf8-coding-cookie-and-utf8-bom-sig.txt Lib/threading.py Lib/token.py Lib/tokenize.py Lib/trace.py Lib/types.py Lib/unittest.py Lib/urllib.py Lib/urllib2.py Lib/warnings.py Lib/weakref.py Lib/xml/dom/minidom.py Lib/xml/sax/expatreader.py Lib/xmlrpclib.py Lib/zipfile.py Mac/BuildScript/build-installer.py Mac/Demo/PICTbrowse/ICONbrowse.py Mac/Demo/PICTbrowse/PICTbrowse.py Mac/Demo/PICTbrowse/PICTbrowse2.py Mac/Demo/PICTbrowse/cicnbrowse.py Mac/Demo/PICTbrowse/oldPICTbrowse.py Mac/Demo/applescript/Disk_Copy/Utility_Events.py Mac/Demo/example1/dnslookup-1.py Mac/Demo/example2/dnslookup-2.py Mac/Demo/imgbrowse/imgbrowse.py Mac/Demo/imgbrowse/mac_image.py Mac/Modules/ae/aescan.py Mac/Modules/ah/ahscan.py Mac/Modules/app/appscan.py Mac/Modules/carbonevt/CarbonEvtscan.py Mac/Modules/cf/cfscan.py Mac/Modules/cg/cgscan.py Mac/Modules/cm/cmscan.py Mac/Modules/ctl/ctlscan.py Mac/Modules/dlg/dlgscan.py Mac/Modules/drag/dragscan.py Mac/Modules/evt/evtscan.py Mac/Modules/file/filescan.py Mac/Modules/fm/fmscan.py Mac/Modules/folder/folderscan.py Mac/Modules/help/helpscan.py Mac/Modules/ibcarbon/IBCarbonscan.py Mac/Modules/icn/icnscan.py Mac/Modules/launch/launchscan.py Mac/Modules/list/listscan.py Mac/Modules/menu/menuscan.py Mac/Modules/mlte/mltescan.py Mac/Modules/osa/osascan.py Mac/Modules/qd/qdscan.py Mac/Modules/qdoffs/qdoffsscan.py Mac/Modules/qt/qtscan.py Mac/Modules/res/resscan.py Mac/Modules/scrap/scrapscan.py Mac/Modules/snd/sndscan.py Mac/Modules/te/tescan.py Mac/Modules/win/winscan.py Mac/Tools/Doc/HelpIndexingTool/Standard_Suite.py Mac/Tools/Doc/setup.py Mac/scripts/buildpkg.py Makefile.pre.in Misc/ACKS Misc/HISTORY Misc/NEWS Misc/RPM/python-2.6.spec Misc/RPM/python-3.0.spec Misc/Vim/python.vim Misc/Vim/syntax_test.py Misc/Vim/vim_syntax.py Misc/build.sh Misc/cheatsheet Misc/developers.txt Misc/python-mode.el Modules/Setup.dist Modules/_bsddb.c Modules/_collectionsmodule.c Modules/_ctypes/_ctypes.c Modules/_ctypes/_ctypes_test.c Modules/_ctypes/callbacks.c Modules/_ctypes/callproc.c Modules/_ctypes/cfield.c Modules/_ctypes/ctypes.h Modules/_ctypes/libffi/LICENSE Modules/_ctypes/libffi/Makefile.am Modules/_ctypes/libffi/Makefile.in Modules/_ctypes/libffi/README Modules/_ctypes/libffi/acinclude.m4 Modules/_ctypes/libffi/aclocal.m4 Modules/_ctypes/libffi/config.guess Modules/_ctypes/libffi/config.sub Modules/_ctypes/libffi/configure Modules/_ctypes/libffi/configure.ac Modules/_ctypes/libffi/configure.host Modules/_ctypes/libffi/fficonfig.h.in Modules/_ctypes/libffi/fficonfig.py.in Modules/_ctypes/libffi/include/Makefile.am Modules/_ctypes/libffi/include/Makefile.in Modules/_ctypes/libffi/include/ffi.h.in Modules/_ctypes/libffi/include/ffi_common.h Modules/_ctypes/libffi/install-sh Modules/_ctypes/libffi/missing Modules/_ctypes/libffi/src/alpha/ffi.c Modules/_ctypes/libffi/src/alpha/ffitarget.h Modules/_ctypes/libffi/src/alpha/osf.S Modules/_ctypes/libffi/src/arm/ffi.c Modules/_ctypes/libffi/src/arm/ffitarget.h Modules/_ctypes/libffi/src/arm/sysv.S Modules/_ctypes/libffi/src/cris/ffi.c Modules/_ctypes/libffi/src/cris/ffitarget.h Modules/_ctypes/libffi/src/frv/eabi.S Modules/_ctypes/libffi/src/frv/ffi.c Modules/_ctypes/libffi/src/frv/ffitarget.h Modules/_ctypes/libffi/src/ia64/ffi.c Modules/_ctypes/libffi/src/ia64/ffitarget.h Modules/_ctypes/libffi/src/ia64/ia64_flags.h Modules/_ctypes/libffi/src/ia64/unix.S Modules/_ctypes/libffi/src/m32r/ffi.c Modules/_ctypes/libffi/src/m68k/ffi.c Modules/_ctypes/libffi/src/m68k/ffitarget.h Modules/_ctypes/libffi/src/m68k/sysv.S Modules/_ctypes/libffi/src/mips/ffi.c Modules/_ctypes/libffi/src/mips/ffitarget.h Modules/_ctypes/libffi/src/mips/n32.S Modules/_ctypes/libffi/src/mips/o32.S Modules/_ctypes/libffi/src/pa/ffi.c Modules/_ctypes/libffi/src/pa/ffitarget.h Modules/_ctypes/libffi/src/pa/hpux32.S Modules/_ctypes/libffi/src/pa/linux.S Modules/_ctypes/libffi/src/powerpc/darwin.S Modules/_ctypes/libffi/src/powerpc/darwin_closure.S Modules/_ctypes/libffi/src/powerpc/ffi.c Modules/_ctypes/libffi/src/powerpc/ffi_darwin.c Modules/_ctypes/libffi/src/powerpc/ffitarget.h Modules/_ctypes/libffi/src/powerpc/linux64.S Modules/_ctypes/libffi/src/powerpc/linux64_closure.S Modules/_ctypes/libffi/src/powerpc/ppc_closure.S Modules/_ctypes/libffi/src/powerpc/sysv.S Modules/_ctypes/libffi/src/prep_cif.c Modules/_ctypes/libffi/src/s390/ffi.c Modules/_ctypes/libffi/src/s390/ffitarget.h Modules/_ctypes/libffi/src/s390/sysv.S Modules/_ctypes/libffi/src/sh/ffi.c Modules/_ctypes/libffi/src/sh/ffitarget.h Modules/_ctypes/libffi/src/sh/sysv.S Modules/_ctypes/libffi/src/sh64/ffi.c Modules/_ctypes/libffi/src/sh64/ffitarget.h Modules/_ctypes/libffi/src/sh64/sysv.S Modules/_ctypes/libffi/src/sparc/ffi.c Modules/_ctypes/libffi/src/sparc/ffitarget.h Modules/_ctypes/libffi/src/sparc/v8.S Modules/_ctypes/libffi/src/sparc/v9.S Modules/_ctypes/libffi/src/x86/darwin.S Modules/_ctypes/libffi/src/x86/darwin64.S Modules/_ctypes/libffi/src/x86/ffi.c Modules/_ctypes/libffi/src/x86/ffi64.c Modules/_ctypes/libffi/src/x86/ffi_darwin.c Modules/_ctypes/libffi/src/x86/ffitarget.h Modules/_ctypes/libffi/src/x86/freebsd.S Modules/_ctypes/libffi/src/x86/sysv.S Modules/_ctypes/libffi/src/x86/unix64.S Modules/_ctypes/libffi/src/x86/win32.S Modules/_ctypes/libffi_osx Modules/_ctypes/stgdict.c Modules/_cursesmodule.c Modules/_fileio.c Modules/_heapqmodule.c Modules/_localemodule.c Modules/_sqlite/cache.c Modules/_sqlite/cache.h Modules/_sqlite/connection.c Modules/_sqlite/connection.h Modules/_sqlite/cursor.c Modules/_sqlite/cursor.h Modules/_sqlite/microprotocols.h Modules/_sqlite/module.c Modules/_sqlite/module.h Modules/_sqlite/prepare_protocol.h Modules/_sqlite/row.c Modules/_sqlite/row.h Modules/_sqlite/statement.c Modules/_sqlite/statement.h Modules/_sqlite/util.c Modules/_sqlite/util.h Modules/_ssl.c Modules/_struct.c Modules/_testcapimodule.c Modules/_tkinter.c Modules/_typesmodule.c Modules/arraymodule.c Modules/binascii.c Modules/cStringIO.c Modules/cjkcodecs/_codecs_hk.c Modules/cjkcodecs/mappings_hk.h Modules/cmathmodule.c Modules/config.c.in Modules/datetimemodule.c Modules/dbmmodule.c Modules/dlmodule.c Modules/fcntlmodule.c Modules/gcmodule.c Modules/gdbmmodule.c Modules/getpath.c Modules/itertoolsmodule.c Modules/main.c Modules/mathmodule.c Modules/mmapmodule.c Modules/operator.c Modules/posixmodule.c Modules/python.c Modules/selectmodule.c Modules/signalmodule.c Modules/socketmodule.c Modules/syslogmodule.c Modules/timemodule.c Modules/zlibmodule.c Objects/abstract.c Objects/bytesobject.c Objects/cellobject.c Objects/classobject.c Objects/codeobject.c Objects/complexobject.c Objects/descrobject.c Objects/dictobject.c Objects/doubledigits.c Objects/floatobject.c Objects/frameobject.c Objects/genobject.c Objects/iterobject.c Objects/listobject.c Objects/longobject.c Objects/methodobject.c Objects/rangeobject.c Objects/setobject.c Objects/stringlib/formatter.h Objects/stringlib/string_format.h Objects/stringlib/stringdefs.h Objects/stringlib/unicodedefs.h Objects/stringobject.c Objects/tupleobject.c Objects/typeobject.c Objects/unicodeobject.c PC/VC6/pythoncore.dsp PC/VS7.1/pythoncore.vcproj PC/VS8.0/build_ssl.py PC/VS8.0/build_tkinter.py PC/VS8.0/pythoncore.vcproj PC/WinMain.c PC/_msi.c PC/_winreg.c PC/config.c PC/example_nt/readme.txt PC/example_nt/setup.py PC/getpathp.c PC/os2emx/Makefile PC/os2emx/README.os2emx PC/os2emx/python25.def PC/os2emx/python26.def PC/os2vacpp/makefile PC/os2vacpp/makefile.omk PC/pyconfig.h PC/python_nt.rc PC/readme.txt PC/w9xpopen.c PCbuild/_bsddb.vcproj PCbuild/_bsddb44.vcproj PCbuild/_hashlib.vcproj PCbuild/_sqlite3.vcproj PCbuild/_ssl.vcproj PCbuild/_tkinter.vcproj PCbuild/bdist_wininst.vcproj PCbuild/build.bat PCbuild/build_ssl.py PCbuild/build_tkinter.py PCbuild/debug.vsprops PCbuild/kill_python.c PCbuild/kill_python.vcproj PCbuild/pcbuild.sln PCbuild/pyd.vsprops PCbuild/pyd_d.vsprops PCbuild/pyproject.vsprops PCbuild/python.vcproj PCbuild/pythoncore.vcproj PCbuild/readme.txt PCbuild/release.vsprops PCbuild/rt.bat PCbuild/sqlite3.vcproj PCbuild/x64.vsprops Parser/Python.asdl Parser/asdl.py Parser/asdl_c.py Parser/parser.c Parser/parser.h Parser/parsetok.c Parser/printgrammar.c Parser/spark.py Parser/tokenizer.c Python/Python-ast.c Python/_warnings.c Python/ast.c Python/bltinmodule.c Python/ceval.c Python/compile.c Python/errors.c Python/frozenmain.c Python/future.c Python/getargs.c Python/getcopyright.c Python/getopt.c Python/graminit.c Python/hypot.c Python/import.c Python/marshal.c Python/memmove.c Python/mystrtoul.c Python/peephole.c Python/pymath.c Python/pystrcmp.c Python/pystrtod.c Python/pythonrun.c Python/strerror.c Python/strtod.c Python/symtable.c Python/sysmodule.c Python/traceback.c README Tools Tools/bgen/bgen/bgenGenerator.py Tools/buildbot/Makefile Tools/buildbot/build-amd64.bat Tools/buildbot/build.bat Tools/buildbot/buildmsi.bat Tools/buildbot/clean-amd64.bat Tools/buildbot/clean.bat Tools/buildbot/external-amd64.bat Tools/buildbot/external-common.bat Tools/buildbot/external.bat Tools/buildbot/kill_python.bat Tools/buildbot/kill_python.c Tools/buildbot/kill_python.mak Tools/buildbot/test-amd64.bat Tools/faqwiz/faqw.py Tools/i18n/pygettext.py Tools/modulator/Tkextra.py Tools/msi/merge.py Tools/msi/msi.py Tools/msi/schema.py Tools/msi/uuids.py Tools/pybench/Setup.py Tools/pybench/With.py Tools/pybench/pybench.py Tools/pybench/systimes.py Tools/pynche/ChipViewer.py Tools/pynche/ColorDB.py Tools/pynche/TypeinViewer.py Tools/scripts Tools/scripts/2to3 Tools/scripts/checkappend.py Tools/scripts/finddiv.py Tools/scripts/logmerge.py Tools/scripts/nm2def.py Tools/scripts/patchcheck.py Tools/scripts/pindent.py Tools/scripts/pysource.py Tools/scripts/reindent.py Tools/scripts/texcheck.py Tools/scripts/xxci.py Tools/ssl/get-remote-certificate.py Tools/unicode/gencodec.py Tools/unicode/makeunicodedata.py Tools/webchecker/wcgui.py Tools/webchecker/wsgui.py configure configure.in pyconfig.h.in setup.py Message-ID: <20080430135756.754971E4007@bag.python.org> Author: thomas.heller Date: Wed Apr 30 15:57:13 2008 New Revision: 62590 Log: Merged revisions 60285-62589 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r60302 | thomas.wouters | 2008-01-26 00:21:16 +0100 (Sat, 26 Jan 2008) | 5 lines Make the testall target work again when building in a separate directory (with '../path/to/source/configure') ................ r60313 | georg.brandl | 2008-01-26 10:39:23 +0100 (Sat, 26 Jan 2008) | 2 lines #1939: update code object docstring. ................ r60315 | georg.brandl | 2008-01-26 10:45:58 +0100 (Sat, 26 Jan 2008) | 2 lines #1929: fix httplib _read_chunked (str/bytes confusion). ................ r60318 | georg.brandl | 2008-01-26 12:23:13 +0100 (Sat, 26 Jan 2008) | 2 lines Fix merge glitch that let test_urllib fail. ................ r60328 | neal.norwitz | 2008-01-26 20:49:41 +0100 (Sat, 26 Jan 2008) | 1 line Get this test to pass ................ r60332 | neal.norwitz | 2008-01-26 22:52:30 +0100 (Sat, 26 Jan 2008) | 1 line Get this test to run ................ r60333 | christian.heimes | 2008-01-26 23:09:42 +0100 (Sat, 26 Jan 2008) | 1 line Copied plistlib.py from r60150 Lib/plat-mac/plistlib.py to Lib/ ................ r60350 | christian.heimes | 2008-01-27 16:18:18 +0100 (Sun, 27 Jan 2008) | 191 lines Merged revisions 60284-60349 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60286 | christian.heimes | 2008-01-25 15:54:23 +0100 (Fri, 25 Jan 2008) | 1 line setup.py doesn't pick up changes to a header file ........ r60287 | christian.heimes | 2008-01-25 16:52:11 +0100 (Fri, 25 Jan 2008) | 2 lines Added the Python core headers Include/*.h and pyconfig.h as dependencies for the extensions in Modules/ It forces a rebuild of all extensions when a header files has been modified ........ r60291 | raymond.hettinger | 2008-01-25 20:24:46 +0100 (Fri, 25 Jan 2008) | 4 lines Changes 54857 and 54840 broke code and were reverted in Py2.5 just before it was released, but that reversion never made it to the Py2.6 head. ........ r60296 | guido.van.rossum | 2008-01-25 20:50:26 +0100 (Fri, 25 Jan 2008) | 2 lines Rewrite the list_inline_repeat overflow check slightly differently. ........ r60301 | thomas.wouters | 2008-01-25 22:09:34 +0100 (Fri, 25 Jan 2008) | 4 lines Use the right (portable) definition of the max of a Py_ssize_t. ........ r60303 | thomas.wouters | 2008-01-26 02:47:05 +0100 (Sat, 26 Jan 2008) | 5 lines Make 'testall' work again when building in a separate directory. test_distutils still fails when doing that. ........ r60305 | neal.norwitz | 2008-01-26 06:54:48 +0100 (Sat, 26 Jan 2008) | 3 lines Prevent this test from failing if there are transient network problems by retrying the host for up to 3 times. ........ r60306 | neal.norwitz | 2008-01-26 08:26:12 +0100 (Sat, 26 Jan 2008) | 12 lines Use a condition variable (threading.Event) rather than sleeps and checking a global to determine when the server is ready to be used. This slows the test down, but should make it correct. There was a race condition before where the server could have assigned a port, yet it wasn't ready to serve requests. If the client sent a request before the server was completely ready, it would get an exception. There was machinery to try to handle this condition. All of that should be unnecessary and removed if this change works. A NOTE was added as a comment about what needs to be fixed. The buildbots will tell us if there are more errors or if this test is now stable. ........ r60307 | neal.norwitz | 2008-01-26 08:38:03 +0100 (Sat, 26 Jan 2008) | 3 lines Fix exception in tearDown on ppc buildbot. If there's no directory, that shouldn't cause the test to fail. Just like it setUp. ........ r60308 | raymond.hettinger | 2008-01-26 09:19:06 +0100 (Sat, 26 Jan 2008) | 3 lines Make PySet_Add() work with frozensets. Works like PyTuple_SetItem() to build-up values in a brand new frozenset. ........ r60309 | neal.norwitz | 2008-01-26 09:26:00 +0100 (Sat, 26 Jan 2008) | 1 line The OS X buildbot had errors with the unavailable exceptions disabled. Restore it. ........ r60310 | raymond.hettinger | 2008-01-26 09:37:28 +0100 (Sat, 26 Jan 2008) | 4 lines Let marshal build-up sets and frozensets one element at a time. Saves the unnecessary creation of a tuple as intermediate container. ........ r60311 | raymond.hettinger | 2008-01-26 09:41:13 +0100 (Sat, 26 Jan 2008) | 1 line Update test code for change to PySet_Add(). ........ r60312 | raymond.hettinger | 2008-01-26 10:31:11 +0100 (Sat, 26 Jan 2008) | 1 line Revert PySet_Add() changes. ........ r60314 | georg.brandl | 2008-01-26 10:43:35 +0100 (Sat, 26 Jan 2008) | 2 lines #1934: fix os.path.isabs docs. ........ r60316 | georg.brandl | 2008-01-26 12:00:18 +0100 (Sat, 26 Jan 2008) | 2 lines Add missing things in re docstring. ........ r60317 | georg.brandl | 2008-01-26 12:02:22 +0100 (Sat, 26 Jan 2008) | 2 lines Slashes allowed on Windows. ........ r60319 | georg.brandl | 2008-01-26 14:41:21 +0100 (Sat, 26 Jan 2008) | 2 lines Fix markup again. ........ r60320 | andrew.kuchling | 2008-01-26 14:50:51 +0100 (Sat, 26 Jan 2008) | 1 line Add some items ........ r60321 | georg.brandl | 2008-01-26 15:02:38 +0100 (Sat, 26 Jan 2008) | 2 lines Clarify "b" mode under Unix. ........ r60322 | georg.brandl | 2008-01-26 15:03:47 +0100 (Sat, 26 Jan 2008) | 3 lines #1940: make it possible to use curses.filter() before curses.initscr() as the documentation says. ........ r60324 | georg.brandl | 2008-01-26 15:14:20 +0100 (Sat, 26 Jan 2008) | 3 lines #1473257: add generator.gi_code attribute that refers to the original code object backing the generator. Patch by Collin Winter. ........ r60325 | georg.brandl | 2008-01-26 15:19:22 +0100 (Sat, 26 Jan 2008) | 2 lines Move C API entries to the corresponding section. ........ r60326 | christian.heimes | 2008-01-26 17:43:35 +0100 (Sat, 26 Jan 2008) | 1 line Unit test fix from Giampaolo Rodola, #1938 ........ r60327 | gregory.p.smith | 2008-01-26 19:51:05 +0100 (Sat, 26 Jan 2008) | 2 lines Update docs for new callpack params added in r60188 ........ r60329 | neal.norwitz | 2008-01-26 21:24:36 +0100 (Sat, 26 Jan 2008) | 3 lines Cleanup the code a bit. test_rfind is failing on PPC and PPC64 buildbots, this might fix the problem. ........ r60330 | neal.norwitz | 2008-01-26 22:02:45 +0100 (Sat, 26 Jan 2008) | 1 line Always try to remove the test file even if close raises an exception ........ r60331 | neal.norwitz | 2008-01-26 22:21:59 +0100 (Sat, 26 Jan 2008) | 3 lines Reduce the race condition by signalling when the server is ready and not trying to connect before. ........ r60334 | neal.norwitz | 2008-01-27 00:13:46 +0100 (Sun, 27 Jan 2008) | 5 lines On some systems (e.g., Ubuntu on hppa) the flush() doesn't cause the exception, but the close() does. Will backport. ........ r60335 | neal.norwitz | 2008-01-27 00:14:17 +0100 (Sun, 27 Jan 2008) | 2 lines Consistently use tempfile.tempdir for the db_home directory. ........ r60338 | neal.norwitz | 2008-01-27 02:44:05 +0100 (Sun, 27 Jan 2008) | 4 lines Eliminate the sleeps that assume the server will start in .5 seconds. This should make the test less flaky. It also speeds up the test by about 75% on my box (20+ seconds -> ~4 seconds). ........ r60342 | neal.norwitz | 2008-01-27 06:02:34 +0100 (Sun, 27 Jan 2008) | 6 lines Try to prevent this test from being flaky. We might need a sleep in here which isn't as bad as it sounds. The close() *should* raise an exception, so if it didn't we should give more time to sync and really raise it. Will backport. ........ r60344 | jeffrey.yasskin | 2008-01-27 06:40:35 +0100 (Sun, 27 Jan 2008) | 3 lines Make rational.gcd() public and allow Rational to take decimal strings, per Raymond's advice. ........ r60345 | neal.norwitz | 2008-01-27 08:36:03 +0100 (Sun, 27 Jan 2008) | 3 lines Mostly reformat. Also set an error and return NULL if neither MS_WINDOWS nor UNIX is defined. This may have caused problems on cygwin. ........ r60346 | neal.norwitz | 2008-01-27 08:37:38 +0100 (Sun, 27 Jan 2008) | 3 lines Use int for the sign rather than a char. char can be signed or unsigned. It's system dependent. This might fix the problem with test_rfind failing. ........ r60347 | neal.norwitz | 2008-01-27 08:41:33 +0100 (Sun, 27 Jan 2008) | 1 line Add stdarg include for va_list to get this to compile on cygwin ........ r60348 | raymond.hettinger | 2008-01-27 11:13:57 +0100 (Sun, 27 Jan 2008) | 1 line Docstring nit ........ r60349 | raymond.hettinger | 2008-01-27 11:47:55 +0100 (Sun, 27 Jan 2008) | 1 line Removed an unnecessary and confusing paragraph from the namedtuple docs. ........ ................ r60351 | christian.heimes | 2008-01-27 16:19:17 +0100 (Sun, 27 Jan 2008) | 1 line Remove plistlib. Apparently svn chokes on svn rm + svn cp in the same revision ................ r60352 | christian.heimes | 2008-01-27 16:20:13 +0100 (Sun, 27 Jan 2008) | 1 line svn cp -r60150 svn+ssh://pythondev at svn.python.org/python/branches/py3k/Lib/plat-mac/plistlib.py Lib/ ................ r60353 | christian.heimes | 2008-01-27 16:45:24 +0100 (Sun, 27 Jan 2008) | 1 line Fixed test_urllibnet ................ r60354 | alexandre.vassalotti | 2008-01-27 17:16:19 +0100 (Sun, 27 Jan 2008) | 4 lines Fix build error. Use a list comprehension instead of filter(), since filter() needs the itertools module which isn't available at build time. ................ r60366 | georg.brandl | 2008-01-27 19:16:00 +0100 (Sun, 27 Jan 2008) | 2 lines Use a list comprehension instead of list(filter()). ................ r60369 | christian.heimes | 2008-01-27 19:55:54 +0100 (Sun, 27 Jan 2008) | 43 lines Merged revisions 60350-60363 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60355 | neal.norwitz | 2008-01-27 18:10:14 +0100 (Sun, 27 Jan 2008) | 1 line Whitespace cleanup ........ r60356 | neal.norwitz | 2008-01-27 18:10:29 +0100 (Sun, 27 Jan 2008) | 1 line Add assertion that we do not blow out newl ........ r60357 | neal.norwitz | 2008-01-27 18:10:35 +0100 (Sun, 27 Jan 2008) | 1 line Initialize variable to prevent warning on some platform/config. ........ r60358 | neal.norwitz | 2008-01-27 18:10:43 +0100 (Sun, 27 Jan 2008) | 1 line Update to newer version of ffi. Fixes crashes and test failures of longdouble ........ r60359 | neal.norwitz | 2008-01-27 18:10:50 +0100 (Sun, 27 Jan 2008) | 1 line Add a tiny sleep and additional flush to force the file to really be synced. ........ r60360 | neal.norwitz | 2008-01-27 18:10:58 +0100 (Sun, 27 Jan 2008) | 1 line Retry connection in case it fails to reduce flakiness ........ r60361 | neal.norwitz | 2008-01-27 18:11:11 +0100 (Sun, 27 Jan 2008) | 4 lines Catch socket errors that are often the cause of transient failures. Many of these exceptions are due to resource unavailable, so the existing code should be able to handle many more spurious errors. ........ r60362 | neal.norwitz | 2008-01-27 18:12:15 +0100 (Sun, 27 Jan 2008) | 1 line Reduce buffer size since we do not need 1k ........ r60363 | neal.norwitz | 2008-01-27 18:13:07 +0100 (Sun, 27 Jan 2008) | 1 line Print periodic "still working" messages since this suite is slow. ........ ................ r60376 | eric.smith | 2008-01-27 22:07:59 +0100 (Sun, 27 Jan 2008) | 1 line Restrict format presentation types to those specified in the 'Standard Format Specifiers' section of PEP 3101. ................ r60379 | christian.heimes | 2008-01-28 00:50:43 +0100 (Mon, 28 Jan 2008) | 44 lines Merged revisions 60364-60378 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60364 | neal.norwitz | 2008-01-27 19:09:48 +0100 (Sun, 27 Jan 2008) | 4 lines Update the comment and remove the close. If we close we can't flush anymore. We might still need to close after the for loop if flushing 6! times still doesn't cause the signal/exception. ........ r60365 | georg.brandl | 2008-01-27 19:14:43 +0100 (Sun, 27 Jan 2008) | 2 lines Remove effectless expression statement. ........ r60367 | neal.norwitz | 2008-01-27 19:19:04 +0100 (Sun, 27 Jan 2008) | 1 line Try to handle socket.errors properly in is_unavailable ........ r60370 | christian.heimes | 2008-01-27 20:01:45 +0100 (Sun, 27 Jan 2008) | 1 line Change isbasestring function as discussed on the cvs list a while ago ........ r60372 | neal.norwitz | 2008-01-27 21:03:13 +0100 (Sun, 27 Jan 2008) | 3 lines socket.error doesn't have a headers attribute like ProtocolError. Handle that situation where we catch socket.errors. ........ r60375 | georg.brandl | 2008-01-27 21:25:12 +0100 (Sun, 27 Jan 2008) | 2 lines Add refcounting extension to build config. ........ r60377 | jeffrey.yasskin | 2008-01-28 00:08:46 +0100 (Mon, 28 Jan 2008) | 6 lines Moved Rational._binary_float_to_ratio() to float.as_integer_ratio() because it's useful outside of rational numbers. This is my first C code that had to do anything significant. Please be more careful when looking over it. ........ r60378 | christian.heimes | 2008-01-28 00:34:59 +0100 (Mon, 28 Jan 2008) | 1 line Added clear cache methods to clear the internal type lookup cache for ref leak test runs. ........ ................ r60383 | christian.heimes | 2008-01-28 03:38:20 +0100 (Mon, 28 Jan 2008) | 9 lines Merged revisions 60379-60382 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60381 | christian.heimes | 2008-01-28 03:07:53 +0100 (Mon, 28 Jan 2008) | 1 line static PyObject* variables should use PyString_InternFromString() instead of PyObject_FromString() to store a python string in a function level static var. ........ ................ r60390 | eric.smith | 2008-01-28 11:59:27 +0100 (Mon, 28 Jan 2008) | 1 line Partially revert r60376: restore ability for ints to be automatically converted to floats, if a float type specifier is given to an int. PEP 3101 should be clarified on this point.Also, remove unused local variables left over from r60376. ................ r60394 | christian.heimes | 2008-01-28 19:36:44 +0100 (Mon, 28 Jan 2008) | 1 line Fixed two bugs in the bsddb tests. One was reported as #1956 ................ r60396 | christian.heimes | 2008-01-28 20:26:56 +0100 (Mon, 28 Jan 2008) | 1 line Another fix for the bsddb3 tests ................ r60408 | christian.heimes | 2008-01-29 13:18:50 +0100 (Tue, 29 Jan 2008) | 50 lines Merged revisions 60383-60407 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60388 | thomas.heller | 2008-01-28 09:44:13 +0100 (Mon, 28 Jan 2008) | 1 line Revert rev. 59925, it breaks comtypes (I need to further examine this). ........ r60397 | raymond.hettinger | 2008-01-28 21:34:33 +0100 (Mon, 28 Jan 2008) | 5 lines Make PySet_Add() work with frozensets. Works like PyTuple_SetItem() to build-up values in a brand new frozenset. Also, PyFrozenSet_New() is now guaranteed to produce a distinct new frozenset. ........ r60398 | raymond.hettinger | 2008-01-28 22:34:30 +0100 (Mon, 28 Jan 2008) | 1 line Let marshal built-up sets and frozensets one element at a time (without creating an intermediate tuple). ........ r60399 | raymond.hettinger | 2008-01-28 22:47:42 +0100 (Mon, 28 Jan 2008) | 1 line Factor-out common code with a new macro ........ r60400 | raymond.hettinger | 2008-01-28 22:48:07 +0100 (Mon, 28 Jan 2008) | 1 line Factor-out common code with a new macro ........ r60401 | raymond.hettinger | 2008-01-28 22:51:25 +0100 (Mon, 28 Jan 2008) | 1 line Removed unnecessary conditional (spotted by Neal Norwitz). ........ r60403 | gregory.p.smith | 2008-01-29 00:21:00 +0100 (Tue, 29 Jan 2008) | 4 lines Disable use of BerkeleyDB 4.6.x to see what the odd platform buildbots think. In particular, neal norwitz has traced an Ubuntu sparc64 crash to the Lib/test/bsddb/test_basics.py test when opening a db with DB_THREAD. ........ r60405 | brett.cannon | 2008-01-29 05:13:07 +0100 (Tue, 29 Jan 2008) | 2 lines Fix the reindent rule to use $(BUILDPYTHON). ........ r60406 | brett.cannon | 2008-01-29 05:18:04 +0100 (Tue, 29 Jan 2008) | 3 lines Update Vim syntax highlighting to specify what revision was used to generate the file. ........ r60407 | brett.cannon | 2008-01-29 05:20:56 +0100 (Tue, 29 Jan 2008) | 2 lines Ignore .pyc and .pyo files. ........ ................ r60434 | raymond.hettinger | 2008-01-30 03:55:10 +0100 (Wed, 30 Jan 2008) | 1 line Convert some custom sort comparison functions to equivalent key functions. ................ r60437 | christian.heimes | 2008-01-30 10:51:48 +0100 (Wed, 30 Jan 2008) | 1 line Fixed #1969: split and rsplit in bytearray are inconsistent ................ r60438 | christian.heimes | 2008-01-30 12:27:57 +0100 (Wed, 30 Jan 2008) | 1 line Fixed issue #1973: bytes.fromhex('') raises SystemError ................ r60439 | christian.heimes | 2008-01-30 12:28:29 +0100 (Wed, 30 Jan 2008) | 1 line Fixed issue #1973: bytes.fromhex('') raises SystemError ................ r60442 | christian.heimes | 2008-01-30 12:57:58 +0100 (Wed, 30 Jan 2008) | 1 line Patch #1972 by Antoine Pitrou: improve bytes and bytearray tests ................ r60443 | christian.heimes | 2008-01-30 12:58:22 +0100 (Wed, 30 Jan 2008) | 25 lines Merged revisions 60408-60440 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60425 | raymond.hettinger | 2008-01-29 20:52:09 +0100 (Tue, 29 Jan 2008) | 1 line CallMethod is faster with a NULL third-argument than with an empty format string. ........ r60431 | raymond.hettinger | 2008-01-30 01:01:07 +0100 (Wed, 30 Jan 2008) | 1 line Add isdisjoint() to the Set/MutableSet ABCs. ........ r60432 | raymond.hettinger | 2008-01-30 01:08:31 +0100 (Wed, 30 Jan 2008) | 1 line MutableSets support a remove() method. ........ r60433 | raymond.hettinger | 2008-01-30 01:51:58 +0100 (Wed, 30 Jan 2008) | 1 line Demonstrate new except/as syntax. ........ r60440 | christian.heimes | 2008-01-30 12:32:37 +0100 (Wed, 30 Jan 2008) | 1 line Patch #1970 by Antoine Pitrou: Speedup unicode whitespace and linebreak detection. The speedup is about 25% for split() (571 / 457 usec) and 35% (175 / 127 usec )for splitlines() ........ ................ r60444 | christian.heimes | 2008-01-30 13:01:19 +0100 (Wed, 30 Jan 2008) | 1 line Removed unused import ................ r60447 | christian.heimes | 2008-01-30 16:02:52 +0100 (Wed, 30 Jan 2008) | 1 line Enabled fromhex('') test for bytes ................ r60453 | raymond.hettinger | 2008-01-30 21:15:17 +0100 (Wed, 30 Jan 2008) | 1 line Issue #1771: Remove cmp parameter from list.sort() and builtin.sorted(). ................ r60466 | raymond.hettinger | 2008-01-31 00:33:08 +0100 (Thu, 31 Jan 2008) | 1 line Remove duplicate function. ................ r60467 | christian.heimes | 2008-01-31 02:08:32 +0100 (Thu, 31 Jan 2008) | 1 line Fixed r60466 ................ r60468 | raymond.hettinger | 2008-01-31 02:10:03 +0100 (Thu, 31 Jan 2008) | 1 line Update pprint() to match the new repr style for frozensets ................ r60476 | christian.heimes | 2008-01-31 15:31:45 +0100 (Thu, 31 Jan 2008) | 42 lines Merged revisions 60441-60474 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60441 | christian.heimes | 2008-01-30 12:46:00 +0100 (Wed, 30 Jan 2008) | 1 line Removed unused var ........ r60448 | christian.heimes | 2008-01-30 18:21:22 +0100 (Wed, 30 Jan 2008) | 1 line Fixed some references leaks in sys. ........ r60450 | christian.heimes | 2008-01-30 19:58:29 +0100 (Wed, 30 Jan 2008) | 1 line The previous change was causing a segfault after multiple calls to Py_Initialize() and Py_Finalize(). ........ r60463 | raymond.hettinger | 2008-01-30 23:17:31 +0100 (Wed, 30 Jan 2008) | 1 line Update itertool recipes ........ r60464 | christian.heimes | 2008-01-30 23:54:18 +0100 (Wed, 30 Jan 2008) | 1 line Bug #1234: Fixed semaphore errors on AIX 5.2 ........ r60469 | raymond.hettinger | 2008-01-31 02:38:15 +0100 (Thu, 31 Jan 2008) | 6 lines Fix defect in __ixor__ which would get the wrong answer if the input iterable had a duplicate element (two calls to toggle() reverse each other). Borrow the correct code from sets.py. ........ r60470 | raymond.hettinger | 2008-01-31 02:42:11 +0100 (Thu, 31 Jan 2008) | 1 line Missing return ........ r60471 | jeffrey.yasskin | 2008-01-31 08:44:11 +0100 (Thu, 31 Jan 2008) | 4 lines Added more documentation on how mixed-mode arithmetic should be implemented. I also noticed and fixed a bug in Rational's forward operators (they were claiming all instances of numbers.Rational instead of just the concrete types). ........ ................ r60477 | christian.heimes | 2008-01-31 16:16:38 +0100 (Thu, 31 Jan 2008) | 1 line Fixed multiple reinitialization of the Python interpreter. The small int list in longobject.c has caused a seg fault during the third finalization. ................ r60481 | christian.heimes | 2008-01-31 19:04:10 +0100 (Thu, 31 Jan 2008) | 1 line svnmerge.py block -r60480 ................ r60485 | bill.janssen | 2008-02-01 03:16:46 +0100 (Fri, 01 Feb 2008) | 1 line fix bug 1482: IMAP4 SSL isn't working ................ r60489 | christian.heimes | 2008-02-01 09:12:03 +0100 (Fri, 01 Feb 2008) | 34 lines Merged revisions 60475-60479,60481-60488 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60482 | raymond.hettinger | 2008-01-31 23:07:16 +0100 (Thu, 31 Jan 2008) | 1 line Minor wordsmithing on docstring ........ r60483 | mark.dickinson | 2008-01-31 23:17:37 +0100 (Thu, 31 Jan 2008) | 5 lines Issue #1678380. Fix a bug that identifies 0j and -0j when they appear in the same code unit. The fix is essentially the same as the fix for a previous bug identifying 0. and -0. ........ r60484 | christian.heimes | 2008-02-01 00:08:23 +0100 (Fri, 01 Feb 2008) | 1 line Fixed bug #1983: Return from fork() is pid_t, not int ........ r60486 | jeffrey.yasskin | 2008-02-01 07:22:46 +0100 (Fri, 01 Feb 2008) | 4 lines Move __builtins__.trunc() to math.trunc() per http://mail.python.org/pipermail/python-dev/2008-January/076626.html and issue 1965. ........ r60487 | jeffrey.yasskin | 2008-02-01 08:05:46 +0100 (Fri, 01 Feb 2008) | 3 lines Roll back r60248. It's useful to encourage users not to change Rational instances. ........ r60488 | neal.norwitz | 2008-02-01 08:22:59 +0100 (Fri, 01 Feb 2008) | 1 line Fix refleak ........ ................ r60491 | georg.brandl | 2008-02-01 12:30:18 +0100 (Fri, 01 Feb 2008) | 2 lines Remove the deprecated array.read/write methods. ................ r60492 | georg.brandl | 2008-02-01 12:56:49 +0100 (Fri, 01 Feb 2008) | 2 lines Update docs w.r.t. PEP 3100 changes -- patch for GHOP by Dan Finnie. ................ r60495 | georg.brandl | 2008-02-01 16:47:37 +0100 (Fri, 01 Feb 2008) | 2 lines Make print docstring consistent with its docs. ................ r60498 | christian.heimes | 2008-02-01 17:56:30 +0100 (Fri, 01 Feb 2008) | 1 line Get the ref counting for static allocated longs right. ................ r60508 | raymond.hettinger | 2008-02-01 21:38:12 +0100 (Fri, 01 Feb 2008) | 1 line Context flags get set, not incremented. ................ r60523 | georg.brandl | 2008-02-02 11:30:18 +0100 (Sat, 02 Feb 2008) | 2 lines Some new 3.0 whatsnew items, written for GHOP by Andreas Freund. ................ r60524 | georg.brandl | 2008-02-02 11:44:37 +0100 (Sat, 02 Feb 2008) | 2 lines Update whatsnew document to use specific markup for identifiers, thus enabling cross-linking. ................ r60552 | christian.heimes | 2008-02-03 17:51:08 +0100 (Sun, 03 Feb 2008) | 159 lines Merged revisions 60481,60485,60489-60520,60523-60527,60530-60533,60535-60538,60540-60551 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk NOTE: I blocked the following revisions: svnmerge.py block -r 60521,60522,60528,60529,60534,60539 The new tests must be merged with lots of manual work. ........ r60493 | georg.brandl | 2008-02-01 12:59:08 +0100 (Fri, 01 Feb 2008) | 2 lines Update IPv6 RFC number. ........ r60497 | georg.brandl | 2008-02-01 16:50:15 +0100 (Fri, 01 Feb 2008) | 2 lines Add link checker builder, written for GHOP by Thomas Lamb. ........ r60500 | georg.brandl | 2008-02-01 19:08:09 +0100 (Fri, 01 Feb 2008) | 2 lines Rename batch file. ........ r60504 | christian.heimes | 2008-02-01 19:49:26 +0100 (Fri, 01 Feb 2008) | 1 line More int -> pid_t. ........ r60507 | georg.brandl | 2008-02-01 20:24:01 +0100 (Fri, 01 Feb 2008) | 2 lines Wording nit. ........ r60510 | georg.brandl | 2008-02-01 21:45:33 +0100 (Fri, 01 Feb 2008) | 2 lines Update for latest sphinx latex writer. ........ r60511 | raymond.hettinger | 2008-02-01 22:30:23 +0100 (Fri, 01 Feb 2008) | 1 line Issue #1996: float.as_integer_ratio() should return fraction in lowest terms. ........ r60512 | raymond.hettinger | 2008-02-01 23:15:52 +0100 (Fri, 01 Feb 2008) | 1 line Integer ratio should return ints instead of longs whereever possible. ........ r60513 | raymond.hettinger | 2008-02-01 23:22:50 +0100 (Fri, 01 Feb 2008) | 1 line labs() takes a long for an input. ........ r60514 | raymond.hettinger | 2008-02-01 23:42:59 +0100 (Fri, 01 Feb 2008) | 1 line Test round-trip on float.as_integer_ratio() and float.__truediv__(). ........ r60515 | marc-andre.lemburg | 2008-02-01 23:58:17 +0100 (Fri, 01 Feb 2008) | 3 lines Bump distutils version number to match Python version. ........ r60516 | raymond.hettinger | 2008-02-02 00:12:19 +0100 (Sat, 02 Feb 2008) | 1 line Fix int/long typecase. Add check for non-binary floating point. ........ r60517 | raymond.hettinger | 2008-02-02 00:45:44 +0100 (Sat, 02 Feb 2008) | 1 line Add protection from weirdness while scaling the mantissa to an integer. ........ r60518 | raymond.hettinger | 2008-02-02 06:11:40 +0100 (Sat, 02 Feb 2008) | 1 line Simpler solution to handling non-IEEE 754 environments. ........ r60519 | raymond.hettinger | 2008-02-02 06:24:44 +0100 (Sat, 02 Feb 2008) | 1 line Neaten-up a bit. ........ r60520 | georg.brandl | 2008-02-02 10:56:20 +0100 (Sat, 02 Feb 2008) | 2 lines Amendments to the urllib2 docs, written for GHOP by Thomas Lamb. ........ r60525 | georg.brandl | 2008-02-02 11:49:58 +0100 (Sat, 02 Feb 2008) | 3 lines Add email example how to send a multipart message. Written for GHOP by Martin Matejek. ........ r60526 | georg.brandl | 2008-02-02 12:05:00 +0100 (Sat, 02 Feb 2008) | 2 lines Rewrite test_socketserver as unittest, written for GHOP by Benjamin Petersen. ........ r60527 | georg.brandl | 2008-02-02 12:05:34 +0100 (Sat, 02 Feb 2008) | 2 lines Add GHOP contributor. ........ r60530 | mark.dickinson | 2008-02-02 18:16:13 +0100 (Sat, 02 Feb 2008) | 2 lines Make the Rational constructor accept '3.' and '.2' as well as '3.2'. ........ r60531 | neal.norwitz | 2008-02-02 19:52:51 +0100 (Sat, 02 Feb 2008) | 1 line Update the leaky tests (ie, ignore these tests if they report leaks). This version has been running for a while. ........ r60533 | skip.montanaro | 2008-02-02 20:11:57 +0100 (Sat, 02 Feb 2008) | 7 lines Split the refleak mail body into two parts, the first being those failing tests which are deemed more important issues, the second those which are known to have difficult to solve problems and are generally expected to leak. Hopefully this doesn't break the script... ........ r60535 | georg.brandl | 2008-02-03 01:04:50 +0100 (Sun, 03 Feb 2008) | 3 lines Wait for a delay before reaping children -- this should fix the test_socketserver failures on several platforms. ........ r60536 | brett.cannon | 2008-02-03 03:07:55 +0100 (Sun, 03 Feb 2008) | 2 lines Fix a minor typo. ........ r60537 | brett.cannon | 2008-02-03 03:08:45 +0100 (Sun, 03 Feb 2008) | 3 lines Directories from CPPFLAGS and LDFLAGS were being added in the reverse order for searches as to how they were listed in the environment variable. ........ r60538 | brett.cannon | 2008-02-03 03:34:14 +0100 (Sun, 03 Feb 2008) | 2 lines Remove extra tick marks and add a missing closing parenthesis. ........ r60540 | andrew.macintyre | 2008-02-03 07:58:06 +0100 (Sun, 03 Feb 2008) | 2 lines Update OS/2 EMX build bits for 2.6. ........ r60541 | andrew.macintyre | 2008-02-03 08:01:11 +0100 (Sun, 03 Feb 2008) | 2 lines Rename module definition file to reflect v2.6. ........ r60542 | andrew.macintyre | 2008-02-03 08:07:31 +0100 (Sun, 03 Feb 2008) | 6 lines The wrapper function is supposed to be for spawnvpe() so that's what we should call [this wrapper only available on OS/2]. Backport candidate to 2.5. ........ r60544 | gregory.p.smith | 2008-02-03 08:20:53 +0100 (Sun, 03 Feb 2008) | 6 lines Merge this fix from the pybsddb tree: r293 | jcea | 2008-01-31 01:08:19 -0800 (Thu, 31 Jan 2008) | 4 lines Solved memory leak when using cursors with databases without environment. ........ r60546 | gregory.p.smith | 2008-02-03 09:01:46 +0100 (Sun, 03 Feb 2008) | 2 lines remove a repeated occurance of a hardcoded berkeleydb library version number ........ r60549 | brett.cannon | 2008-02-03 10:59:21 +0100 (Sun, 03 Feb 2008) | 2 lines Add an entry for r60537. ........ r60550 | georg.brandl | 2008-02-03 13:29:00 +0100 (Sun, 03 Feb 2008) | 2 lines #2003: fix sentence. ........ r60551 | christian.heimes | 2008-02-03 15:34:18 +0100 (Sun, 03 Feb 2008) | 2 lines Fixed paths to Windows build directories in build_ext.py Use vsbuild instead of devenv in build.bat and _bsddb.vcproj ........ ................ r60554 | christian.heimes | 2008-02-03 18:32:13 +0100 (Sun, 03 Feb 2008) | 1 line Fixed socketserver tests ................ r60569 | christian.heimes | 2008-02-04 19:48:49 +0100 (Mon, 04 Feb 2008) | 44 lines Merged revisions 60481,60485,60489-60492,60494-60496,60498-60499,60501-60503,60505-60506,60508-60509,60523-60524,60532,60543,60545,60547-60548,60552-60567 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60553 | neal.norwitz | 2008-02-03 17:53:09 +0100 (Sun, 03 Feb 2008) | 1 line Ignore leaky warnings from test_asynchat ........ r60555 | christian.heimes | 2008-02-03 20:51:13 +0100 (Sun, 03 Feb 2008) | 1 line Another int -> pid_t case ........ r60560 | amaury.forgeotdarc | 2008-02-03 23:51:43 +0100 (Sun, 03 Feb 2008) | 6 lines Ensure that PySet_Add() operates on a newly created frozenset, like PyTuple_SetItem does. Add PyFrozenSet_Check(), which was not needed before; The list of Py*Set_Check* macros seems to be complete now. Add missing NEWS entries about all this. ........ r60563 | amaury.forgeotdarc | 2008-02-04 00:14:32 +0100 (Mon, 04 Feb 2008) | 2 lines Nasty typo in setobject.h ........ r60564 | amaury.forgeotdarc | 2008-02-04 00:15:32 +0100 (Mon, 04 Feb 2008) | 3 lines Correct test_mailbox on win32: since the test sets a custom 'colon' attribute to the main mailbox, copy it to secondary mailbox instances. ........ r60565 | amaury.forgeotdarc | 2008-02-04 00:57:24 +0100 (Mon, 04 Feb 2008) | 2 lines Let test_socketserver pass on win32, which does not have AF_UNIX sockets. ........ r60566 | jeffrey.yasskin | 2008-02-04 02:04:35 +0100 (Mon, 04 Feb 2008) | 2 lines Make int() and long() fall back to __trunc__(). See issue 2002. ........ r60567 | christian.heimes | 2008-02-04 19:00:12 +0100 (Mon, 04 Feb 2008) | 3 lines Patch #1953 I implemented the function sys._compact_freelists() and C API functions PyInt_/PyFloat_CompactFreeList() to compact the pre-allocated blocks of ints and floats. They allow the user to reduce the memory usage of a Python process that deals with lots of numbers. The patch also renames sys._cleartypecache to sys._clear_type_cache ........ ................ r60571 | raymond.hettinger | 2008-02-04 21:44:31 +0100 (Mon, 04 Feb 2008) | 1 line Start replacing UserDict.DictMixin with collections.MutableMapping (the bsddb modules are next). ................ r60572 | raymond.hettinger | 2008-02-04 21:50:22 +0100 (Mon, 04 Feb 2008) | 1 line Save bsddb changes for a separate check-in. ................ r60574 | raymond.hettinger | 2008-02-04 22:26:27 +0100 (Mon, 04 Feb 2008) | 5 lines In bsddb, replace UserDict.DictMixin with collections.MutableMapping. I can't test this directly on my build, so letting the buildbots do it for me. If it fails, expect a reversion. ................ r60577 | raymond.hettinger | 2008-02-04 23:07:15 +0100 (Mon, 04 Feb 2008) | 1 line Remove DictMixin which is superceded by collections.MutableMapping ................ r60578 | raymond.hettinger | 2008-02-04 23:09:30 +0100 (Mon, 04 Feb 2008) | 1 line Fix typo (thanks Nick). ................ r60580 | raymond.hettinger | 2008-02-04 23:43:27 +0100 (Mon, 04 Feb 2008) | 1 line Remove one use of UserDict.UserDict ................ r60583 | raymond.hettinger | 2008-02-05 01:20:01 +0100 (Tue, 05 Feb 2008) | 5 lines Moved WeakSet into a bootstap module use by abc.py. This makes it possible to use ABCs in weakref.py (which will be done in a later checkin). ................ r60585 | raymond.hettinger | 2008-02-05 02:15:57 +0100 (Tue, 05 Feb 2008) | 8 lines Decouple weakref containers from UserDict and teach them to use ABC instead. More work left to do later. Still need to modernize the API of the dictlike objects to more closely match regulars dicts. ................ r60586 | raymond.hettinger | 2008-02-05 02:53:00 +0100 (Tue, 05 Feb 2008) | 8 lines Put an updated UserDict class in the collections module and register it as a compliant Mutable Mapping. Todo: Convert the UserDict dependent tests to the new API and then remove the old UserDict module. Move the UserDict docs to collections.rst. ................ r60591 | raymond.hettinger | 2008-02-05 13:10:29 +0100 (Tue, 05 Feb 2008) | 1 line Fix-up mapping equality tests to include both keys and values ................ r60597 | georg.brandl | 2008-02-05 19:13:15 +0100 (Tue, 05 Feb 2008) | 2 lines Manually merge r60521 from trunk. ................ r60598 | georg.brandl | 2008-02-05 19:31:41 +0100 (Tue, 05 Feb 2008) | 2 lines Merge r60522 from trunk. ................ r60600 | georg.brandl | 2008-02-05 19:33:58 +0100 (Tue, 05 Feb 2008) | 8 lines Blocked revisions 60599 via svnmerge ........ r60599 | georg.brandl | 2008-02-05 19:32:47 +0100 (Tue, 05 Feb 2008) | 2 lines Fix unittest conversion breakage. ........ ................ r60601 | georg.brandl | 2008-02-05 19:48:51 +0100 (Tue, 05 Feb 2008) | 2 lines Merge r60528, r60534 and r60539 from trunk. ................ r60607 | georg.brandl | 2008-02-05 21:48:58 +0100 (Tue, 05 Feb 2008) | 2 lines Respect EOL 80. ................ r60608 | georg.brandl | 2008-02-05 22:00:53 +0100 (Tue, 05 Feb 2008) | 2 lines Fix. ................ r60609 | raymond.hettinger | 2008-02-05 23:54:43 +0100 (Tue, 05 Feb 2008) | 5 lines Convert test_userdict to use the collections.UserDict. Fix-up collections.UserDict.__contains__ to work correctly when __missing__ is defined. Fix-up Mapping.__eq__ to only match instances of Mapping. ................ r60610 | raymond.hettinger | 2008-02-06 01:07:11 +0100 (Wed, 06 Feb 2008) | 1 line Migrate remaining tests from UserDict.UserDict to collections.UserDict. ................ r60611 | raymond.hettinger | 2008-02-06 01:15:42 +0100 (Wed, 06 Feb 2008) | 1 line Remove the old UserDict module. ................ r60612 | raymond.hettinger | 2008-02-06 02:23:58 +0100 (Wed, 06 Feb 2008) | 3 lines Update docs for collections ABCs and for collections.UserDict. ................ r60615 | mark.summerfield | 2008-02-06 14:30:44 +0100 (Wed, 06 Feb 2008) | 3 lines Fixed a table and a title that were broken. ................ r60617 | christian.heimes | 2008-02-06 15:31:34 +0100 (Wed, 06 Feb 2008) | 106 lines Merged revisions 60481,60485,60489-60492,60494-60496,60498-60499,60501-60503,60505-60506,60508-60509,60523-60524,60532,60543,60545,60547-60548,60552,60554,60556-60559,60561-60562,60568-60598,60600-60616 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60568 | christian.heimes | 2008-02-04 19:48:38 +0100 (Mon, 04 Feb 2008) | 1 line Increase debugging to investige failing tests on some build bots ........ r60570 | christian.heimes | 2008-02-04 20:30:05 +0100 (Mon, 04 Feb 2008) | 1 line Small adjustments for test compact freelist test. It's no passing on Windows as well. ........ r60573 | amaury.forgeotdarc | 2008-02-04 21:53:14 +0100 (Mon, 04 Feb 2008) | 2 lines Correct quotes in NEWS file ........ r60575 | amaury.forgeotdarc | 2008-02-04 22:45:05 +0100 (Mon, 04 Feb 2008) | 13 lines #1750076: Debugger did not step on every iteration of a while statement. The mapping between bytecode offsets and source lines (lnotab) did not contain an entry for the beginning of the loop. Now it does, and the lnotab can be a bit larger: in particular, several statements on the same line generate several entries. However, this does not bother the settrace function, which will trigger only one 'line' event. The lnotab seems to be exactly the same as with python2.4. ........ r60584 | amaury.forgeotdarc | 2008-02-05 01:26:21 +0100 (Tue, 05 Feb 2008) | 3 lines Change r60575 broke test_compile: there is no need to emit co_lnotab item when both offsets are zeros. ........ r60587 | skip.montanaro | 2008-02-05 03:32:16 +0100 (Tue, 05 Feb 2008) | 1 line sync with most recent version from python-mode sf project ........ r60588 | lars.gustaebel | 2008-02-05 12:51:40 +0100 (Tue, 05 Feb 2008) | 5 lines Issue #2004: Use mode 0700 for temporary directories and default permissions for missing directories. (will backport to 2.5) ........ r60590 | georg.brandl | 2008-02-05 13:01:24 +0100 (Tue, 05 Feb 2008) | 2 lines Convert external links to internal links. Fixes #2010. ........ r60592 | marc-andre.lemburg | 2008-02-05 15:50:40 +0100 (Tue, 05 Feb 2008) | 3 lines Keep distutils Python 2.1 compatible (or even Python 2.4 in this case). ........ r60593 | andrew.kuchling | 2008-02-05 17:06:57 +0100 (Tue, 05 Feb 2008) | 5 lines Update PEP URL. (This code is duplicated between pydoc and DocXMLRPCServer; maybe it should be refactored as a GHOP project.) 2.5.2 backport candidate. ........ r60596 | guido.van.rossum | 2008-02-05 18:32:15 +0100 (Tue, 05 Feb 2008) | 2 lines In the experimental 'Scanner' feature, the group count was set wrong. ........ r60602 | facundo.batista | 2008-02-05 20:03:32 +0100 (Tue, 05 Feb 2008) | 3 lines Issue 1951. Converts wave test cases to unittest. ........ r60603 | georg.brandl | 2008-02-05 20:07:10 +0100 (Tue, 05 Feb 2008) | 2 lines Actually run the test. ........ r60604 | skip.montanaro | 2008-02-05 20:24:30 +0100 (Tue, 05 Feb 2008) | 2 lines correct object name ........ r60605 | georg.brandl | 2008-02-05 20:58:17 +0100 (Tue, 05 Feb 2008) | 7 lines * Use the same code to profile for test_profile and test_cprofile. * Convert both to unittest. * Use the same unit testing code. * Include the expected output in both test files. * Make it possible to regenerate the expected output by running the file as a script with an '-r' argument. ........ r60613 | raymond.hettinger | 2008-02-06 02:49:00 +0100 (Wed, 06 Feb 2008) | 1 line Sync-up with Py3k work. ........ r60614 | christian.heimes | 2008-02-06 13:44:34 +0100 (Wed, 06 Feb 2008) | 1 line Limit free list of method and builtin function objects to 256 entries each. ........ r60616 | christian.heimes | 2008-02-06 14:33:44 +0100 (Wed, 06 Feb 2008) | 7 lines Unified naming convention for free lists and their limits. All free lists in Object/ are named ``free_list``, the counter ``numfree`` and the upper limit is a macro ``PyName_MAXFREELIST`` inside an #ifndef block. The chances should make it easier to adjust Python for platforms with less memory, e.g. mobile phones. ........ ................ r60623 | raymond.hettinger | 2008-02-06 20:54:00 +0100 (Wed, 06 Feb 2008) | 6 lines Fix-up the collections docs. * Start filling in detail and examples for ABCs * Fix old reference to IterableUserDict. * Neaten-up the introduction. ................ r60627 | raymond.hettinger | 2008-02-06 21:47:09 +0100 (Wed, 06 Feb 2008) | 8 lines Fix-up the _from_iterable() method to return instances of the subclass where it is used. In its previous form, it always returned instance of frozenset which makes this ABC nearly useless as a mixin. In its new form, it needs to be able to assume that the constructor will take a frozenset input. This will usually be true. If it is not, then only one method (this one) will need to be overriden by the subclass to let it know about the unique constructor signature. Will add info on this to the docs. ................ r60628 | raymond.hettinger | 2008-02-06 21:59:41 +0100 (Wed, 06 Feb 2008) | 1 line Let the world know that UserList is a MutableSequence. ................ r60631 | raymond.hettinger | 2008-02-06 23:14:55 +0100 (Wed, 06 Feb 2008) | 1 line MutableSequence requires an insert() method. ................ r60633 | raymond.hettinger | 2008-02-06 23:45:43 +0100 (Wed, 06 Feb 2008) | 1 line Reversed UserLists are not required to support __length_hint__. ................ r60635 | raymond.hettinger | 2008-02-07 01:41:02 +0100 (Thu, 07 Feb 2008) | 4 lines Issue 2025: Add index() and count() methods to tuple so that it will follow the ABC for collections.Sequence. ................ r60656 | raymond.hettinger | 2008-02-07 21:09:43 +0100 (Thu, 07 Feb 2008) | 1 line Simplify float conversion recipe. ................ r60669 | mark.summerfield | 2008-02-08 14:24:20 +0100 (Fri, 08 Feb 2008) | 3 lines Tiny grammatical fix. ................ r60676 | raymond.hettinger | 2008-02-09 00:46:23 +0100 (Sat, 09 Feb 2008) | 1 line Smalls improvement to example in the docs for collections ABCs. ................ r60678 | raymond.hettinger | 2008-02-09 01:08:16 +0100 (Sat, 09 Feb 2008) | 3 lines Merge r60674 an 60675. ................ r60680 | raymond.hettinger | 2008-02-09 03:17:06 +0100 (Sat, 09 Feb 2008) | 6 lines Finish the collections ABC table. Identify which abstract methods need to be defined. Show the inheritance hierarchy. List all of the mixin methods provided automatically. ................ r60681 | christian.heimes | 2008-02-09 03:18:51 +0100 (Sat, 09 Feb 2008) | 162 lines Merged revisions 60481,60485,60489-60492,60494-60496,60498-60499,60501-60503,60505-60506,60508-60509,60523-60524,60532,60543,60545,60547-60548,60552,60554,60556-60559,60561-60562,60569,60571-60572,60574,60576-60583,60585-60586,60589,60591,60594-60595,60597-60598,60600-60601,60606-60612,60615,60617-60678 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60618 | walter.doerwald | 2008-02-06 15:31:55 +0100 (Wed, 06 Feb 2008) | 6 lines Remove month parameter from Calendar.yeardatescalendar(), Calendar.yeardays2calendar() and Calendar.yeardayscalendar() as the methods don't have such a parameter. Fixes issue #2017. Rewrap content to 80 chars. ........ r60622 | facundo.batista | 2008-02-06 20:28:49 +0100 (Wed, 06 Feb 2008) | 4 lines Fixes issue 1959. Converted tests to unittest. Thanks Giampaolo Rodola. ........ r60626 | thomas.heller | 2008-02-06 21:29:17 +0100 (Wed, 06 Feb 2008) | 3 lines Fixed refcounts and error handling. Should not be merged to py3k branch. ........ r60630 | mark.dickinson | 2008-02-06 23:10:50 +0100 (Wed, 06 Feb 2008) | 4 lines Issue 1979: Make Decimal comparisons (other than !=, ==) involving NaN raise InvalidOperation (and return False if InvalidOperation is trapped). ........ r60632 | mark.dickinson | 2008-02-06 23:25:16 +0100 (Wed, 06 Feb 2008) | 2 lines Remove incorrect usage of :const: in documentation. ........ r60634 | georg.brandl | 2008-02-07 00:45:51 +0100 (Thu, 07 Feb 2008) | 2 lines Revert accidental changes to test_queue in r60605. ........ r60636 | raymond.hettinger | 2008-02-07 01:54:20 +0100 (Thu, 07 Feb 2008) | 1 line Issue 2025: Add tuple.count() and tuple.index() to follow the ABC in collections.Sequence. ........ r60637 | mark.dickinson | 2008-02-07 02:14:23 +0100 (Thu, 07 Feb 2008) | 2 lines Fix broken link in decimal documentation. ........ r60638 | mark.dickinson | 2008-02-07 02:42:06 +0100 (Thu, 07 Feb 2008) | 3 lines IEEE 754 should be IEEE 854; give precise reference for comparisons involving NaNs. ........ r60639 | raymond.hettinger | 2008-02-07 03:12:52 +0100 (Thu, 07 Feb 2008) | 1 line Return ints instead of longs for tuple.count() and tuple.index(). ........ r60640 | raymond.hettinger | 2008-02-07 04:10:33 +0100 (Thu, 07 Feb 2008) | 1 line Merge 60627. ........ r60641 | raymond.hettinger | 2008-02-07 04:25:46 +0100 (Thu, 07 Feb 2008) | 1 line Merge r60628, r60631, and r60633. Register UserList and UserString will the appropriate ABCs. ........ r60642 | brett.cannon | 2008-02-07 08:47:31 +0100 (Thu, 07 Feb 2008) | 3 lines Cast a struct to a void pointer so as to do a type-safe pointer comparison (mistmatch found by clang). ........ r60643 | brett.cannon | 2008-02-07 09:04:07 +0100 (Thu, 07 Feb 2008) | 2 lines Remove unnecessary curly braces around an int literal. ........ r60644 | andrew.kuchling | 2008-02-07 12:43:47 +0100 (Thu, 07 Feb 2008) | 1 line Update URL ........ r60645 | facundo.batista | 2008-02-07 17:16:29 +0100 (Thu, 07 Feb 2008) | 4 lines Fixes issue 2026. Tests converted to unittest. Thanks Giampaolo Rodola. ........ r60646 | christian.heimes | 2008-02-07 18:15:30 +0100 (Thu, 07 Feb 2008) | 1 line Added some statistics code to dict and list object code. I wanted to test how a larger freelist affects the reusage of freed objects. Contrary to my gut feelings 80 objects is more than fine for small apps. I haven't profiled a large app yet. ........ r60648 | facundo.batista | 2008-02-07 20:06:52 +0100 (Thu, 07 Feb 2008) | 6 lines Fixes Issue 1401. When redirected, a possible POST get converted to GET, so it loses its payload. So, it also must lose the headers related to the payload (if it has no content any more, it shouldn't indicate content length and type). ........ r60649 | walter.doerwald | 2008-02-07 20:30:22 +0100 (Thu, 07 Feb 2008) | 3 lines Clarify that the output of TextCalendar.formatmonth() and TextCalendar.formatyear() for custom instances won't be influenced by calls to the module global setfirstweekday() function. Fixes #2018. ........ r60651 | walter.doerwald | 2008-02-07 20:48:34 +0100 (Thu, 07 Feb 2008) | 3 lines Fix documentation for Calendar.iterweekdays(): firstweekday is a property. Fixes second part of #2018. ........ r60653 | walter.doerwald | 2008-02-07 20:57:32 +0100 (Thu, 07 Feb 2008) | 2 lines Fix typo in docstring for Calendar.itermonthdays(). ........ r60655 | raymond.hettinger | 2008-02-07 21:04:37 +0100 (Thu, 07 Feb 2008) | 1 line The float conversion recipe is simpler in Py2.6 ........ r60657 | raymond.hettinger | 2008-02-07 21:10:49 +0100 (Thu, 07 Feb 2008) | 1 line Fix typo ........ r60660 | brett.cannon | 2008-02-07 23:27:10 +0100 (Thu, 07 Feb 2008) | 3 lines Make sure a switch statement does not have repetitive case statements. Error found through LLVM post-2.1 svn. ........ r60661 | christian.heimes | 2008-02-08 01:11:31 +0100 (Fri, 08 Feb 2008) | 1 line Deallocate content of the dict free list on interpreter shutdown ........ r60662 | christian.heimes | 2008-02-08 01:14:34 +0100 (Fri, 08 Feb 2008) | 1 line Use prefix decrement ........ r60663 | amaury.forgeotdarc | 2008-02-08 01:56:02 +0100 (Fri, 08 Feb 2008) | 5 lines issue 2045: Infinite recursion when printing a subclass of defaultdict, if default_factory is set to a bound method. Will backport. ........ r60667 | jeffrey.yasskin | 2008-02-08 07:45:40 +0100 (Fri, 08 Feb 2008) | 2 lines Oops! 2.6's Rational.__ne__ didn't work. ........ r60671 | hyeshik.chang | 2008-02-08 18:10:20 +0100 (Fri, 08 Feb 2008) | 2 lines Update big5hkscs codec to conform to the HKSCS:2004 revision. ........ r60673 | raymond.hettinger | 2008-02-08 23:30:04 +0100 (Fri, 08 Feb 2008) | 4 lines Remove unnecessary modulo division. The preceding test guarantees that 0 <= i < len. ........ r60674 | raymond.hettinger | 2008-02-09 00:02:27 +0100 (Sat, 09 Feb 2008) | 1 line Speed-up __iter__() mixin method. ........ r60675 | raymond.hettinger | 2008-02-09 00:34:21 +0100 (Sat, 09 Feb 2008) | 1 line Fill-in missing Set comparisons ........ r60677 | raymond.hettinger | 2008-02-09 00:57:06 +0100 (Sat, 09 Feb 2008) | 1 line Add advice on choosing between DictMixin and MutableMapping ........ ................ r60682 | raymond.hettinger | 2008-02-09 03:53:48 +0100 (Sat, 09 Feb 2008) | 1 line Merge r60679 ................ r60683 | raymond.hettinger | 2008-02-09 04:25:08 +0100 (Sat, 09 Feb 2008) | 1 line Document how to use Set and MutableSet as a mixin. ................ r60685 | raymond.hettinger | 2008-02-09 04:48:16 +0100 (Sat, 09 Feb 2008) | 1 line Add another usage note for collections.Set ................ r60686 | raymond.hettinger | 2008-02-09 05:13:49 +0100 (Sat, 09 Feb 2008) | 1 line Merge r60673 ................ r60690 | raymond.hettinger | 2008-02-09 11:04:32 +0100 (Sat, 09 Feb 2008) | 1 line MappingView is Sized. ................ r60698 | christian.heimes | 2008-02-09 21:51:34 +0100 (Sat, 09 Feb 2008) | 29 lines Merged revisions 60481,60485,60489-60492,60494-60496,60498-60499,60501-60503,60505-60506,60508-60509,60523-60524,60532,60543,60545,60547-60548,60552,60554,60556-60559,60561-60562,60569,60571-60572,60574,60576-60583,60585-60586,60589,60591,60594-60595,60597-60598,60600-60601,60606-60612,60615,60617,60619-60621,60623-60625,60627-60629,60631,60633,60635,60647,60650,60652,60654,60656,60658-60659,60664-60666,60668-60670,60672,60676,60678-60695 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60679 | raymond.hettinger | 2008-02-09 02:18:42 +0100 (Sat, 09 Feb 2008) | 1 line Make ABC containers inherit as documented. ........ r60684 | raymond.hettinger | 2008-02-09 04:34:52 +0100 (Sat, 09 Feb 2008) | 1 line Merge with r60683. ........ r60687 | raymond.hettinger | 2008-02-09 05:37:49 +0100 (Sat, 09 Feb 2008) | 1 line Add -3 warnings that set.copy(), dict.copy(), and defaultdict.copy() will go away in Py3.x ........ r60689 | raymond.hettinger | 2008-02-09 11:04:19 +0100 (Sat, 09 Feb 2008) | 1 line Metaclass declaration is inherited ........ r60691 | raymond.hettinger | 2008-02-09 11:06:20 +0100 (Sat, 09 Feb 2008) | 1 line Temporarily disable this test. It's been broken for a week. ........ r60695 | nick.coghlan | 2008-02-09 16:28:09 +0100 (Sat, 09 Feb 2008) | 1 line Issue 2021: Allow NamedTemporaryFile and SpooledTemporaryFile to be used as context managers. (The NamedTemporaryFile fix should be considered for backporting to 2.5) ........ ................ r60699 | christian.heimes | 2008-02-09 21:58:00 +0100 (Sat, 09 Feb 2008) | 12 lines Merged revisions 60481,60485,60489-60492,60494-60496,60498-60499,60501-60503,60505-60506,60508-60509,60523-60524,60532,60543,60545,60547-60548,60552,60554,60556-60559,60561-60562,60569,60571-60572,60574,60576-60583,60585-60586,60589,60591,60594-60595,60597-60598,60600-60601,60606-60612,60615,60617,60619-60621,60623-60625,60627-60629,60631,60633,60635,60647,60650,60652,60654,60656,60658-60659,60664-60666,60668-60670,60672,60676,60678,60680-60683,60685-60686,60688,60690,60692-60694,60696-60698 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60696 | christian.heimes | 2008-02-09 20:55:22 +0100 (Sat, 09 Feb 2008) | 5 lines Issue #1706: Require Windows 2000+ Added Py_BUILD_CORE_MODULES macro to set WINVER and NTDDI_VERSION to Windows 2000 for core modules, too Added -d option to build.bat (same as -c Debug) and fixed warning about /build option Updated Windows related readme.txt files ........ ................ r60708 | eric.smith | 2008-02-10 02:44:44 +0100 (Sun, 10 Feb 2008) | 1 line r60707 does not need porting to py3k from trunk. ................ r60714 | eric.smith | 2008-02-10 16:09:40 +0100 (Sun, 10 Feb 2008) | 1 line Block r60713 with svnmerge. ................ r60720 | raymond.hettinger | 2008-02-10 21:41:56 +0100 (Sun, 10 Feb 2008) | 1 line The new default protocol is two. ................ r60725 | christian.heimes | 2008-02-11 07:19:17 +0100 (Mon, 11 Feb 2008) | 68 lines Merged revisions 60481,60485,60489-60492,60494-60496,60498-60499,60501-60503,60505-60506,60508-60509,60523-60524,60532,60543,60545,60547-60548,60552,60554,60556-60559,60561-60562,60569,60571-60572,60574,60576-60583,60585-60586,60589,60591,60594-60595,60597-60598,60600-60601,60606-60612,60615,60617,60619-60621,60623-60625,60627-60629,60631,60633,60635,60647,60650,60652,60654,60656,60658-60659,60664-60666,60668-60670,60672,60676,60678,60680-60683,60685-60686,60688,60690,60692-60694,60697-60706,60708-60712,60714-60724 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60701 | georg.brandl | 2008-02-09 22:36:15 +0100 (Sat, 09 Feb 2008) | 2 lines Needs only 2.4 now. ........ r60702 | georg.brandl | 2008-02-09 22:38:54 +0100 (Sat, 09 Feb 2008) | 2 lines Docs are rst now. ........ r60703 | georg.brandl | 2008-02-09 23:00:00 +0100 (Sat, 09 Feb 2008) | 2 lines Fix link. ........ r60704 | georg.brandl | 2008-02-10 00:09:25 +0100 (Sun, 10 Feb 2008) | 2 lines Fix for newest doctools. ........ r60709 | raymond.hettinger | 2008-02-10 08:21:09 +0100 (Sun, 10 Feb 2008) | 1 line Clarify that decimal also supports fixed-point arithmetic. ........ r60710 | nick.coghlan | 2008-02-10 08:32:52 +0100 (Sun, 10 Feb 2008) | 1 line Add missing NEWS entry for r60695 ........ r60712 | mark.dickinson | 2008-02-10 15:58:38 +0100 (Sun, 10 Feb 2008) | 3 lines Turn classmethods into staticmethods, and avoid calling the constructor of subclasses of Rational. (See discussion in issue #1682.) ........ r60715 | mark.dickinson | 2008-02-10 16:19:58 +0100 (Sun, 10 Feb 2008) | 2 lines Typos in decimal comment and documentation ........ r60716 | skip.montanaro | 2008-02-10 16:31:54 +0100 (Sun, 10 Feb 2008) | 2 lines Get the saying right. ;-) ........ r60717 | skip.montanaro | 2008-02-10 16:32:16 +0100 (Sun, 10 Feb 2008) | 2 lines whoops - revert ........ r60718 | mark.dickinson | 2008-02-10 20:23:36 +0100 (Sun, 10 Feb 2008) | 2 lines Remove reference to Rational ........ r60719 | raymond.hettinger | 2008-02-10 21:35:16 +0100 (Sun, 10 Feb 2008) | 1 line Complete an open todo on pickletools -- add a pickle optimizer. ........ r60721 | mark.dickinson | 2008-02-10 22:29:51 +0100 (Sun, 10 Feb 2008) | 3 lines Rename rational.Rational to fractions.Fraction, to avoid name clash with numbers.Rational. See issue #1682 for related discussion. ........ r60722 | christian.heimes | 2008-02-11 03:26:22 +0100 (Mon, 11 Feb 2008) | 1 line The test requires the network resource ........ r60723 | mark.dickinson | 2008-02-11 04:11:55 +0100 (Mon, 11 Feb 2008) | 3 lines Put an extra space into the repr of a Fraction: Fraction(1, 2) instead of Fraction(1,2). ........ ................ r60729 | eric.smith | 2008-02-11 18:55:01 +0100 (Mon, 11 Feb 2008) | 1 line Renamed test_format to test__format__, since it really tests the __format__ method. It was hiding another method of the same name. ................ r60732 | raymond.hettinger | 2008-02-11 20:00:13 +0100 (Mon, 11 Feb 2008) | 1 line No need to register classes that already inherit from ABCs. ................ r60736 | christian.heimes | 2008-02-11 23:57:17 +0100 (Mon, 11 Feb 2008) | 17 lines Merged revisions 60481,60485,60489-60492,60494-60496,60498-60499,60501-60503,60505-60506,60508-60509,60523-60524,60532,60543,60545,60547-60548,60552,60554,60556-60559,60561-60562,60569,60571-60572,60574,60576-60583,60585-60586,60589,60591,60594-60595,60597-60598,60600-60601,60606-60612,60615,60617,60619-60621,60623-60625,60627-60629,60631,60633,60635,60647,60650,60652,60654,60656,60658-60659,60664-60666,60668-60670,60672,60676,60678,60680-60683,60685-60686,60688,60690,60692-60694,60697-60700,60705-60706,60708,60711,60714,60720,60724-60734 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60731 | raymond.hettinger | 2008-02-11 19:51:08 +0100 (Mon, 11 Feb 2008) | 1 line No need to register classes that already inherit from ABCs. ........ r60733 | lars.gustaebel | 2008-02-11 20:17:10 +0100 (Mon, 11 Feb 2008) | 2 lines Make sure that xstar headers are read correctly. ........ r60734 | raymond.hettinger | 2008-02-11 21:05:53 +0100 (Mon, 11 Feb 2008) | 1 line Add tests for pickletools.optimize(). ........ ................ r60746 | thomas.heller | 2008-02-12 18:44:23 +0100 (Tue, 12 Feb 2008) | 3 lines Revert the last svnmerge (r60681) from trunk to _ctypes.c, it should not have been merged as was noticed in the commit message. ................ r60750 | martin.v.loewis | 2008-02-12 20:30:35 +0100 (Tue, 12 Feb 2008) | 2 lines Bug #1595: Remove extra semicolon. ................ r60751 | raymond.hettinger | 2008-02-12 21:03:09 +0100 (Tue, 12 Feb 2008) | 1 line Move UserList to collections. ................ r60753 | kurt.kaiser | 2008-02-12 22:34:12 +0100 (Tue, 12 Feb 2008) | 2 lines Convert some custom sort comparison functions to equivalent key functions. ................ r60756 | christian.heimes | 2008-02-12 23:59:25 +0100 (Tue, 12 Feb 2008) | 47 lines Merged revisions 60481,60485,60489-60492,60494-60496,60498-60499,60501-60503,60505-60506,60508-60509,60523-60524,60532,60543,60545,60547-60548,60552,60554,60556-60559,60561-60562,60569,60571-60572,60574,60576-60583,60585-60586,60589,60591,60594-60595,60597-60598,60600-60601,60606-60612,60615,60617,60619-60621,60623-60625,60627-60629,60631,60633,60635,60647,60650,60652,60654,60656,60658-60659,60664-60666,60668-60670,60672,60676,60678,60680-60683,60685-60686,60688,60690,60692-60694,60697-60700,60705-60706,60708,60711,60714,60720,60724-60730,60732,60735-60751 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60735 | raymond.hettinger | 2008-02-11 23:53:01 +0100 (Mon, 11 Feb 2008) | 1 line Add notes on how decimal fits into the model. ........ r60737 | raymond.hettinger | 2008-02-12 00:34:56 +0100 (Tue, 12 Feb 2008) | 1 line Fix markup ........ r60738 | raymond.hettinger | 2008-02-12 00:38:00 +0100 (Tue, 12 Feb 2008) | 1 line Backport ABC docs ........ r60739 | raymond.hettinger | 2008-02-12 01:15:32 +0100 (Tue, 12 Feb 2008) | 1 line Restore fractions.rst to the document tree. ........ r60740 | raymond.hettinger | 2008-02-12 01:48:20 +0100 (Tue, 12 Feb 2008) | 1 line Fix typo in comments ........ r60741 | raymond.hettinger | 2008-02-12 02:18:03 +0100 (Tue, 12 Feb 2008) | 1 line Bring decimal a bit closer to the spec for Reals. ........ r60743 | martin.v.loewis | 2008-02-12 14:47:26 +0100 (Tue, 12 Feb 2008) | 2 lines Patch #1736: Fix file name handling of _msi.FCICreate. ........ r60745 | kurt.kaiser | 2008-02-12 16:45:50 +0100 (Tue, 12 Feb 2008) | 2 lines what??! Correct r60225. ........ r60747 | martin.v.loewis | 2008-02-12 19:47:34 +0100 (Tue, 12 Feb 2008) | 4 lines Patch #1966: Break infinite loop in httplib when the servers implements the chunked encoding incorrectly. Will backport to 2.5. ........ r60749 | raymond.hettinger | 2008-02-12 20:05:36 +0100 (Tue, 12 Feb 2008) | 1 line dict.copy() rises from the ashes. Revert r60687. ........ ................ r60761 | kurt.kaiser | 2008-02-13 17:09:27 +0100 (Wed, 13 Feb 2008) | 2 lines list.sort() and builtin.sorted() no longer accept 'cmp' argument. ................ r60763 | kurt.kaiser | 2008-02-13 19:03:11 +0100 (Wed, 13 Feb 2008) | 2 lines Improve formatting for arg names in previous checkin. ................ r60769 | thomas.heller | 2008-02-13 21:40:44 +0100 (Wed, 13 Feb 2008) | 13 lines Merged revisions 60767,60768 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60767 | thomas.heller | 2008-02-13 21:21:53 +0100 (Mi, 13 Feb 2008) | 1 line Add pickle support to ctypes types. ........ r60768 | thomas.heller | 2008-02-13 21:36:51 +0100 (Mi, 13 Feb 2008) | 1 line Make the test somewhat clearer (I hope). ........ ................ r60774 | kurt.kaiser | 2008-02-14 03:47:50 +0100 (Thu, 14 Feb 2008) | 2 lines typo ................ r60787 | christian.heimes | 2008-02-14 09:27:37 +0100 (Thu, 14 Feb 2008) | 76 lines Merged revisions 60481,60485,60489-60492,60494-60496,60498-60499,60501-60503,60505-60506,60508-60509,60523-60524,60532,60543,60545,60547-60548,60552,60554,60556-60559,60561-60562,60569,60571-60572,60574,60576-60583,60585-60586,60589,60591,60594-60595,60597-60598,60600-60601,60606-60612,60615,60617,60619-60621,60623-60625,60627-60629,60631,60633,60635,60647,60650,60652,60654,60656,60658-60659,60664-60666,60668-60670,60672,60676,60678,60680-60683,60685-60686,60688,60690,60692-60694,60697-60700,60705-60706,60708,60711,60714,60720,60724-60730,60732,60736,60742,60744,60746,60748,60750-60766,60769-60786 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60752 | mark.dickinson | 2008-02-12 22:31:59 +0100 (Tue, 12 Feb 2008) | 5 lines Implementation of Fraction.limit_denominator. Remove Fraction.to_continued_fraction and Fraction.from_continued_fraction ........ r60754 | mark.dickinson | 2008-02-12 22:40:53 +0100 (Tue, 12 Feb 2008) | 3 lines Revert change in r60712: turn alternate constructors back into classmethods instead of staticmethods. ........ r60755 | mark.dickinson | 2008-02-12 22:46:54 +0100 (Tue, 12 Feb 2008) | 4 lines Replace R=fractions.Fraction with F=fractions.Fraction in test_fractions.py. This should have been part of the name change from Rational to Fraction. ........ r60758 | georg.brandl | 2008-02-13 08:20:22 +0100 (Wed, 13 Feb 2008) | 3 lines #2063: correct order of utime and stime in os.times() result on Windows. ........ r60762 | jeffrey.yasskin | 2008-02-13 18:58:04 +0100 (Wed, 13 Feb 2008) | 7 lines Working on issue #1762: Brought ./python.exe -m timeit -s 'from fractions import Fraction; f = Fraction(3, 2)' 'isinstance(3, Fraction); isinstance(f, Fraction)' from 12.3 usec/loop to 3.44 usec/loop and ./python.exe -m timeit -s 'from fractions import Fraction' 'Fraction(3, 2)' from 48.8 usec to 23.6 usec by avoiding genexps and sets in __instancecheck__ and inlining the common case from __subclasscheck__. ........ r60765 | brett.cannon | 2008-02-13 20:15:44 +0100 (Wed, 13 Feb 2008) | 5 lines Fix --enable-universalsdk and its comment line so that zsh's flag completion works. Thanks to Jeroen Ruigrok van der Werven for the fix. ........ r60771 | kurt.kaiser | 2008-02-14 01:08:55 +0100 (Thu, 14 Feb 2008) | 2 lines Bring NEWS.txt up to date from check-in msgs. ........ r60772 | raymond.hettinger | 2008-02-14 02:08:02 +0100 (Thu, 14 Feb 2008) | 3 lines Update notes on Decimal. ........ r60773 | raymond.hettinger | 2008-02-14 03:41:22 +0100 (Thu, 14 Feb 2008) | 1 line Fix decimal repr which should have used single quotes like other reprs. ........ r60785 | jeffrey.yasskin | 2008-02-14 07:12:24 +0100 (Thu, 14 Feb 2008) | 11 lines Performance optimizations on Fraction's constructor. ./python.exe -m timeit -s 'from fractions import Fraction' 'Fraction(3)` 31.7 usec/loop -> 9.2 usec/loop ./python.exe -m timeit -s 'from fractions import Fraction' 'Fraction(3, 2)'` 27.7 usec/loop -> 9.32 usec/loop ./python.exe -m timeit -s 'from fractions import Fraction; f = Fraction(3, 2)' 'Fraction(f)' 31.9 usec/loop -> 14.3 usec/loop ........ r60786 | jeffrey.yasskin | 2008-02-14 08:49:25 +0100 (Thu, 14 Feb 2008) | 5 lines Change simple instances (in Fraction) of self.numerator and self.denominator to self._numerator and self._denominator. This speeds abs() up from 12.2us to 10.8us and trunc() from 2.07us to 1.11us. This doesn't change _add and friends because they're more complicated. ........ ................ r60802 | raymond.hettinger | 2008-02-14 14:32:18 +0100 (Thu, 14 Feb 2008) | 1 line Documentation nit. ................ r60803 | raymond.hettinger | 2008-02-14 14:34:38 +0100 (Thu, 14 Feb 2008) | 1 line Note the the sort arguments are required to be keywords. ................ r60804 | raymond.hettinger | 2008-02-14 14:52:24 +0100 (Thu, 14 Feb 2008) | 1 line Note that the key and reverse arguments must be specified as keywords ................ r60806 | raymond.hettinger | 2008-02-14 15:08:04 +0100 (Thu, 14 Feb 2008) | 1 line Minor doc updates for Py3.0 ................ r60809 | mark.summerfield | 2008-02-14 17:28:00 +0100 (Thu, 14 Feb 2008) | 4 lines Deleted two duplicated paragraphs in the intro. Added mention of UserDict and UserList and mixins in the intro. Fixed a typo. ................ r60853 | christian.heimes | 2008-02-16 08:38:31 +0100 (Sat, 16 Feb 2008) | 110 lines Merged revisions 60481,60485,60489-60492,60494-60496,60498-60499,60501-60503,60505-60506,60508-60509,60523-60524,60532,60543,60545,60547-60548,60552,60554,60556-60559,60561-60562,60569,60571-60572,60574,60576-60583,60585-60586,60589,60591,60594-60595,60597-60598,60600-60601,60606-60612,60615,60617,60619-60621,60623-60625,60627-60629,60631,60633,60635,60647,60650,60652,60654,60656,60658-60659,60664-60666,60668-60670,60672,60676,60678,60680-60683,60685-60686,60688,60690,60692-60694,60697-60700,60705-60706,60708,60711,60714,60720,60724-60730,60732,60736,60742,60744,60746,60748,60750-60751,60753,60756-60757,60759-60761,60763-60764,60766,60769-60770,60774-60784,60787-60845 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60790 | raymond.hettinger | 2008-02-14 10:32:45 +0100 (Thu, 14 Feb 2008) | 4 lines Add diagnostic message to help figure-out why SocketServer tests occasionally crash when trying to remove a pid that in not in the activechildren list. ........ r60791 | raymond.hettinger | 2008-02-14 11:46:57 +0100 (Thu, 14 Feb 2008) | 1 line Add fixed-point examples to the decimal FAQ ........ r60792 | raymond.hettinger | 2008-02-14 12:01:10 +0100 (Thu, 14 Feb 2008) | 1 line Improve rst markup ........ r60794 | raymond.hettinger | 2008-02-14 12:57:25 +0100 (Thu, 14 Feb 2008) | 1 line Show how to remove exponents. ........ r60795 | raymond.hettinger | 2008-02-14 13:05:42 +0100 (Thu, 14 Feb 2008) | 1 line Fix markup. ........ r60797 | christian.heimes | 2008-02-14 13:47:33 +0100 (Thu, 14 Feb 2008) | 1 line Implemented Martin's suggestion to clear the free lists during the garbage collection of the highest generation. ........ r60798 | raymond.hettinger | 2008-02-14 13:49:37 +0100 (Thu, 14 Feb 2008) | 1 line Simplify moneyfmt() recipe. ........ r60810 | raymond.hettinger | 2008-02-14 20:02:39 +0100 (Thu, 14 Feb 2008) | 1 line Fix markup ........ r60811 | raymond.hettinger | 2008-02-14 20:30:30 +0100 (Thu, 14 Feb 2008) | 1 line No need to register subclass of ABCs. ........ r60814 | thomas.heller | 2008-02-14 22:00:28 +0100 (Thu, 14 Feb 2008) | 1 line Try to correct a markup error that does hide the following paragraph. ........ r60822 | christian.heimes | 2008-02-14 23:40:11 +0100 (Thu, 14 Feb 2008) | 1 line Use a static and interned string for __subclasscheck__ and __instancecheck__ as suggested by Thomas Heller in #2115 ........ r60827 | christian.heimes | 2008-02-15 07:57:08 +0100 (Fri, 15 Feb 2008) | 1 line Fixed repr() and str() of complex numbers. Complex suffered from the same problem as floats but I forgot to test and fix them. ........ r60830 | christian.heimes | 2008-02-15 09:20:11 +0100 (Fri, 15 Feb 2008) | 2 lines Bug #2111: mmap segfaults when trying to write a block opened with PROT_READ Thanks to Thomas Herve for the fix. ........ r60835 | eric.smith | 2008-02-15 13:14:32 +0100 (Fri, 15 Feb 2008) | 1 line In PyNumber_ToBase, changed from an assert to returning an error when PyObject_Index() returns something other than an int or long. It should never be possible to trigger this, as PyObject_Index checks to make sure it returns an int or long. ........ r60837 | skip.montanaro | 2008-02-15 20:03:59 +0100 (Fri, 15 Feb 2008) | 8 lines Two new functions: * place_summary_first copies the regrtest summary to the front of the file making it easier to scan quickly for problems. * count_failures gets the actual count of the number of failing tests, not just a 1 (some failures) or 0 (no failures). ........ r60840 | raymond.hettinger | 2008-02-15 22:21:25 +0100 (Fri, 15 Feb 2008) | 1 line Update example to match the current syntax. ........ r60841 | amaury.forgeotdarc | 2008-02-15 22:22:45 +0100 (Fri, 15 Feb 2008) | 8 lines Issue #2115: __slot__ attributes setting was 10x slower. Also correct a possible crash using ABCs. This change is exactly the same as an optimisation done 5 years ago, but on slot *access*: http://svn.python.org/view?view=rev&rev=28297 ........ r60842 | amaury.forgeotdarc | 2008-02-15 22:27:44 +0100 (Fri, 15 Feb 2008) | 2 lines Temporarily let these tests pass ........ r60843 | kurt.kaiser | 2008-02-15 22:56:36 +0100 (Fri, 15 Feb 2008) | 2 lines ScriptBinding event handlers weren't returning 'break'. Patch 2050, Tal Einat. ........ r60844 | kurt.kaiser | 2008-02-15 23:25:09 +0100 (Fri, 15 Feb 2008) | 4 lines Configured selection highlighting colors were ignored; updating highlighting in the config dialog would cause non-Python files to be colored as if they were Python source; improve use of ColorDelagator. Patch 1334. Tal Einat. ........ r60845 | amaury.forgeotdarc | 2008-02-15 23:44:20 +0100 (Fri, 15 Feb 2008) | 9 lines Re-enable tests, they were failing since gc.collect() clears the various freelists. They still remain fragile. For example, a call to assertEqual currently does not make any allocation (which surprised me at first). But this can change when gc.collect also deletes the numerous "zombie frames" attached to each function. ........ ................ r60874 | christian.heimes | 2008-02-17 14:31:39 +0100 (Sun, 17 Feb 2008) | 57 lines Merged revisions 60481,60485,60489-60492,60494-60496,60498-60499,60501-60503,60505-60506,60508-60509,60523-60524,60532,60543,60545,60547-60548,60552,60554,60556-60559,60561-60562,60569,60571-60572,60574,60576-60583,60585-60586,60589,60591,60594-60595,60597-60598,60600-60601,60606-60612,60615,60617,60619-60621,60623-60625,60627-60629,60631,60633,60635,60647,60650,60652,60654,60656,60658-60659,60664-60666,60668-60670,60672,60676,60678,60680-60683,60685-60686,60688,60690,60692-60694,60697-60700,60705-60706,60708,60711,60714,60720,60724-60730,60732,60736,60742,60744,60746,60748,60750-60751,60753,60756-60757,60759-60761,60763-60764,60766,60769-60770,60774-60784,60787-60789,60793,60796,60799-60809,60812-60813,60815-60821,60823-60826,60828-60829,60831-60834,60836,60838-60839,60846-60873 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60850 | amaury.forgeotdarc | 2008-02-16 01:16:50 +0100 (Sat, 16 Feb 2008) | 3 lines mmap.PROT_READ does not exists on win32; Skip this test created by r60830. ........ r60851 | raymond.hettinger | 2008-02-16 02:22:54 +0100 (Sat, 16 Feb 2008) | 1 line Add __all__ to logging module. ........ r60855 | georg.brandl | 2008-02-16 10:37:32 +0100 (Sat, 16 Feb 2008) | 2 lines #2120: broken links in advocacy document. ........ r60860 | amaury.forgeotdarc | 2008-02-16 15:34:57 +0100 (Sat, 16 Feb 2008) | 23 lines Crashers of the day: Py_CLEAR must be used when there is a chance that the function can be called recursively. This was discussed in issue1020188. In python codebase, all occurrences of Py_[X]DECREF(xxx->yyy) are suspect, except when they appear in tp_new or tp_dealloc functions, or when the member cannot be of a user-defined class. Note that tp_init is not safe. I do have a (crashing) example for every changed line. Is it worth adding them to the test suite? Example: class SpecialStr(str): def __del__(self): s.close() import cStringIO s = cStringIO.StringIO(SpecialStr("text")) s.close() # Segfault ........ r60871 | amaury.forgeotdarc | 2008-02-16 21:55:24 +0100 (Sat, 16 Feb 2008) | 3 lines Prevent a crash with nested scopes, again caused by calling Py_DECREF when the pointer is still present in the containing structure. ........ r60872 | brett.cannon | 2008-02-17 02:59:18 +0100 (Sun, 17 Feb 2008) | 4 lines Move test_logging over to doctest. Thanks to Christopher White from GHOP. ........ r60873 | georg.brandl | 2008-02-17 12:33:38 +0100 (Sun, 17 Feb 2008) | 2 lines #2131: note that codecs.open() always opens files in binary mode. ........ ................ r60880 | eric.smith | 2008-02-17 20:48:00 +0100 (Sun, 17 Feb 2008) | 17 lines Fixes for shared 2.6 code that implements PEP 3101, advanced string formatting. Includes: - Modifying tests for basic types to use __format__ methods, instead of builtin "format". - Adding PyObject_Format. - General str/unicode cleanup discovered when backporting to 2.6. - Removing datetimemodule.c's time_format, since it was identical to date_format. The files in Objects/stringlib that implement PEP 3101 (stringdefs.h, unicodedefs.h, formatter.h, string_format.h) are identical in trunk and py3k. Any changes from here on should be made to trunk, and changes will propogate to py3k). ................ r60881 | eric.smith | 2008-02-17 20:48:57 +0100 (Sun, 17 Feb 2008) | 1 line Blocked 60879 (backport of PEP 3101). ................ r60894 | eric.smith | 2008-02-18 19:07:47 +0100 (Mon, 18 Feb 2008) | 1 line Port 60893 to py3k, without unicode test. ................ r60895 | eric.smith | 2008-02-18 19:09:30 +0100 (Mon, 18 Feb 2008) | 1 line block r60893 ................ r60897 | georg.brandl | 2008-02-18 23:20:55 +0100 (Mon, 18 Feb 2008) | 2 lines Clarification. ................ r60900 | eric.smith | 2008-02-19 13:29:58 +0100 (Tue, 19 Feb 2008) | 1 line block r60899 ................ r60902 | christian.heimes | 2008-02-19 15:21:46 +0100 (Tue, 19 Feb 2008) | 53 lines Merged revisions 60481,60485,60489-60492,60494-60496,60498-60499,60501-60503,60505-60506,60508-60509,60523-60524,60532,60543,60545,60547-60548,60552,60554,60556-60559,60561-60562,60569,60571-60572,60574,60576-60583,60585-60586,60589,60591,60594-60595,60597-60598,60600-60601,60606-60612,60615,60617,60619-60621,60623-60625,60627-60629,60631,60633,60635,60647,60650,60652,60654,60656,60658-60659,60664-60666,60668-60670,60672,60676,60678,60680-60683,60685-60686,60688,60690,60692-60694,60697-60700,60705-60706,60708,60711,60714,60720,60724-60730,60732,60736,60742,60744,60746,60748,60750-60751,60753,60756-60757,60759-60761,60763-60764,60766,60769-60770,60774-60784,60787-60789,60793,60796,60799-60809,60812-60813,60815-60821,60823-60826,60828-60829,60831-60834,60836,60838-60839,60846-60849,60852-60854,60856-60859,60861-60870,60874-60878,60880-60892,60894-60898 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60876 | georg.brandl | 2008-02-17 16:14:10 +0100 (Sun, 17 Feb 2008) | 2 lines Fix function name. ........ r60877 | facundo.batista | 2008-02-17 17:21:13 +0100 (Sun, 17 Feb 2008) | 4 lines Now we handle different the backup copy, because of security issues regarding user/group and permissions. Fixes 1050828. ........ r60878 | facundo.batista | 2008-02-17 19:59:29 +0100 (Sun, 17 Feb 2008) | 4 lines Issue 2112. mmap does not raises EnvironmentError no more, but a subclass of it. Thanks John Lenton. ........ r60882 | amaury.forgeotdarc | 2008-02-17 21:56:31 +0100 (Sun, 17 Feb 2008) | 5 lines Compilation was broken on Windows since the introduction of Advanced String Formatting. Only PCBuild (vs9) was really tested. Changes for older compilers were done manually. ........ r60883 | georg.brandl | 2008-02-17 22:18:55 +0100 (Sun, 17 Feb 2008) | 2 lines #2133: fix HTML color spec. ........ r60884 | facundo.batista | 2008-02-18 04:43:43 +0100 (Mon, 18 Feb 2008) | 5 lines Issue #1916. Added isgenerator() and isgeneratorfunction() to inspect.py. Thanks Javi Mansilla for patch review and corrections. ........ r60885 | facundo.batista | 2008-02-18 13:48:43 +0100 (Mon, 18 Feb 2008) | 4 lines Issue 1224. Now we support again the double slash in the URL. Thanks Anthony Lenton. ........ r60887 | eric.smith | 2008-02-18 15:25:02 +0100 (Mon, 18 Feb 2008) | 1 line Temporarily removed float tests. See issue 1600. ........ r60891 | kristjan.jonsson | 2008-02-18 18:40:47 +0100 (Mon, 18 Feb 2008) | 1 line Perform correct handling of stack overflow for windows: Catch the correct exception code and reset the overflow condition when handled. ........ ................ r60906 | travis.oliphant | 2008-02-19 19:03:53 +0100 (Tue, 19 Feb 2008) | 1 line Remove unused and non-PEP-related entry from PyBufferProcs ................ r60931 | guido.van.rossum | 2008-02-21 21:16:31 +0100 (Thu, 21 Feb 2008) | 4 lines Remove merge turds. Break long lines. Remove item that was rolled back (float formatting). ................ r60934 | eric.smith | 2008-02-21 21:18:44 +0100 (Thu, 21 Feb 2008) | 1 line Block r60932 with svnmerge. ................ r60941 | raymond.hettinger | 2008-02-21 23:11:37 +0100 (Thu, 21 Feb 2008) | 5 lines Move UserString to collections. Removed decode() method. Added isidentifier() and format() methods. Drop MutableUserString class. ................ r60959 | georg.brandl | 2008-02-22 15:22:51 +0100 (Fri, 22 Feb 2008) | 2 lines Link to whatsnew document. ................ r60963 | eric.smith | 2008-02-22 17:31:15 +0100 (Fri, 22 Feb 2008) | 1 line Block r60962 with svnmerge. ................ r60964 | christian.heimes | 2008-02-22 17:37:40 +0100 (Fri, 22 Feb 2008) | 85 lines Merged revisions 60481,60485,60489-60492,60494-60496,60498-60499,60501-60503,60505-60506,60508-60509,60523-60524,60532,60543,60545,60547-60548,60552,60554,60556-60559,60561-60562,60569,60571-60572,60574,60576-60583,60585-60586,60589,60591,60594-60595,60597-60598,60600-60601,60606-60612,60615,60617,60619-60621,60623-60625,60627-60629,60631,60633,60635,60647,60650,60652,60654,60656,60658-60659,60664-60666,60668-60670,60672,60676,60678,60680-60683,60685-60686,60688,60690,60692-60694,60697-60700,60705-60706,60708,60711,60714,60720,60724-60730,60732,60736,60742,60744,60746,60748,60750-60751,60753,60756-60757,60759-60761,60763-60764,60766,60769-60770,60774-60784,60787-60789,60793,60796,60799-60809,60812-60813,60815-60821,60823-60826,60828-60829,60831-60834,60836,60838-60839,60846-60849,60852-60854,60856-60859,60861-60870,60874-60875,60880-60881,60886,60888-60890,60892,60894-60898,60900-60931,60933-60958 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60901 | eric.smith | 2008-02-19 14:21:56 +0100 (Tue, 19 Feb 2008) | 1 line Added PEP 3101. ........ r60907 | georg.brandl | 2008-02-20 20:12:36 +0100 (Wed, 20 Feb 2008) | 2 lines Fixes contributed by Ori Avtalion. ........ r60909 | eric.smith | 2008-02-21 00:34:22 +0100 (Thu, 21 Feb 2008) | 1 line Trim leading zeros from a floating point exponent, per C99. See issue 1600. As far as I know, this only affects Windows. Add float type 'n' to PyOS_ascii_formatd (see PEP 3101 for 'n' description). ........ r60910 | eric.smith | 2008-02-21 00:39:28 +0100 (Thu, 21 Feb 2008) | 1 line Now that PyOS_ascii_formatd supports the 'n' format, simplify the float formatting code to just call it. ........ r60918 | andrew.kuchling | 2008-02-21 15:23:38 +0100 (Thu, 21 Feb 2008) | 2 lines Close manifest file. This change doesn't make any difference to CPython, but is a necessary fix for Jython. ........ r60921 | guido.van.rossum | 2008-02-21 18:46:16 +0100 (Thu, 21 Feb 2008) | 2 lines Remove news about float repr() -- issue 1580 is still in limbo. ........ r60923 | guido.van.rossum | 2008-02-21 19:18:37 +0100 (Thu, 21 Feb 2008) | 5 lines Removed uses of dict.has_key() from distutils, and uses of callable() from copy_reg.py, so the interpreter now starts up without warnings when '-3' is given. More work like this needs to be done in the rest of the stdlib. ........ r60924 | thomas.heller | 2008-02-21 19:28:48 +0100 (Thu, 21 Feb 2008) | 4 lines configure.ac: Remove the configure check for _Bool, it is already done in the top-level Python configure script. configure, fficonfig.h.in: regenerated. ........ r60925 | thomas.heller | 2008-02-21 19:52:20 +0100 (Thu, 21 Feb 2008) | 3 lines Replace 'has_key()' with 'in'. Replace 'raise Error, stuff' with 'raise Error(stuff)'. ........ r60927 | raymond.hettinger | 2008-02-21 20:24:53 +0100 (Thu, 21 Feb 2008) | 1 line Update more instances of has_key(). ........ r60928 | guido.van.rossum | 2008-02-21 20:46:35 +0100 (Thu, 21 Feb 2008) | 3 lines Fix a few typos and layout glitches (more work is needed). Move 2.5 news to Misc/HISTORY. ........ r60936 | georg.brandl | 2008-02-21 21:33:38 +0100 (Thu, 21 Feb 2008) | 2 lines #2079: typo in userdict docs. ........ r60938 | georg.brandl | 2008-02-21 21:38:13 +0100 (Thu, 21 Feb 2008) | 2 lines Part of #2154: minimal syntax fixes in doc example snippets. ........ r60942 | raymond.hettinger | 2008-02-22 04:16:42 +0100 (Fri, 22 Feb 2008) | 1 line First draft for itertools.product(). Docs and other updates forthcoming. ........ r60955 | nick.coghlan | 2008-02-22 11:54:06 +0100 (Fri, 22 Feb 2008) | 1 line Try to make command line error messages from runpy easier to understand (and suppress traceback cruft from the implicitly invoked runpy machinery) ........ r60956 | georg.brandl | 2008-02-22 13:31:45 +0100 (Fri, 22 Feb 2008) | 2 lines A lot more typo fixes by Ori Avtalion. ........ r60957 | georg.brandl | 2008-02-22 13:56:34 +0100 (Fri, 22 Feb 2008) | 2 lines Don't reference pyshell. ........ r60958 | georg.brandl | 2008-02-22 13:57:05 +0100 (Fri, 22 Feb 2008) | 2 lines Another fix. ........ ................ r60971 | eric.smith | 2008-02-23 04:11:44 +0100 (Sat, 23 Feb 2008) | 1 line Blocked r60970 with svnmerge. ................ r60977 | christian.heimes | 2008-02-23 14:18:03 +0100 (Sat, 23 Feb 2008) | 52 lines Merged revisions 60481,60485,60489-60492,60494-60496,60498-60499,60501-60503,60505-60506,60508-60509,60523-60524,60532,60543,60545,60547-60548,60552,60554,60556-60559,60561-60562,60569,60571-60572,60574,60576-60583,60585-60586,60589,60591,60594-60595,60597-60598,60600-60601,60606-60612,60615,60617,60619-60621,60623-60625,60627-60629,60631,60633,60635,60647,60650,60652,60654,60656,60658-60659,60664-60666,60668-60670,60672,60676,60678,60680-60683,60685-60686,60688,60690,60692-60694,60697-60700,60705-60706,60708,60711,60714,60720,60724-60730,60732,60736,60742,60744,60746,60748,60750-60751,60753,60756-60757,60759-60761,60763-60764,60766,60769-60770,60774-60784,60787-60789,60793,60796,60799-60809,60812-60813,60815-60821,60823-60826,60828-60829,60831-60834,60836,60838-60839,60846-60849,60852-60854,60856-60859,60861-60870,60874-60875,60880-60881,60886,60888-60890,60892,60894-60898,60900,60902-60906,60908,60911-60917,60919-60920,60922,60926,60929-60931,60933-60935,60937,60939-60941,60943-60954,60959-60961,60963-60969,60971-60976 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60965 | eric.smith | 2008-02-22 18:43:17 +0100 (Fri, 22 Feb 2008) | 1 line Tests for bin() builtin. These need to get merged into py3k, which has no tests for bin. ........ r60968 | raymond.hettinger | 2008-02-22 20:50:06 +0100 (Fri, 22 Feb 2008) | 1 line Document itertools.product(). ........ r60969 | raymond.hettinger | 2008-02-23 03:20:41 +0100 (Sat, 23 Feb 2008) | 9 lines Improve the implementation of itertools.product() * Fix-up issues pointed-out by Neal Norwitz. * Add extensive comments. * The lz->result variable is now a tuple instead of a list. * Use fast macro getitem/setitem calls so most code is in-line. * Re-use the result tuple if available (modify in-place instead of copy). ........ r60972 | raymond.hettinger | 2008-02-23 05:03:50 +0100 (Sat, 23 Feb 2008) | 1 line Add more comments ........ r60973 | raymond.hettinger | 2008-02-23 11:04:15 +0100 (Sat, 23 Feb 2008) | 1 line Add recipe using itertools.product(). ........ r60974 | facundo.batista | 2008-02-23 13:01:13 +0100 (Sat, 23 Feb 2008) | 6 lines Issue 1881. Increased the stack limit from 500 to 1500. Also added a test for this (and because of this test you'll see in stderr a message that parser.c sends before raising MemoryError). Thanks Ralf Schmitt. ........ r60975 | facundo.batista | 2008-02-23 13:27:17 +0100 (Sat, 23 Feb 2008) | 4 lines Issue 1776581. Minor corrections to smtplib, and two small tests. Thanks Alan McIntyre. ........ r60976 | facundo.batista | 2008-02-23 13:46:10 +0100 (Sat, 23 Feb 2008) | 5 lines Issue 1781. Now ConfigParser.add_section does not let you add a DEFAULT section any more, because it duplicated sections with the rest of the machinery. Thanks Tim Lesher and Manuel Kaufmann. ........ ................ r60979 | christian.heimes | 2008-02-23 16:01:06 +0100 (Sat, 23 Feb 2008) | 1 line Patch from Georg Brandl: Fix co_lineno of decorated function and class objects. If you see an error in test_inspect please delete all pyc files. ................ r60981 | christian.heimes | 2008-02-23 16:03:07 +0100 (Sat, 23 Feb 2008) | 1 line block -r60978 ................ r60992 | christian.heimes | 2008-02-23 17:23:06 +0100 (Sat, 23 Feb 2008) | 42 lines Merged revisions 60481,60485,60489-60492,60494-60496,60498-60499,60501-60503,60505-60506,60508-60509,60523-60524,60532,60543,60545,60547-60548,60552,60554,60556-60559,60561-60562,60569,60571-60572,60574,60576-60583,60585-60586,60589,60591,60594-60595,60597-60598,60600-60601,60606-60612,60615,60617,60619-60621,60623-60625,60627-60629,60631,60633,60635,60647,60650,60652,60654,60656,60658-60659,60664-60666,60668-60670,60672,60676,60678,60680-60683,60685-60686,60688,60690,60692-60694,60697-60700,60705-60706,60708,60711,60714,60720,60724-60730,60732,60736,60742,60744,60746,60748,60750-60751,60753,60756-60757,60759-60761,60763-60764,60766,60769-60770,60774-60784,60787-60789,60793,60796,60799-60809,60812-60813,60815-60821,60823-60826,60828-60829,60831-60834,60836,60838-60839,60846-60849,60852-60854,60856-60859,60861-60870,60874-60875,60880-60881,60886,60888-60890,60892,60894-60898,60900,60902-60906,60908,60911-60917,60919-60920,60922,60926,60929-60931,60933-60935,60937,60939-60941,60943-60954,60959-60961,60963-60964,60966-60967,60971,60977,60979-60989 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60980 | georg.brandl | 2008-02-23 16:02:28 +0100 (Sat, 23 Feb 2008) | 2 lines #1492: allow overriding BaseHTTPServer's content type for error messages. ........ r60982 | georg.brandl | 2008-02-23 16:06:25 +0100 (Sat, 23 Feb 2008) | 2 lines #2165: fix test_logging failure on some machines. ........ r60983 | facundo.batista | 2008-02-23 16:07:35 +0100 (Sat, 23 Feb 2008) | 6 lines Issue 1089358. Adds the siginterrupt() function, that is just a wrapper around the system call with the same name. Also added test cases, doc changes and NEWS entry. Thanks Jason and Ralf Schmitt. ........ r60984 | georg.brandl | 2008-02-23 16:11:18 +0100 (Sat, 23 Feb 2008) | 2 lines #2067: file.__exit__() now calls subclasses' close() method. ........ r60985 | georg.brandl | 2008-02-23 16:19:54 +0100 (Sat, 23 Feb 2008) | 2 lines More difflib examples. Written for GHOP by Josip Dzolonga. ........ r60987 | andrew.kuchling | 2008-02-23 16:41:51 +0100 (Sat, 23 Feb 2008) | 1 line #2072: correct documentation for .rpc_paths ........ r60988 | georg.brandl | 2008-02-23 16:43:48 +0100 (Sat, 23 Feb 2008) | 2 lines #2161: Fix opcode name. ........ r60989 | andrew.kuchling | 2008-02-23 16:49:35 +0100 (Sat, 23 Feb 2008) | 2 lines #1119331: ncurses will just call exit() if the terminal name isn't found. Call setupterm() first so that we get a Python exception instead of just existing. ........ ................ r60993 | christian.heimes | 2008-02-23 17:29:43 +0100 (Sat, 23 Feb 2008) | 3 lines Simplified svnmerge blocked and integrated. We are never ever going to integrate the blocked revisions. The old values were: svnmerge-blocked : /python/trunk:60480,60521-60522,60528-60529,60534,60539,60599,60707,60713,60879,60893,60899,60932,60962,60970,60978 svnmerge-integrated : /python/trunk:1-60479,60481-60520,60523-60527,60530-60533,60535-60538,60540-60598,60600-60706,60708-60712,60714-60878,60880-60892,60894-60898,60900-60931,60933-60961,60963-60969,60971-60977,60979-60989 ................ r61003 | christian.heimes | 2008-02-23 19:30:17 +0100 (Sat, 23 Feb 2008) | 38 lines Merged revisions 60990-61002 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r60990 | eric.smith | 2008-02-23 17:05:26 +0100 (Sat, 23 Feb 2008) | 1 line Removed duplicate Py_CHARMASK define. It's already defined in Python.h. ........ r60991 | andrew.kuchling | 2008-02-23 17:23:05 +0100 (Sat, 23 Feb 2008) | 4 lines #1330538: Improve comparison of xmlrpclib.DateTime and datetime instances. Remove automatic handling of datetime.date and datetime.time. This breaks backward compatibility, but python-dev discussion was strongly against this automatic conversion; see the bug for a link. ........ r60994 | andrew.kuchling | 2008-02-23 17:39:43 +0100 (Sat, 23 Feb 2008) | 1 line #835521: Add index entries for various pickle-protocol methods and attributes ........ r60995 | andrew.kuchling | 2008-02-23 18:10:46 +0100 (Sat, 23 Feb 2008) | 2 lines #1433694: minidom's .normalize() failed to set .nextSibling for last element. Fix by Malte Helmert ........ r61000 | christian.heimes | 2008-02-23 18:40:11 +0100 (Sat, 23 Feb 2008) | 1 line Patch #2167 from calvin: Remove unused imports ........ r61001 | christian.heimes | 2008-02-23 18:42:31 +0100 (Sat, 23 Feb 2008) | 1 line Patch #1957: syslogmodule: Release GIL when calling syslog(3) ........ r61002 | christian.heimes | 2008-02-23 18:52:07 +0100 (Sat, 23 Feb 2008) | 2 lines Issue #2051 and patch from Alexander Belopolsky: Permission for pyc and pyo files are inherited from the py file. ........ ................ r61036 | christian.heimes | 2008-02-24 01:38:49 +0100 (Sun, 24 Feb 2008) | 87 lines Merged revisions 61003-61033 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61004 | georg.brandl | 2008-02-23 19:47:04 +0100 (Sat, 23 Feb 2008) | 2 lines Documentation coverage builder, part 1. ........ r61006 | andrew.kuchling | 2008-02-23 20:02:33 +0100 (Sat, 23 Feb 2008) | 1 line #1389051: IMAP module tries to read entire message in one chunk. Patch by Fredrik Lundh. ........ r61008 | andrew.kuchling | 2008-02-23 20:28:58 +0100 (Sat, 23 Feb 2008) | 1 line #1389051, #1092502: fix excessively large allocations when using read() on a socket ........ r61011 | jeffrey.yasskin | 2008-02-23 20:40:54 +0100 (Sat, 23 Feb 2008) | 13 lines Prevent classes like: class RunSelfFunction(object): def __init__(self): self.thread = threading.Thread(target=self._run) self.thread.start() def _run(self): pass from creating a permanent cycle between the object and the thread by having the Thread delete its references to the object when it completes. As an example of the effect of this bug, paramiko.Transport inherits from Thread to avoid it. ........ r61013 | jeffrey.yasskin | 2008-02-23 21:40:35 +0100 (Sat, 23 Feb 2008) | 3 lines Followup to r61011: Also avoid the reference cycle when the Thread's target raises an exception. ........ r61017 | georg.brandl | 2008-02-23 22:59:11 +0100 (Sat, 23 Feb 2008) | 2 lines #2101: fix removeAttribute docs. ........ r61018 | georg.brandl | 2008-02-23 23:05:38 +0100 (Sat, 23 Feb 2008) | 2 lines Add examples to modulefinder docs. Written for GHOP by Josip Dzolonga. ........ r61019 | georg.brandl | 2008-02-23 23:09:24 +0100 (Sat, 23 Feb 2008) | 2 lines Use os.closerange() in popen2. ........ r61020 | georg.brandl | 2008-02-23 23:14:02 +0100 (Sat, 23 Feb 2008) | 2 lines Use os.closerange(). ........ r61021 | georg.brandl | 2008-02-23 23:35:33 +0100 (Sat, 23 Feb 2008) | 3 lines In test_heapq and test_bisect, test both the Python and the C implementation. Originally written for GHOP by Josip Dzolonga, heavily patched by me. ........ r61024 | facundo.batista | 2008-02-23 23:54:12 +0100 (Sat, 23 Feb 2008) | 3 lines Added simple test case. Thanks Benjamin Peterson. ........ r61025 | georg.brandl | 2008-02-23 23:55:18 +0100 (Sat, 23 Feb 2008) | 2 lines #1825: correctly document msilib.add_data. ........ r61027 | georg.brandl | 2008-02-24 00:02:23 +0100 (Sun, 24 Feb 2008) | 2 lines #1826: allow dotted attribute paths in operator.attrgetter. ........ r61028 | georg.brandl | 2008-02-24 00:04:35 +0100 (Sun, 24 Feb 2008) | 2 lines #1506171: added operator.methodcaller(). ........ r61029 | georg.brandl | 2008-02-24 00:25:26 +0100 (Sun, 24 Feb 2008) | 2 lines Document import ./. threading issues. #1720705. ........ r61032 | georg.brandl | 2008-02-24 00:43:01 +0100 (Sun, 24 Feb 2008) | 2 lines Specify what kind of warning -3 emits. ........ r61033 | christian.heimes | 2008-02-24 00:59:45 +0100 (Sun, 24 Feb 2008) | 1 line MS Windows doesn't have mode_t but stat.st_mode is defined as unsigned short. ........ ................ r61038 | neal.norwitz | 2008-02-24 03:22:41 +0100 (Sun, 24 Feb 2008) | 8 lines Blocked revisions 61037 via svnmerge ........ r61037 | neal.norwitz | 2008-02-23 18:20:25 -0800 (Sat, 23 Feb 2008) | 2 lines map(None, ...) is not supported in 3.0. ........ ................ r61050 | christian.heimes | 2008-02-24 14:08:18 +0100 (Sun, 24 Feb 2008) | 41 lines Merged revisions 61034-61036,61038-61048 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61034 | georg.brandl | 2008-02-24 01:03:22 +0100 (Sun, 24 Feb 2008) | 4 lines #900744: If an invalid chunked-encoding header is sent by a server, httplib will now raise IncompleteRead and close the connection instead of raising ValueError. ........ r61035 | georg.brandl | 2008-02-24 01:14:24 +0100 (Sun, 24 Feb 2008) | 2 lines #1627: httplib now ignores negative Content-Length headers. ........ r61039 | andrew.kuchling | 2008-02-24 03:39:15 +0100 (Sun, 24 Feb 2008) | 1 line Remove stray word ........ r61040 | neal.norwitz | 2008-02-24 03:40:58 +0100 (Sun, 24 Feb 2008) | 3 lines Add a little info to the 3k deprecation warnings about what to use instead. Suggested by Raymond Hettinger. ........ r61041 | facundo.batista | 2008-02-24 04:17:21 +0100 (Sun, 24 Feb 2008) | 4 lines Issue 1742669. Now %d accepts very big float numbers. Thanks Gabriel Genellina. ........ r61046 | neal.norwitz | 2008-02-24 08:21:56 +0100 (Sun, 24 Feb 2008) | 5 lines Get ctypes working on the Alpha (Tru64). The problem was that there were two module_methods and the one used depended on the order the modules were loaded. By making the test module_methods static, it is not exported and the correct version is picked up. ........ r61048 | neal.norwitz | 2008-02-24 09:27:49 +0100 (Sun, 24 Feb 2008) | 1 line Fix typo of hexidecimal ........ ................ r61055 | eric.smith | 2008-02-24 22:43:18 +0100 (Sun, 24 Feb 2008) | 1 line Block r61054. I'll manually merge it, since it's breaking the buildbots. ................ r61056 | eric.smith | 2008-02-24 22:44:34 +0100 (Sun, 24 Feb 2008) | 1 line Corrected assert to check for correct type in py3k. ................ r61061 | christian.heimes | 2008-02-25 13:39:23 +0100 (Mon, 25 Feb 2008) | 31 lines Merged revisions 61038,61042-61045,61047,61049-61053,61055-61057 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61049 | christian.heimes | 2008-02-24 13:26:16 +0100 (Sun, 24 Feb 2008) | 1 line Use PY_FORMAT_SIZE_T instead of z for string formatting. Thanks Neal. ........ r61051 | mark.dickinson | 2008-02-24 19:12:36 +0100 (Sun, 24 Feb 2008) | 2 lines Remove duplicate 'import re' in decimal.py ........ r61052 | neal.norwitz | 2008-02-24 19:47:03 +0100 (Sun, 24 Feb 2008) | 11 lines Create a db_home directory with a unique name so multiple users can run the test simultaneously. The simplest thing I found that worked on both Windows and Unix was to use the PID. It's unique so should be sufficient. This should prevent many of the spurious failures of the automated tests since they run as different users. Also cleanup the directory consistenly in the tearDown methods. It would be nice if someone ensured that the directories are always created with a consistent name. ........ r61057 | christian.heimes | 2008-02-24 23:48:05 +0100 (Sun, 24 Feb 2008) | 2 lines Added dependency rules for Objects/stringlib/*.h stringobject, unicodeobject and the two formatters are rebuild whenever a header files changes ........ ................ r61062 | christian.heimes | 2008-02-25 14:19:43 +0100 (Mon, 25 Feb 2008) | 17 lines Merged revisions 61038,61042-61045,61047,61050,61053,61055-61056,61058-61061 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61058 | neal.norwitz | 2008-02-25 02:45:37 +0100 (Mon, 25 Feb 2008) | 1 line Fix indentation ........ r61059 | brett.cannon | 2008-02-25 06:33:07 +0100 (Mon, 25 Feb 2008) | 2 lines Add minor markup for a string. ........ r61060 | brett.cannon | 2008-02-25 06:33:33 +0100 (Mon, 25 Feb 2008) | 2 lines Fix a minor typo in a docstring. ........ ................ r61066 | christian.heimes | 2008-02-25 18:33:32 +0100 (Mon, 25 Feb 2008) | 1 line svnmerge.py block -r 61065 ................ r61083 | christian.heimes | 2008-02-26 09:18:30 +0100 (Tue, 26 Feb 2008) | 67 lines Merged revisions 61038,61042-61045,61047,61050,61053,61055-61056,61061-61064,61066-61080 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61063 | andrew.kuchling | 2008-02-25 17:29:19 +0100 (Mon, 25 Feb 2008) | 1 line Move .setupterm() output so that we don't try to call endwin() if it fails ........ r61064 | andrew.kuchling | 2008-02-25 17:29:58 +0100 (Mon, 25 Feb 2008) | 1 line Use file descriptor for real stdout ........ r61067 | facundo.batista | 2008-02-25 19:06:00 +0100 (Mon, 25 Feb 2008) | 4 lines Issue 2117. Update compiler module to handle class decorators. Thanks Thomas Herve ........ r61069 | georg.brandl | 2008-02-25 21:17:56 +0100 (Mon, 25 Feb 2008) | 2 lines Rename sphinx.addons to sphinx.ext. ........ r61071 | georg.brandl | 2008-02-25 21:20:45 +0100 (Mon, 25 Feb 2008) | 2 lines Revert r61029. ........ r61072 | facundo.batista | 2008-02-25 23:33:55 +0100 (Mon, 25 Feb 2008) | 4 lines Issue 2168. gdbm and dbm needs to be iterable; this fixes a failure in the shelve module. Thanks Thomas Herve. ........ r61073 | raymond.hettinger | 2008-02-25 23:42:32 +0100 (Mon, 25 Feb 2008) | 1 line Make sure the itertools filter functions give the same performance for func=bool as func=None. ........ r61074 | raymond.hettinger | 2008-02-26 00:17:41 +0100 (Tue, 26 Feb 2008) | 1 line Revert part of r60927 which made invalid assumptions about the API offered by db modules. ........ r61075 | facundo.batista | 2008-02-26 00:46:02 +0100 (Tue, 26 Feb 2008) | 3 lines Coerced PyBool_Type to be able to compare it. ........ r61076 | raymond.hettinger | 2008-02-26 03:46:54 +0100 (Tue, 26 Feb 2008) | 1 line Docs for itertools.combinations(). Implementation in forthcoming checkin. ........ r61077 | neal.norwitz | 2008-02-26 05:50:37 +0100 (Tue, 26 Feb 2008) | 3 lines Don't use a hard coded port. This test could hang/fail if the port is in use. Speed this test up by avoiding a sleep and using the event. ........ r61078 | neal.norwitz | 2008-02-26 06:12:50 +0100 (Tue, 26 Feb 2008) | 1 line Whitespace normalization ........ r61079 | neal.norwitz | 2008-02-26 06:23:51 +0100 (Tue, 26 Feb 2008) | 1 line Whitespace normalization ........ r61080 | georg.brandl | 2008-02-26 07:40:10 +0100 (Tue, 26 Feb 2008) | 2 lines Banish tab. ........ ................ r61085 | mark.summerfield | 2008-02-26 14:27:00 +0100 (Tue, 26 Feb 2008) | 4 lines Updated super() as per http://www.artima.com/weblogs/viewpost.jsp?thread=208549 but would be worth someone else checking if poss. ................ r61103 | christian.heimes | 2008-02-28 12:19:05 +0100 (Thu, 28 Feb 2008) | 48 lines Merged revisions 61038,61042-61045,61047,61050,61053,61055-61056,61061-61062,61066,61068,61070,61081-61095 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61081 | neal.norwitz | 2008-02-26 09:04:59 +0100 (Tue, 26 Feb 2008) | 7 lines Speed up this test by about 99%. Remove sleeps and replace with events. (This may fail on some slow platforms, but we can fix those cases which should be relatively isolated and easier to find now.) Move two test cases that didn't require a server to be started to a separate TestCase. These tests were taking 3 seconds which is what the timeout was set to. ........ r61082 | christian.heimes | 2008-02-26 09:18:11 +0100 (Tue, 26 Feb 2008) | 1 line The contains function raised a gcc warning. The new code is copied straight from py3k. ........ r61084 | neal.norwitz | 2008-02-26 09:21:28 +0100 (Tue, 26 Feb 2008) | 3 lines Add a timing flag to Trace so you can see where slowness occurs like waiting for socket timeouts in test_smtplib :-). ........ r61086 | christian.heimes | 2008-02-26 18:23:51 +0100 (Tue, 26 Feb 2008) | 3 lines Patch #1691070 from Roger Upole: Speed up PyArg_ParseTupleAndKeywords() and improve error msg My tests don't show the promised speed up of 10%. The code is as fast as the old code for simple cases and slightly faster for complex cases with several of args and kwargs. But the patch simplifies the code, too. ........ r61087 | georg.brandl | 2008-02-26 20:13:45 +0100 (Tue, 26 Feb 2008) | 2 lines #2194: fix some typos. ........ r61088 | raymond.hettinger | 2008-02-27 00:40:50 +0100 (Wed, 27 Feb 2008) | 1 line Add itertools.combinations(). ........ r61089 | raymond.hettinger | 2008-02-27 02:08:04 +0100 (Wed, 27 Feb 2008) | 1 line One too many decrefs. ........ r61090 | raymond.hettinger | 2008-02-27 02:08:30 +0100 (Wed, 27 Feb 2008) | 1 line Larger test range ........ r61091 | raymond.hettinger | 2008-02-27 02:44:34 +0100 (Wed, 27 Feb 2008) | 1 line Simply the sample code for combinations(). ........ ................ r61104 | christian.heimes | 2008-02-28 13:27:11 +0100 (Thu, 28 Feb 2008) | 50 lines Merged revisions 61038,61042-61045,61047,61050,61053,61055-61056,61061-61062,61066,61068,61070,61083,61085,61092-61103 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61098 | jeffrey.yasskin | 2008-02-28 05:45:36 +0100 (Thu, 28 Feb 2008) | 7 lines Move abc._Abstract into object by adding a new flag Py_TPFLAGS_IS_ABSTRACT, which forbids constructing types that have it set. The effect is to speed ./python.exe -m timeit -s 'import abc' -s 'class Foo(object): __metaclass__ = abc.ABCMeta' 'Foo()' up from 2.5us to 0.201us. This fixes issue 1762. ........ r61099 | jeffrey.yasskin | 2008-02-28 06:53:18 +0100 (Thu, 28 Feb 2008) | 3 lines Speed test_socketserver up from 28.739s to 0.226s, simplify the logic, and make sure all tests run even if some fail. ........ r61100 | jeffrey.yasskin | 2008-02-28 07:09:19 +0100 (Thu, 28 Feb 2008) | 21 lines Thread.start() used sleep(0.000001) to make sure it didn't return before the new thread had started. At least on my MacBook Pro, that wound up sleeping for a full 10ms (probably 1 jiffy). By using an Event instead, we can be absolutely certain that the thread has started, and return more quickly (217us). Before: $ ./python.exe -m timeit -s 'from threading import Thread' 't = Thread(); t.start(); t.join()' 100 loops, best of 3: 10.3 msec per loop $ ./python.exe -m timeit -s 'from threading import Thread; t = Thread()' 't.isAlive()' 1000000 loops, best of 3: 0.47 usec per loop After: $ ./python.exe -m timeit -s 'from threading import Thread' 't = Thread(); t.start(); t.join()' 1000 loops, best of 3: 217 usec per loop $ ./python.exe -m timeit -s 'from threading import Thread; t = Thread()' 't.isAlive()' 1000000 loops, best of 3: 0.86 usec per loop To be fair, the 10ms isn't CPU time, and other threads including the spawned one get to run during it. There are also some slightly more complicated ways to get back the .4us in isAlive() if we want. ........ r61101 | raymond.hettinger | 2008-02-28 10:23:48 +0100 (Thu, 28 Feb 2008) | 1 line Add repeat keyword argument to itertools.product(). ........ r61102 | christian.heimes | 2008-02-28 12:18:49 +0100 (Thu, 28 Feb 2008) | 1 line The empty tuple is usually a singleton with a much higher refcnt than 1 ........ ................ r61110 | christian.heimes | 2008-02-28 21:02:27 +0100 (Thu, 28 Feb 2008) | 23 lines Merged revisions 61038,61042-61045,61047,61050,61053,61055-61056,61061-61062,61066,61068,61070,61083,61085,61092-61097,61103-61108 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61105 | andrew.kuchling | 2008-02-28 15:03:03 +0100 (Thu, 28 Feb 2008) | 1 line #2169: make generated HTML more valid ........ r61106 | jeffrey.yasskin | 2008-02-28 19:03:15 +0100 (Thu, 28 Feb 2008) | 4 lines Prevent SocketServer.ForkingMixIn from waiting on child processes that it didn't create, in most cases. When there are max_children handlers running, it will still wait for any child process, not just handler processes. ........ r61107 | raymond.hettinger | 2008-02-28 20:41:24 +0100 (Thu, 28 Feb 2008) | 1 line Document impending updates to itertools. ........ r61108 | martin.v.loewis | 2008-02-28 20:44:22 +0100 (Thu, 28 Feb 2008) | 1 line Add 2.6aN uuids. ........ ................ r61112 | christian.heimes | 2008-02-28 21:52:40 +0100 (Thu, 28 Feb 2008) | 9 lines Merged revisions 61038,61042-61045,61047,61050,61053,61055-61056,61061-61062,61066,61068,61070,61083,61085,61092-61097,61103-61104,61109-61111 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61109 | martin.v.loewis | 2008-02-28 20:57:34 +0100 (Thu, 28 Feb 2008) | 1 line Bundle msvcr90.dll as a "private assembly". ........ ................ r61114 | christian.heimes | 2008-02-28 22:10:17 +0100 (Thu, 28 Feb 2008) | 1 line iter() doesn't use __getattr__ to find an __iter__ method. I'm not sure if the behavior is deliberately but this workaround fixes the issue for the next alpha release tomorrow. ................ r61115 | christian.heimes | 2008-02-28 22:17:00 +0100 (Thu, 28 Feb 2008) | 9 lines Merged revisions 61038,61042-61045,61047,61050,61053,61055-61056,61061-61062,61066,61068,61070,61083,61085,61092-61097,61103-61104,61110-61113 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61113 | christian.heimes | 2008-02-28 22:00:45 +0100 (Thu, 28 Feb 2008) | 2 lines Windows fix for signal test - skip it earlier ........ ................ r61117 | christian.heimes | 2008-02-28 23:21:11 +0100 (Thu, 28 Feb 2008) | 1 line As Guido says ................ r61120 | martin.v.loewis | 2008-02-29 00:01:33 +0100 (Fri, 29 Feb 2008) | 9 lines Merged revisions 61116 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61116 | martin.v.loewis | 2008-02-28 23:20:50 +0100 (Do, 28 Feb 2008) | 1 line Locate VS installation dir from environment, so that it works with the express edition. ........ ................ r61121 | martin.v.loewis | 2008-02-29 00:03:52 +0100 (Fri, 29 Feb 2008) | 2 lines Package 2to3. ................ r61126 | christian.heimes | 2008-02-29 15:57:44 +0100 (Fri, 29 Feb 2008) | 25 lines Merged revisions 61038,61042-61045,61047,61050,61053,61055-61056,61061-61062,61066,61068,61070,61083,61085,61092-61097,61103-61104,61110-61112,61114-61115,61117-61125 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61118 | raymond.hettinger | 2008-02-28 23:30:42 +0100 (Thu, 28 Feb 2008) | 1 line Have itertools.chain() consume its inputs lazily instead of building a tuple of iterators at the outset. ........ r61119 | raymond.hettinger | 2008-02-28 23:46:41 +0100 (Thu, 28 Feb 2008) | 1 line Add alternate constructor for itertools.chain(). ........ r61123 | mark.dickinson | 2008-02-29 03:16:37 +0100 (Fri, 29 Feb 2008) | 2 lines Add __format__ method to Decimal, to support PEP 3101 ........ r61124 | raymond.hettinger | 2008-02-29 03:21:48 +0100 (Fri, 29 Feb 2008) | 1 line Handle the repeat keyword argument for itertools.product(). ........ r61125 | mark.dickinson | 2008-02-29 04:29:17 +0100 (Fri, 29 Feb 2008) | 2 lines Fix docstring typo. ........ ................ r61127 | christian.heimes | 2008-02-29 16:03:39 +0100 (Fri, 29 Feb 2008) | 1 line I forgot to start the unit test suite first. ................ r61137 | martin.v.loewis | 2008-02-29 20:39:25 +0100 (Fri, 29 Feb 2008) | 25 lines Merged revisions 61038,61042-61045,61047,61050,61053,61055-61056,61061-61062,61066,61068,61070,61083,61085,61092-61097,61103-61104,61110-61112,61114-61115,61117,61120-61122,61126-61136 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61128 | martin.v.loewis | 2008-02-29 17:59:21 +0100 (Fr, 29 Feb 2008) | 1 line Make _hashlib a separate project. ........ r61132 | georg.brandl | 2008-02-29 19:15:36 +0100 (Fr, 29 Feb 2008) | 2 lines Until we got downloadable docs, stop confusing viewers by talking about a nonexisting table. ........ r61133 | martin.v.loewis | 2008-02-29 19:17:23 +0100 (Fr, 29 Feb 2008) | 1 line Build db-4.4.20 with VS9; remove VS2003 build if necessary. ........ r61135 | georg.brandl | 2008-02-29 19:21:29 +0100 (Fr, 29 Feb 2008) | 2 lines #2208: allow for non-standard HHC location. ........ r61136 | martin.v.loewis | 2008-02-29 19:54:45 +0100 (Fr, 29 Feb 2008) | 1 line Port build_ssl.py to 2.4; support HOST_PYTHON variable ........ ................ r61140 | martin.v.loewis | 2008-02-29 22:03:38 +0100 (Fri, 29 Feb 2008) | 13 lines Merged revisions 61038,61042-61045,61047,61050,61053,61055-61056,61061-61062,61066,61068,61070,61083,61085,61092-61097,61103-61104,61110-61112,61114-61115,61117,61120-61122,61126-61127,61129-61131,61134,61137-61139 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61138 | martin.v.loewis | 2008-02-29 21:26:53 +0100 (Fr, 29 Feb 2008) | 1 line Make _hashlib depend on pythoncore. ........ r61139 | martin.v.loewis | 2008-02-29 21:54:44 +0100 (Fr, 29 Feb 2008) | 1 line Package Tcl from tcltk64 on AMD64. ........ ................ r61142 | gerhard.haering | 2008-02-29 23:22:09 +0100 (Fri, 29 Feb 2008) | 2 lines Make sure we get usable error messages when text could not be decoded when fetched from the database. ................ r61145 | mark.dickinson | 2008-03-01 03:27:46 +0100 (Sat, 01 Mar 2008) | 9 lines Fix failing itertools test: since revision 61118, itertools.chain consumes its arguments lazily, so chain(non_iterable) doesn't raise TypeError until the first call to__next__. The test has been changed to reflect this. Committing this in during the code freeze; the checkin was approved by Barry. ................ r61153 | neal.norwitz | 2008-03-01 04:38:40 +0100 (Sat, 01 Mar 2008) | 3 lines Remove bogus entries from r60902 which was a problem from merging. There might be some extra stuff left in here, but it should be close to accurate now. Checked in with permission from Barry. ................ r61154 | neal.norwitz | 2008-03-01 05:06:19 +0100 (Sat, 01 Mar 2008) | 5 lines When the _iter_mixin stopped inheritting from UsserDictMixin, it lost the __repr__ which caused bsddb.test.test_misc.py to fail in test03_repr_closed_db Restore the repr so the test passes. I think this is correct, but it would be good to have some more review. ................ r61155 | brett.cannon | 2008-03-01 05:28:23 +0100 (Sat, 01 Mar 2008) | 8 lines Change test_profile to only compare data that originates from the test file. Including the full output becomes hairy in the face of the I/O system being written in Python and thus profiled (i.e., running the test on its own and then under regrtest created a different profile thanks to an extra flush() call in the latter case). No need to backport as 2.x's I/O is entirely C-based and thus not profiled. ................ r61156 | barry.warsaw | 2008-03-01 18:05:53 +0100 (Sat, 01 Mar 2008) | 2 lines Disable the cProfile test for now -- it's broken. ................ r61158 | barry.warsaw | 2008-03-01 18:45:23 +0100 (Sat, 01 Mar 2008) | 2 lines Copyright and version tweaks for 3.0a3. ................ r61161 | barry.warsaw | 2008-03-01 19:38:07 +0100 (Sat, 01 Mar 2008) | 1 line Prep for 3.0a4 ................ r61187 | christian.heimes | 2008-03-02 22:36:14 +0100 (Sun, 02 Mar 2008) | 2 lines svnmerge.py block -r 61141,61174,61175 Blocking last chances to the sqlite module. ................ r61188 | christian.heimes | 2008-03-02 23:46:37 +0100 (Sun, 02 Mar 2008) | 79 lines Merged revisions 61143-61144,61146-61147,61150-61151,61157,61165-61168,61170-61173,61176-61177,61183 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61143 | barry.warsaw | 2008-03-01 03:23:38 +0100 (Sat, 01 Mar 2008) | 2 lines Bump to version 2.6a1 ........ r61144 | barry.warsaw | 2008-03-01 03:26:42 +0100 (Sat, 01 Mar 2008) | 1 line bump idle version number ........ r61146 | fred.drake | 2008-03-01 03:45:07 +0100 (Sat, 01 Mar 2008) | 2 lines fix typo ........ r61147 | barry.warsaw | 2008-03-01 03:53:36 +0100 (Sat, 01 Mar 2008) | 1 line Add date to NEWS ........ r61150 | barry.warsaw | 2008-03-01 04:00:52 +0100 (Sat, 01 Mar 2008) | 1 line Give IDLE a release date ........ r61151 | barry.warsaw | 2008-03-01 04:15:20 +0100 (Sat, 01 Mar 2008) | 1 line More copyright year and version number bumps ........ r61157 | barry.warsaw | 2008-03-01 18:11:41 +0100 (Sat, 01 Mar 2008) | 2 lines Set things up for 2.6a2. ........ r61165 | georg.brandl | 2008-03-02 07:28:16 +0100 (Sun, 02 Mar 2008) | 2 lines It's 2.6 now. ........ r61166 | georg.brandl | 2008-03-02 07:32:32 +0100 (Sun, 02 Mar 2008) | 2 lines Update year. ........ r61167 | georg.brandl | 2008-03-02 07:44:08 +0100 (Sun, 02 Mar 2008) | 2 lines Make patchlevel print out the release if called as a script. ........ r61168 | georg.brandl | 2008-03-02 07:45:40 +0100 (Sun, 02 Mar 2008) | 2 lines New default basename for HTML help files. ........ r61170 | raymond.hettinger | 2008-03-02 11:59:31 +0100 (Sun, 02 Mar 2008) | 1 line Finish-up docs for combinations() and permutations() in itertools. ........ r61171 | raymond.hettinger | 2008-03-02 12:17:51 +0100 (Sun, 02 Mar 2008) | 1 line Tighten example code. ........ r61172 | raymond.hettinger | 2008-03-02 12:57:16 +0100 (Sun, 02 Mar 2008) | 1 line Simplify code for itertools.product(). ........ r61173 | raymond.hettinger | 2008-03-02 13:02:19 +0100 (Sun, 02 Mar 2008) | 1 line Handle 0-tuples which can be singletons. ........ r61176 | georg.brandl | 2008-03-02 14:41:39 +0100 (Sun, 02 Mar 2008) | 2 lines Make clear that the constants are strings. ........ r61177 | georg.brandl | 2008-03-02 15:15:04 +0100 (Sun, 02 Mar 2008) | 2 lines Fix factual error. ........ r61183 | gregory.p.smith | 2008-03-02 21:00:53 +0100 (Sun, 02 Mar 2008) | 4 lines Modify import of test_support so that the code can also be used with a stand alone distribution of bsddb that includes its own small copy of test_support for the needed functionality on older pythons. ........ ................ r61191 | brett.cannon | 2008-03-03 03:31:43 +0100 (Mon, 03 Mar 2008) | 3 lines Actually have test_largefile execute. Call to test.test_support.run_unittest() somehow got lost. ................ r61193 | alexandre.vassalotti | 2008-03-03 03:59:49 +0100 (Mon, 03 Mar 2008) | 3 lines Fixed failing unit tests due to str/bytes mismatch. Changed "assert isinstance(...)" in hmac.py to raise proper TypeError. ................ r61196 | brett.cannon | 2008-03-03 04:36:27 +0100 (Mon, 03 Mar 2008) | 2 lines Toss test.testall. ................ r61205 | christian.heimes | 2008-03-03 20:15:45 +0100 (Mon, 03 Mar 2008) | 43 lines Merged revisions 61189-61190,61192,61194-61195,61198-61199 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61189 | brett.cannon | 2008-03-03 01:38:58 +0100 (Mon, 03 Mar 2008) | 5 lines Refactor test_logging to use unittest. This should finally solve the flakiness issues. Thanks to Antoine Pitrou for the patch. ........ r61190 | jeffrey.yasskin | 2008-03-03 02:27:03 +0100 (Mon, 03 Mar 2008) | 3 lines compile.c always emits END_FINALLY after WITH_CLEANUP, so predict that in ceval.c. This is worth about a .03-.04us speedup on a simple with block. ........ r61192 | brett.cannon | 2008-03-03 03:41:40 +0100 (Mon, 03 Mar 2008) | 4 lines Move test_largefile over to using 'with' statements for open files. Also rename the driver function to test_main() instead of main_test(). ........ r61194 | brett.cannon | 2008-03-03 04:24:48 +0100 (Mon, 03 Mar 2008) | 3 lines Add a note in the main test class' docstring that the order of execution of the tests is important. ........ r61195 | brett.cannon | 2008-03-03 04:26:43 +0100 (Mon, 03 Mar 2008) | 3 lines Add a note in the main test class' docstring that the order of execution of the tests is important. ........ r61198 | brett.cannon | 2008-03-03 05:19:29 +0100 (Mon, 03 Mar 2008) | 4 lines Add test_main() functions to various tests where it was simple to do. Done so that regrtest can execute the test_main() directly instead of relying on import side-effects. ........ r61199 | neal.norwitz | 2008-03-03 05:37:45 +0100 (Mon, 03 Mar 2008) | 1 line Only DECREF if ret != NULL ........ ................ r61206 | christian.heimes | 2008-03-03 20:18:51 +0100 (Mon, 03 Mar 2008) | 14 lines Merged revisions 61203-61204 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61203 | christian.heimes | 2008-03-03 13:40:17 +0100 (Mon, 03 Mar 2008) | 3 lines Initialized merge tracking via "svnmerge" with revisions "1-60195" from svn+ssh://pythondev at svn.python.org/python/branches/trunk-math ........ r61204 | christian.heimes | 2008-03-03 19:28:04 +0100 (Mon, 03 Mar 2008) | 1 line Since abc._Abstract was replaces by a new type flags the regression test suite fails. I've added a new function inspect.isabstract(). Is the mmethod fine or should I check if object is a instance of type or subclass of object, too? ........ ................ r61208 | christian.heimes | 2008-03-03 21:34:40 +0100 (Mon, 03 Mar 2008) | 9 lines Merged revisions 61207 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61207 | christian.heimes | 2008-03-03 21:30:29 +0100 (Mon, 03 Mar 2008) | 1 line 15 -> 16 ........ ................ r61238 | christian.heimes | 2008-03-05 00:39:23 +0100 (Wed, 05 Mar 2008) | 93 lines Merged revisions 61209-61214,61217-61222,61224-61226,61233-61237 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61209 | georg.brandl | 2008-03-03 21:37:55 +0100 (Mon, 03 Mar 2008) | 2 lines There are now sixteen isfoo functions. ........ r61210 | georg.brandl | 2008-03-03 21:39:00 +0100 (Mon, 03 Mar 2008) | 2 lines 15 -> 16, the 2nd ........ r61211 | georg.brandl | 2008-03-03 22:22:47 +0100 (Mon, 03 Mar 2008) | 2 lines Actually import itertools. ........ r61212 | georg.brandl | 2008-03-03 22:31:50 +0100 (Mon, 03 Mar 2008) | 2 lines Expand a bit on genexp scopes. ........ r61213 | raymond.hettinger | 2008-03-03 23:04:55 +0100 (Mon, 03 Mar 2008) | 1 line Remove dependency on itertools -- a simple genexp suffices. ........ r61214 | raymond.hettinger | 2008-03-03 23:19:58 +0100 (Mon, 03 Mar 2008) | 1 line Issue 2226: Callable checked for the wrong abstract method. ........ r61217 | andrew.kuchling | 2008-03-04 01:40:32 +0100 (Tue, 04 Mar 2008) | 1 line Typo fix ........ r61218 | andrew.kuchling | 2008-03-04 02:30:10 +0100 (Tue, 04 Mar 2008) | 1 line Grammar fix; markup fix ........ r61219 | andrew.kuchling | 2008-03-04 02:47:38 +0100 (Tue, 04 Mar 2008) | 1 line Fix sentence fragment ........ r61220 | andrew.kuchling | 2008-03-04 02:48:26 +0100 (Tue, 04 Mar 2008) | 1 line Typo fix ........ r61221 | andrew.kuchling | 2008-03-04 02:49:37 +0100 (Tue, 04 Mar 2008) | 1 line Add versionadded tags ........ r61222 | andrew.kuchling | 2008-03-04 02:50:32 +0100 (Tue, 04 Mar 2008) | 1 line Thesis night results: add various items ........ r61224 | raymond.hettinger | 2008-03-04 05:17:08 +0100 (Tue, 04 Mar 2008) | 1 line Beef-up docs and tests for itertools. Fix-up end-case for product(). ........ r61225 | georg.brandl | 2008-03-04 08:25:54 +0100 (Tue, 04 Mar 2008) | 2 lines Fix some patch attributions. ........ r61226 | georg.brandl | 2008-03-04 08:33:30 +0100 (Tue, 04 Mar 2008) | 2 lines #2230: document that PyArg_* leaves addresses alone on error. ........ r61233 | neal.norwitz | 2008-03-04 17:22:46 +0100 (Tue, 04 Mar 2008) | 3 lines Close the file before trying to remove the directory so it works on Windows. As reported by Trent Nelson on python-dev. ........ r61234 | thomas.heller | 2008-03-04 21:09:11 +0100 (Tue, 04 Mar 2008) | 9 lines Merged changes from libffi3-branch. The bundled libffi copy is now in sync with the recently released libffi3.0.4 version, apart from some small changes to Modules/_ctypes/libffi/configure.ac. I gave up on using libffi3 files on os x. Instead, static configuration with files from pyobjc is used. ........ r61235 | thomas.heller | 2008-03-04 21:21:42 +0100 (Tue, 04 Mar 2008) | 1 line Try to fix the build for PY_LINUX. ........ r61236 | fred.drake | 2008-03-04 22:14:04 +0100 (Tue, 04 Mar 2008) | 2 lines fix typo ........ r61237 | raymond.hettinger | 2008-03-04 23:29:44 +0100 (Tue, 04 Mar 2008) | 1 line Fix refleak in chain(). ........ ................ r61267 | georg.brandl | 2008-03-06 08:09:43 +0100 (Thu, 06 Mar 2008) | 2 lines Remove 1.5.2 incompatibility notes from RE docs. ................ r61280 | martin.v.loewis | 2008-03-06 19:28:18 +0100 (Thu, 06 Mar 2008) | 2 lines Force rebuild of Tcl/Tk. ................ r61281 | martin.v.loewis | 2008-03-06 19:38:56 +0100 (Thu, 06 Mar 2008) | 2 lines Revert previous checkin; Tcl/Tk seems to build fine. ................ r61306 | martin.v.loewis | 2008-03-08 11:40:41 +0100 (Sat, 08 Mar 2008) | 2 lines Use wchar_t functions in _locale module. ................ r61307 | martin.v.loewis | 2008-03-08 11:54:31 +0100 (Sat, 08 Mar 2008) | 2 lines Properly size memory blocks in units of wchar_t. ................ r61308 | martin.v.loewis | 2008-03-08 11:59:49 +0100 (Sat, 08 Mar 2008) | 2 lines Fix typo in assertion. ................ r61309 | martin.v.loewis | 2008-03-08 12:24:24 +0100 (Sat, 08 Mar 2008) | 4 lines Default to ASCII as the locale.getpreferredencoding, if the POSIX system doesn't support CODESET and LANG isn't set or doesn't allow deduction of an encoding. ................ r61310 | martin.v.loewis | 2008-03-08 12:59:08 +0100 (Sat, 08 Mar 2008) | 2 lines Skip tests if the file mapping file cannot be fetched. ................ r61311 | martin.v.loewis | 2008-03-08 14:39:58 +0100 (Sat, 08 Mar 2008) | 2 lines Fix another buffer overflow. ................ r61339 | neal.norwitz | 2008-03-10 05:49:25 +0100 (Mon, 10 Mar 2008) | 1 line strxfrm and strcoll are conditionally defined, alwsy provide some impl ................ r61340 | martin.v.loewis | 2008-03-10 11:18:53 +0100 (Mon, 10 Mar 2008) | 2 lines Also set LC_CTYPE, to allow localeconv string conversion. ................ r61352 | georg.brandl | 2008-03-12 09:52:43 +0100 (Wed, 12 Mar 2008) | 9 lines Merged revisions 61330 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61330 | georg.brandl | 2008-03-09 19:18:30 +0100 (Sun, 09 Mar 2008) | 2 lines Update for newest Sphinx. ........ ................ r61356 | raymond.hettinger | 2008-03-13 01:19:26 +0100 (Thu, 13 Mar 2008) | 1 line Issue 2186 and 2187. Move filter from itertools to builtins. ................ r61357 | raymond.hettinger | 2008-03-13 02:26:19 +0100 (Thu, 13 Mar 2008) | 1 line Issues 2186 and 2187. Move map() from itertools to builtins. ................ r61358 | raymond.hettinger | 2008-03-13 02:41:43 +0100 (Thu, 13 Mar 2008) | 1 line Rename ifilterfalse() to filterfalse() and izip_longest() to zip_longest(). ................ r61359 | raymond.hettinger | 2008-03-13 03:05:52 +0100 (Thu, 13 Mar 2008) | 1 line The texcheck script is not needed with reST documentation. ................ r61360 | raymond.hettinger | 2008-03-13 03:09:15 +0100 (Thu, 13 Mar 2008) | 1 line Move itertools izip() code to builtins as zip(). Complete the renaming. ................ r61361 | raymond.hettinger | 2008-03-13 03:39:40 +0100 (Thu, 13 Mar 2008) | 1 line Sync-up with doc improvements in Py2.6 ................ r61362 | raymond.hettinger | 2008-03-13 03:43:14 +0100 (Thu, 13 Mar 2008) | 1 line In Py3.0, the recipes can use keyword-only arguments instead of using the **kwds trick. ................ r61377 | georg.brandl | 2008-03-14 14:28:59 +0100 (Fri, 14 Mar 2008) | 2 lines #2285: remove cmp keyword from list.sort docstring. ................ r61386 | thomas.wouters | 2008-03-14 18:16:59 +0100 (Fri, 14 Mar 2008) | 5 lines Fix crasher in unpacking assignments with star, where the size constraints weren't checked. ................ r61397 | gregory.p.smith | 2008-03-15 07:05:36 +0100 (Sat, 15 Mar 2008) | 4 lines Fix an apparent typo. This test of the readonly boolean should have been != 0 rather than >= 0. This change means the PyBUF_LOCK flag to the buffer api works on immutable bytes objects as one would expect. ................ r61408 | christian.heimes | 2008-03-16 01:07:10 +0100 (Sun, 16 Mar 2008) | 352 lines Merged revisions 61239-61249,61252-61257,61260-61264,61269-61275,61278-61279,61285-61286,61288-61290,61298,61303-61305,61312-61314,61317,61329,61332,61344,61350-61351,61363-61376,61378-61379,61382-61383,61387-61388,61392,61395-61396,61402-61403 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61239 | andrew.kuchling | 2008-03-05 01:44:41 +0100 (Wed, 05 Mar 2008) | 1 line Add more items; add fragmentary notes ........ r61240 | amaury.forgeotdarc | 2008-03-05 02:50:33 +0100 (Wed, 05 Mar 2008) | 13 lines Issue#2238: some syntax errors from *args or **kwargs expressions would give bogus error messages, because of untested exceptions:: >>> f(**g(1=2)) XXX undetected error Traceback (most recent call last): File "", line 1, in TypeError: 'int' object is not iterable instead of the expected SyntaxError: keyword can't be an expression Will backport. ........ r61241 | neal.norwitz | 2008-03-05 06:10:48 +0100 (Wed, 05 Mar 2008) | 3 lines Remove the files/dirs after closing the DB so the tests work on Windows. Patch from Trent Nelson. Also simplified removing a file by using test_support. ........ r61242 | neal.norwitz | 2008-03-05 06:14:18 +0100 (Wed, 05 Mar 2008) | 3 lines Get this test to pass even when there is no sound card in the system. Patch from Trent Nelson. (I can't test this.) ........ r61243 | neal.norwitz | 2008-03-05 06:20:44 +0100 (Wed, 05 Mar 2008) | 3 lines Catch OSError when trying to remove a file in case removal fails. This should prevent a failure in tearDown masking any real test failure. ........ r61244 | neal.norwitz | 2008-03-05 06:38:06 +0100 (Wed, 05 Mar 2008) | 5 lines Make the timeout longer to give slow machines a chance to pass the test before timing out. This doesn't change the duration of the test under normal circumstances. This is targetted at fixing the spurious failures on the FreeBSD buildbot primarily. ........ r61245 | neal.norwitz | 2008-03-05 06:49:03 +0100 (Wed, 05 Mar 2008) | 1 line Tabs -> spaces ........ r61246 | neal.norwitz | 2008-03-05 06:50:20 +0100 (Wed, 05 Mar 2008) | 1 line Use -u urlfetch to run more tests ........ r61247 | neal.norwitz | 2008-03-05 06:51:20 +0100 (Wed, 05 Mar 2008) | 1 line test_smtplib sometimes reports leaks too, suppress it ........ r61248 | jeffrey.yasskin | 2008-03-05 07:19:56 +0100 (Wed, 05 Mar 2008) | 5 lines Fix test_socketserver on Windows after r61099 added several signal.alarm() calls (which don't exist on non-Unix platforms). Thanks to Trent Nelson for the report and patch. ........ r61249 | georg.brandl | 2008-03-05 08:10:35 +0100 (Wed, 05 Mar 2008) | 2 lines Fix some rst. ........ r61252 | thomas.heller | 2008-03-05 15:53:39 +0100 (Wed, 05 Mar 2008) | 2 lines News entry for yesterdays commit. ........ r61253 | thomas.heller | 2008-03-05 16:34:29 +0100 (Wed, 05 Mar 2008) | 3 lines Issue 1872: Changed the struct module typecode from 't' to '?', for compatibility with PEP3118. ........ r61254 | skip.montanaro | 2008-03-05 17:41:09 +0100 (Wed, 05 Mar 2008) | 4 lines Elaborate on the role of the altinstall target when installing multiple versions. ........ r61255 | georg.brandl | 2008-03-05 20:31:44 +0100 (Wed, 05 Mar 2008) | 2 lines #2239: PYTHONPATH delimiter is os.pathsep. ........ r61256 | raymond.hettinger | 2008-03-05 21:59:58 +0100 (Wed, 05 Mar 2008) | 1 line C implementation of itertools.permutations(). ........ r61257 | raymond.hettinger | 2008-03-05 22:04:32 +0100 (Wed, 05 Mar 2008) | 1 line Small code cleanup. ........ r61260 | martin.v.loewis | 2008-03-05 23:24:31 +0100 (Wed, 05 Mar 2008) | 2 lines cd PCbuild only after deleting all pyc files. ........ r61261 | raymond.hettinger | 2008-03-06 02:15:52 +0100 (Thu, 06 Mar 2008) | 1 line Add examples. ........ r61262 | andrew.kuchling | 2008-03-06 02:36:27 +0100 (Thu, 06 Mar 2008) | 1 line Add two items ........ r61263 | georg.brandl | 2008-03-06 07:47:18 +0100 (Thu, 06 Mar 2008) | 2 lines #1725737: ignore other VC directories other than CVS and SVN's too. ........ r61264 | martin.v.loewis | 2008-03-06 07:55:22 +0100 (Thu, 06 Mar 2008) | 4 lines Patch #2232: os.tmpfile might fail on Windows if the user has no permission to create files in the root directory. Will backport to 2.5. ........ r61269 | georg.brandl | 2008-03-06 08:19:15 +0100 (Thu, 06 Mar 2008) | 2 lines Expand on re.split behavior with captured expressions. ........ r61270 | georg.brandl | 2008-03-06 08:22:09 +0100 (Thu, 06 Mar 2008) | 2 lines Little clarification of assignments. ........ r61271 | georg.brandl | 2008-03-06 08:31:34 +0100 (Thu, 06 Mar 2008) | 2 lines Add isinstance/issubclass to tutorial. ........ r61272 | georg.brandl | 2008-03-06 08:34:52 +0100 (Thu, 06 Mar 2008) | 2 lines Add missing NEWS entry for r61263. ........ r61273 | georg.brandl | 2008-03-06 08:41:16 +0100 (Thu, 06 Mar 2008) | 2 lines #2225: return nonzero status code from py_compile if not all files could be compiled. ........ r61274 | georg.brandl | 2008-03-06 08:43:02 +0100 (Thu, 06 Mar 2008) | 2 lines #2220: handle matching failure more gracefully. ........ r61275 | georg.brandl | 2008-03-06 08:45:52 +0100 (Thu, 06 Mar 2008) | 2 lines Bug #2220: handle rlcompleter attribute match failure more gracefully. ........ r61278 | martin.v.loewis | 2008-03-06 14:49:47 +0100 (Thu, 06 Mar 2008) | 1 line Rely on x64 platform configuration when building _bsddb on AMD64. ........ r61279 | martin.v.loewis | 2008-03-06 14:50:28 +0100 (Thu, 06 Mar 2008) | 1 line Update db-4.4.20 build procedure. ........ r61285 | raymond.hettinger | 2008-03-06 21:52:01 +0100 (Thu, 06 Mar 2008) | 1 line More tests. ........ r61286 | raymond.hettinger | 2008-03-06 23:51:36 +0100 (Thu, 06 Mar 2008) | 1 line Issue 2246: itertools grouper object did not participate in GC (should be backported). ........ r61288 | raymond.hettinger | 2008-03-07 02:33:20 +0100 (Fri, 07 Mar 2008) | 1 line Tweak recipes and tests ........ r61289 | jeffrey.yasskin | 2008-03-07 07:22:15 +0100 (Fri, 07 Mar 2008) | 5 lines Progress on issue #1193577 by adding a polling .shutdown() method to SocketServers. The core of the patch was written by Pedro Werneck, but any bugs are mine. I've also rearranged the code for timeouts in order to avoid interfering with the shutdown poll. ........ r61290 | nick.coghlan | 2008-03-07 15:13:28 +0100 (Fri, 07 Mar 2008) | 1 line Speed up with statements by storing the __exit__ method on the stack instead of in a temp variable (bumps the magic number for pyc files) ........ r61298 | andrew.kuchling | 2008-03-07 22:09:23 +0100 (Fri, 07 Mar 2008) | 1 line Grammar fix ........ r61303 | georg.brandl | 2008-03-08 10:54:06 +0100 (Sat, 08 Mar 2008) | 2 lines #2253: fix continue vs. finally docs. ........ r61304 | marc-andre.lemburg | 2008-03-08 11:01:43 +0100 (Sat, 08 Mar 2008) | 3 lines Add new name for Mandrake: Mandriva. ........ r61305 | georg.brandl | 2008-03-08 11:05:24 +0100 (Sat, 08 Mar 2008) | 2 lines #1533486: fix types in refcount intro. ........ r61312 | facundo.batista | 2008-03-08 17:50:27 +0100 (Sat, 08 Mar 2008) | 5 lines Issue 1106316. post_mortem()'s parameter, traceback, is now optional: it defaults to the traceback of the exception that is currently being handled. ........ r61313 | jeffrey.yasskin | 2008-03-08 19:26:54 +0100 (Sat, 08 Mar 2008) | 2 lines Add tests for with and finally performance to pybench. ........ r61314 | jeffrey.yasskin | 2008-03-08 21:08:21 +0100 (Sat, 08 Mar 2008) | 2 lines Fix pybench for pythons < 2.6, tested back to 2.3. ........ r61317 | jeffrey.yasskin | 2008-03-08 22:35:15 +0100 (Sat, 08 Mar 2008) | 3 lines Well that was dumb. platform.python_implementation returns a function, not a string. ........ r61329 | georg.brandl | 2008-03-09 16:11:39 +0100 (Sun, 09 Mar 2008) | 2 lines #2249: document assertTrue and assertFalse. ........ r61332 | neal.norwitz | 2008-03-09 20:03:42 +0100 (Sun, 09 Mar 2008) | 4 lines Introduce a lock to fix a race condition which caused an exception in the test. Some buildbots were consistently failing (e.g., amd64). Also remove a couple of semi-colons. ........ r61344 | raymond.hettinger | 2008-03-11 01:19:07 +0100 (Tue, 11 Mar 2008) | 1 line Add recipe to docs. ........ r61350 | guido.van.rossum | 2008-03-11 22:18:06 +0100 (Tue, 11 Mar 2008) | 3 lines Fix the overflows in expandtabs(). "This time for sure!" (Exploit at request.) ........ r61351 | raymond.hettinger | 2008-03-11 22:37:46 +0100 (Tue, 11 Mar 2008) | 1 line Improve docs for itemgetter(). Show that it works with slices. ........ r61363 | georg.brandl | 2008-03-13 08:15:56 +0100 (Thu, 13 Mar 2008) | 2 lines #2265: fix example. ........ r61364 | georg.brandl | 2008-03-13 08:17:14 +0100 (Thu, 13 Mar 2008) | 2 lines #2270: fix typo. ........ r61365 | georg.brandl | 2008-03-13 08:21:41 +0100 (Thu, 13 Mar 2008) | 2 lines #1720705: add docs about import/threading interaction, wording by Nick. ........ r61366 | andrew.kuchling | 2008-03-13 12:07:35 +0100 (Thu, 13 Mar 2008) | 1 line Add class decorators ........ r61367 | raymond.hettinger | 2008-03-13 17:43:17 +0100 (Thu, 13 Mar 2008) | 1 line Add 2-to-3 support for the itertools moved to builtins or renamed. ........ r61368 | raymond.hettinger | 2008-03-13 17:43:59 +0100 (Thu, 13 Mar 2008) | 1 line Consistent tense. ........ r61369 | raymond.hettinger | 2008-03-13 20:03:51 +0100 (Thu, 13 Mar 2008) | 1 line Issue 2274: Add heapq.heappushpop(). ........ r61370 | raymond.hettinger | 2008-03-13 20:33:34 +0100 (Thu, 13 Mar 2008) | 1 line Simplify the nlargest() code using heappushpop(). ........ r61371 | brett.cannon | 2008-03-13 21:27:00 +0100 (Thu, 13 Mar 2008) | 4 lines Move test_thread over to unittest. Commits GHOP 237. Thanks Benjamin Peterson for the patch. ........ r61372 | brett.cannon | 2008-03-13 21:33:10 +0100 (Thu, 13 Mar 2008) | 4 lines Move test_tokenize to doctest. Done as GHOP 238 by Josip Dzolonga. ........ r61373 | brett.cannon | 2008-03-13 21:47:41 +0100 (Thu, 13 Mar 2008) | 4 lines Convert test_contains, test_crypt, and test_select to unittest. Patch from GHOP 294 by David Marek. ........ r61374 | brett.cannon | 2008-03-13 22:02:16 +0100 (Thu, 13 Mar 2008) | 4 lines Move test_gdbm to use unittest. Closes issue #1960. Thanks Giampaolo Rodola. ........ r61375 | brett.cannon | 2008-03-13 22:09:28 +0100 (Thu, 13 Mar 2008) | 4 lines Convert test_fcntl to unittest. Closes issue #2055. Thanks Giampaolo Rodola. ........ r61376 | raymond.hettinger | 2008-03-14 06:03:44 +0100 (Fri, 14 Mar 2008) | 1 line Leave heapreplace() unchanged. ........ r61378 | martin.v.loewis | 2008-03-14 14:56:09 +0100 (Fri, 14 Mar 2008) | 2 lines Patch #2284: add -x64 option to rt.bat. ........ r61379 | martin.v.loewis | 2008-03-14 14:57:59 +0100 (Fri, 14 Mar 2008) | 2 lines Use -x64 flag. ........ r61382 | brett.cannon | 2008-03-14 15:03:10 +0100 (Fri, 14 Mar 2008) | 2 lines Remove a bad test. ........ r61383 | mark.dickinson | 2008-03-14 15:23:37 +0100 (Fri, 14 Mar 2008) | 9 lines Issue 705836: Fix struct.pack(">f", 1e40) to behave consistently across platforms: it should now raise OverflowError on all platforms. (Previously it raised OverflowError only on non IEEE 754 platforms.) Also fix the (already existing) test for this behaviour so that it actually raises TestFailed instead of just referencing it. ........ r61387 | thomas.heller | 2008-03-14 22:06:21 +0100 (Fri, 14 Mar 2008) | 1 line Remove unneeded initializer. ........ r61388 | martin.v.loewis | 2008-03-14 22:19:28 +0100 (Fri, 14 Mar 2008) | 2 lines Run debug version, cd to PCbuild. ........ r61392 | georg.brandl | 2008-03-15 00:10:34 +0100 (Sat, 15 Mar 2008) | 2 lines Remove obsolete paragraph. #2288. ........ r61395 | georg.brandl | 2008-03-15 01:20:19 +0100 (Sat, 15 Mar 2008) | 2 lines Fix lots of broken links in the docs, found by Sphinx' external link checker. ........ r61396 | skip.montanaro | 2008-03-15 03:32:49 +0100 (Sat, 15 Mar 2008) | 1 line note that fork and forkpty raise OSError on failure ........ r61402 | skip.montanaro | 2008-03-15 17:04:45 +0100 (Sat, 15 Mar 2008) | 1 line add %f format to datetime - issue 1158 ........ r61403 | skip.montanaro | 2008-03-15 17:07:11 +0100 (Sat, 15 Mar 2008) | 2 lines . ........ ................ r61409 | christian.heimes | 2008-03-16 01:32:36 +0100 (Sun, 16 Mar 2008) | 41 lines Merged revisions 61404-61407 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61404 | raymond.hettinger | 2008-03-15 21:02:04 +0100 (Sat, 15 Mar 2008) | 17 lines Removed Exact/Inexact after discussion with Yasskin. Unlike Scheme where exactness is implemented as taints, the Python implementation associated exactness with data types. This created inheritance issues (making an exact subclass of floats would result in the subclass having both an explicit Exact registration and an inherited Inexact registration). This was a problem for the decimal module which was designed to span both exact and inexact arithmetic. There was also a question of use cases and no examples were found where ABCs for exactness could be used to improve code. One other issue was having separate tags for both the affirmative and negative cases. This is at odds with the approach taken elsewhere in the Python (i.e. we don't have an ABC both Hashable and Unhashable). ........ r61405 | raymond.hettinger | 2008-03-15 21:37:50 +0100 (Sat, 15 Mar 2008) | 1 line Zap one more use of Exact/Inexact. ........ r61406 | neal.norwitz | 2008-03-15 23:03:18 +0100 (Sat, 15 Mar 2008) | 9 lines Add a warning for code like: assert (0, 'message') An empty tuple does not create a warning. While questionable usage: assert (), 'message' should not display a warning. Tested manually. The warning message could be improved. Feel free to update it. ........ r61407 | neal.norwitz | 2008-03-15 23:36:01 +0100 (Sat, 15 Mar 2008) | 1 line Handle memory allocation failure. Found by Adam Olsen ........ ................ r61410 | mark.dickinson | 2008-03-16 03:29:03 +0100 (Sun, 16 Mar 2008) | 2 lines Fix failing test test_bool following merge from trunk. ................ r61411 | mark.dickinson | 2008-03-16 04:45:34 +0100 (Sun, 16 Mar 2008) | 4 lines Fix datetime_strptime following svnmerge from trunk; it was using the wrong format codes ('s' instead of 'u') in PyObject_CallMethod. ................ r61412 | mark.dickinson | 2008-03-16 06:05:12 +0100 (Sun, 16 Mar 2008) | 5 lines Fix doctests in test_tokenize by converting Python 2.x syntax to Python 3.0 syntax (drop leading '0' and trailing 'L' from integer literals, remove leading 'u' from unicode string literals), and adjusting expected output accordingly. ................ r61426 | christian.heimes | 2008-03-16 18:29:44 +0100 (Sun, 16 Mar 2008) | 13 lines Merged revisions 61413-61414 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61413 | raymond.hettinger | 2008-03-16 06:20:42 +0100 (Sun, 16 Mar 2008) | 1 line Update docs to reflect removal of Exact/Inexact ........ r61414 | georg.brandl | 2008-03-16 09:00:19 +0100 (Sun, 16 Mar 2008) | 2 lines #2299: typos in newtypes.rst. ........ ................ r61427 | christian.heimes | 2008-03-16 18:32:59 +0100 (Sun, 16 Mar 2008) | 1 line Clean up svnmerge properties ................ r61440 | jeffrey.yasskin | 2008-03-17 17:35:48 +0100 (Mon, 17 Mar 2008) | 2 lines Block r61438 from forward porting sinc it's a classic-classes fix. ................ r61443 | ka-ping.yee | 2008-03-17 18:34:48 +0100 (Mon, 17 Mar 2008) | 3 lines Remove the "unsafe" flag on peek() -- it is no longer used, because self._read_buf is an immutable bytes object. ................ r61445 | eric.smith | 2008-03-17 18:38:14 +0100 (Mon, 17 Mar 2008) | 1 line Blocked r61442, which is a backport of PEP 3127 features already in py3k. ................ r61446 | neal.norwitz | 2008-03-17 19:02:30 +0100 (Mon, 17 Mar 2008) | 1 line Remove __{get,set,del}slice__ dingleberries. ................ r61447 | neal.norwitz | 2008-03-17 19:03:56 +0100 (Mon, 17 Mar 2008) | 1 line Add missing parameter spotted by Jared Flatow ................ r61448 | eric.smith | 2008-03-17 19:40:10 +0100 (Mon, 17 Mar 2008) | 3 lines Renamed test_hexoct.py to test_int_literal.py, to match r61422 in the trunk. Added tests for binary literals. Removed separate tests for 32 bit platforms. ................ r61455 | eric.smith | 2008-03-17 20:49:19 +0100 (Mon, 17 Mar 2008) | 1 line Added tests for tokenize, blocked corresponding checkin from trunk. ................ r61457 | gregory.p.smith | 2008-03-17 21:16:47 +0100 (Mon, 17 Mar 2008) | 3 lines use PyBUF_LOCK instead of PyBUF_SIMPLE for bsddb data access as it'll often be using the data buffer provided without the GIL held. ................ r61459 | gregory.p.smith | 2008-03-17 21:24:09 +0100 (Mon, 17 Mar 2008) | 5 lines zlib.crc32 and zlib.adler32 now return an unsigned value as any sane person would expect. Fixes issues1202. ................ r61460 | ka-ping.yee | 2008-03-17 21:30:22 +0100 (Mon, 17 Mar 2008) | 2 lines Document the expected convention for getstate() (as explained to me by Guido). ................ r61461 | ka-ping.yee | 2008-03-17 21:35:15 +0100 (Mon, 17 Mar 2008) | 2 lines Patch from jbalogh fixes issue #2282 (misnamed seekable() method). ................ r61462 | martin.v.loewis | 2008-03-17 21:43:42 +0100 (Mon, 17 Mar 2008) | 3 lines Bug #2301: Don't try decoding the source code into the original encoding for syntax errors. ................ r61463 | gregory.p.smith | 2008-03-17 21:45:21 +0100 (Mon, 17 Mar 2008) | 2 lines mention the zlib crc32/adler32 changes ................ r61464 | neal.norwitz | 2008-03-17 21:50:44 +0100 (Mon, 17 Mar 2008) | 1 line Whoops, I missed a few more places that were using slicing from the operator module ................ r61467 | guido.van.rossum | 2008-03-17 23:56:06 +0100 (Mon, 17 Mar 2008) | 12 lines - A new pickle protocol (protocol 3) is added with explicit support for bytes. This is the default protocol. It intentionally cannot be unpickled by Python 2.x. - When a pickle written by Python 2.x contains an (8-bit) str instance, this is now decoded to a (Unicode) str instance. The encoding used to do this defaults to ASCII, but can be overridden via two new keyword arguments to the Unpickler class. Previously this would create bytes instances, which is usually wrong: str instances are often used to pickle attribute names etc., and text is more common than binary data anyway. ................ r61476 | guido.van.rossum | 2008-03-18 03:51:35 +0100 (Tue, 18 Mar 2008) | 9 lines Blocked revisions 61475 via svnmerge ........ r61475 | guido.van.rossum | 2008-03-17 21:49:46 -0500 (Mon, 17 Mar 2008) | 3 lines - Issue #2371: Add a Py3k warning when catching an exception that doesn't derive from BaseException. ........ ................ r61482 | guido.van.rossum | 2008-03-18 05:05:39 +0100 (Tue, 18 Mar 2008) | 10 lines Blocked revisions 61478 via svnmerge ........ r61478 | guido.van.rossum | 2008-03-17 22:15:05 -0500 (Mon, 17 Mar 2008) | 4 lines Clean up the Py3k warnings for non-BaseException-subclasses a bit. We now don't warn for some corner cases that deserve a warning, rather than warning double or incorrectly for some other corner cases. ........ ................ r61487 | guido.van.rossum | 2008-03-18 05:27:57 +0100 (Tue, 18 Mar 2008) | 9 lines Blocked revisions 61486 via svnmerge ........ r61486 | guido.van.rossum | 2008-03-17 23:26:48 -0500 (Mon, 17 Mar 2008) | 3 lines Issue #2341: Add a Py3k warning when raising an exception that doesn't derive from BaseException. ........ ................ r61490 | guido.van.rossum | 2008-03-18 05:44:10 +0100 (Tue, 18 Mar 2008) | 9 lines Blocked revisions 61489 via svnmerge ........ r61489 | guido.van.rossum | 2008-03-17 23:42:22 -0500 (Mon, 17 Mar 2008) | 3 lines - Issue 2379: Raise a Py3K warning for __getitem__ or __getslice__ on exception instances. ........ ................ r61493 | guido.van.rossum | 2008-03-18 05:46:49 +0100 (Tue, 18 Mar 2008) | 8 lines Blocked revisions 61492 via svnmerge ........ r61492 | neal.norwitz | 2008-03-17 23:46:00 -0500 (Mon, 17 Mar 2008) | 1 line Issue 2332: add new attribute names for instance method objects ........ ................ r61494 | ka-ping.yee | 2008-03-18 05:51:32 +0100 (Tue, 18 Mar 2008) | 8 lines Make TextIOWrapper's seek/tell work properly with stateful decoders; document and rename things to make seek/tell workings a little clearer. Add a weird decoder for testing TextIOWrapper's seek/tell methods. Document the getstate/setstate protocol conventions for IncrementalDecoders. ................ r61508 | ka-ping.yee | 2008-03-18 08:01:49 +0100 (Tue, 18 Mar 2008) | 7 lines In TextIOWrapper: - Switch from consuming _decoded_text to advancing an offset into it. - Fix readline() interaction with seek/tell. - Fix readline() handling of 'limit' argument. Add tests for seek/tell after readline(). ................ r61519 | christian.heimes | 2008-03-18 15:08:26 +0100 (Tue, 18 Mar 2008) | 2 lines block r61491 Finish backporting new buffer API to Python 2.6. Left to do: memoryview object and structmodule. But, these need to be finished in Python 3.0 first. No objects support the new buffer API in Python 2.6 as of yet, and except for the memoryview object, I don't think they will. ................ r61521 | christian.heimes | 2008-03-18 16:15:01 +0100 (Tue, 18 Mar 2008) | 177 lines Merged revisions 61431,61433-61436,61439,61444,61449-61450,61453,61458,61465,61468,61471-61474,61480,61483-61484,61488,61495-61496,61498,61503-61504,61507,61509-61510,61515-61518 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61431 | vinay.sajip | 2008-03-16 22:35:58 +0100 (So, 16 M??r 2008) | 1 line Clarified documentation on use of shutdown(). ........ r61433 | mark.summerfield | 2008-03-17 09:28:15 +0100 (Mo, 17 M??r 2008) | 5 lines Added a footnote to each pointing out that for XML output if an encoding string is given it should conform to the appropriate XML standards---for example, "UTF-8" is okay, but "UTF8" is not. ........ r61434 | eric.smith | 2008-03-17 12:01:01 +0100 (Mo, 17 M??r 2008) | 7 lines Issue 2264: empty float presentation type needs to have at least one digit past the decimal point. Added "Z" format_char to PyOS_ascii_formatd to support empty float presentation type. Renamed buf_size in PyOS_ascii_formatd to more accurately reflect it's meaning. Modified format.__float__ to use the new "Z" format as the default. Added test cases. ........ r61435 | eric.smith | 2008-03-17 13:14:29 +0100 (Mo, 17 M??r 2008) | 2 lines Reformated lines > 79 chars. Deleted unused macro ISXDIGIT. ........ r61436 | jeffrey.yasskin | 2008-03-17 15:40:53 +0100 (Mo, 17 M??r 2008) | 13 lines Allow Gnu gcc's to build python on OSX by removing -Wno-long-double, -no-cpp-precomp, and -mno-fused-madd from configure. * r22183 added -no-cpp-precomp, which http://gcc.gnu.org/ml/gcc/2005-12/msg00368.html claims hasn't been needed since gcc-3.1. * r25607 added -Wno-long-double to avoid a warning in Include/objimpl.h (issue 525481). The long double is still there, but OSX 10.4's gcc no longer warns about it. * r33666 fixed issue 775892 on OSX 10.3 by adding -mno-fused-madd, which changed the sign of some float 0s. Tim Peters said it wasn't a real issue anyway, and it no longer causes test failures. Fixes issue #1779871. ........ r61439 | martin.v.loewis | 2008-03-17 17:31:57 +0100 (Mo, 17 M??r 2008) | 2 lines Add Trent Nelson. ........ r61444 | travis.oliphant | 2008-03-17 18:36:12 +0100 (Mo, 17 M??r 2008) | 1 line Add necessary headers to back-port new buffer protocol to Python 2.6 ........ r61449 | gregory.p.smith | 2008-03-17 19:48:05 +0100 (Mo, 17 M??r 2008) | 8 lines Force zlib.crc32 and zlib.adler32 to return a signed integer on all platforms regardless of the native sizeof(long) used in the integer object. This somewhat odd behavior of returning a signed is maintained in 2.x for compatibility reasons of always returning an integer rather than a long object. Fixes Issue1202 for Python 2.6 ........ r61450 | neal.norwitz | 2008-03-17 20:02:45 +0100 (Mo, 17 M??r 2008) | 3 lines Use a buffer large enough to ensure we don't overrun, even if the value is outside the range we expect. ........ r61453 | steven.bethard | 2008-03-17 20:33:11 +0100 (Mo, 17 M??r 2008) | 1 line Document unicode.isnumeric() and unicode.isdecimal() (issue2326) ........ r61458 | neal.norwitz | 2008-03-17 21:22:43 +0100 (Mo, 17 M??r 2008) | 5 lines Issue 2321: reduce memory usage (increase the memory that is returned to the system) by using pymalloc for the data of unicode objects. Will backport. ........ r61465 | martin.v.loewis | 2008-03-17 22:55:30 +0100 (Mo, 17 M??r 2008) | 2 lines Add David Wolever. ........ r61468 | gregory.p.smith | 2008-03-18 01:20:01 +0100 (Di, 18 M??r 2008) | 3 lines Fix the IOError message text when opening a file with an invalid filename. Error reported by Ilan Schnell. ........ r61471 | brett.cannon | 2008-03-18 02:00:07 +0100 (Di, 18 M??r 2008) | 2 lines Convert test_strftime, test_getargs, and test_pep247 to use unittest. ........ r61472 | jeffrey.yasskin | 2008-03-18 02:09:59 +0100 (Di, 18 M??r 2008) | 2 lines Fix build on platforms that don't have intptr_t. Patch by Joseph Armbruster. ........ r61473 | brett.cannon | 2008-03-18 02:50:25 +0100 (Di, 18 M??r 2008) | 2 lines Convert test_dummy_threading and test_dbm to unittest. ........ r61474 | brett.cannon | 2008-03-18 02:58:56 +0100 (Di, 18 M??r 2008) | 2 lines Move test_extcall to doctest. ........ r61480 | brett.cannon | 2008-03-18 04:46:22 +0100 (Di, 18 M??r 2008) | 2 lines test_errno was a no-op test; now it actually tests things and uses unittest. ........ r61483 | brett.cannon | 2008-03-18 05:09:00 +0100 (Di, 18 M??r 2008) | 3 lines Remove our implementation of memmove() and strerror(); both are in the C89 standard library. ........ r61484 | brett.cannon | 2008-03-18 05:16:06 +0100 (Di, 18 M??r 2008) | 2 lines The output directory for tests that compare against stdout is now gone! ........ r61488 | jeffrey.yasskin | 2008-03-18 05:29:35 +0100 (Di, 18 M??r 2008) | 2 lines Block the "socket.ssl() is deprecated" warning from test_socket_ssl. ........ r61495 | jeffrey.yasskin | 2008-03-18 05:56:06 +0100 (Di, 18 M??r 2008) | 4 lines Speed test_thread up from 51.328s to 0.081s by reducing its sleep times. We still sleep at all to make it likely that all threads are active at the same time. ........ r61496 | jeffrey.yasskin | 2008-03-18 06:12:41 +0100 (Di, 18 M??r 2008) | 4 lines Speed up test_dict by about 10x by only checking selected dict literal sizes, instead of every integer from 0 to 400. Exhaustive testing wastes time without providing enough more assurance that the code is correct. ........ r61498 | neal.norwitz | 2008-03-18 06:20:29 +0100 (Di, 18 M??r 2008) | 1 line Try increasing the timeout to reduce the flakiness of this test. ........ r61503 | brett.cannon | 2008-03-18 06:43:04 +0100 (Di, 18 M??r 2008) | 2 lines Improve the error message for a test that failed on the S-390 Debian buildbot. ........ r61504 | jeffrey.yasskin | 2008-03-18 06:45:40 +0100 (Di, 18 M??r 2008) | 3 lines Add a -S/--slow flag to regrtest to have it print the 10 slowest tests with their times. ........ r61507 | neal.norwitz | 2008-03-18 07:03:46 +0100 (Di, 18 M??r 2008) | 1 line Add some info to the failure messages ........ r61509 | trent.nelson | 2008-03-18 08:02:12 +0100 (Di, 18 M??r 2008) | 1 line Issue 2286: bump up the stack size of the 64-bit debug python_d.exe to 2100000. The default value of 200000 causes a stack overflow at 1965 iterations of r_object() in marshal.c, 35 iterations before the 2000 limit enforced by MAX_MARSHAL_STACK_DEPTH. ........ r61510 | trent.nelson | 2008-03-18 08:32:47 +0100 (Di, 18 M??r 2008) | 5 lines The behaviour of winsound.Beep() seems to differ between different versions of Windows when there's either: a) no sound card entirely b) legacy beep driver has been disabled c) the legacy beep driver has been uninstalled Sometimes RuntimeErrors are raised, sometimes they're not. If _have_soundcard() returns False, don't expect winsound.Beep() to raise a RuntimeError, as this clearly isn't the case, as demonstrated by the various Win32 XP buildbots. ........ r61515 | martin.v.loewis | 2008-03-18 13:20:15 +0100 (Di, 18 M??r 2008) | 2 lines norwitz-amd64 (gentoo) has EREMOTEIO. ........ r61516 | martin.v.loewis | 2008-03-18 13:45:37 +0100 (Di, 18 M??r 2008) | 2 lines Add more Linux error codes. ........ r61517 | martin.v.loewis | 2008-03-18 14:05:03 +0100 (Di, 18 M??r 2008) | 2 lines Add WSA errors. ........ r61518 | martin.v.loewis | 2008-03-18 14:16:05 +0100 (Di, 18 M??r 2008) | 2 lines Note that the stderr output of the test is intentional. ........ ................ r61522 | eric.smith | 2008-03-18 16:35:27 +0100 (Tue, 18 Mar 2008) | 1 line Added test_print.py. I want to have a test suite when the print function is backported to 2.6 as a future import. ................ r61530 | neal.norwitz | 2008-03-18 18:44:29 +0100 (Tue, 18 Mar 2008) | 6 lines Fix a bunch of problems from merges. * Ensure local vars are always initialized * Re-enable use of the start flag * Pass the right parameters to runtest * Remove generation of output files, since those should all be gone now ................ r61531 | christian.heimes | 2008-03-18 18:57:55 +0100 (Tue, 18 Mar 2008) | 4 lines svnmerge.py block -r61529 Add py3k warnings for object, type, cell and dict comparisons. This should resolve issue2342 and partly resolve issue2373. ................ r61533 | neal.norwitz | 2008-03-18 18:58:37 +0100 (Tue, 18 Mar 2008) | 1 line Remove unnused vars that I missed in previous removal of output file generation. ................ r61535 | christian.heimes | 2008-03-18 19:26:33 +0100 (Tue, 18 Mar 2008) | 55 lines Merged revisions 61520,61523-61528,61532 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61520 | thomas.heller | 2008-03-18 16:03:17 +0100 (Di, 18 M??r 2008) | 5 lines Include on Solaris, see issue #1506. It would probably be better to have a configure test for that, but this is outside of my configure expertise. ........ r61523 | brett.cannon | 2008-03-18 16:35:58 +0100 (Di, 18 M??r 2008) | 5 lines Remove all traces of HAVE_STRERROR. The removal of strerror.c led to the function check being removed from configure.in. ........ r61524 | brett.cannon | 2008-03-18 16:52:00 +0100 (Di, 18 M??r 2008) | 2 lines Fix test_errno to only check for error numbers that are defined by Standard C. ........ r61525 | steven.bethard | 2008-03-18 17:00:19 +0100 (Di, 18 M??r 2008) | 1 line Use test_support.unlink instead of os.unlink in tearDown(). (Seems to fix an occasional failure in Windows Vista.) ........ r61526 | brett.cannon | 2008-03-18 17:47:51 +0100 (Di, 18 M??r 2008) | 3 lines Cast the arguments to PyString_AsStringAndSize() to silence compiler warnings on OS X. ........ r61527 | sean.reifschneider | 2008-03-18 18:24:12 +0100 (Di, 18 M??r 2008) | 3 lines Issue 1577: shutil.move() where destination is a directory was doing a copy, now it is doing a os.rename() if it's on the same file-system. ........ r61528 | brett.cannon | 2008-03-18 18:25:13 +0100 (Di, 18 M??r 2008) | 12 lines Add Tools/scripts/patchcheck.py. Invoked from ``make check``, the script does some verification: - Runs reindent.py on all .py files. - Checks if any changes in Doc exist. - Whether Misc/ACKS was changed. - Whether Misc/NEWS was changed. The hope is that ``make check`` can become a command anybody can run to get reminders about what all the requisite steps needed to create a proper patch/checkin. ........ r61532 | neal.norwitz | 2008-03-18 18:58:02 +0100 (Di, 18 M??r 2008) | 1 line Get regrtest working when re-running tests ........ ................ r61553 | neal.norwitz | 2008-03-18 20:52:05 +0100 (Tue, 18 Mar 2008) | 2 lines Revert r61508: it caused test_mailbox to fail on all platforms. ................ r61557 | thomas.wouters | 2008-03-18 21:13:50 +0100 (Tue, 18 Mar 2008) | 4 lines Add missing UNPACK_EX opcode. ................ r61558 | thomas.wouters | 2008-03-18 21:19:54 +0100 (Tue, 18 Mar 2008) | 4 lines Fix 're' to work on bytes. It could do with a few more tests, though. ................ r61561 | neal.norwitz | 2008-03-18 21:47:14 +0100 (Tue, 18 Mar 2008) | 5 lines Get this test to work (it was skipped previously): * Remove warnings and import the proper modules * Use bytes appropriately * Test the proper sha* objects on hashlib ................ r61562 | neal.norwitz | 2008-03-18 21:58:39 +0100 (Tue, 18 Mar 2008) | 1 line Get this test to pass (UserList/UserDict no longer exist and caused a skip). ................ r61566 | david.wolever | 2008-03-18 22:40:45 +0100 (Tue, 18 Mar 2008) | 3 lines Blocked a rev in which I added a warning. ................ r61567 | brett.cannon | 2008-03-18 22:45:57 +0100 (Tue, 18 Mar 2008) | 2 lines Convert the input from stdout to text. ................ r61568 | christian.heimes | 2008-03-18 22:50:42 +0100 (Tue, 18 Mar 2008) | 1 line svnmerge.py block -r61564 ................ r61572 | brett.cannon | 2008-03-18 23:34:31 +0100 (Tue, 18 Mar 2008) | 2 lines Block revision 61570. ................ r61573 | trent.nelson | 2008-03-18 23:41:35 +0100 (Tue, 18 Mar 2008) | 8 lines - Issue #719888: Updated tokenize to use a bytes API. generate_tokens has been renamed tokenize and now works with bytes rather than strings. A new detect_encoding function has been added for determining source file encoding according to PEP-0263. Token sequences returned by tokenize always start with an ENCODING token which specifies the encoding used to decode the file. This token is used to encode the output of untokenize back to bytes. Credit goes to Michael "I'm-going-to-name-my-first-child-unittest" Foord from Resolver Systems for this work. ................ r61578 | eric.smith | 2008-03-19 00:48:28 +0100 (Wed, 19 Mar 2008) | 3 lines Blocked 61577, implementation of print function. Added myself to ACKS. Added some more print tests, and made the test file mostly compatible with 2.6. ................ r61579 | trent.nelson | 2008-03-19 01:41:27 +0100 (Wed, 19 Mar 2008) | 1 line Add the -n option back to getopt(); it was lost in r61521. ................ r61588 | david.wolever | 2008-03-19 03:38:07 +0100 (Wed, 19 Mar 2008) | 3 lines Blocked revision which added zip, filter, map to future_builtins. ................ r61592 | eric.smith | 2008-03-19 04:17:57 +0100 (Wed, 19 Mar 2008) | 1 line Blocked -r61590 -r61585: tests from __future__ print_function. ................ r61600 | martin.v.loewis | 2008-03-19 06:04:44 +0100 (Wed, 19 Mar 2008) | 14 lines Merged revisions 61596-61597 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61596 | martin.v.loewis | 2008-03-18 23:43:46 -0500 (Di, 18 M??r 2008) | 2 lines Import lib2to3. ........ r61597 | martin.v.loewis | 2008-03-18 23:58:04 -0500 (Di, 18 M??r 2008) | 3 lines Initialized merge tracking via "svnmerge" with revisions "1-61595" from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ ................ r61603 | martin.v.loewis | 2008-03-19 06:26:18 +0100 (Wed, 19 Mar 2008) | 24 lines Merged revisions 61602 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ................ r61602 | martin.v.loewis | 2008-03-19 00:22:42 -0500 (Mi, 19 M??r 2008) | 17 lines Merged revisions 61598-61599,61601 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r61598 | david.wolever | 2008-03-18 23:58:33 -0500 (Di, 18 M??r 2008) | 1 line Added fixer for zip, and refactored a bit of code in the process. Closing #2171. ........ r61599 | david.wolever | 2008-03-19 00:04:26 -0500 (Mi, 19 M??r 2008) | 3 lines Removed a bunch of duplicate code -- it's in util now. ........ r61601 | martin.v.loewis | 2008-03-19 00:21:12 -0500 (Mi, 19 M??r 2008) | 2 lines Fix whitespace. ........ ................ ................ r61604 | martin.v.loewis | 2008-03-19 06:33:36 +0100 (Wed, 19 Mar 2008) | 2 lines Run 2to3 on this library. ................ r61607 | trent.nelson | 2008-03-19 07:45:48 +0100 (Wed, 19 Mar 2008) | 4 lines Issue2297: Fix a stack overflow in Windows caused by -v and -vv. When python is invoked with -v or -vv under Windows, the process of importing the codec for sys.stderr causes a message to be written to stderr, which in turn causes the codec to be recursively imported. Sometimes the stack overflow exception is swallowed, other times it is not. The bug depends on the particular locale settings of the Windows machine. Kudos to Douglas Greiman for reporting the issue and providing a patch and test case. ................ r61624 | barry.warsaw | 2008-03-19 15:25:51 +0100 (Wed, 19 Mar 2008) | 2 lines Fix a WTF noticed by Jerry Seutter. ................ r61643 | christian.heimes | 2008-03-19 22:50:51 +0100 (Wed, 19 Mar 2008) | 160 lines Merged revisions 61538-61540,61556,61559-61560,61563,61565,61571,61575-61576,61580-61582,61586,61591,61593,61595,61605-61606,61613-61616,61618,61621-61623,61625,61627,61631-61634 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61538 | steven.bethard | 2008-03-18 20:03:50 +0100 (Di, 18 M??r 2008) | 1 line cell_compare needs to return -2 instead of NULL. ........ r61539 | steven.bethard | 2008-03-18 20:04:32 +0100 (Di, 18 M??r 2008) | 1 line _have_soundcard() is a bad check for winsound.Beep, since you can have a soundcard but have the beep driver disabled. This revision basically disables the beep tests by wrapping them in a try/except. The Right Way To Do It is to come up with a _have_enabled_beep_driver() and use that. ........ r61540 | gregory.p.smith | 2008-03-18 20:05:32 +0100 (Di, 18 M??r 2008) | 8 lines Fix chown on 64-bit linux. It needed to take a long (64-bit on 64bit linux) as uid and gid input to accept values >=2**31 as valid while still accepting negative numbers to pass -1 to chown for "no change". Fixes issue1747858. This should be backported to release25-maint. ........ r61556 | steven.bethard | 2008-03-18 20:59:14 +0100 (Di, 18 M??r 2008) | 1 line Fix test_atexit so that it still passes when -3 is supplied. (It was catching the warning messages on stdio from using the reload() function.) ........ r61559 | neal.norwitz | 2008-03-18 21:30:38 +0100 (Di, 18 M??r 2008) | 1 line Import the test properly. This is especially important for py3k. ........ r61560 | gregory.p.smith | 2008-03-18 21:40:01 +0100 (Di, 18 M??r 2008) | 2 lines news entry for the chown fix ........ r61563 | brett.cannon | 2008-03-18 22:12:42 +0100 (Di, 18 M??r 2008) | 2 lines Ignore BIG5HKSCS-2004.TXT which is downloaded as part of a test. ........ r61565 | steven.bethard | 2008-03-18 22:30:13 +0100 (Di, 18 M??r 2008) | 1 line Have regrtest skip test_py3kwarn when the -3 flag is missing. ........ r61571 | gregory.p.smith | 2008-03-18 23:27:41 +0100 (Di, 18 M??r 2008) | 4 lines Add a test to make sure zlib.crc32 and binascii.crc32 return the same thing. Fix a buglet in binascii.crc32, the second optional argument could previously have a signedness mismatch with the C variable its going into. ........ r61575 | raymond.hettinger | 2008-03-19 00:22:29 +0100 (Mi, 19 M??r 2008) | 1 line Speed-up isinstance() for one easy case. ........ r61576 | raymond.hettinger | 2008-03-19 00:33:08 +0100 (Mi, 19 M??r 2008) | 1 line Issue: 2354: Add 3K warning for the cmp argument to list.sort() and sorted(). ........ r61580 | andrew.kuchling | 2008-03-19 02:05:35 +0100 (Mi, 19 M??r 2008) | 1 line Add Jeff Rush ........ r61581 | gregory.p.smith | 2008-03-19 02:38:35 +0100 (Mi, 19 M??r 2008) | 3 lines Mention that crc32 and adler32 are available in a different module (zlib). Some people look for them in hashlib. ........ r61582 | gregory.p.smith | 2008-03-19 02:46:10 +0100 (Mi, 19 M??r 2008) | 3 lines Use zlib's crc32 routine instead of binascii when available. zlib's is faster when compiled properly optimized and about the same speed otherwise. ........ r61586 | david.wolever | 2008-03-19 03:26:57 +0100 (Mi, 19 M??r 2008) | 1 line Added my name to ACKS ........ r61591 | gregory.p.smith | 2008-03-19 04:14:41 +0100 (Mi, 19 M??r 2008) | 5 lines Fix the struct module DeprecationWarnings that zipfile was triggering by removing all use of signed struct values. test_zipfile and test_zipfile64 pass. no more warnings. ........ r61593 | raymond.hettinger | 2008-03-19 04:56:59 +0100 (Mi, 19 M??r 2008) | 1 line Fix compiler warning. ........ r61595 | martin.v.loewis | 2008-03-19 05:39:13 +0100 (Mi, 19 M??r 2008) | 2 lines Issue #2400: Allow relative imports to "import *". ........ r61605 | martin.v.loewis | 2008-03-19 07:00:28 +0100 (Mi, 19 M??r 2008) | 2 lines Import relimport using a relative import. ........ r61606 | trent.nelson | 2008-03-19 07:28:24 +0100 (Mi, 19 M??r 2008) | 1 line Issue2290: Support x64 Windows builds that live in pcbuild/amd64. Without it, sysutils._python_build() returns the wrong directory, which causes the test_get_config_h_filename method in Lib/distutils/tests/test_sysconfig.py to fail. ........ r61613 | trent.nelson | 2008-03-19 08:45:19 +0100 (Mi, 19 M??r 2008) | 3 lines Refine the Visual Studio 2008 build solution in order to improve how we deal with external components, as well as fixing outstanding issues with Windows x64 build support. Introduce two new .vcproj files, _bsddb44.vcproj and sqlite3.vcproj, which replace the previous pre-link event scripts for _bsddb and _sqlite3 respectively. The new project files inherit from our property files as if they were any other Python module. This has numerous benefits. First, the components get built with exactly the same compiler flags and settings as the rest of Python. Second, it makes it much easier to debug problems in the external components when they're part of the build system. Third, they'll benefit from profile guided optimisation in the release builds, just like the rest of Python core. I've also introduced a slightly new pattern for managing externals in subversion. New components get checked in as -.x, where matches the exact vendor version string. After the initial import of the external component, the .x is tagged as .0 (i.e. tcl-8.4.18.x -> tcl-8.4.18.0). Some components may not need any tweaking, whereas there are others that might (tcl/tk fall into this bucket). In that case, the relevant modifications are made to the .x branch, which will be subsequently tagged as .1 (and then n+1 going forward) when they build successfully and all tests pass. Buildbots will be converted to rely on these explicit tags only, which makes it easy for us to switch them over to a new version as and when required. (Simple change to external(-amd64).bat: if we've bumped tcl to 8.4.18.1, change the .bat to rmdir 8.4.18.0 if it exists and check out a new .1 copy.) ........ r61614 | trent.nelson | 2008-03-19 08:56:39 +0100 (Mi, 19 M??r 2008) | 1 line Remove extraneous apostrophe and semi-colon from AdditionalIncludeDirectories. ........ r61615 | georg.brandl | 2008-03-19 08:56:40 +0100 (Mi, 19 M??r 2008) | 2 lines Remove footnote from versionchanged as it upsets LaTeX. ........ r61616 | georg.brandl | 2008-03-19 08:57:57 +0100 (Mi, 19 M??r 2008) | 2 lines Another one. ........ r61618 | trent.nelson | 2008-03-19 09:06:03 +0100 (Mi, 19 M??r 2008) | 1 line Fix the tcl-8.4.18.1 path and make sure we cd into the right directory when building tcl/tk. ........ r61621 | trent.nelson | 2008-03-19 10:23:08 +0100 (Mi, 19 M??r 2008) | 1 line Lets have another try at getting the Windows buildbots in a consistent state before rebuilding using the new process. ........ r61622 | eric.smith | 2008-03-19 13:09:55 +0100 (Mi, 19 M??r 2008) | 2 lines Use test.test_support.captured_stdout instead of a custom contextmanager. Thanks Nick Coghlan. ........ r61623 | eric.smith | 2008-03-19 13:15:10 +0100 (Mi, 19 M??r 2008) | 1 line Trivial typo. ........ r61625 | thomas.heller | 2008-03-19 17:10:57 +0100 (Mi, 19 M??r 2008) | 2 lines Checkout sqlite-source when it is not there. ........ r61627 | brett.cannon | 2008-03-19 17:50:13 +0100 (Mi, 19 M??r 2008) | 5 lines test_nis would fail if test.test_support.verbose was true but NIS was not set up on the machine. Closes issue2411. Thanks Michael Bishop. ........ r61631 | brett.cannon | 2008-03-19 18:37:43 +0100 (Mi, 19 M??r 2008) | 2 lines Use sys.py3kwarning instead of trying to trigger a Py3k-related warning. ........ r61632 | raymond.hettinger | 2008-03-19 18:45:19 +0100 (Mi, 19 M??r 2008) | 1 line Issue 2354: Fix-up compare warning. Patch contributed by Jeff Balogh. ........ r61633 | raymond.hettinger | 2008-03-19 18:58:59 +0100 (Mi, 19 M??r 2008) | 1 line The filter() function does support a None argument in Py3.0. ........ r61634 | raymond.hettinger | 2008-03-19 19:01:58 +0100 (Mi, 19 M??r 2008) | 1 line Remove itertools warnings I had added before the 2-to-3 handled the migration. ........ ................ r61648 | christian.heimes | 2008-03-19 23:42:51 +0100 (Wed, 19 Mar 2008) | 1 line Create a signed CRC32 hash. I'm not absolutely sure it's correct. At least it fixes the unit tests and doesn't create a different hash than Python 2.x ................ r61653 | amaury.forgeotdarc | 2008-03-20 00:15:45 +0100 (Thu, 20 Mar 2008) | 2 lines These files should have been merged in r61643 ................ r61655 | amaury.forgeotdarc | 2008-03-20 01:35:03 +0100 (Thu, 20 Mar 2008) | 3 lines - Revert a change that should have been blocked: py3k has no -3 flag! - also remove a bogus debug print ................ r61659 | amaury.forgeotdarc | 2008-03-20 02:02:48 +0100 (Thu, 20 Mar 2008) | 2 lines Another 2.6-ism in test file ................ r61660 | amaury.forgeotdarc | 2008-03-20 02:10:45 +0100 (Thu, 20 Mar 2008) | 3 lines Another missing file after merge from trunk. test_import now passes ................ r61661 | trent.nelson | 2008-03-20 02:18:35 +0100 (Thu, 20 Mar 2008) | 13 lines Merged revisions 61639 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61639 | trent.nelson | 2008-03-19 16:11:55 -0500 (Wed, 19 Mar 2008) | 6 lines Fix the x64 Windows build environment used by the buildbots. %VS90COMNTOOLS%\vsvars32.bat is fine for 32-bit builds, but doesn't work for x64 builds, regardless of /MACHINE:AMD64 and /USECL:MS_OPTERON flags passed to cl.exe. Launch the x86_64 cross compilation environment via '%VS90COMNTOOLS%\..\..\VC\vcvarsall.bat x86_amd64'. I don't have access to any systems *without* Visual Studio 2008 Professional installed (i.e. just Express Edition), so I can't test if x64 compilation works w/ VS Express at the moment. Additionally, force a clean in our build.bat files before building, just whilst we're going through these build system updates. And finally, add in the missing MACHINE=AMD64 option to our Tcl/Tk x64 build. ........ ................ r61662 | trent.nelson | 2008-03-20 02:20:22 +0100 (Thu, 20 Mar 2008) | 1 line Bring over external-commit.bat manually, wasn't picked up via svnmerge. ................ r61666 | gregory.p.smith | 2008-03-20 07:20:09 +0100 (Thu, 20 Mar 2008) | 3 lines crc32 always returns unsigned. cleanup the code a bit and revert r61648 with the proper fix. ................ r61668 | ka-ping.yee | 2008-03-20 11:34:07 +0100 (Thu, 20 Mar 2008) | 10 lines This is r61508 plus additional fixes to the handling of 'limit' in TextIOWrapper.readline(). All tests now pass for me (except for expected skips on darwin: bsddb, bsddb3, cProfile, codecmaps_*, curses, gdbm, largefile, locale, normalization, ossaudiodev, pep277, socketserver, startfile, timeout, urllib2net, urllibnet, winreg, winsound, xmlrpc_net, zipfile64, and the -u largefile part of test_io). ................ r61669 | ka-ping.yee | 2008-03-20 11:37:32 +0100 (Thu, 20 Mar 2008) | 2 lines Clean up the TextIOWrapper code; pick better names; improve documentation. ................ r61670 | christian.heimes | 2008-03-20 11:49:03 +0100 (Thu, 20 Mar 2008) | 73 lines Merged revisions 61644,61646-61647,61649-61652,61656-61658,61663,61665,61667 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61644 | trent.nelson | 2008-03-19 22:51:16 +0100 (Mi, 19 M??r 2008) | 1 line Force a clean of the tcltk/tcltk64 directories now that we've completely changed the tcl/tk build environment. ........ r61646 | gregory.p.smith | 2008-03-19 23:23:51 +0100 (Mi, 19 M??r 2008) | 2 lines Improve the error message when the CRCs don't match. ........ r61647 | trent.nelson | 2008-03-19 23:41:10 +0100 (Mi, 19 M??r 2008) | 1 line Comment out tcltk/tcltk64 removal. ........ r61649 | raymond.hettinger | 2008-03-19 23:47:48 +0100 (Mi, 19 M??r 2008) | 1 line Remove unnecessary traceback save/restore pair. ........ r61650 | trent.nelson | 2008-03-19 23:51:42 +0100 (Mi, 19 M??r 2008) | 1 line Bump the SIGALM delay from 3 seconds to 20 seconds, mainly in an effort to see if it fixes the alarm failures in this test experienced by some of the buildbots. ........ r61651 | brett.cannon | 2008-03-20 00:01:17 +0100 (Do, 20 M??r 2008) | 5 lines Make sure that the warnings filter is not reset or changed beyond the current running test file. Closes issue2407. Thanks Jerry Seutter. ........ r61652 | gregory.p.smith | 2008-03-20 00:03:25 +0100 (Do, 20 M??r 2008) | 10 lines Prevent ioctl op codes from being sign extended from int to unsigned long when used on platforms that actually define ioctl as taking an unsigned long. (the BSDs and OS X / Darwin) Adds a unittest for fcntl.ioctl that tests what happens with both positive and negative numbers. This was done because of issue1471 but I'm not able to reproduce -that- problem in the first place on Linux 32bit or 64bit or OS X 10.4 & 10.5 32bit or 64 bit. ........ r61656 | sean.reifschneider | 2008-03-20 01:46:50 +0100 (Do, 20 M??r 2008) | 2 lines Issue #2143: Fix embedded readline() hang on SSL socket EOF. ........ r61657 | sean.reifschneider | 2008-03-20 01:50:07 +0100 (Do, 20 M??r 2008) | 2 lines Forgot to add NEWS item about smtplib SSL readline hang fix. ........ r61658 | trent.nelson | 2008-03-20 01:58:44 +0100 (Do, 20 M??r 2008) | 1 line Revert r61650; the intent of this commit was to try and address alarm failures on some of the build slaves. As Neal points out, it's called after test_main(), so it's not going to factor into the test when run via regrtest.py (and removes the original functionality that Jeffrey wanted that would kill the test if it took longer than 3 seconds to run when executing it directly during development). ........ r61663 | sean.reifschneider | 2008-03-20 04:20:48 +0100 (Do, 20 M??r 2008) | 2 lines Issue 2188: Documentation hint about disabling proxy detection. ........ r61665 | gregory.p.smith | 2008-03-20 06:41:53 +0100 (Do, 20 M??r 2008) | 7 lines Attempt to fix the Solaris Sparc 10 buildbot. It was failing with an invalid argument error on ioctl. This was caused by the added test_fcntl ioctl test that hard coded 0 as the fd to use. Without a terminal, this fails on solaris. (it passed from the command line on sol 10, both 32 and 64 bit) Also, test_ioctl exists so I moved the test into there where it belongs. ........ r61667 | georg.brandl | 2008-03-20 08:25:55 +0100 (Do, 20 M??r 2008) | 2 lines #2383: remove obsolete XXX comment in stat.py. ........ ................ r61671 | ka-ping.yee | 2008-03-20 11:51:27 +0100 (Thu, 20 Mar 2008) | 2 lines Added a longish test case to stress seek/tell with a stateful decoder. ................ r61680 | amaury.forgeotdarc | 2008-03-20 22:22:04 +0100 (Thu, 20 Mar 2008) | 3 lines #2435: missing file in pybench svnmerge seems to forget every added file. ................ r61682 | eric.smith | 2008-03-21 00:02:08 +0100 (Fri, 21 Mar 2008) | 2 lines Add __future__ import for print_function. It's a no-op in 3.0, but it needs to not be a syntax error. Closes issue 2436. ................ r61685 | christian.heimes | 2008-03-21 02:05:49 +0100 (Fri, 21 Mar 2008) | 1 line Disabled some unused functions to silence compiler warnings ................ r61686 | christian.heimes | 2008-03-21 02:11:52 +0100 (Fri, 21 Mar 2008) | 43 lines Merged revisions 61672,61674,61676-61678,61681,61683-61684 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61672 | brett.cannon | 2008-03-20 17:13:48 +0100 (Do, 20 M??r 2008) | 2 lines Gave Jerry Seutter svn access for general Python development. ........ r61674 | marc-andre.lemburg | 2008-03-20 18:31:36 +0100 (Do, 20 M??r 2008) | 7 lines If Mark Hammonds win32 tools are not available, try to use the _winreg module and sys.getwindowsversion() to get at the Windows version info. For the machine and processor uname() values, use the environment variables for these on Windows XP and later. ........ r61676 | marc-andre.lemburg | 2008-03-20 18:55:31 +0100 (Do, 20 M??r 2008) | 5 lines Add documentation for updated Windows support in win32_ver(). Add documentation for linux_distribution() API. ........ r61677 | marc-andre.lemburg | 2008-03-20 19:08:00 +0100 (Do, 20 M??r 2008) | 2 lines Add news items for platform module changes. ........ r61678 | marc-andre.lemburg | 2008-03-20 19:58:14 +0100 (Do, 20 M??r 2008) | 3 lines Clarfiy the availability of the extended support for win32_ver() in Py2.6. ........ r61681 | andrew.kuchling | 2008-03-20 23:49:26 +0100 (Do, 20 M??r 2008) | 1 line Add lots of items ........ r61683 | eric.smith | 2008-03-21 00:04:04 +0100 (Fr, 21 M??r 2008) | 1 line Fixed PEP name. ........ r61684 | eric.smith | 2008-03-21 00:56:08 +0100 (Fr, 21 M??r 2008) | 1 line Comment how 'from __future__ import print_function' operates in 3.0. ........ ................ r61710 | georg.brandl | 2008-03-21 20:42:31 +0100 (Fri, 21 Mar 2008) | 2 lines file.write() may return something with the new IO framework. ................ r61717 | georg.brandl | 2008-03-21 21:46:11 +0100 (Fri, 21 Mar 2008) | 2 lines Add XXX comments for whoever cleans up getargs.c :) ................ r61726 | martin.v.loewis | 2008-03-22 01:07:09 +0100 (Sat, 22 Mar 2008) | 60 lines Merged revisions 61724-61725 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ................ r61724 | martin.v.loewis | 2008-03-22 01:01:12 +0100 (Sa, 22 M??r 2008) | 49 lines Merged revisions 61602-61723 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r61626 | david.wolever | 2008-03-19 17:19:16 +0100 (Mi, 19 M??r 2008) | 1 line Added fixer for implicit local imports. See #2414. ........ r61628 | david.wolever | 2008-03-19 17:57:43 +0100 (Mi, 19 M??r 2008) | 1 line Added a class for tests which should not run if a particular import is found. ........ r61629 | collin.winter | 2008-03-19 17:58:19 +0100 (Mi, 19 M??r 2008) | 1 line Two more relative import fixes in pgen2. ........ r61635 | david.wolever | 2008-03-19 20:16:03 +0100 (Mi, 19 M??r 2008) | 1 line Fixed print fixer so it will do the Right Thing when it encounters __future__.print_function. 2to3 gets upset, though, so the tests have been commented out. ........ r61637 | david.wolever | 2008-03-19 21:37:17 +0100 (Mi, 19 M??r 2008) | 3 lines Added a fixer for itertools imports (from itertools import imap, ifilterfalse --> from itertools import filterfalse) ........ r61645 | david.wolever | 2008-03-19 23:22:35 +0100 (Mi, 19 M??r 2008) | 1 line SVN is happier when you add the files you create... -_-' ........ r61654 | david.wolever | 2008-03-20 01:09:56 +0100 (Do, 20 M??r 2008) | 1 line Added an explicit sort order to fixers -- fixes problems like #2427 ........ r61664 | david.wolever | 2008-03-20 04:32:40 +0100 (Do, 20 M??r 2008) | 3 lines Fixes #2428 -- comments are no longer eatten by __future__ fixer. ........ r61673 | david.wolever | 2008-03-20 17:22:40 +0100 (Do, 20 M??r 2008) | 1 line Added 2to3 node pretty-printer ........ r61679 | david.wolever | 2008-03-20 20:50:42 +0100 (Do, 20 M??r 2008) | 1 line Made node printing a little bit prettier ........ r61723 | martin.v.loewis | 2008-03-22 00:59:27 +0100 (Sa, 22 M??r 2008) | 2 lines Fix whitespace. ........ ................ r61725 | martin.v.loewis | 2008-03-22 01:02:41 +0100 (Sa, 22 M??r 2008) | 2 lines Install lib2to3. ................ ................ r61727 | martin.v.loewis | 2008-03-22 01:35:10 +0100 (Sat, 22 Mar 2008) | 2 lines Add build_py_2to3. ................ r61728 | christian.heimes | 2008-03-22 01:47:35 +0100 (Sat, 22 Mar 2008) | 93 lines Merged revisions 61687-61688,61696,61700,61704-61705,61707-61709,61711-61712,61714-61716,61718-61722 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61687 | jeffrey.yasskin | 2008-03-21 06:02:44 +0100 (Fri, 21 Mar 2008) | 2 lines Speed up test_signal from ~24s to 4s by avoiding nearly all of the sleep calls. ........ r61688 | jeffrey.yasskin | 2008-03-21 06:51:37 +0100 (Fri, 21 Mar 2008) | 5 lines Try to fix test_signal breakages on Linux due to r61687. It appears that at least two of the linux build bots aren't leaving zombie processes around for os.waitpid to wait for, causing ECHILD errors. This would be a symptom of a bug somewhere, but probably not in signal itself. ........ r61696 | georg.brandl | 2008-03-21 15:32:33 +0100 (Fri, 21 Mar 2008) | 2 lines Mark the descitems in the tutorial as "noindex" so that :meth: cross-refs don't link to them. ........ r61700 | georg.brandl | 2008-03-21 18:19:29 +0100 (Fri, 21 Mar 2008) | 2 lines Fix markup. ........ r61704 | jeffrey.yasskin | 2008-03-21 19:25:06 +0100 (Fri, 21 Mar 2008) | 3 lines Try to fix test_signal on FreeBSD. I'm assuming that os.kill is failing to raise a signal, but switching to subprocess makes the code cleaner anyway. ........ r61705 | jeffrey.yasskin | 2008-03-21 19:48:04 +0100 (Fri, 21 Mar 2008) | 7 lines Speed test_threading up from 14s to .5s, and avoid a deadlock on certain failures. The test for enumerate-after-join is now a little less rigorous, but the bug it references says the error happened in the first couple iterations, so 100 iterations should still be enough. cProfile was useful for identifying the slow tests here. ........ r61707 | georg.brandl | 2008-03-21 20:14:38 +0100 (Fri, 21 Mar 2008) | 2 lines Fix a code block in __future__ docs. ........ r61708 | georg.brandl | 2008-03-21 20:20:21 +0100 (Fri, 21 Mar 2008) | 2 lines Add docs for __func__ and __self__ on methods. ........ r61709 | georg.brandl | 2008-03-21 20:37:57 +0100 (Fri, 21 Mar 2008) | 2 lines Add docs for print_function and future_builtins. Fixes #2442. ........ r61711 | georg.brandl | 2008-03-21 20:54:00 +0100 (Fri, 21 Mar 2008) | 2 lines #2136: allow single quotes in realm spec. ........ r61712 | georg.brandl | 2008-03-21 21:01:51 +0100 (Fri, 21 Mar 2008) | 3 lines Issue #2432: give DictReader the dialect and line_num attributes advertised in the docs. ........ r61714 | georg.brandl | 2008-03-21 21:11:46 +0100 (Fri, 21 Mar 2008) | 2 lines #2358: add py3k warning to sys.exc_clear(). ........ r61715 | georg.brandl | 2008-03-21 21:21:46 +0100 (Fri, 21 Mar 2008) | 2 lines #2346/#2347: add py3k warning for __methods__ and __members__. Patch by Jack Diederich. ........ r61716 | georg.brandl | 2008-03-21 21:38:24 +0100 (Fri, 21 Mar 2008) | 2 lines #2348: add py3k warning for file.softspace. ........ r61718 | georg.brandl | 2008-03-21 21:55:20 +0100 (Fri, 21 Mar 2008) | 2 lines #2160: document PyImport_GetImporter. ........ r61719 | georg.brandl | 2008-03-21 21:55:51 +0100 (Fri, 21 Mar 2008) | 2 lines Update doc ACKS. ........ r61720 | steven.bethard | 2008-03-21 22:01:18 +0100 (Fri, 21 Mar 2008) | 1 line Replace hack in regrtest.py with use of sys.py3kwarning. ........ r61721 | georg.brandl | 2008-03-21 22:05:03 +0100 (Fri, 21 Mar 2008) | 2 lines Add missing versionadded tag. ........ r61722 | christian.heimes | 2008-03-22 00:49:44 +0100 (Sat, 22 Mar 2008) | 3 lines Applied patch #1657 epoll and kqueue wrappers for the select module The patch adds wrappers for the Linux epoll syscalls and the BSD kqueue syscalls. Thanks to Thomas Herve and the Twisted people for their support and help. TODO: Finish documentation documentation ........ ................ r61729 | martin.v.loewis | 2008-03-22 02:20:40 +0100 (Sat, 22 Mar 2008) | 2 lines unicode->str. ................ r61747 | christian.heimes | 2008-03-22 19:37:22 +0100 (Sat, 22 Mar 2008) | 1 line Replace spaces by tabs, added ................ r61770 | martin.v.loewis | 2008-03-22 23:07:13 +0100 (Sat, 22 Mar 2008) | 2 lines Properly terminate file name. ................ r61771 | martin.v.loewis | 2008-03-22 23:07:43 +0100 (Sat, 22 Mar 2008) | 2 lines Invoke byte-compilation after running 2to3. ................ r61774 | christian.heimes | 2008-03-23 03:11:13 +0100 (Sun, 23 Mar 2008) | 1 line Fixed parent class init ................ r61811 | gregory.p.smith | 2008-03-23 21:34:14 +0100 (Sun, 23 Mar 2008) | 2 lines Prevent 61779 and 61810 from merging into in py3k ................ r61818 | christian.heimes | 2008-03-23 22:54:12 +0100 (Sun, 23 Mar 2008) | 199 lines Merged revisions 61724-61725,61731-61735,61737,61739,61741,61743-61744,61753,61761,61765-61767,61769,61773,61776-61778,61780-61783,61788,61793,61796,61807,61813 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ................ r61724 | martin.v.loewis | 2008-03-22 01:01:12 +0100 (Sat, 22 Mar 2008) | 49 lines Merged revisions 61602-61723 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r61626 | david.wolever | 2008-03-19 17:19:16 +0100 (Mi, 19 M?\195?\164r 2008) | 1 line Added fixer for implicit local imports. See #2414. ........ r61628 | david.wolever | 2008-03-19 17:57:43 +0100 (Mi, 19 M?\195?\164r 2008) | 1 line Added a class for tests which should not run if a particular import is found. ........ r61629 | collin.winter | 2008-03-19 17:58:19 +0100 (Mi, 19 M?\195?\164r 2008) | 1 line Two more relative import fixes in pgen2. ........ r61635 | david.wolever | 2008-03-19 20:16:03 +0100 (Mi, 19 M?\195?\164r 2008) | 1 line Fixed print fixer so it will do the Right Thing when it encounters __future__.print_function. 2to3 gets upset, though, so the tests have been commented out. ........ r61637 | david.wolever | 2008-03-19 21:37:17 +0100 (Mi, 19 M?\195?\164r 2008) | 3 lines Added a fixer for itertools imports (from itertools import imap, ifilterfalse --> from itertools import filterfalse) ........ r61645 | david.wolever | 2008-03-19 23:22:35 +0100 (Mi, 19 M?\195?\164r 2008) | 1 line SVN is happier when you add the files you create... -_-' ........ r61654 | david.wolever | 2008-03-20 01:09:56 +0100 (Do, 20 M?\195?\164r 2008) | 1 line Added an explicit sort order to fixers -- fixes problems like #2427 ........ r61664 | david.wolever | 2008-03-20 04:32:40 +0100 (Do, 20 M?\195?\164r 2008) | 3 lines Fixes #2428 -- comments are no longer eatten by __future__ fixer. ........ r61673 | david.wolever | 2008-03-20 17:22:40 +0100 (Do, 20 M?\195?\164r 2008) | 1 line Added 2to3 node pretty-printer ........ r61679 | david.wolever | 2008-03-20 20:50:42 +0100 (Do, 20 M?\195?\164r 2008) | 1 line Made node printing a little bit prettier ........ r61723 | martin.v.loewis | 2008-03-22 00:59:27 +0100 (Sa, 22 M?\195?\164r 2008) | 2 lines Fix whitespace. ........ ................ r61725 | martin.v.loewis | 2008-03-22 01:02:41 +0100 (Sat, 22 Mar 2008) | 2 lines Install lib2to3. ................ r61731 | facundo.batista | 2008-03-22 03:45:37 +0100 (Sat, 22 Mar 2008) | 4 lines Small fix that complicated the test actually when that test failed. ................ r61732 | alexandre.vassalotti | 2008-03-22 05:08:44 +0100 (Sat, 22 Mar 2008) | 2 lines Added warning for the removal of 'hotshot' in Py3k. ................ r61733 | georg.brandl | 2008-03-22 11:07:29 +0100 (Sat, 22 Mar 2008) | 4 lines #1918: document that weak references *to* an object are cleared before the object's __del__ is called, to ensure that the weak reference callback (if any) finds the object healthy. ................ r61734 | georg.brandl | 2008-03-22 11:56:23 +0100 (Sat, 22 Mar 2008) | 2 lines Activate the Sphinx doctest extension and convert howto/functional to use it. ................ r61735 | georg.brandl | 2008-03-22 11:58:38 +0100 (Sat, 22 Mar 2008) | 2 lines Allow giving source names on the cmdline. ................ r61737 | georg.brandl | 2008-03-22 12:00:48 +0100 (Sat, 22 Mar 2008) | 2 lines Fixup this HOWTO's doctest blocks so that they can be run with sphinx' doctest builder. ................ r61739 | georg.brandl | 2008-03-22 12:47:10 +0100 (Sat, 22 Mar 2008) | 2 lines Test decimal.rst doctests as far as possible with sphinx doctest. ................ r61741 | georg.brandl | 2008-03-22 13:04:26 +0100 (Sat, 22 Mar 2008) | 2 lines Make doctests in re docs usable with sphinx' doctest. ................ r61743 | georg.brandl | 2008-03-22 13:59:37 +0100 (Sat, 22 Mar 2008) | 2 lines Make more doctests in pprint docs testable. ................ r61744 | georg.brandl | 2008-03-22 14:07:06 +0100 (Sat, 22 Mar 2008) | 2 lines No need to specify explicit "doctest_block" anymore. ................ r61753 | georg.brandl | 2008-03-22 21:08:43 +0100 (Sat, 22 Mar 2008) | 2 lines Fix-up syntax problems. ................ r61761 | georg.brandl | 2008-03-22 22:06:20 +0100 (Sat, 22 Mar 2008) | 4 lines Make collections' doctests executable. (The s will be stripped from presentation output.) ................ r61765 | georg.brandl | 2008-03-22 22:21:57 +0100 (Sat, 22 Mar 2008) | 2 lines Test doctests in datetime docs. ................ r61766 | georg.brandl | 2008-03-22 22:26:44 +0100 (Sat, 22 Mar 2008) | 2 lines Test doctests in operator docs. ................ r61767 | georg.brandl | 2008-03-22 22:38:33 +0100 (Sat, 22 Mar 2008) | 2 lines Enable doctests in functions.rst. Already found two errors :) ................ r61769 | georg.brandl | 2008-03-22 23:04:10 +0100 (Sat, 22 Mar 2008) | 3 lines Enable doctest running for several other documents. We have now over 640 doctests that are run with "make doctest". ................ r61773 | raymond.hettinger | 2008-03-23 01:55:46 +0100 (Sun, 23 Mar 2008) | 1 line Simplify demo code. ................ r61776 | neal.norwitz | 2008-03-23 04:43:33 +0100 (Sun, 23 Mar 2008) | 7 lines Try to make this test a little more robust and not fail with: timeout (10.0025) is more than 2 seconds more than expected (0.001) I'm assuming this problem is caused by DNS lookup. This change does a DNS lookup of the hostname before trying to connect, so the time is not included. ................ r61777 | neal.norwitz | 2008-03-23 05:08:30 +0100 (Sun, 23 Mar 2008) | 1 line Speed up the test by avoiding socket timeouts. ................ r61778 | neal.norwitz | 2008-03-23 05:43:09 +0100 (Sun, 23 Mar 2008) | 1 line Skip the epoll test if epoll() does not work ................ r61780 | neal.norwitz | 2008-03-23 06:47:20 +0100 (Sun, 23 Mar 2008) | 1 line Suppress failure (to avoid a flaky test) if we cannot connect to svn.python.org ................ r61781 | neal.norwitz | 2008-03-23 07:13:25 +0100 (Sun, 23 Mar 2008) | 4 lines Move itertools before future_builtins since the latter depends on the former. From a clean build importing future_builtins would fail since itertools wasn't built yet. ................ r61782 | neal.norwitz | 2008-03-23 07:16:04 +0100 (Sun, 23 Mar 2008) | 1 line Try to prevent the alarm going off early in tearDown ................ r61783 | neal.norwitz | 2008-03-23 07:19:57 +0100 (Sun, 23 Mar 2008) | 4 lines Remove compiler warnings (on Alpha at least) about using chars as array subscripts. Using chars are dangerous b/c they are signed on some platforms and unsigned on others. ................ r61788 | georg.brandl | 2008-03-23 09:05:30 +0100 (Sun, 23 Mar 2008) | 2 lines Make the doctests presentation-friendlier. ................ r61793 | amaury.forgeotdarc | 2008-03-23 10:55:29 +0100 (Sun, 23 Mar 2008) | 4 lines #1477: ur'\U0010FFFF' raised in narrow unicode builds. Corrected the raw-unicode-escape codec to use UTF-16 surrogates in this case, just like the unicode-escape codec. ................ r61796 | raymond.hettinger | 2008-03-23 14:32:32 +0100 (Sun, 23 Mar 2008) | 1 line Issue 1681432: Add triangular distribution the random module. ................ r61807 | raymond.hettinger | 2008-03-23 20:37:53 +0100 (Sun, 23 Mar 2008) | 4 lines Adopt Nick's suggestion for useful default arguments. Clean-up floating point issues by adding true division and float constants. ................ r61813 | gregory.p.smith | 2008-03-23 22:04:43 +0100 (Sun, 23 Mar 2008) | 6 lines Fix gzip to deal with CRC's being signed values in Python 2.x properly and to read 32bit values as unsigned to start with rather than applying signedness fixups allover the place afterwards. This hopefully fixes the test_tarfile failure on the alpha/tru64 buildbot. ................ ................ r61826 | martin.v.loewis | 2008-03-24 01:50:58 +0100 (Mon, 24 Mar 2008) | 24 lines Merged revisions 61825 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ................ r61825 | martin.v.loewis | 2008-03-24 01:46:53 +0100 (Mo, 24 M??r 2008) | 17 lines Merged revisions 61724-61824 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r61730 | martin.v.loewis | 2008-03-22 02:20:58 +0100 (Sa, 22 M??r 2008) | 2 lines More explicit relative imports. ........ r61755 | david.wolever | 2008-03-22 21:33:52 +0100 (Sa, 22 M??r 2008) | 1 line Fixing #2446 -- 2to3 now translates 'import foo' to 'from . import foo' ........ r61824 | david.wolever | 2008-03-24 01:30:24 +0100 (Mo, 24 M??r 2008) | 3 lines Fixed a bug where 'from itertools import izip' would return 'from itertools import' ........ ................ ................ r61827 | martin.v.loewis | 2008-03-24 01:52:58 +0100 (Mon, 24 Mar 2008) | 2 lines Stop including 2to3 in Tools, as it is in Lib now. ................ r61829 | christian.heimes | 2008-03-24 03:19:29 +0100 (Mon, 24 Mar 2008) | 23 lines Merged revisions 61820-61823 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61820 | gregory.p.smith | 2008-03-23 23:14:38 +0100 (Sun, 23 Mar 2008) | 2 lines replace calls to get the initial values with the raw constants. ........ r61821 | gregory.p.smith | 2008-03-24 00:43:02 +0100 (Mon, 24 Mar 2008) | 2 lines A bugfix for r61813, it would fail if the data size was >=2**32. ........ r61822 | gregory.p.smith | 2008-03-24 00:45:12 +0100 (Mon, 24 Mar 2008) | 2 lines prevent a warning from the struct module when data size >= 2**32. ........ r61823 | gregory.p.smith | 2008-03-24 01:08:01 +0100 (Mon, 24 Mar 2008) | 4 lines Have the binascii module use zlib's optimized crc32() function when available to reduce our code size (1k data table and tiny bit of code). It falls back to its own without zlib. ........ ................ r61831 | neal.norwitz | 2008-03-24 05:59:05 +0100 (Mon, 24 Mar 2008) | 1 line Fix crash on 64-bit platforms ................ r61832 | neal.norwitz | 2008-03-24 06:03:36 +0100 (Mon, 24 Mar 2008) | 1 line Add missing closing paren ................ r61833 | neal.norwitz | 2008-03-24 06:51:45 +0100 (Mon, 24 Mar 2008) | 1 line Skip test if socket gets reset, the problem is on the other side. ................ r61835 | neal.norwitz | 2008-03-24 07:10:13 +0100 (Mon, 24 Mar 2008) | 1 line Ensure cleanup does not reference variables that don't yet exist. ................ r61836 | neal.norwitz | 2008-03-24 07:18:09 +0100 (Mon, 24 Mar 2008) | 4 lines Always try to delete the data file before and after the test. This will hopefully avoid spurious failures if the file doesn't have the proper permissions to write for some reason. ................ r61837 | neal.norwitz | 2008-03-24 07:22:57 +0100 (Mon, 24 Mar 2008) | 2 lines Remove the dl module per PEP 3108. ................ r61848 | martin.v.loewis | 2008-03-24 14:39:54 +0100 (Mon, 24 Mar 2008) | 13 lines Merged revisions 61846-61847 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61846 | martin.v.loewis | 2008-03-24 13:57:53 +0100 (Mo, 24 M??r 2008) | 2 lines Install 2to3 script. ........ r61847 | martin.v.loewis | 2008-03-24 14:31:16 +0100 (Mo, 24 M??r 2008) | 2 lines Patch #2240: Implement signal.setitimer and signal.getitimer. ........ ................ r61850 | martin.v.loewis | 2008-03-24 15:05:07 +0100 (Mon, 24 Mar 2008) | 9 lines Merged revisions 61849 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61849 | martin.v.loewis | 2008-03-24 14:54:23 +0100 (Mo, 24 M??r 2008) | 2 lines Conditionalize sys/time.h inclusion. ........ ................ r61868 | gregory.p.smith | 2008-03-25 07:16:18 +0100 (Tue, 25 Mar 2008) | 2 lines 61867 not needed in 3k ................ r61872 | georg.brandl | 2008-03-25 08:21:32 +0100 (Tue, 25 Mar 2008) | 2 lines #868845: document <...> reprs. ................ r61873 | georg.brandl | 2008-03-25 08:22:15 +0100 (Tue, 25 Mar 2008) | 8 lines Blocked revisions 61871 via svnmerge ........ r61871 | georg.brandl | 2008-03-25 08:20:15 +0100 (Tue, 25 Mar 2008) | 2 lines #868845: document <...> reprs. ........ ................ r61876 | gregory.p.smith | 2008-03-25 08:48:30 +0100 (Tue, 25 Mar 2008) | 2 lines i'll merge this revision by hand since its a mix of cleanup and 2.x specifics ................ r61877 | gregory.p.smith | 2008-03-25 08:51:12 +0100 (Tue, 25 Mar 2008) | 2 lines Merge the table type change to save space on LP64 platforms from trunk r61875. ................ r61883 | georg.brandl | 2008-03-25 09:40:58 +0100 (Tue, 25 Mar 2008) | 2 lines Block the mere addition of a versionadded tag. ................ r61891 | christian.heimes | 2008-03-25 15:17:23 +0100 (Tue, 25 Mar 2008) | 1 line Block revisions 61878-61881 aka Georgs py3k warnings ................ r61894 | christian.heimes | 2008-03-25 15:56:36 +0100 (Tue, 25 Mar 2008) | 61 lines Merged revisions 61834,61841-61842,61851-61853,61863-61864,61869-61870,61874,61889 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61834 | raymond.hettinger | 2008-03-24 07:07:49 +0100 (Mon, 24 Mar 2008) | 1 line Tighten documentation for Random.triangular. ........ r61841 | raymond.hettinger | 2008-03-24 09:17:39 +0100 (Mon, 24 Mar 2008) | 1 line Issue 2460: Make Ellipsis objects copyable. ........ r61842 | georg.brandl | 2008-03-24 10:34:34 +0100 (Mon, 24 Mar 2008) | 2 lines #1700821: add a note to audioop docs about signedness of sample formats. ........ r61851 | christian.heimes | 2008-03-24 20:57:42 +0100 (Mon, 24 Mar 2008) | 1 line Added quick hack for bzr ........ r61852 | christian.heimes | 2008-03-24 20:58:17 +0100 (Mon, 24 Mar 2008) | 1 line Added quick hack for bzr ........ r61853 | amaury.forgeotdarc | 2008-03-24 22:04:10 +0100 (Mon, 24 Mar 2008) | 4 lines Issue2469: Correct a typo I introduced at r61793: compilation error with UCS4 builds. All buildbots compile with UCS2... ........ r61863 | neal.norwitz | 2008-03-25 05:17:38 +0100 (Tue, 25 Mar 2008) | 2 lines Fix a bunch of UnboundLocalErrors when the tests fail. ........ r61864 | neal.norwitz | 2008-03-25 05:18:18 +0100 (Tue, 25 Mar 2008) | 2 lines Try to fix a bunch of compiler warnings on Win64. ........ r61869 | neal.norwitz | 2008-03-25 07:35:10 +0100 (Tue, 25 Mar 2008) | 3 lines Don't try to close a non-open file. Don't let file removal cause the test to fail. ........ r61870 | neal.norwitz | 2008-03-25 08:00:39 +0100 (Tue, 25 Mar 2008) | 7 lines Try to get this test to be more stable: * disable gc during the test run because we are spawning objects and there was an exception when calling Popen.__del__ * Always set an alarm handler so the process doesn't exit if the test fails (should probably add assertions on the value of hndl_called in more places) * Using a negative time causes Linux to treat it as zero, so disable that test. ........ r61874 | gregory.p.smith | 2008-03-25 08:31:28 +0100 (Tue, 25 Mar 2008) | 2 lines Use a 32-bit unsigned int here, a long is not needed. ........ r61889 | georg.brandl | 2008-03-25 12:59:51 +0100 (Tue, 25 Mar 2008) | 2 lines Move declarations to block start. ........ ................ r61896 | georg.brandl | 2008-03-25 16:33:31 +0100 (Tue, 25 Mar 2008) | 2 lines Fix duplicated paragraph. ................ r61905 | mark.dickinson | 2008-03-25 19:49:36 +0100 (Tue, 25 Mar 2008) | 1 line block r61904 ................ r61914 | benjamin.peterson | 2008-03-25 22:14:46 +0100 (Tue, 25 Mar 2008) | 2 lines Merged the ACKS from 2.6 ................ r61921 | neal.norwitz | 2008-03-26 05:23:27 +0100 (Wed, 26 Mar 2008) | 3 lines Get the test to pass on space Ubuntu/Debian and ppc. It was failing to decode 'Journ\xc3\xa9es Python' as ASCII. ................ r61927 | georg.brandl | 2008-03-26 10:00:12 +0100 (Wed, 26 Mar 2008) | 2 lines #2484: remove duplicate variable definition. ................ r61941 | christian.heimes | 2008-03-26 13:55:56 +0100 (Wed, 26 Mar 2008) | 14 lines Merged revisions 61892,61900 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61892 | mark.dickinson | 2008-03-25 15:33:23 +0100 (Tue, 25 Mar 2008) | 3 lines Issue #2478: Decimal(sqrt(0)) failed when the decimal context was not explicitly supplied. ........ r61900 | georg.brandl | 2008-03-25 18:36:43 +0100 (Tue, 25 Mar 2008) | 2 lines Add Benjamin. ........ ................ r61942 | christian.heimes | 2008-03-26 13:56:21 +0100 (Wed, 26 Mar 2008) | 1 line block backport of bytearray and io infrastructure ................ r61944 | christian.heimes | 2008-03-26 14:00:06 +0100 (Wed, 26 Mar 2008) | 1 line Block correct revision ................ r61948 | christian.heimes | 2008-03-26 14:45:42 +0100 (Wed, 26 Mar 2008) | 78 lines Merged revisions 61913,61915-61916,61918-61919,61922-61926,61928-61929,61931,61935,61938,61943 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61913 | benjamin.peterson | 2008-03-25 22:14:42 +0100 (Tue, 25 Mar 2008) | 2 lines Merged the ACKS from py3k ........ r61915 | thomas.heller | 2008-03-25 22:18:39 +0100 (Tue, 25 Mar 2008) | 1 line Make _ctypes.c PY_SSIZE_T_CLEAN. ........ r61916 | benjamin.peterson | 2008-03-25 22:55:50 +0100 (Tue, 25 Mar 2008) | 3 lines Opps! I merged the revisions, but forgot to add the header to ACKS ........ r61918 | andrew.kuchling | 2008-03-26 01:16:50 +0100 (Wed, 26 Mar 2008) | 1 line Minor docstring typos ........ r61919 | andrew.kuchling | 2008-03-26 01:30:02 +0100 (Wed, 26 Mar 2008) | 1 line Add various items ........ r61922 | neal.norwitz | 2008-03-26 05:55:51 +0100 (Wed, 26 Mar 2008) | 6 lines Try to get this test to be less flaky. It was failing sometimes because the connect would succeed before the timeout occurred. Try using an address and port that hopefully doesn't exist to ensure we get no response. If this doesn't work, we can use a public address close to python.org and hopefully that address never gets taken. ........ r61923 | jerry.seutter | 2008-03-26 06:03:03 +0100 (Wed, 26 Mar 2008) | 1 line Changed test so it no longer runs as a side effect of importing. ........ r61924 | neal.norwitz | 2008-03-26 06:19:41 +0100 (Wed, 26 Mar 2008) | 5 lines Ensure that the mailbox is closed to prevent problems on Windows with removing an open file. This doesn't seem to be a problem in 2.6, but that appears to be somewhat accidental (specific to reference counting). When this gets merged to 3.0, it will make the 3.0 code simpler. ........ r61925 | jerry.seutter | 2008-03-26 06:32:51 +0100 (Wed, 26 Mar 2008) | 1 line Changed test so it no longer runs as a side effect of importing. ........ r61926 | jerry.seutter | 2008-03-26 06:58:14 +0100 (Wed, 26 Mar 2008) | 1 line Changed test so it no longer runs as a side effect of importing. ........ r61928 | georg.brandl | 2008-03-26 10:04:36 +0100 (Wed, 26 Mar 2008) | 2 lines Add Josiah. ........ r61929 | georg.brandl | 2008-03-26 10:32:46 +0100 (Wed, 26 Mar 2008) | 2 lines Add an example for an RFC 822 continuation. ........ r61931 | benjamin.peterson | 2008-03-26 12:57:47 +0100 (Wed, 26 Mar 2008) | 2 lines Added help options to PDB ........ r61935 | christian.heimes | 2008-03-26 13:32:49 +0100 (Wed, 26 Mar 2008) | 1 line Prepare integration of bytearray backport branch ........ r61938 | christian.heimes | 2008-03-26 13:50:43 +0100 (Wed, 26 Mar 2008) | 3 lines Removed merge tracking for "svnmerge" for svn+ssh://pythondev at svn.python.org/python/branches/trunk-bytearray ........ r61943 | georg.brandl | 2008-03-26 13:57:47 +0100 (Wed, 26 Mar 2008) | 2 lines Fix and simplify error handling, silencing a compiler warning. ........ ................ r61951 | amaury.forgeotdarc | 2008-03-26 20:49:26 +0100 (Wed, 26 Mar 2008) | 3 lines Correct Issue#1561: test_mailbox failed on Windows. Open all text files with newline='', this is the only way to have consistent offsets. ................ r61955 | christian.heimes | 2008-03-26 23:34:47 +0100 (Wed, 26 Mar 2008) | 15 lines Merged revisions 61952-61953 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61952 | mark.dickinson | 2008-03-26 22:41:36 +0100 (Wed, 26 Mar 2008) | 2 lines Typo: "objects reference count" -> "object's reference count" ........ r61953 | christian.heimes | 2008-03-26 23:01:37 +0100 (Wed, 26 Mar 2008) | 4 lines Patch #2477: Added from __future__ import unicode_literals The new PyParser_*Ex() functions are based on Neal's suggestion and initial patch. The new __future__ feature makes all '' and r'' unicode strings. b'' and br'' stay (byte) strings. ........ ................ r61960 | christian.heimes | 2008-03-27 00:24:27 +0100 (Thu, 27 Mar 2008) | 17 lines Merged revisions 61954,61956-61957 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61954 | christian.heimes | 2008-03-26 23:20:26 +0100 (Wed, 26 Mar 2008) | 1 line Surround p_flags access with #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD ........ r61956 | christian.heimes | 2008-03-26 23:51:58 +0100 (Wed, 26 Mar 2008) | 1 line Initialize PyCompilerFlags cf_flags with 0 ........ r61957 | christian.heimes | 2008-03-26 23:55:31 +0100 (Wed, 26 Mar 2008) | 1 line I forgot to svn add the future test ........ ................ r61961 | christian.heimes | 2008-03-27 00:25:24 +0100 (Thu, 27 Mar 2008) | 9 lines Merged revisions 61958-61959 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61958 | amaury.forgeotdarc | 2008-03-27 00:07:43 +0100 (Thu, 27 Mar 2008) | 2 lines C89 compliance: Microsoft compilers want variable declarations at the top ........ ................ r61982 | christian.heimes | 2008-03-28 01:55:15 +0100 (Fri, 28 Mar 2008) | 77 lines Merged revisions 61964-61979 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61964 | benjamin.peterson | 2008-03-27 01:25:33 +0100 (Thu, 27 Mar 2008) | 2 lines add commas for introductory clauses ........ r61965 | christian.heimes | 2008-03-27 02:36:21 +0100 (Thu, 27 Mar 2008) | 1 line Hopefully added _fileio module to the Windows build system ........ r61966 | christian.heimes | 2008-03-27 02:38:47 +0100 (Thu, 27 Mar 2008) | 1 line Revert commit accident ........ r61967 | neal.norwitz | 2008-03-27 04:49:54 +0100 (Thu, 27 Mar 2008) | 3 lines Fix bytes so it works on 64-bit platforms. (Also remove some #if 0 code that is already handled in _getbytevalue.) ........ r61968 | neal.norwitz | 2008-03-27 05:40:07 +0100 (Thu, 27 Mar 2008) | 1 line Fix memory leaks ........ r61969 | neal.norwitz | 2008-03-27 05:40:50 +0100 (Thu, 27 Mar 2008) | 3 lines Fix warnings about using char as an array subscript. This is not portable since char is signed on some platforms and unsigned on others. ........ r61970 | neal.norwitz | 2008-03-27 06:02:57 +0100 (Thu, 27 Mar 2008) | 1 line Fix test_compiler after adding unicode_literals ........ r61971 | neal.norwitz | 2008-03-27 06:03:11 +0100 (Thu, 27 Mar 2008) | 1 line Fix compiler warnings ........ r61972 | neal.norwitz | 2008-03-27 07:52:01 +0100 (Thu, 27 Mar 2008) | 1 line Pluralss only need one s, not 2 (intss -> ints) ........ r61973 | christian.heimes | 2008-03-27 10:02:33 +0100 (Thu, 27 Mar 2008) | 1 line Quick 'n dirty hack: Increase the magic by 2 to force a rebuild of pyc/pyo files on the build bots ........ r61974 | eric.smith | 2008-03-27 10:42:35 +0100 (Thu, 27 Mar 2008) | 3 lines Added test cases for single quoted strings, both forms of triple quotes, and some string concatenations. Removed unneeded __future__ print_function import. ........ r61975 | christian.heimes | 2008-03-27 11:35:52 +0100 (Thu, 27 Mar 2008) | 1 line Build bots are working again - removing the hack ........ r61976 | christian.heimes | 2008-03-27 12:46:37 +0100 (Thu, 27 Mar 2008) | 2 lines Fixed tokenize tests The tokenize module doesn't understand __future__.unicode_literals yet ........ r61977 | georg.brandl | 2008-03-27 14:27:31 +0100 (Thu, 27 Mar 2008) | 2 lines #2248: return result of QUIT from quit(). ........ r61978 | georg.brandl | 2008-03-27 14:34:59 +0100 (Thu, 27 Mar 2008) | 2 lines The bug for which there was a test in outstanding_bugs.py was agreed not to be a bug. ........ r61979 | amaury.forgeotdarc | 2008-03-28 00:23:54 +0100 (Fri, 28 Mar 2008) | 5 lines Issue2495: tokenize.untokenize did not insert space between two consecutive string literals: "" "" => """", which is invalid code. Will backport ........ ................ r61991 | martin.v.loewis | 2008-03-28 06:29:57 +0100 (Fri, 28 Mar 2008) | 28 lines Merged revisions 61988-61990 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ................ r61988 | martin.v.loewis | 2008-03-28 06:25:36 +0100 (Fr, 28 M??r 2008) | 2 lines Disable test that depends on #2412 being fixed. ................ r61989 | martin.v.loewis | 2008-03-28 06:26:10 +0100 (Fr, 28 M??r 2008) | 2 lines Run 2to3 tests. ................ r61990 | martin.v.loewis | 2008-03-28 06:27:44 +0100 (Fr, 28 M??r 2008) | 13 lines Merged revisions 61825-61989 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r61899 | collin.winter | 2008-03-25 17:53:41 +0100 (Di, 25 M??r 2008) | 1 line Add a missing explicit fixer to test_all_fixers. ........ r61983 | collin.winter | 2008-03-28 03:19:46 +0100 (Fr, 28 M??r 2008) | 2 lines Fix http://bugs.python.org/issue2453: support empty excepts in fix_except. ........ ................ ................ r62002 | christian.heimes | 2008-03-28 11:52:42 +0100 (Fri, 28 Mar 2008) | 1 line Fixed an import ................ r62003 | christian.heimes | 2008-03-28 11:53:29 +0100 (Fri, 28 Mar 2008) | 72 lines Merged revisions 61981,61984-61987,61992-61993,61997-62000 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r61981 | amaury.forgeotdarc | 2008-03-28 01:21:34 +0100 (Fri, 28 Mar 2008) | 2 lines test_future3.py is a regular test file, and should be part of the test suite ........ r61984 | jeffrey.yasskin | 2008-03-28 05:11:18 +0100 (Fri, 28 Mar 2008) | 6 lines Kill a race in test_threading in which the exception info in a thread finishing up after it was joined had a traceback pointing to that thread's (deleted) target attribute, while the test was trying to check that the target was destroyed. Big thanks to Antoine Pitrou for diagnosing the race and pointing out sys.exc_clear() to kill the exception early. This fixes issue 2496. ........ r61985 | neal.norwitz | 2008-03-28 05:41:34 +0100 (Fri, 28 Mar 2008) | 1 line Allow use of other ports so the test can pass if 9091 is in use ........ r61986 | jeffrey.yasskin | 2008-03-28 05:53:10 +0100 (Fri, 28 Mar 2008) | 2 lines Print more information the next time test_socket throws the wrong exception. ........ r61987 | neal.norwitz | 2008-03-28 05:58:51 +0100 (Fri, 28 Mar 2008) | 5 lines Revert r61969 which added casts to Py_CHARMASK to avoid compiler warnings. Rather than sprinkle casts throughout the code, change Py_CHARMASK to always cast it's result to an unsigned char. This should ensure we do the right thing when accessing an array with the result. ........ r61992 | neal.norwitz | 2008-03-28 06:34:59 +0100 (Fri, 28 Mar 2008) | 2 lines Fix compiler warning about finite() missing on Solaris. ........ r61993 | neal.norwitz | 2008-03-28 07:34:03 +0100 (Fri, 28 Mar 2008) | 11 lines Bug 1503: Get the test to pass on OSX. This should make the test more reliable, but I'm not convinced it is the right solution. We need to determine if this causes the test to hang on any platforms or do other bad things. Even if it gets the test to pass reliably, it might be that we want to fix this in socket. The socket returned from accept() is different on different platforms (inheriting attributes or not) and we might want to ensure that the attributes (at least blocking) is the same across all platforms. ........ r61997 | neal.norwitz | 2008-03-28 08:36:31 +0100 (Fri, 28 Mar 2008) | 1 line Name the main method correctly so the test is run ........ r61998 | gregory.p.smith | 2008-03-28 09:00:44 +0100 (Fri, 28 Mar 2008) | 7 lines This patch moves some tests from test_urllib2_net to test_urllib2_localnet. The moved tests use a local server rather than going out to external servers. Accepts patch from issue2429. Contributed by Jerry Seutter & Michael Foord (fuzzyman) at PyCon 2008. ........ r61999 | georg.brandl | 2008-03-28 09:06:56 +0100 (Fri, 28 Mar 2008) | 2 lines #2406: add examples to gzip docs. ........ r62000 | gregory.p.smith | 2008-03-28 09:32:09 +0100 (Fri, 28 Mar 2008) | 4 lines Accept patch issue2426 by Paul Kippes (kippesp). Adds sqlite3.Connection.iterdump to allow dumping of databases. ........ ................ r62022 | gerhard.haering | 2008-03-29 01:41:18 +0100 (Sat, 29 Mar 2008) | 2 lines Added missing files for new iterdump method. ................ r62024 | gerhard.haering | 2008-03-29 01:45:29 +0100 (Sat, 29 Mar 2008) | 3 lines Bring sqlite3 module up-to-date with what's now in 2.6. Almost. I intentionally left out the stuff about creating a connection object from a APSW connection. ................ r62027 | gerhard.haering | 2008-03-29 02:32:44 +0100 (Sat, 29 Mar 2008) | 2 lines Same documentation for sqlite3 module as in 2.6. ................ r62032 | georg.brandl | 2008-03-29 03:00:47 +0100 (Sat, 29 Mar 2008) | 9 lines Blocked revisions 62026 via svnmerge ........ r62026 | gerhard.haering | 2008-03-29 02:27:37 +0100 (Sat, 29 Mar 2008) | 3 lines Brought documentation for sqlite3 module up-to-date. Fixed Issue1625205 which complained about commit, rollback and close not being documented. ........ ................ r62033 | georg.brandl | 2008-03-29 03:04:05 +0100 (Sat, 29 Mar 2008) | 8 lines Blocked revisions 62030 via svnmerge ........ r62030 | georg.brandl | 2008-03-29 02:50:06 +0100 (Sat, 29 Mar 2008) | 2 lines Backport #1442: report exception when startup file cannot be run. ........ ................ r62034 | jeffrey.yasskin | 2008-03-29 06:06:52 +0100 (Sat, 29 Mar 2008) | 3 lines Update test_threading with a couple changes from trunk that got lost due, I presume, to merge conflicts. ................ r62041 | gerhard.haering | 2008-03-29 15:11:55 +0100 (Sat, 29 Mar 2008) | 2 lines Moved DECREF to correct place to get rid of leaked references. ................ r62045 | gerhard.haering | 2008-03-29 20:13:55 +0100 (Sat, 29 Mar 2008) | 2 lines Documented lastrowid attribute in py3k branch. ................ r62055 | martin.v.loewis | 2008-03-30 22:03:44 +0200 (Sun, 30 Mar 2008) | 11 lines Merged revisions 62004 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62004 | georg.brandl | 2008-03-28 13:11:56 +0100 (Fr, 28 M??r 2008) | 4 lines Patch #1810 by Thomas Lee, reviewed by myself: allow compiling Python AST objects into code objects in compile(). ........ ................ r62056 | martin.v.loewis | 2008-03-30 22:09:13 +0200 (Sun, 30 Mar 2008) | 2 lines Block 62005, as it applies only to the trunk. ................ r62057 | martin.v.loewis | 2008-03-30 22:16:56 +0200 (Sun, 30 Mar 2008) | 2 lines Block 62006, as that section was rewritten in 58038. ................ r62058 | martin.v.loewis | 2008-03-30 22:18:05 +0200 (Sun, 30 Mar 2008) | 9 lines Merged revisions 62007 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62007 | georg.brandl | 2008-03-28 13:58:26 +0100 (Fr, 28 M??r 2008) | 2 lines #2502: add example how to do enum types with named tuples. ........ ................ r62060 | martin.v.loewis | 2008-03-30 22:21:00 +0200 (Sun, 30 Mar 2008) | 9 lines Merged revisions 62011 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62011 | gerhard.haering | 2008-03-28 21:08:36 +0100 (Fr, 28 M??r 2008) | 2 lines Update sqlite3 module to match current version of pysqlite. ........ ................ r62061 | martin.v.loewis | 2008-03-30 22:23:50 +0200 (Sun, 30 Mar 2008) | 11 lines Merged revisions 62012 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62012 | gregory.p.smith | 2008-03-28 21:11:49 +0100 (Fr, 28 M??r 2008) | 2 lines These svn adds were forgotten in r62000 ........ test/dump.py was already added in r62022, so it was not merged. ................ r62062 | martin.v.loewis | 2008-03-30 22:29:36 +0200 (Sun, 30 Mar 2008) | 13 lines Merged revisions 62013-62014 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62013 | amaury.forgeotdarc | 2008-03-28 21:17:51 +0100 (Fr, 28 M??r 2008) | 2 lines Silence a compilation warning ........ r62014 | georg.brandl | 2008-03-28 21:22:56 +0100 (Fr, 28 M??r 2008) | 2 lines Silence compiler warning at the source. ........ ................ r62063 | martin.v.loewis | 2008-03-30 22:38:01 +0200 (Sun, 30 Mar 2008) | 11 lines Blocked revisions 62015 via svnmerge This was apparently fixed in r54428 already ........ r62015 | amaury.forgeotdarc | 2008-03-28 21:30:50 +0100 (Fr, 28 M??r 2008) | 5 lines Fix a reference leak found by Georg, when compiling a class nested in another class. Now "regrtest.py -R:: test_compile" is satisfied. Will backport. ........ ................ r62064 | martin.v.loewis | 2008-03-30 22:43:50 +0200 (Sun, 30 Mar 2008) | 9 lines Merged revisions 62018 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62018 | benjamin.peterson | 2008-03-28 21:56:00 +0100 (Fr, 28 M??r 2008) | 2 lines #2498 modernized try, except, finally statments in bdb ........ ................ r62065 | martin.v.loewis | 2008-03-30 22:45:26 +0200 (Sun, 30 Mar 2008) | 13 lines Blocked revisions 62019 via svnmerge ........ r62019 | amaury.forgeotdarc | 2008-03-28 22:55:29 +0100 (Fr, 28 M??r 2008) | 7 lines Repair compilation for Visual Studio 2005. I applied the same changes manually to VS7.1 and VC6 files; completely untested. (Christian, don't try too hard merging this change into py3k. It will be easier to do the same work again on the branch) ........ ................ r62066 | neal.norwitz | 2008-03-31 00:49:52 +0200 (Mon, 31 Mar 2008) | 19 lines Blocked revisions 62023,62025,62028 via svnmerge ........ r62023 | amaury.forgeotdarc | 2008-03-28 17:44:58 -0700 (Fri, 28 Mar 2008) | 5 lines Try to understand why most buildbots suddenly turned to red. Undo the only change that might have unexpected effects. To be followed. ........ r62025 | amaury.forgeotdarc | 2008-03-28 17:49:07 -0700 (Fri, 28 Mar 2008) | 2 lines At least let the module compile ........ r62028 | amaury.forgeotdarc | 2008-03-28 18:41:08 -0700 (Fri, 28 Mar 2008) | 2 lines Revert my experiment. I found one reason of failures in test_logging. ........ ................ r62068 | jeffrey.yasskin | 2008-03-31 02:38:53 +0200 (Mon, 31 Mar 2008) | 8 lines Blocked revisions 62067 via svnmerge ........ r62067 | jeffrey.yasskin | 2008-03-30 17:35:53 -0700 (Sun, 30 Mar 2008) | 2 lines Block the sys.exc_clear -3 warning from threading.py. ........ ................ r62069 | benjamin.peterson | 2008-03-31 03:51:45 +0200 (Mon, 31 Mar 2008) | 46 lines Merged revisions 62021,62029,62035-62038,62043-62044,62052-62053 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62021 | benjamin.peterson | 2008-03-28 18:11:01 -0500 (Fri, 28 Mar 2008) | 2 lines NIL => NULL ........ r62029 | amaury.forgeotdarc | 2008-03-28 20:42:31 -0500 (Fri, 28 Mar 2008) | 3 lines Correctly call the base class tearDown(); otherwise running test_logging twice produce the errors we see on all buildbots ........ r62035 | raymond.hettinger | 2008-03-29 05:42:07 -0500 (Sat, 29 Mar 2008) | 1 line Be explicit about what efficient means. ........ r62036 | georg.brandl | 2008-03-29 06:46:18 -0500 (Sat, 29 Mar 2008) | 2 lines Fix capitalization. ........ r62037 | amaury.forgeotdarc | 2008-03-29 07:42:54 -0500 (Sat, 29 Mar 2008) | 5 lines lib2to3 should install a logging handler only when run as a main program, not when used as a library. This may please the buildbots, which fail when test_lib2to3 is run before test_logging. ........ r62043 | benjamin.peterson | 2008-03-29 10:24:25 -0500 (Sat, 29 Mar 2008) | 3 lines #2503 make singletons compared with "is" not == or != Thanks to Wummel for the patch ........ r62044 | gerhard.haering | 2008-03-29 14:11:52 -0500 (Sat, 29 Mar 2008) | 2 lines Documented the lastrowid attribute. ........ r62052 | benjamin.peterson | 2008-03-30 14:35:10 -0500 (Sun, 30 Mar 2008) | 2 lines Updated README regarding doc formats ........ r62053 | georg.brandl | 2008-03-30 14:41:39 -0500 (Sun, 30 Mar 2008) | 2 lines The other download formats will be available for 2.6 too. ........ ................ r62070 | benjamin.peterson | 2008-03-31 04:36:22 +0200 (Mon, 31 Mar 2008) | 3 lines Rolled back revisions 62038 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk This was incorrectly merged. ................ r62071 | neal.norwitz | 2008-03-31 04:55:15 +0200 (Mon, 31 Mar 2008) | 1 line Revert r62070 due to syntax errors ................ r62072 | neal.norwitz | 2008-03-31 04:56:33 +0200 (Mon, 31 Mar 2008) | 1 line Revert r62070 due to syntax errors ................ r62073 | neal.norwitz | 2008-03-31 05:02:08 +0200 (Mon, 31 Mar 2008) | 11 lines Blocked revisions 62020 via svnmerge ........ r62020 | amaury.forgeotdarc | 2008-03-28 15:43:38 -0700 (Fri, 28 Mar 2008) | 5 lines One #ifdef too much, and I broke all windows buildbots: in pyconfig.h, NTDDI_WIN2KSP4 is not *yet* defined, but will be at some point on some modules. Let this line even for older SDKs, they don't use it anyway. ........ ................ r62074 | neal.norwitz | 2008-03-31 06:20:05 +0200 (Mon, 31 Mar 2008) | 22 lines Merged revisions 62039-62042 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62039 | georg.brandl | 2008-03-29 06:24:23 -0700 (Sat, 29 Mar 2008) | 3 lines Properly check for consistency with the third argument of compile() when compiling an AST node. ........ r62040 | amaury.forgeotdarc | 2008-03-29 06:47:05 -0700 (Sat, 29 Mar 2008) | 5 lines The buildbot "x86 W2k8 trunk" seems to hang in test_socket. http://www.python.org/dev/buildbot/trunk/x86%20W2k8%20trunk/builds/255/step-test/0 Temporarily increase verbosity of this test. ........ r62042 | amaury.forgeotdarc | 2008-03-29 07:53:05 -0700 (Sat, 29 Mar 2008) | 3 lines Still investigating on the hanging test_socket. the test itself doesn't do anything on windows, focus on setUp and tearDown. ........ ................ r62076 | neal.norwitz | 2008-03-31 06:42:11 +0200 (Mon, 31 Mar 2008) | 13 lines Merged revisions 62049,62054 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62049 | georg.brandl | 2008-03-30 00:01:47 -0700 (Sun, 30 Mar 2008) | 2 lines #2505: allow easier creation of AST nodes. ........ r62054 | georg.brandl | 2008-03-30 12:43:27 -0700 (Sun, 30 Mar 2008) | 2 lines Fix error message -- "expects either 0 or 0 arguments" ........ ................ r62077 | neal.norwitz | 2008-03-31 06:47:25 +0200 (Mon, 31 Mar 2008) | 8 lines Blocked revisions 62075 via svnmerge ........ r62075 | neal.norwitz | 2008-03-30 21:28:40 -0700 (Sun, 30 Mar 2008) | 1 line Use file.write instead of print to make it easier to merge with 3k. ........ ................ r62078 | neal.norwitz | 2008-03-31 07:14:30 +0200 (Mon, 31 Mar 2008) | 9 lines Merged revisions 62047 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62047 | georg.brandl | 2008-03-29 23:40:17 -0700 (Sat, 29 Mar 2008) | 2 lines Patch #2511: Give the "excepthandler" AST item proper attributes by making it a Sum. ........ ................ r62081 | neal.norwitz | 2008-03-31 07:29:39 +0200 (Mon, 31 Mar 2008) | 21 lines Merged revisions 61440-61441,61443,61445-61448,61451-61452,61455-61457,61459-61464,61466-61467,61469-61470,61476-61477,61479,61481-61482,61485,61487,61490,61493-61494,61497,61499-61502,61505-61506,61508,61511-61514,61519,61521-61522,61530-61531,61533-61537,61541-61555,61557-61558,61561-61562,61566-61569,61572-61574,61578-61579,61583-61584,61588-61589,61592,61594,61598-61601,61603-61604,61607-61612,61617,61619-61620,61624,61626,61628-61630,61635-61638,61640-61643,61645,61648,61653-61655,61659-61662,61664,61666,61668-61671,61673,61675,61679-61680,61682,61685-61686,61689-61695,61697-61699,61701-61703,61706,61710,61713,61717,61723,61726-61730,61736,61738,61740,61742,61745-61752,61754-61760,61762-61764,61768,61770-61772,61774-61775,61784-61787,61789-61792,61794-61795,61797-61806,61808-61809,61811-61812,61814-61819,61824,61826-61833,61835-61840,61843-61845,61848,61850,61854-61862,61865-61866,61868,61872-61873,61876-61877,61883-61888,61890-61891,61893-61899,61901-61903,61905-61912,61914,61917,61920-61921,61927,61930,61932-61934,61939,61941-61942,61944-61951,61955,61960-61963,61980,61982-61983,61991,61994-61996,62001-62003,62008-62010,62016-62017,62022,62024,62027,62031-62034,62041,62045-62046,62048,62050-62051,62055-62066,62068-62074,62076-62078 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62048 | georg.brandl | 2008-03-29 23:53:55 -0700 (Sat, 29 Mar 2008) | 2 lines Adapt test_ast to the new ExceptHandler type. ........ r62050 | georg.brandl | 2008-03-30 00:09:22 -0700 (Sun, 30 Mar 2008) | 2 lines Convert test_ast to unittest and add a test for r62049. ........ r62051 | georg.brandl | 2008-03-30 12:00:49 -0700 (Sun, 30 Mar 2008) | 2 lines Make _fields attr for no fields consistent with _attributes attr. ........ r62059 | georg.brandl | 2008-03-30 13:20:39 -0700 (Sun, 30 Mar 2008) | 2 lines Make AST nodes pickleable. ........ ................ r62082 | neal.norwitz | 2008-03-31 07:39:26 +0200 (Mon, 31 Mar 2008) | 4 lines This was required on OS X to prevent the test from deadlocking. I'm not sure if this is just a test problem or something deeper. Hopefully the test will stop hanging. ................ r62086 | martin.v.loewis | 2008-04-01 08:17:46 +0200 (Tue, 01 Apr 2008) | 26 lines Merged revisions 61440-61441,61443,61445-61448,61451-61452,61455-61457,61459-61464,61466-61467,61469-61470,61476-61477,61479,61481-61482,61485,61487,61490,61493-61494,61497,61499-61502,61505-61506,61508,61511-61514,61519,61521-61522,61530-61531,61533-61537,61541-61555,61557-61558,61561-61562,61566-61569,61572-61574,61578-61579,61583-61584,61588-61589,61592,61594,61598-61601,61603-61604,61607-61612,61617,61619-61620,61624,61626,61628-61630,61635-61638,61640-61643,61645,61648,61653-61655,61659-61662,61664,61666,61668-61671,61673,61675,61679-61680,61682,61685-61686,61689-61695,61697-61699,61701-61703,61706,61710,61713,61717,61723,61726-61730,61736,61738,61740,61742,61745-61752,61754-61760,61762-61764,61768,61770-61772,61774-61775,61784-61787,61789-61792,61794-61795,61797-61806,61808-61809,61811-61812,61814-61819,61824,61826-61833,61835-61840,61843-61845,61848,61850,61854-61862,61865-61866,61868,61872-61873,61876-61877,61883-61888,61890-61891,61893-61899,61901-61903,61905-61912,61914,61917,61920-61921,61927,61930,61932-61934,61939,61941-61942,61944-61951,61955,61960-61963,61980,61982-61983,61991,61994-61996,62001-62003,62008-62010,62016-62017,62022,62024,62027,62031-62034,62041,62045-62046,62055-62058,62060-62066,62068-62074,62076-62085 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ................ r62080 | martin.v.loewis | 2008-03-31 07:20:55 +0200 (Mo, 31 M??r 2008) | 9 lines Merged revisions 61990-62079 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r62017 | david.wolever | 2008-03-28 21:54:37 +0100 (Fr, 28 M??r 2008) | 1 line Fixed an out-of-date comment. ........ ................ r62084 | benjamin.peterson | 2008-03-31 23:57:13 +0200 (Mo, 31 M??r 2008) | 2 lines PyErr_Warn is decrepated. Use PyErr_WarnEx ................ r62085 | neal.norwitz | 2008-04-01 07:40:43 +0200 (Di, 01 Apr 2008) | 4 lines Be sure to close the file. 2 places were deleting the file, so it was probably fine, but the last change may be required for the test to pass on Windows. Should we always close the mmap too? ................ ................ r62087 | neal.norwitz | 2008-04-01 09:37:58 +0200 (Tue, 01 Apr 2008) | 1 line Fix a refleak ................ r62088 | neal.norwitz | 2008-04-01 09:38:41 +0200 (Tue, 01 Apr 2008) | 1 line Be more forgiving if we get an error, there are lots of potential socket errors ................ r62089 | neal.norwitz | 2008-04-01 10:08:09 +0200 (Tue, 01 Apr 2008) | 2 lines Fix refleak with nested classes. Fix originally by Amaury in r62015. ................ r62093 | amaury.forgeotdarc | 2008-04-01 23:23:34 +0200 (Tue, 01 Apr 2008) | 5 lines Prevent test_queue from leaking: one worker thread was not stopped. The version in trunk/ is correct; the problem with 3.0 is that None cannot be used as a marker in a PriorityQueue, because it cannot be compared with ints. ................ r62101 | benjamin.peterson | 2008-04-02 04:27:22 +0200 (Wed, 02 Apr 2008) | 27 lines Blocked revisions 62095,62099 via svnmerge ........ r62095 | amaury.forgeotdarc | 2008-04-01 17:37:33 -0500 (Tue, 01 Apr 2008) | 5 lines Fix and enable a skipped test: with python 2.6, enumerating bytes yields 1-char strings, not numbers. Don't merge this into the py3k branch. ........ r62099 | amaury.forgeotdarc | 2008-04-01 19:25:14 -0500 (Tue, 01 Apr 2008) | 14 lines Correct the apparent refleak in test_io: When cls is an ABCMeta, every call to isinstance(x, cls) records type(x) in the cls._abc_cache of cls_abc_negative_cache. So we clear these caches at the end of the test. inspect.isabstract() is not the correct test for all ABCs, because there is no @abstractmethod in io.py (why?) isinstance(cls, ABCMeta) would be more exact, but it fails with an infinite recursion. So I used a hack to determine whether a class is an ABCMeta. The true correction would be to turn cls._abc_cache &co into a WeakSet, as py3k does. But classic classes are not weak referenceable... Of course, this change should not be merged into the py3k branch. ........ ................ r62104 | neal.norwitz | 2008-04-02 09:06:14 +0200 (Wed, 02 Apr 2008) | 9 lines Blocked revisions 62103 via svnmerge ........ r62103 | neal.norwitz | 2008-04-01 22:54:27 -0700 (Tue, 01 Apr 2008) | 3 lines Apply same patch from 3k branch to try and prevent this test from hanging on various platforms, most recently the Alpha Tru64. ........ ................ r62106 | trent.nelson | 2008-04-02 17:06:49 +0200 (Wed, 02 Apr 2008) | 9 lines Merged revisions 62105 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62105 | trent.nelson | 2008-04-02 16:01:00 +0100 (Wed, 02 Apr 2008) | 1 line Update information pertaining to building external components, as well as notes on x64 builds. This file now accurately describes the build process as is; however, there's still a lot of room for improvement, especially with regards to how we build Tcl/Tk, Tix, and OpenSSL. Watch this space for further improvements. ........ ................ r62115 | benjamin.peterson | 2008-04-02 23:21:29 +0200 (Wed, 02 Apr 2008) | 9 lines Blocked revisions 62097 via svnmerge ........ r62097 | guido.van.rossum | 2008-04-01 18:57:36 -0500 (Tue, 01 Apr 2008) | 3 lines Remove the advertising clause from the BSD license in timing.h. I have the email trail to prove that George Neville-Neil approved this. ........ ................ r62116 | benjamin.peterson | 2008-04-02 23:49:44 +0200 (Wed, 02 Apr 2008) | 52 lines Merged revisions 62090-62091,62096,62100,62102,62110-62114 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62090 | brett.cannon | 2008-04-01 07:37:43 -0500 (Tue, 01 Apr 2008) | 3 lines Generalize test.test_support.test_stdout() with a base context manager so that it is easy to capture stderr if desired. ........ r62091 | brett.cannon | 2008-04-01 07:46:02 -0500 (Tue, 01 Apr 2008) | 3 lines Add ``if __name__ == '__main__'`` to some test files where it didn't take a lot of effort to do so. ........ r62096 | amaury.forgeotdarc | 2008-04-01 17:52:48 -0500 (Tue, 01 Apr 2008) | 4 lines Newly enabled test appears to leak: it registers the same codec on each iteration. Do it only once at load time. ........ r62100 | amaury.forgeotdarc | 2008-04-01 19:55:04 -0500 (Tue, 01 Apr 2008) | 4 lines A DocTestSuite cannot run multiple times: it clears its globals dictionary after the first run. Rebuild the DocTestSuite on each iteration. ........ r62102 | jeffrey.yasskin | 2008-04-01 23:07:44 -0500 (Tue, 01 Apr 2008) | 3 lines Try to make test_signal less flaky. I still see some flakiness in test_itimer_prof. ........ r62110 | vinay.sajip | 2008-04-02 16:09:27 -0500 (Wed, 02 Apr 2008) | 1 line Fix: #2315, #2316, #2317: TimedRotatingFileHandler - changed logic to better handle daylight savings time, deletion of old log files, and fixed a bug in calculating rollover when no logging occurs for a longer interval than the rollover period. ........ r62111 | vinay.sajip | 2008-04-02 16:10:23 -0500 (Wed, 02 Apr 2008) | 1 line Added updates with respect to recent changes to TimedRotatingFileHandler. ........ r62112 | vinay.sajip | 2008-04-02 16:17:25 -0500 (Wed, 02 Apr 2008) | 1 line Added updates with respect to recent changes to TimedRotatingFileHandler. ........ r62113 | amaury.forgeotdarc | 2008-04-02 16:18:46 -0500 (Wed, 02 Apr 2008) | 2 lines Remove debug prints; the buildbot now passes the tests ........ r62114 | benjamin.peterson | 2008-04-02 16:20:35 -0500 (Wed, 02 Apr 2008) | 2 lines Suggested proposed changes to Python be considered on some mailing lists first ........ ................ r62117 | benjamin.peterson | 2008-04-03 00:44:10 +0200 (Thu, 03 Apr 2008) | 2 lines Fixed NEWS due to my bad merging skills ................ r62118 | barry.warsaw | 2008-04-03 00:51:13 +0200 (Thu, 03 Apr 2008) | 2 lines release.py wants to rename the spec file. ................ r62119 | barry.warsaw | 2008-04-03 01:33:27 +0200 (Thu, 03 Apr 2008) | 2 lines release.py induced and manual editing steps for 3.0a4. ................ r62125 | barry.warsaw | 2008-04-03 06:13:12 +0200 (Thu, 03 Apr 2008) | 1 line Post tag version tweak ................ r62128 | benjamin.peterson | 2008-04-03 18:27:27 +0200 (Thu, 03 Apr 2008) | 2 lines #2541 Allow unicode escapes in raw strings ................ r62130 | trent.nelson | 2008-04-03 20:39:00 +0200 (Thu, 03 Apr 2008) | 25 lines [XXX: this is a temporary block, given the addition/deletion of new files I'll unblock and merge it to py3k myself once I've observed trunk buildbots' behaviour.] Blocked revisions 62129 via svnmerge ........ r62129 | trent.nelson | 2008-04-03 19:27:06 +0100 (Thu, 03 Apr 2008) | 16 lines Reimplement kill_python. The existing version had a number of flaws, namely, it didn't work for x64 and it wasn't precise about which python_d.exe it was killing -- it just killed the first one it came across that happened to have 'pcbuild\python_d.exe' or 'build\python_d.exe' in it's path. The new version has been rewritten from the ground up and now lives in PCbuild, instead of Tools\buildbot, and it has also been incorporated into the Visual Studio solution (pcbuild.sln) as 'kill_python'. The solution has also been altered such that kill_python is called where necessary in the build process in order to prevent any linking errors due to open file locks. In lieu of this, all of the existing bits and pieces in Tools\buildbot that called out to kill_python at various points have also been removed as they are now obsolete. Tested on both Win32 and x64. Change set (included to improve usefulness of svnmerge log entry): M PCbuild\pythoncore.vcproj M PCbuild\pcbuild.sln M PCbuild\release.vsprops A PCbuild\kill_python.vcproj M PCbuild\debug.vsprops A PCbuild\kill_python.c D Tools\buildbot\kill_python.bat D Tools\buildbot\kill_python.mak M Tools\buildbot\build.bat D Tools\buildbot\Makefile M Tools\buildbot\build-amd64.bat M Tools\buildbot\buildmsi.bat D Tools\buildbot\kill_python.c ........ ................ r62132 | benjamin.peterson | 2008-04-03 21:48:41 +0200 (Thu, 03 Apr 2008) | 12 lines Blocked revisions 62123,62126 via svnmerge ........ r62123 | barry.warsaw | 2008-04-02 23:10:02 -0500 (Wed, 02 Apr 2008) | 2 lines Updating for 2.6a2 ........ r62126 | barry.warsaw | 2008-04-02 23:14:19 -0500 (Wed, 02 Apr 2008) | 1 line Post tag version tweak ........ ................ r62134 | trent.nelson | 2008-04-03 22:44:03 +0200 (Thu, 03 Apr 2008) | 1 line Unblock revision 62129. ................ r62135 | trent.nelson | 2008-04-03 22:47:30 +0200 (Thu, 03 Apr 2008) | 32 lines Merged revisions 62129,62131,62133 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62129 | trent.nelson | 2008-04-03 19:27:06 +0100 (Thu, 03 Apr 2008) | 16 lines Reimplement kill_python. The existing version had a number of flaws, namely, it didn't work for x64 and it wasn't precise about which python_d.exe it was killing -- it just killed the first one it came across that happened to have 'pcbuild\python_d.exe' or 'build\python_d.exe' in it's path. The new version has been rewritten from the ground up and now lives in PCbuild, instead of Tools\buildbot, and it has also been incorporated into the Visual Studio solution (pcbuild.sln) as 'kill_python'. The solution has also been altered such that kill_python is called where necessary in the build process in order to prevent any linking errors due to open file locks. In lieu of this, all of the existing bits and pieces in Tools\buildbot that called out to kill_python at various points have also been removed as they are now obsolete. Tested on both Win32 and x64. Change set (included to improve usefulness of svnmerge log entry): M PCbuild\pythoncore.vcproj M PCbuild\pcbuild.sln M PCbuild\release.vsprops A PCbuild\kill_python.vcproj M PCbuild\debug.vsprops A PCbuild\kill_python.c D Tools\buildbot\kill_python.bat D Tools\buildbot\kill_python.mak M Tools\buildbot\build.bat D Tools\buildbot\Makefile M Tools\buildbot\build-amd64.bat M Tools\buildbot\buildmsi.bat D Tools\buildbot\kill_python.c ........ r62131 | trent.nelson | 2008-04-03 19:48:53 +0100 (Thu, 03 Apr 2008) | 1 line Add the correct OutputFile values for debug builds. Fixes r62129's commit. ........ r62133 | trent.nelson | 2008-04-03 21:00:08 +0100 (Thu, 03 Apr 2008) | 1 line Make kill_python a little more forgiving if it can't obtain a snapshot of module information for a given python[_d].exe process. Failing here was too pessimistic; the python[_d].exe process may be owned by another user, which is the case in some buildbot environments. ........ ................ r62139 | barry.warsaw | 2008-04-04 03:36:36 +0200 (Fri, 04 Apr 2008) | 1 line post release updates ................ r62140 | benjamin.peterson | 2008-04-04 04:31:12 +0200 (Fri, 04 Apr 2008) | 8 lines Blocked revisions 62138 via svnmerge ........ r62138 | barry.warsaw | 2008-04-03 20:34:41 -0500 (Thu, 03 Apr 2008) | 1 line post release updates ........ ................ r62144 | thomas.heller | 2008-04-04 10:37:59 +0200 (Fri, 04 Apr 2008) | 8 lines Blocked revisions 62143 via svnmerge ........ r62143 | thomas.heller | 2008-04-04 10:35:44 +0200 (Fr, 04 Apr 2008) | 1 line Issue #2543: Make ctypes compatible (again) with Python 2.3, 2.4, and 2.5. ........ ................ r62146 | thomas.heller | 2008-04-04 12:18:23 +0200 (Fri, 04 Apr 2008) | 10 lines Merged revisions 62145 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62145 | thomas.heller | 2008-04-04 12:07:55 +0200 (Fri, 04 Apr 2008) | 3 lines Issue #2544: On HP-UX systems, use 'gcc -shared' for linking when gcc is used as compiler. ........ ................ r62155 | thomas.heller | 2008-04-04 21:53:14 +0200 (Fri, 04 Apr 2008) | 10 lines Merged revisions 62149, 62153, 62154 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk Sync with files from the just released libffi 3.0.5 version. More files from libffi 3.0.5. Removed libffi.pc.in because it is not needed for ctypes. News entry for: Sync with files from the just released libffi 3.0.5 version. ................ r62157 | amaury.forgeotdarc | 2008-04-05 01:25:27 +0200 (Sat, 05 Apr 2008) | 8 lines Issue2221: in Idle, exec('xx') raised a SystemError('error return without exception set') instead of the expected NameError This happens when sys.stdout is redirected to something that cannot flush(). the flush_io() function must be exception-neutral: don't raise, and don't clear exceptions. Next step: exec() is not supposed to flush sys.stdout... ................ r62162 | neal.norwitz | 2008-04-05 06:47:45 +0200 (Sat, 05 Apr 2008) | 72 lines Merged revisions 61440-61441,61443,61445-61448,61451-61452,61455-61457,61459-61464,61466-61467,61469-61470,61476-61477,61479,61481-61482,61485,61487,61490,61493-61494,61497,61499-61502,61505-61506,61508,61511-61514,61519,61521-61522,61530-61531,61533-61537,61541-61555,61557-61558,61561-61562,61566-61569,61572-61574,61578-61579,61583-61584,61588-61589,61592,61594,61598-61601,61603-61604,61607-61612,61617,61619-61620,61624,61626,61628-61630,61635-61638,61640-61643,61645,61648,61653-61655,61659-61662,61664,61666,61668-61671,61673,61675,61679-61680,61682,61685-61686,61689-61695,61697-61699,61701-61703,61706,61710,61713,61717,61723,61726-61730,61736,61738,61740,61742,61745-61752,61754-61760,61762-61764,61768,61770-61772,61774-61775,61784-61787,61789-61792,61794-61795,61797-61806,61808-61809,61811-61812,61814-61819,61824,61826-61833,61835-61840,61843-61845,61848,61850,61854-61862,61865-61866,61868,61872-61873,61876-61877,61883-61888,61890-61891,61893-61899,61901-61903,61905-61912,61914,61917,61920-61921,61927,61930,61932-61934,61939,61941-61942,61944-61951,61955,61960-61963,61980,61982-61983,61991,61994-61996,62001-62003,62008-62010,62016-62017,62022,62024,62027,62031-62034,62041,62045-62046,62055-62058,62060-62066,62068-62074,62076-62079,62081-62083,62086-62089,62092-62094,62098,62101,62104,62106-62109,62115-62122,62124-62125,62127-62128,62130,62132,62134-62137,62139-62142,62144,62146-62148,62150-62152,62155-62161 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62127 | trent.nelson | 2008-04-03 08:39:17 -0700 (Thu, 03 Apr 2008) | 1 line Remove the building of Berkeley DB step; _bsddb44.vcproj takes care of this for us now. ........ r62136 | amaury.forgeotdarc | 2008-04-03 16:07:55 -0700 (Thu, 03 Apr 2008) | 9 lines #1733757: the interpreter would hang on shutdown, if the function set by sys.settrace calls threading.currentThread. The correction somewhat improves the code, but it was close. Many thanks to the "with" construct, which turns python code into C calls. I wonder if it is not better to sys.settrace(None) just after running the __main__ module and before finalization. ........ r62141 | jeffrey.yasskin | 2008-04-03 21:51:19 -0700 (Thu, 03 Apr 2008) | 5 lines Doh! os.read() raises an OSError, not an IOError when it's interrupted. And fix some flakiness in test_itimer_prof, which could detect that the timer had reached 0 before the signal arrived announcing that fact. ........ r62142 | fred.drake | 2008-04-03 22:41:30 -0700 (Thu, 03 Apr 2008) | 4 lines - Issue #2385: distutils.core.run_script() makes __file__ available, so the controlled environment will more closely mirror the typical script environment. This supports setup.py scripts that refer to data files. ........ r62147 | fred.drake | 2008-04-04 04:31:14 -0700 (Fri, 04 Apr 2008) | 6 lines my previous change did what I said it should not: it changed the current directory to the directory in which the setup.py script lived (which made __file__ wrong) fixed, with test that the script is run in the current directory of the caller ........ r62148 | fred.drake | 2008-04-04 04:38:51 -0700 (Fri, 04 Apr 2008) | 2 lines stupid, stupid, stupid! ........ r62150 | jeffrey.yasskin | 2008-04-04 09:48:19 -0700 (Fri, 04 Apr 2008) | 2 lines Oops again. EINTR is in errno, not signal. ........ r62158 | andrew.kuchling | 2008-04-04 19:42:20 -0700 (Fri, 04 Apr 2008) | 1 line Minor edits ........ r62159 | andrew.kuchling | 2008-04-04 19:47:07 -0700 (Fri, 04 Apr 2008) | 1 line Markup fix; explain what interval timers do; typo fix ........ r62160 | andrew.kuchling | 2008-04-04 20:38:39 -0700 (Fri, 04 Apr 2008) | 1 line Various edits ........ r62161 | neal.norwitz | 2008-04-04 21:26:31 -0700 (Fri, 04 Apr 2008) | 9 lines Prevent test_sqlite from hanging on older versions of sqlite. The problem is that when trying to do the second insert, sqlite seems to sleep for a very long time. Here is the output from strace: read(6, "SQLite format 3\0\4\0\1\1\0@ \0\0\0\1\0\0\0\0"..., 1024) = 1024 nanosleep({4294, 966296000}, I don't know which version this was fixed in, but 3.2.1 definitely fails. ........ ................ r62163 | neal.norwitz | 2008-04-05 08:16:50 +0200 (Sat, 05 Apr 2008) | 3 lines Change \u which is causing a syntax error. I'm not sure if that should be, but at least this should let the build get farther on amd64 machines. ................ r62165 | benjamin.peterson | 2008-04-05 16:49:54 +0200 (Sat, 05 Apr 2008) | 2 lines Reverted r62128 on Guido's orders ................ r62166 | benjamin.peterson | 2008-04-05 17:09:30 +0200 (Sat, 05 Apr 2008) | 2 lines Added a test to make sure raw strings don't get unicode escapes ................ r62172 | georg.brandl | 2008-04-05 19:37:09 +0200 (Sat, 05 Apr 2008) | 2 lines ceil and floor return ints in 3k. ................ r62175 | martin.v.loewis | 2008-04-05 20:58:09 +0200 (Sat, 05 Apr 2008) | 29 lines Merged revisions 61440-61441,61443,61445-61448,61451-61452,61455-61457,61459-61464,61466-61467,61469-61470,61476-61477,61479,61481-61482,61485,61487,61490,61493-61494,61497,61499-61502,61505-61506,61508,61511-61514,61519,61521-61522,61530-61531,61533-61537,61541-61555,61557-61558,61561-61562,61566-61569,61572-61574,61578-61579,61583-61584,61588-61589,61592,61594,61598-61601,61603-61604,61607-61612,61617,61619-61620,61624,61626,61628-61630,61635-61638,61640-61643,61645,61648,61653-61655,61659-61662,61664,61666,61668-61671,61673,61675,61679-61680,61682,61685-61686,61689-61695,61697-61699,61701-61703,61706,61710,61713,61717,61723,61726-61730,61736,61738,61740,61742,61745-61752,61754-61760,61762-61764,61768,61770-61772,61774-61775,61784-61787,61789-61792,61794-61795,61797-61806,61808-61809,61811-61812,61814-61819,61824,61826-61833,61835-61840,61843-61845,61848,61850,61854-61862,61865-61866,61868,61872-61873,61876-61877,61883-61888,61890-61891,61893-61899,61901-61903,61905-61912,61914,61917,61920-61921,61927,61930,61932-61934,61939,61941-61942,61944-61951,61955,61960-61963,61980,61982-61983,61991,61994-61996,62001-62003,62008-62010,62016-62017,62022,62024,62027,62031-62034,62041,62045-62046,62055-62058,62060-62066,62068-62074,62076-62079,62081-62083,62086-62089,62092-62094,62098,62101,62104,62106-62109,62115-62122,62124-62125,62128,62130,62132,62134-62135,62137,62139-62140,62144,62146,62151,62155,62157,62162-62174 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62167 | martin.v.loewis | 2008-04-05 17:45:25 +0200 (Sa, 05 Apr 2008) | 1 line Extend sizes of various fields, to support the CRT90 merge module. ........ r62168 | martin.v.loewis | 2008-04-05 17:48:36 +0200 (Sa, 05 Apr 2008) | 1 line Add two features to distinguish between private and SxS CRT. ........ r62169 | martin.v.loewis | 2008-04-05 17:50:58 +0200 (Sa, 05 Apr 2008) | 1 line Add script to merge msvcr90. ........ r62170 | andrew.kuchling | 2008-04-05 17:57:46 +0200 (Sa, 05 Apr 2008) | 1 line Markup fixes; write PEP 3118 section ........ r62173 | georg.brandl | 2008-04-05 19:45:58 +0200 (Sa, 05 Apr 2008) | 2 lines Mention that the tuple returned by __reduce__ is pickled as normal. ........ r62174 | andrew.kuchling | 2008-04-05 20:15:30 +0200 (Sa, 05 Apr 2008) | 1 line Write PEP 3119 section ........ ................ r62176 | martin.v.loewis | 2008-04-05 21:47:23 +0200 (Sat, 05 Apr 2008) | 3 lines Remove baseName argument from Tkapp_New, as it apparently isn't used anymore. ................ r62178 | martin.v.loewis | 2008-04-05 22:41:37 +0200 (Sat, 05 Apr 2008) | 3 lines Change command line processing API to use wchar_t. Fixes #2128. ................ r62181 | georg.brandl | 2008-04-06 10:39:37 +0200 (Sun, 06 Apr 2008) | 2 lines #2558: document pickle protocol version 3. Thanks to Guilherme Polo. ................ r62185 | benjamin.peterson | 2008-04-06 18:47:13 +0200 (Sun, 06 Apr 2008) | 2 lines fix typo in doc string ................ r62190 | martin.v.loewis | 2008-04-06 19:57:16 +0200 (Sun, 06 Apr 2008) | 2 lines Convert another %s to %ls. ................ r62192 | georg.brandl | 2008-04-06 22:27:02 +0200 (Sun, 06 Apr 2008) | 2 lines Docstring fix. ................ r62196 | thomas.wouters | 2008-04-07 02:25:59 +0200 (Mon, 07 Apr 2008) | 16 lines Merged revisions 62179 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62179 | thomas.wouters | 2008-04-06 01:39:15 +0200 (Sun, 06 Apr 2008) | 10 lines Fix test_distutils to not fail when running 'make test' from a Python build directory that is not the source directory (ie, one created using '/path/to/source/configure'.) Leaves this test very slightly degraded in that particular case, compared to the build-in-sourcedir case, but that case isn't a particularly strong test either: neither test the actual path that will be used after installing. There isn't a particularly good way to test this, and a poor test beats a failing test. ........ ................ r62200 | martin.v.loewis | 2008-04-07 05:17:54 +0200 (Mon, 07 Apr 2008) | 23 lines Merged revisions 62177-62178,62180-62193 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62177 | skip.montanaro | 2008-04-05 21:47:47 +0200 (Sa, 05 Apr 2008) | 2 lines Declare inittimezone static. ........ r62180 | mark.hammond | 2008-04-06 03:42:06 +0200 (So, 06 Apr 2008) | 4 lines From issue 1753245 - better _winreg support for x64. Adds _winreg.DisableReflectionKey, EnableReflectionKey, QueryReflectionKey, KEY_WOW64_64KEY and KEY_WOW64_32KEY. ........ r62187 | skip.montanaro | 2008-04-06 19:05:57 +0200 (So, 06 Apr 2008) | 1 line type ........ r62193 | trent.nelson | 2008-04-06 22:51:23 +0200 (So, 06 Apr 2008) | 1 line Don't run kill_python as part of the build process. Change the buildbots so they have to call it explicitly instead. ........ ................ r62201 | martin.v.loewis | 2008-04-07 05:22:07 +0200 (Mon, 07 Apr 2008) | 9 lines Merged revisions 62199 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62199 | martin.v.loewis | 2008-04-07 05:08:28 +0200 (Mo, 07 Apr 2008) | 2 lines Bug #2388: Fix gcc warnings when compiling with --enable-unicode=ucs4. ........ ................ r62203 | martin.v.loewis | 2008-04-07 07:43:42 +0200 (Mon, 07 Apr 2008) | 3 lines Bug #2565: The repr() of type objects now calls them 'class', not 'type' - whether they are builtin types or not. ................ r62211 | martin.v.loewis | 2008-04-07 18:44:13 +0200 (Mon, 07 Apr 2008) | 1 line Add uuids for 3.0a4 and 3.0a5. ................ r62213 | guido.van.rossum | 2008-04-07 20:37:41 +0200 (Mon, 07 Apr 2008) | 5 lines "make install" is now an alias for "make altinstall", to prevent accidentally overwriting a Python 2.x installation. Use "make fullinstall" to force Python 3.0 to be installed as "python". ................ r62216 | georg.brandl | 2008-04-07 21:17:06 +0200 (Mon, 07 Apr 2008) | 2 lines #2567: remove new-style/old-style class docs. ................ r62217 | martin.v.loewis | 2008-04-07 23:14:19 +0200 (Mon, 07 Apr 2008) | 22 lines Merged revisions 62207-62210 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62207 | martin.v.loewis | 2008-04-07 16:53:34 +0200 (Mo, 07 Apr 2008) | 1 line Delete ALLUSERS property merged from CRT merge module, so that per-user installations become possible again. ........ r62208 | martin.v.loewis | 2008-04-07 16:54:16 +0200 (Mo, 07 Apr 2008) | 1 line Make private_crt feature object a global variable. ........ r62209 | martin.v.loewis | 2008-04-07 16:55:53 +0200 (Mo, 07 Apr 2008) | 1 line Drop support for 7.1 CRT. ........ r62210 | martin.v.loewis | 2008-04-07 18:34:04 +0200 (Mo, 07 Apr 2008) | 2 lines Make the "private CRT" case work, by editing the manifest in DLLs to refer to the root copy of the CRT. ........ ................ r62218 | benjamin.peterson | 2008-04-08 00:27:34 +0200 (Tue, 08 Apr 2008) | 2 lines fixed outdated annotation of readinto in io ................ r62222 | christian.heimes | 2008-04-08 11:44:14 +0200 (Tue, 08 Apr 2008) | 16 lines Blocked revisions 62195 via svnmerge ........ r62195 | gregory.p.smith | 2008-04-07 01:11:17 +0200 (Mon, 07 Apr 2008) | 10 lines Make file objects as thread safe as the underlying libc FILE* implementation. close() will now raise an IOError if any operations on the file object are currently in progress in other threads. Most code was written by Antoine Pitrou (pitrou). Additional testing, documentation and test suite cleanup done by me (gregory.p.smith). Fixes issue 815646 and 595601 (as well as many other bugs and references to this problem dating back to the dawn of Python). ........ ................ r62224 | martin.v.loewis | 2008-04-08 18:53:25 +0200 (Tue, 08 Apr 2008) | 9 lines Tentatively Blocked revisions 62223 via svnmerge, as compilation of py3_ should work in py3k. ........ r62223 | martin.v.loewis | 2008-04-08 18:48:35 +0200 (Di, 08 Apr 2008) | 1 line Suppress compilation of py3_ files upon installation. ........ ................ r62225 | martin.v.loewis | 2008-04-08 19:17:46 +0200 (Tue, 08 Apr 2008) | 2 lines Suppress compilation of lib2to3 py2_ test files. ................ r62240 | georg.brandl | 2008-04-09 09:32:07 +0200 (Wed, 09 Apr 2008) | 2 lines Clarify xrange() entry. ................ r62241 | georg.brandl | 2008-04-09 09:33:01 +0200 (Wed, 09 Apr 2008) | 2 lines More docstring fixes, and an XXX. ................ r62242 | christian.heimes | 2008-04-09 10:37:03 +0200 (Wed, 09 Apr 2008) | 136 lines Merged revisions 62194,62197-62198,62204-62205,62214,62219-62221,62227,62229-62231,62233-62235,62237-62239 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62194 | jeffrey.yasskin | 2008-04-07 01:04:28 +0200 (Mon, 07 Apr 2008) | 7 lines Add enough debugging information to diagnose failures where the HandlerBException is ignored, and fix one such problem, where it was thrown during the __del__ method of the previous Popen object. We may want to find a better way of printing verbose information so it's not spammy when the test passes. ........ r62197 | mark.hammond | 2008-04-07 03:53:39 +0200 (Mon, 07 Apr 2008) | 2 lines Issue #2513: enable 64bit cross compilation on windows. ........ r62198 | mark.hammond | 2008-04-07 03:59:40 +0200 (Mon, 07 Apr 2008) | 2 lines correct heading underline for new "Cross-compiling on Windows" section ........ r62204 | gregory.p.smith | 2008-04-07 08:33:21 +0200 (Mon, 07 Apr 2008) | 4 lines Use the new PyFile_IncUseCount & PyFile_DecUseCount calls appropriatly within the standard library. These modules use PyFile_AsFile and later release the GIL while operating on the previously returned FILE*. ........ r62205 | mark.summerfield | 2008-04-07 09:39:23 +0200 (Mon, 07 Apr 2008) | 4 lines changed "2500 components" to "several thousand" since the number keeps growning:-) ........ r62214 | georg.brandl | 2008-04-07 20:51:59 +0200 (Mon, 07 Apr 2008) | 2 lines #2525: update timezone info examples in the docs. ........ r62219 | andrew.kuchling | 2008-04-08 01:57:07 +0200 (Tue, 08 Apr 2008) | 1 line Write PEP 3127 section; add items ........ r62220 | andrew.kuchling | 2008-04-08 01:57:21 +0200 (Tue, 08 Apr 2008) | 1 line Typo fix ........ r62221 | andrew.kuchling | 2008-04-08 03:33:10 +0200 (Tue, 08 Apr 2008) | 1 line Typographical fix: 32bit -> 32-bit, 64bit -> 64-bit ........ r62227 | andrew.kuchling | 2008-04-08 23:22:53 +0200 (Tue, 08 Apr 2008) | 1 line Add items ........ r62229 | amaury.forgeotdarc | 2008-04-08 23:27:42 +0200 (Tue, 08 Apr 2008) | 7 lines Issue2564: Prevent a hang in "import test.autotest", which runs the entire test suite as a side-effect of importing the module. - in test_capi, a thread tried to import other modules - re.compile() imported sre_parse again on every call. ........ r62230 | amaury.forgeotdarc | 2008-04-08 23:51:57 +0200 (Tue, 08 Apr 2008) | 2 lines Prevent an error when inspect.isabstract() is called with something else than a new-style class. ........ r62231 | amaury.forgeotdarc | 2008-04-09 00:07:05 +0200 (Wed, 09 Apr 2008) | 8 lines Issue 2408: remove the _types module It was only used as a helper in types.py to access types (GetSetDescriptorType and MemberDescriptorType), when they can easily be obtained with python code. These expressions even work with Jython. I don't know what the future of the types module is; (cf. discussion in http://bugs.python.org/issue1605 ) at least this change makes it simpler. ........ r62233 | amaury.forgeotdarc | 2008-04-09 01:10:07 +0200 (Wed, 09 Apr 2008) | 2 lines Add a NEWS entry for previous checkin ........ r62234 | trent.nelson | 2008-04-09 01:47:30 +0200 (Wed, 09 Apr 2008) | 37 lines - Issue #2550: The approach used by client/server code for obtaining ports to listen on in network-oriented tests has been refined in an effort to facilitate running multiple instances of the entire regression test suite in parallel without issue. test_support.bind_port() has been fixed such that it will always return a unique port -- which wasn't always the case with the previous implementation, especially if socket options had been set that affected address reuse (i.e. SO_REUSEADDR, SO_REUSEPORT). The new implementation of bind_port() will actually raise an exception if it is passed an AF_INET/SOCK_STREAM socket with either the SO_REUSEADDR or SO_REUSEPORT socket option set. Furthermore, if available, bind_port() will set the SO_EXCLUSIVEADDRUSE option on the socket it's been passed. This currently only applies to Windows. This option prevents any other sockets from binding to the host/port we've bound to, thus removing the possibility of the 'non-deterministic' behaviour, as Microsoft puts it, that occurs when a second SOCK_STREAM socket binds and accepts to a host/port that's already been bound by another socket. The optional preferred port parameter to bind_port() has been removed. Under no circumstances should tests be hard coding ports! test_support.find_unused_port() has also been introduced, which will pass a temporary socket object to bind_port() in order to obtain an unused port. The temporary socket object is then closed and deleted, and the port is returned. This method should only be used for obtaining an unused port in order to pass to an external program (i.e. the -accept [port] argument to openssl's s_server mode) or as a parameter to a server-oriented class that doesn't give you direct access to the underlying socket used. Finally, test_support.HOST has been introduced, which should be used for the host argument of any relevant socket calls (i.e. bind and connect). The following tests were updated to following the new conventions: test_socket, test_smtplib, test_asyncore, test_ssl, test_httplib, test_poplib, test_ftplib, test_telnetlib, test_socketserver, test_asynchat and test_socket_ssl. It is now possible for multiple instances of the regression test suite to run in parallel without issue. ........ r62235 | gregory.p.smith | 2008-04-09 02:25:17 +0200 (Wed, 09 Apr 2008) | 3 lines Fix zlib crash from zlib.decompressobj().flush(val) when val was not positive. It tried to allocate negative or zero memory. That fails. ........ r62237 | trent.nelson | 2008-04-09 02:34:53 +0200 (Wed, 09 Apr 2008) | 1 line Fix typo with regards to self.PORT shadowing class variables with the same name. ........ r62238 | andrew.kuchling | 2008-04-09 03:08:32 +0200 (Wed, 09 Apr 2008) | 1 line Add items ........ r62239 | jerry.seutter | 2008-04-09 07:07:58 +0200 (Wed, 09 Apr 2008) | 1 line Changed test so it no longer runs as a side effect of importing. ........ ................ r62251 | georg.brandl | 2008-04-09 20:40:09 +0200 (Wed, 09 Apr 2008) | 2 lines Remove __repr__ that doesn't have any advantage compared to the standard one. ................ r62252 | georg.brandl | 2008-04-09 20:40:51 +0200 (Wed, 09 Apr 2008) | 2 lines #2530: io module documentation. ................ r62253 | georg.brandl | 2008-04-09 20:45:14 +0200 (Wed, 09 Apr 2008) | 2 lines #2580: int() docs revision. ................ r62254 | georg.brandl | 2008-04-09 20:46:46 +0200 (Wed, 09 Apr 2008) | 2 lines #2575: bininteger missing in production list. ................ r62258 | benjamin.peterson | 2008-04-09 23:38:38 +0200 (Wed, 09 Apr 2008) | 2 lines zap the last of the class.method typos in io docs ................ r62264 | martin.v.loewis | 2008-04-10 04:50:50 +0200 (Thu, 10 Apr 2008) | 26 lines Merged revisions 62263 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ................ r62263 | martin.v.loewis | 2008-04-10 04:48:01 +0200 (Do, 10 Apr 2008) | 19 lines Merged revisions 62080-62262 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r62092 | collin.winter | 2008-04-01 18:27:10 +0200 (Di, 01 Apr 2008) | 1 line Add get_prev_sibling() to complement pytree's get_next_sibling(). ........ r62226 | collin.winter | 2008-04-08 21:07:56 +0200 (Di, 08 Apr 2008) | 1 line Add min() and max() to the list of special contexts that don't require adding list() calls around dict methods. ........ r62232 | collin.winter | 2008-04-09 00:12:38 +0200 (Mi, 09 Apr 2008) | 4 lines Fix for http://bugs.python.org/issue2596 This extends fix_xrange to know about the (mostly) same special contexts as fix_dict (where a special context is something that is guaranteed to fully consume the iterable), adding list() calls where appropriate. It also special-cases "x in range(y)". ........ ................ ................ r62265 | martin.v.loewis | 2008-04-10 05:06:53 +0200 (Thu, 10 Apr 2008) | 25 lines Merged revisions 62246-62259 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62246 | georg.brandl | 2008-04-09 19:57:38 +0200 (Mi, 09 Apr 2008) | 2 lines #2585: initialize code attribute of HTTPError. ........ r62247 | georg.brandl | 2008-04-09 19:58:56 +0200 (Mi, 09 Apr 2008) | 2 lines Add :issue: directive for easy linking to bugs.python.org. ........ r62249 | gregory.p.smith | 2008-04-09 20:18:43 +0200 (Mi, 09 Apr 2008) | 2 lines Add a note about the zlib.decompressobj().flush() fix. ........ r62255 | martin.v.loewis | 2008-04-09 20:56:20 +0200 (Mi, 09 Apr 2008) | 2 lines Package wininst*.exe from distutils/command. ........ r62259 | andrew.kuchling | 2008-04-10 00:28:43 +0200 (Do, 10 Apr 2008) | 1 line Try out the new issue role. Thanks, Georg! ........ ................ r62269 | trent.nelson | 2008-04-10 18:25:37 +0200 (Thu, 10 Apr 2008) | 1 line Issue 2440: fix the handling of %n in Python/getargs.c's convertsimple(), extend Objects/abstract.c's PyNumber_Index() to accept PyObjects that have nb_int slots, and update test_getargs2 to test that an exception is thrown when __int__() returns a non-int object. ................ r62270 | martin.v.loewis | 2008-04-10 21:02:25 +0200 (Thu, 10 Apr 2008) | 2 lines Bug #2606: Avoid calling .sort() on a dict_keys object. ................ r62273 | trent.nelson | 2008-04-10 22:12:06 +0200 (Thu, 10 Apr 2008) | 1 line Revert r62242: trunk's test_ssl.py isn't as up-to-date as py3k's, and should't have been brought over in the merge. ................ r62275 | trent.nelson | 2008-04-10 22:54:35 +0200 (Thu, 10 Apr 2008) | 1 line Update test_ssl.py to reflect the new approach for writing network-oriented tests in such a way that contention for ports is eliminated, thus allowing multiple instances of the same test to be run in parallel without issue (import for buildbots to run smoothly). This change is in line with the changes made to network-oriented tests in trunk in r62234. test_ssl.py is an odd case because the py3k version was newer than trunk. When the most recent svnmerge was run from trunk to py3k in r62242, the older trunk version was brought over on top of the newer py3k version. So, the plan was/is: revert the recent svnmerged version (done), manually make the changes to improve running in parallel (done with this commit), copy this version back to trunk and manually 3to2 it (to do next), check that in, then svnmerge block it. Then when future changes need to be made to test_ssl.py, we can make them against trunk, and hopefully the merge to py3k should be a lot less painful. ................ r62276 | amaury.forgeotdarc | 2008-04-10 23:03:09 +0200 (Thu, 10 Apr 2008) | 5 lines Add a NEWS entry for issue2221. Also don't flush stdout on each call to exec() or eval(). Only interactive input really needs it. ................ r62280 | trent.nelson | 2008-04-11 00:21:23 +0200 (Fri, 11 Apr 2008) | 1 line Fix change to PyNumber_Index() made in r62269, which incorrectly allowed floats to be interpreted as longs. Thanks to Benjamin Peterson for picking this up. ................ r62291 | benjamin.peterson | 2008-04-11 23:17:32 +0200 (Fri, 11 Apr 2008) | 2 lines Synced builtin open and io.open documentation, taking the best of each ................ r62292 | trent.nelson | 2008-04-12 01:02:37 +0200 (Sat, 12 Apr 2008) | 1 line Issue 2440: revert r62269 and r62279. These changes were made in an effort to fix test_args2.Signed_TestCase.test_n(), which was failing on Windows x64 on the following line: 'self.failUnlessEqual(99, getargs_n(Long()))'. Although the two commits *did* fix the test on Windows x64, it's become clear that it's the test that's incorrect, and the changes to PyNumber_Index() in particular were not warranted (and actually violate PEP 357). This commit will get us back to where we were at r62268, before I started butchering things. ................ r62301 | alexandre.vassalotti | 2008-04-12 23:40:56 +0200 (Sat, 12 Apr 2008) | 2 lines Removed unused variable. ................ r62307 | benjamin.peterson | 2008-04-13 02:27:46 +0200 (Sun, 13 Apr 2008) | 2 lines Fleshed out docstrings in the io module, improving the reST one as I went. ................ r62312 | benjamin.peterson | 2008-04-13 04:21:12 +0200 (Sun, 13 Apr 2008) | 12 lines Blocked revisions 62309-62310 via svnmerge ........ r62309 | benjamin.peterson | 2008-04-12 21:01:27 -0500 (Sat, 12 Apr 2008) | 2 lines Backported io module docs ........ r62310 | benjamin.peterson | 2008-04-12 21:05:48 -0500 (Sat, 12 Apr 2008) | 2 lines Backport the removal of a __repr__ from 62251 ........ ................ r62322 | christian.heimes | 2008-04-13 15:53:33 +0200 (Sun, 13 Apr 2008) | 133 lines Merged revisions 62260-62261,62266,62271,62277-62279,62289-62290,62293-62298,62302-62306,62308,62311,62313-62315,62319-62321 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62260 | gregory.p.smith | 2008-04-10 01:11:56 +0200 (Thu, 10 Apr 2008) | 2 lines better diagnostics ........ r62261 | gregory.p.smith | 2008-04-10 01:16:37 +0200 (Thu, 10 Apr 2008) | 3 lines Raise SystemError when size < 0 is passed into PyString_FromStringAndSize, PyBytes_FromStringAndSize or PyUnicode_FromStringAndSize. [issue2587] ........ r62266 | neal.norwitz | 2008-04-10 07:46:39 +0200 (Thu, 10 Apr 2008) | 5 lines Remove the test file before writing it in case there is no write permission. This might help fix some of the failures on Windows box(es). It doesn't hurt either way and ensure the tests are a little more self contained (ie have less assumptions). ........ r62271 | gregory.p.smith | 2008-04-10 21:50:36 +0200 (Thu, 10 Apr 2008) | 2 lines get rid of assert (size >= 0) now that an explicit if (size < 0) is in the code. ........ r62277 | andrew.kuchling | 2008-04-10 23:27:10 +0200 (Thu, 10 Apr 2008) | 1 line Remove forward-looking statement ........ r62278 | andrew.kuchling | 2008-04-10 23:28:51 +0200 (Thu, 10 Apr 2008) | 1 line Add punctuation ........ r62279 | andrew.kuchling | 2008-04-10 23:29:01 +0200 (Thu, 10 Apr 2008) | 1 line Use issue directive ........ r62289 | thomas.heller | 2008-04-11 15:05:38 +0200 (Fri, 11 Apr 2008) | 3 lines Move backwards compatibility macro to the correct place; PyIndex_Check() was introduced in Python 2.5. ........ r62290 | thomas.heller | 2008-04-11 16:20:26 +0200 (Fri, 11 Apr 2008) | 2 lines Performance improvements. ........ r62293 | christian.heimes | 2008-04-12 15:03:03 +0200 (Sat, 12 Apr 2008) | 2 lines Applied patch #2617 from Frank Wierzbicki wit some extras from me -J and -X are now reserved for Jython and non-standard arguments (e.g. IronPython). I've added some extra comments to make sure the reservation don't get missed in the future. ........ r62294 | georg.brandl | 2008-04-12 20:11:18 +0200 (Sat, 12 Apr 2008) | 2 lines Use absolute path in sys.path. ........ r62295 | georg.brandl | 2008-04-12 20:36:09 +0200 (Sat, 12 Apr 2008) | 2 lines #2615: small consistency update by Jeroen Ruigrok van der Werven. ........ r62296 | georg.brandl | 2008-04-12 21:00:20 +0200 (Sat, 12 Apr 2008) | 2 lines Add Jeroen. ........ r62297 | georg.brandl | 2008-04-12 21:05:37 +0200 (Sat, 12 Apr 2008) | 2 lines Don't offend snake lovers. ........ r62298 | gregory.p.smith | 2008-04-12 22:37:48 +0200 (Sat, 12 Apr 2008) | 2 lines fix compiler warnings ........ r62302 | gregory.p.smith | 2008-04-13 00:24:04 +0200 (Sun, 13 Apr 2008) | 3 lines socket.error inherits from IOError, it no longer needs listing in the all_errors tuple. ........ r62303 | brett.cannon | 2008-04-13 01:44:07 +0200 (Sun, 13 Apr 2008) | 8 lines Re-implement the 'warnings' module in C. This allows for usage of the 'warnings' code in places where it was previously not possible (e.g., the parser). It could also potentially lead to a speed-up in interpreter start-up if the C version of the code (_warnings) is imported over the use of the Python version in key places. Closes issue #1631171. ........ r62304 | gregory.p.smith | 2008-04-13 02:03:25 +0200 (Sun, 13 Apr 2008) | 3 lines Adds a profile-opt target for easy compilation of a python binary using gcc's profile guided optimization. ........ r62305 | brett.cannon | 2008-04-13 02:18:44 +0200 (Sun, 13 Apr 2008) | 3 lines Fix a bug in PySys_HasWarnOption() where it was not properly checking the length of the list storing the warning options. ........ r62306 | brett.cannon | 2008-04-13 02:25:15 +0200 (Sun, 13 Apr 2008) | 2 lines Fix an accidental bug of an non-existent init function. ........ r62308 | andrew.kuchling | 2008-04-13 03:05:59 +0200 (Sun, 13 Apr 2008) | 1 line Mention -J, -X ........ r62311 | benjamin.peterson | 2008-04-13 04:20:05 +0200 (Sun, 13 Apr 2008) | 2 lines Give the "Interactive Interpreter Changes" section in 2.6 whatsnew a unique link name ........ r62313 | brett.cannon | 2008-04-13 04:42:36 +0200 (Sun, 13 Apr 2008) | 3 lines Fix test_warnings by making the state of things more consistent for each test when it is run. ........ r62314 | skip.montanaro | 2008-04-13 05:17:30 +0200 (Sun, 13 Apr 2008) | 2 lines spelling ........ r62315 | georg.brandl | 2008-04-13 09:07:44 +0200 (Sun, 13 Apr 2008) | 2 lines Fix markup. ........ r62319 | christian.heimes | 2008-04-13 11:30:17 +0200 (Sun, 13 Apr 2008) | 1 line Fix compiler warning Include/warnings.h:19:28: warning: no newline at end of file ........ r62320 | christian.heimes | 2008-04-13 11:33:24 +0200 (Sun, 13 Apr 2008) | 1 line Use PyString_InternFromString instead of PyString_FromString for static vars ........ r62321 | christian.heimes | 2008-04-13 11:37:05 +0200 (Sun, 13 Apr 2008) | 1 line Added new files to the pcbuild files ........ ................ r62333 | benjamin.peterson | 2008-04-13 23:39:58 +0200 (Sun, 13 Apr 2008) | 2 lines A few io doc fixes ................ r62335 | benjamin.peterson | 2008-04-14 01:11:15 +0200 (Mon, 14 Apr 2008) | 9 lines Merged revisions 62332 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62332 | georg.brandl | 2008-04-13 15:51:27 -0500 (Sun, 13 Apr 2008) | 2 lines Check out Jinja as a separate step now that it's not included in the Sphinx package anymore. ........ ................ r62336 | benjamin.peterson | 2008-04-14 01:46:27 +0200 (Mon, 14 Apr 2008) | 2 lines Another io doc fix ................ r62337 | lars.gustaebel | 2008-04-14 12:05:48 +0200 (Mon, 14 Apr 2008) | 3 lines Issue #2058: Remove the buf attribute and add __slots__ to the TarInfo class in order to reduce tarfile's memory usage. ................ r62339 | thomas.heller | 2008-04-14 18:17:33 +0200 (Mon, 14 Apr 2008) | 10 lines Merged revisions 62338 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62338 | thomas.heller | 2008-04-14 18:10:07 +0200 (Mo, 14 Apr 2008) | 3 lines Issue #2616: Implement ctypes.pointer() and ctypes.POINTER() in C for better performance. ........ ................ r62342 | alexandre.vassalotti | 2008-04-14 22:51:05 +0200 (Mon, 14 Apr 2008) | 3 lines Improved bytes_extend() to avoid making a full copy of the temporary buffer. This also makes the code slightly cleaner. ................ r62343 | alexandre.vassalotti | 2008-04-14 22:53:13 +0200 (Mon, 14 Apr 2008) | 3 lines Re-indented bytes_getbuffer() and bytes_releasebuffer() to 4-space indents. ................ r62344 | benjamin.peterson | 2008-04-14 23:30:21 +0200 (Mon, 14 Apr 2008) | 2 lines Fix problems in the io docs noted by Alexandre Vassalotti ................ r62346 | alexandre.vassalotti | 2008-04-15 00:46:41 +0200 (Tue, 15 Apr 2008) | 9 lines Recorded merge of revisions 62345 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62345 | alexandre.vassalotti | 2008-04-14 18:40:08 -0400 (Mon, 14 Apr 2008) | 2 lines Backport manually r62342 from the py3k branch to the trunk. ........ ................ r62349 | neal.norwitz | 2008-04-15 08:43:13 +0200 (Tue, 15 Apr 2008) | 51 lines Merged revisions 61440-61441,61443,61445-61448,61451-61452,61455-61457,61459-61464,61466-61467,61469-61470,61476-61477,61479,61481-61482,61485,61487,61490,61493-61494,61497,61499-61502,61505-61506,61508,61511-61514,61519,61521-61522,61530-61531,61533-61537,61541-61555,61557-61558,61561-61562,61566-61569,61572-61574,61578-61579,61583-61584,61588-61589,61592,61594,61598-61601,61603-61604,61607-61612,61617,61619-61620,61624,61626,61628-61630,61635-61638,61640-61643,61645,61648,61653-61655,61659-61662,61664,61666,61668-61671,61673,61675,61679-61680,61682,61685-61686,61689-61695,61697-61699,61701-61703,61706,61710,61713,61717,61723,61726-61730,61736,61738,61740,61742,61745-61752,61754-61760,61762-61764,61768,61770-61772,61774-61775,61784-61787,61789-61792,61794-61795,61797-61806,61808-61809,61811-61812,61814-61819,61824,61826-61833,61835-61840,61843-61845,61848,61850,61854-61862,61865-61866,61868,61872-61873,61876-61877,61883-61888,61890-61891,61893-61899,61901-61903,61905-61912,61914,61917,61920-61921,61927,61930,61932-61934,61939,61941-61942,61944-61951,61955,61960-61963,61980,61982-61983,61991,61994-61996,62001-62003,62008-62010,62016-62017,62022,62024,62027,62031-62034,62041,62045-62046,62055-62058,62060-62066,62068-62074,62076-62079,62081-62083,62086-62089,62092-62094,62098,62101,62104,62106-62109,62115-62122,62124-62125,62128,62130,62132,62134-62135,62137,62139-62140,62144,62146,62151,62155,62157,62162-62166,62171-62172,62175-62176,62178,62181-62186,62188-62192,62196,62200-62203,62206,62211-62213,62215-62218,62222,62224-62226,62228,62232,62236,62240-62245,62248,62250-62254,62256-62258,62262,62264-62265,62267-62270,62272-62276,62280-62288,62291-62292,62299-62301,62307,62312,62316-62318,62322-62331,62333-62337,62339-62344,62346-62348 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62323 | brett.cannon | 2008-04-13 10:09:43 -0700 (Sun, 13 Apr 2008) | 3 lines Add an explicit check for output in a test to try to diagnose a failure on Windows. ........ r62324 | brett.cannon | 2008-04-13 10:41:31 -0700 (Sun, 13 Apr 2008) | 3 lines Fix spliting on colons on Windows machines with a file path by limiting the number of splits. ........ r62329 | benjamin.peterson | 2008-04-13 13:35:56 -0700 (Sun, 13 Apr 2008) | 2 lines #2627 Let it be known what pgen generates ........ r62330 | benjamin.peterson | 2008-04-13 13:40:03 -0700 (Sun, 13 Apr 2008) | 2 lines Added an ignore file for Bazaar #2510 ........ r62331 | georg.brandl | 2008-04-13 13:50:29 -0700 (Sun, 13 Apr 2008) | 2 lines Improve -X error message. ........ r62334 | andrew.kuchling | 2008-04-13 15:39:12 -0700 (Sun, 13 Apr 2008) | 1 line Add example ........ r62340 | amaury.forgeotdarc | 2008-04-14 12:55:40 -0700 (Mon, 14 Apr 2008) | 2 lines Update project files for all Windows supported compilers ........ r62341 | amaury.forgeotdarc | 2008-04-14 13:07:48 -0700 (Mon, 14 Apr 2008) | 6 lines Correct a refleak found by "regrtest.py -R:: test_structmembers" Some other minor updates in _warnings.c: - make a function static - rename a shadowing local variable ........ r62347 | andrew.kuchling | 2008-04-14 19:24:15 -0700 (Mon, 14 Apr 2008) | 1 line Various items; begin writing the SSL section ........ r62348 | neal.norwitz | 2008-04-14 20:46:21 -0700 (Mon, 14 Apr 2008) | 1 line Prevent namespace pollution, add static for internal functions ........ ................ r62356 | mark.dickinson | 2008-04-15 23:42:42 +0200 (Tue, 15 Apr 2008) | 8 lines PyLong_FromSsize_t was incorrect when sizeof(size_t) > sizeof(long); rewrite it so that it doesn't care about relative sizes of size_t, long and long long. The rewrite is modeled on PyLong_FromLong, instead of using PyLong_FromByteArray; this makes the algorithm simpler and more direct, and possibly also slightly faster. ................ r62360 | brett.cannon | 2008-04-17 06:21:10 +0200 (Thu, 17 Apr 2008) | 3 lines Have test_coding conditionally remove test files instead of assuming that they are always there. ................ r62384 | christian.heimes | 2008-04-19 02:31:39 +0200 (Sat, 19 Apr 2008) | 20 lines Merged revisions 62380,62382-62383 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62380 | christian.heimes | 2008-04-19 01:13:07 +0200 (Sat, 19 Apr 2008) | 3 lines I finally got the time to update and merge Mark's and my trunk-math branch. The patch is collaborated work of Mark Dickinson and me. It was mostly done a few months ago. The patch fixes a lot of loose ends and edge cases related to operations with NaN, INF, very small values and complex math. The patch also adds acosh, asinh, atanh, log1p and copysign to all platforms. Finally it fixes differences between platforms like different results or exceptions for edge cases. Have fun :) ........ r62382 | christian.heimes | 2008-04-19 01:40:40 +0200 (Sat, 19 Apr 2008) | 2 lines Added new files to Windows project files More Windows related fixes are coming soon ........ r62383 | christian.heimes | 2008-04-19 01:49:11 +0200 (Sat, 19 Apr 2008) | 1 line Stupid me. Py_RETURN_NAN should actually return something ... ........ ................ r62385 | christian.heimes | 2008-04-19 02:55:37 +0200 (Sat, 19 Apr 2008) | 87 lines Merged revisions 62350-62355,62358-62359,62364-62365,62370,62372-62375,62378-62379,62381 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62350 | nick.coghlan | 2008-04-15 12:25:31 +0200 (Tue, 15 Apr 2008) | 1 line Issue 2439: add pkgutils.get_data() as a convenience wrapper for the PEP 302 get_data() API (contributed by Paul Moore) ........ r62351 | nick.coghlan | 2008-04-15 12:28:14 +0200 (Tue, 15 Apr 2008) | 1 line Add test file missing from rev 62350 ........ r62352 | benjamin.peterson | 2008-04-15 13:58:46 +0200 (Tue, 15 Apr 2008) | 2 lines Add myself to Doc/ACKS.txt ........ r62353 | andrew.kuchling | 2008-04-15 15:10:07 +0200 (Tue, 15 Apr 2008) | 6 lines Add *,**,@ to index, as suggested by http://farmdev.com/thoughts/24/what-does-the-def-star-variable-or-def-asterisk-parameter-syntax-do-in-python-/ The right entry type to use isn't clear; operator seems wrong, because *,**,@ aren't being used in expressions here. I put them as 'statement'; 'syntax' might be better. ........ r62354 | andrew.kuchling | 2008-04-15 15:10:41 +0200 (Tue, 15 Apr 2008) | 1 line Typo fix ........ r62355 | mark.dickinson | 2008-04-15 22:51:18 +0200 (Tue, 15 Apr 2008) | 3 lines Fix for possible signed overflow: the behaviour of -LONG_MIN is undefined in ANSI C. ........ r62358 | jeroen.ruigrok | 2008-04-16 14:47:01 +0200 (Wed, 16 Apr 2008) | 2 lines Reformat to 80 columns prior to adding documentation. ........ r62359 | jeroen.ruigrok | 2008-04-16 14:57:43 +0200 (Wed, 16 Apr 2008) | 2 lines Add details about the return value for mmap.flush(). ........ r62364 | raymond.hettinger | 2008-04-17 12:48:31 +0200 (Thu, 17 Apr 2008) | 1 line Issue 2648: Add leading zero to money format recipe in the docs. ........ r62365 | jeroen.ruigrok | 2008-04-17 14:39:45 +0200 (Thu, 17 Apr 2008) | 2 lines Be consistent in the use of read-only. ........ r62370 | andrew.kuchling | 2008-04-17 22:44:06 +0200 (Thu, 17 Apr 2008) | 1 line Typo fixes ........ r62372 | andrew.kuchling | 2008-04-18 04:40:47 +0200 (Fri, 18 Apr 2008) | 1 line Use correct parameter name ........ r62373 | andrew.kuchling | 2008-04-18 18:53:09 +0200 (Fri, 18 Apr 2008) | 1 line #2654: fix typo ........ r62374 | andrew.kuchling | 2008-04-18 20:28:23 +0200 (Fri, 18 Apr 2008) | 4 lines Remove personal note from Jim Roskind; it no longer applies, and the e-mail address is for a previous employer. Can we move the big long copyright statement into a sidebar or something? ........ r62375 | andrew.kuchling | 2008-04-18 20:39:55 +0200 (Fri, 18 Apr 2008) | 1 line Rewrite introductory section, and remove old section. (It was already commented-out, but why keep it?) ........ r62378 | skip.montanaro | 2008-04-18 22:35:46 +0200 (Fri, 18 Apr 2008) | 1 line resolve issue 2014 ........ r62379 | benjamin.peterson | 2008-04-18 22:45:33 +0200 (Fri, 18 Apr 2008) | 2 lines Fix indentation in sysmodule.c ........ r62381 | amaury.forgeotdarc | 2008-04-19 01:31:33 +0200 (Sat, 19 Apr 2008) | 3 lines Some tests did not pass on repeated calls (regrtest -R::) Perform additional cleanup, mostly deleting from sys.modules, or clearing the warnings registry. ........ ................ r62397 | benjamin.peterson | 2008-04-19 21:32:08 +0200 (Sat, 19 Apr 2008) | 2 lines the io module was added in 2.6 (I know not really, but the end user isn't going to care about backporting.) ................ r62399 | benjamin.peterson | 2008-04-19 21:38:00 +0200 (Sat, 19 Apr 2008) | 8 lines Blocked revisions 62398 via svnmerge ........ r62398 | benjamin.peterson | 2008-04-19 14:34:05 -0500 (Sat, 19 Apr 2008) | 2 lines Copy io documentation back from py3k branch so changes can be merged into it. ........ ................ r62405 | benjamin.peterson | 2008-04-19 23:24:29 +0200 (Sat, 19 Apr 2008) | 2 lines Reverted 62397; no versionadded/changed in 3.0 docs ................ r62411 | georg.brandl | 2008-04-20 00:18:33 +0200 (Sun, 20 Apr 2008) | 2 lines Remove duplicated reduce() entry. ................ r62422 | christian.heimes | 2008-04-20 23:01:16 +0200 (Sun, 20 Apr 2008) | 101 lines Merged revisions 62386-62387,62389-62393,62396,62400-62402,62407,62409-62410,62412-62414,62418-62419 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62386 | christian.heimes | 2008-04-19 04:23:57 +0200 (Sat, 19 Apr 2008) | 2 lines Added kill, terminate and send_signal to subprocess.Popen The bits and pieces for the Windows side were already in place. The POSIX side is trivial (as usual) and uses os.kill(). ........ r62387 | georg.brandl | 2008-04-19 10:23:59 +0200 (Sat, 19 Apr 2008) | 2 lines Fix-up docs for revision 62386. ........ r62389 | georg.brandl | 2008-04-19 18:57:43 +0200 (Sat, 19 Apr 2008) | 2 lines #2369: clarify that copyfile() doesn't take a target directory. ........ r62390 | georg.brandl | 2008-04-19 18:58:28 +0200 (Sat, 19 Apr 2008) | 2 lines #2634: clarify meaning of env parameter to spawn/exec*e. ........ r62391 | georg.brandl | 2008-04-19 18:58:49 +0200 (Sat, 19 Apr 2008) | 2 lines #2633: clarify meaning of env parameter. ........ r62392 | georg.brandl | 2008-04-19 18:59:16 +0200 (Sat, 19 Apr 2008) | 2 lines #2631: clarify IMPORT_NAME semantics. ........ r62393 | georg.brandl | 2008-04-19 19:00:14 +0200 (Sat, 19 Apr 2008) | 2 lines :func: et al. should *not* include the parens. ........ r62396 | mark.dickinson | 2008-04-19 20:51:48 +0200 (Sat, 19 Apr 2008) | 5 lines Additional tests for math.pow, and extra special-case handling code in math.pow, in the hope of making all tests pass on the alpha Tru64 buildbot. ........ r62400 | mark.dickinson | 2008-04-19 21:41:52 +0200 (Sat, 19 Apr 2008) | 3 lines Additional special-case handling for math.pow. Windows/VS2008 doesn't like (-1)**(+-inf). ........ r62401 | benjamin.peterson | 2008-04-19 21:47:34 +0200 (Sat, 19 Apr 2008) | 2 lines Complete documentation for errors argument of io's open and TextIOWrapper ........ r62402 | mark.dickinson | 2008-04-19 22:31:16 +0200 (Sat, 19 Apr 2008) | 2 lines Document updates to math and cmath modules. ........ r62407 | georg.brandl | 2008-04-19 23:28:38 +0200 (Sat, 19 Apr 2008) | 2 lines Update template for newest Sphinx. ........ r62409 | mark.dickinson | 2008-04-19 23:35:35 +0200 (Sat, 19 Apr 2008) | 5 lines Correct documentation for math.pow; 0**nan is nan, not 0. (But nan**0 and 1**nan are 1.) Also fix minor typo: 'quite NaN' -> 'quiet NaN' ........ r62410 | mark.dickinson | 2008-04-19 23:49:22 +0200 (Sat, 19 Apr 2008) | 4 lines Move asinh documentation to the proper place. Remove meaningless 'in radians' from inverse hyperbolic functions. ........ r62412 | mark.dickinson | 2008-04-20 03:22:30 +0200 (Sun, 20 Apr 2008) | 5 lines Report additional diagnostic information in test_math, to help track down debian-alpha buildbot failure. ........ r62413 | mark.dickinson | 2008-04-20 03:39:24 +0200 (Sun, 20 Apr 2008) | 3 lines FreeBSD doesn't follow C99 for modf(inf); so add explicit special-value handling to math.modf code. ........ r62414 | mark.dickinson | 2008-04-20 06:13:13 +0200 (Sun, 20 Apr 2008) | 5 lines Yet more explicit special case handling to make math.pow behave on alpha Tru64. All IEEE 754 special values are now handled directly; only the finite**finite case is handled by libm. ........ r62418 | mark.dickinson | 2008-04-20 18:13:17 +0200 (Sun, 20 Apr 2008) | 7 lines Issue 2662: Initialize special value tables dynamically (i.e. when cmath module is loaded) instead of statically. This fixes compile-time problems on platforms where HUGE_VAL is an extern variable rather than a constant. Thanks Hirokazu Yamamoto for the patch. ........ r62419 | andrew.kuchling | 2008-04-20 18:54:02 +0200 (Sun, 20 Apr 2008) | 1 line Move description of math module changes; various edits to description of cmath changes ........ ................ r62430 | mark.summerfield | 2008-04-21 12:29:45 +0200 (Mon, 21 Apr 2008) | 3 lines A lot of small detailed revisions to the io module's doc. ................ r62432 | benjamin.peterson | 2008-04-21 13:59:36 +0200 (Mon, 21 Apr 2008) | 8 lines Blocked revisions 62431 via svnmerge ........ r62431 | benjamin.peterson | 2008-04-21 06:57:40 -0500 (Mon, 21 Apr 2008) | 2 lines Moved io doc changes back ........ ................ r62433 | christian.heimes | 2008-04-21 15:08:03 +0200 (Mon, 21 Apr 2008) | 25 lines Merged revisions 62420-62421,62423-62424 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62420 | mark.dickinson | 2008-04-20 20:30:05 +0200 (Sun, 20 Apr 2008) | 3 lines Even more fixes for alpha Tru64, this time for the phase and polar methods. ........ r62421 | mark.dickinson | 2008-04-20 22:38:48 +0200 (Sun, 20 Apr 2008) | 2 lines Add test for tanh(-0.) == -0. on IEEE 754 systems ........ r62423 | amaury.forgeotdarc | 2008-04-20 23:02:21 +0200 (Sun, 20 Apr 2008) | 3 lines Correct an apparent refleak in test_pkgutil: zipimport._zip_directory_cache contains info for all processed zip files, even when they are no longer used. ........ r62424 | mark.dickinson | 2008-04-20 23:39:04 +0200 (Sun, 20 Apr 2008) | 4 lines math.atan2 is misbehaving on Windows; this patch should fix the problem in the same way that the cmath.phase problems were fixed. ........ ................ r62437 | mark.summerfield | 2008-04-21 16:47:45 +0200 (Mon, 21 Apr 2008) | 3 lines dumps() and loads() work in terms of bytes objects not strings. ................ r62462 | trent.nelson | 2008-04-22 21:02:40 +0200 (Tue, 22 Apr 2008) | 1 line Issue 2440: remove the guard around the handling of case 'n' in getargs.c's convertsimple() such that we always treat it as an index type, regardless of whether or not sizeof(size_t) == sizeof(long). Fix the test_args2.Signed_TestCase.test_n() such that it tests for adherence to PEP 357 (don't try and coerce objects that don't have nb_index slots but do have nb_int slots (i.e. floats) into indexes 'just because we can'). Three other commits are related to this one: r62269 and r62279, which were changes to PyNumber_Index (among other things) to check for nb_int slots when we lack nb_index slots -- and r62292, which is when I reverted these changes after various people pointed out that the test was in fact wrong, not the code. ................ r62471 | benjamin.peterson | 2008-04-24 04:34:53 +0200 (Thu, 24 Apr 2008) | 2 lines remove some old versionchanged and versionadded directives ................ r62472 | benjamin.peterson | 2008-04-24 04:43:56 +0200 (Thu, 24 Apr 2008) | 2 lines Removed documentation for future_builtins ................ r62482 | amaury.forgeotdarc | 2008-04-24 20:23:22 +0200 (Thu, 24 Apr 2008) | 2 lines There is no reason for imp.get_magic() to return a mutable bytearray ................ r62483 | amaury.forgeotdarc | 2008-04-24 20:26:53 +0200 (Thu, 24 Apr 2008) | 2 lines Obvious simplification, now that "long" has disappeared. ................ r62484 | thomas.heller | 2008-04-24 20:39:36 +0200 (Thu, 24 Apr 2008) | 11 lines Merged revisions 62481 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62481 | thomas.heller | 2008-04-24 20:14:19 +0200 (Do, 24 Apr 2008) | 3 lines Remove cyclic reference in CFuncPtr instances; see issue #2682. Backport candidate for the release25-maint branch. ........ ................ r62488 | amaury.forgeotdarc | 2008-04-24 22:48:12 +0200 (Thu, 24 Apr 2008) | 18 lines Merged revisions 62486-62487 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62486 | amaury.forgeotdarc | 2008-04-24 16:22:26 -0400 (Thu, 24 Apr 2008) | 7 lines Add a few tests for pydoc. This is a modified version of a patch proposed by Humberto Diogenes in the discussion of issue1883. I will merge manually this change into the py3k branch: the tests must be adapted. ........ r62487 | amaury.forgeotdarc | 2008-04-24 16:41:50 -0400 (Thu, 24 Apr 2008) | 2 lines Use absolute import for test package ........ ................ r62489 | amaury.forgeotdarc | 2008-04-24 23:00:04 +0200 (Thu, 24 Apr 2008) | 4 lines Correct recently merged tests: - two bugs in pydoc.py - remove test about classic classes ................ r62491 | benjamin.peterson | 2008-04-25 03:59:09 +0200 (Fri, 25 Apr 2008) | 9 lines Merged revisions 62490 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62490 | benjamin.peterson | 2008-04-24 20:29:10 -0500 (Thu, 24 Apr 2008) | 2 lines reformat some documentation of classes so methods and attributes are under the class directive ........ ................ r62505 | amaury.forgeotdarc | 2008-04-25 22:47:52 +0200 (Fri, 25 Apr 2008) | 4 lines Remove duplicated code in pydoc.py, probably a merge conflict some months ago. Spotted by Humberto Diogenes. ................ r62506 | benjamin.peterson | 2008-04-25 23:15:37 +0200 (Fri, 25 Apr 2008) | 2 lines #2689 Fix indentation in Objects/rangeobject.c ................ r62512 | georg.brandl | 2008-04-26 20:28:08 +0200 (Sat, 26 Apr 2008) | 2 lines Block 2.6-only doc change. ................ r62515 | mark.dickinson | 2008-04-26 22:48:56 +0200 (Sat, 26 Apr 2008) | 14 lines Merged revisions 62499 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62499 | mark.dickinson | 2008-04-25 12:11:04 -0400 (Fri, 25 Apr 2008) | 7 lines Issue #1496032. Add -mieee to BASECFLAGS on alpha, when gcc is the compiler. This should(?) help to fix failures in test_math and test_cmath on Linux/alpha. Also add configure message reporting the result of uname -m, as a debugging aid. ........ ................ r62519 | benjamin.peterson | 2008-04-27 05:02:57 +0200 (Sun, 27 Apr 2008) | 12 lines Blocked revisions 62517-62518 via svnmerge ........ r62517 | benjamin.peterson | 2008-04-26 21:28:02 -0500 (Sat, 26 Apr 2008) | 2 lines Added PyErr_WarnPy3k function. (issue 2671) I will be converting current Py3k warnings to the use of this function soon. ........ r62518 | benjamin.peterson | 2008-04-26 22:01:45 -0500 (Sat, 26 Apr 2008) | 2 lines Use PyErr_WarnPy3k throughout ........ ................ r62537 | benjamin.peterson | 2008-04-27 20:44:04 +0200 (Sun, 27 Apr 2008) | 8 lines Blocked revisions 62536 via svnmerge ........ r62536 | benjamin.peterson | 2008-04-27 13:40:21 -0500 (Sun, 27 Apr 2008) | 2 lines A little reformating of Py3k warnings ........ ................ r62568 | benjamin.peterson | 2008-04-28 23:05:10 +0200 (Mon, 28 Apr 2008) | 2 lines Document the fact that '\U' and '\u' escapes are not treated specially in 3.0 (see issue 2541) ................ r62580 | marc-andre.lemburg | 2008-04-29 13:14:08 +0200 (Tue, 29 Apr 2008) | 3 lines Cleanup the Unicode header documentation and formatting a bit. ................ r62583 | georg.brandl | 2008-04-29 23:00:18 +0200 (Tue, 29 Apr 2008) | 2 lines Fix var name. ................ r62587 | eric.smith | 2008-04-30 04:12:09 +0200 (Wed, 30 Apr 2008) | 12 lines Merged revisions 62586 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62586 | eric.smith | 2008-04-29 21:09:30 -0400 (Tue, 29 Apr 2008) | 5 lines Issue 2526, float.__format__ 'n' specifier does not support thousands grouping. Implemented grouping, with tests. Cleaned up PyOS_ascii_formatd by breaking reformatting into smaller functions. ........ ................ Added: python/branches/py3k-ctypes-pep3118/.bzrignore - copied unchanged from r62587, /python/branches/py3k/.bzrignore python/branches/py3k-ctypes-pep3118/Doc/includes/email-alternative.py - copied unchanged from r62587, /python/branches/py3k/Doc/includes/email-alternative.py python/branches/py3k-ctypes-pep3118/Doc/includes/sqlite3/ctx_manager.py - copied unchanged from r62587, /python/branches/py3k/Doc/includes/sqlite3/ctx_manager.py python/branches/py3k-ctypes-pep3118/Doc/library/fractions.rst - copied unchanged from r62587, /python/branches/py3k/Doc/library/fractions.rst python/branches/py3k-ctypes-pep3118/Doc/library/io.rst - copied unchanged from r62587, /python/branches/py3k/Doc/library/io.rst python/branches/py3k-ctypes-pep3118/Doc/make.bat - copied unchanged from r62587, /python/branches/py3k/Doc/make.bat python/branches/py3k-ctypes-pep3118/Doc/tools/sphinxext/pyspecific.py - copied unchanged from r62587, /python/branches/py3k/Doc/tools/sphinxext/pyspecific.py python/branches/py3k-ctypes-pep3118/Include/pymath.h - copied unchanged from r62587, /python/branches/py3k/Include/pymath.h python/branches/py3k-ctypes-pep3118/Include/warnings.h - copied unchanged from r62587, /python/branches/py3k/Include/warnings.h python/branches/py3k-ctypes-pep3118/Lib/_weakrefset.py - copied unchanged from r62587, /python/branches/py3k/Lib/_weakrefset.py python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_pickling.py - copied unchanged from r62587, /python/branches/py3k/Lib/ctypes/test/test_pickling.py python/branches/py3k-ctypes-pep3118/Lib/distutils/command/wininst-9.0-amd64.exe - copied unchanged from r62587, /python/branches/py3k/Lib/distutils/command/wininst-9.0-amd64.exe python/branches/py3k-ctypes-pep3118/Lib/distutils/tests/test_core.py - copied unchanged from r62587, /python/branches/py3k/Lib/distutils/tests/test_core.py python/branches/py3k-ctypes-pep3118/Lib/fractions.py - copied unchanged from r62587, /python/branches/py3k/Lib/fractions.py python/branches/py3k-ctypes-pep3118/Lib/lib2to3/ (props changed) - copied from r62587, /python/branches/py3k/Lib/lib2to3/ python/branches/py3k-ctypes-pep3118/Lib/sqlite3/dump.py - copied unchanged from r62587, /python/branches/py3k/Lib/sqlite3/dump.py python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/dump.py - copied unchanged from r62587, /python/branches/py3k/Lib/sqlite3/test/dump.py python/branches/py3k-ctypes-pep3118/Lib/test/cmath_testcases.txt - copied unchanged from r62587, /python/branches/py3k/Lib/test/cmath_testcases.txt python/branches/py3k-ctypes-pep3118/Lib/test/ieee754.txt - copied unchanged from r62587, /python/branches/py3k/Lib/test/ieee754.txt python/branches/py3k-ctypes-pep3118/Lib/test/profilee.py - copied unchanged from r62587, /python/branches/py3k/Lib/test/profilee.py python/branches/py3k-ctypes-pep3118/Lib/test/relimport.py - copied unchanged from r62587, /python/branches/py3k/Lib/test/relimport.py python/branches/py3k-ctypes-pep3118/Lib/test/test_SimpleHTTPServer.py - copied unchanged from r62587, /python/branches/py3k/Lib/test/test_SimpleHTTPServer.py python/branches/py3k-ctypes-pep3118/Lib/test/test_epoll.py - copied unchanged from r62587, /python/branches/py3k/Lib/test/test_epoll.py python/branches/py3k-ctypes-pep3118/Lib/test/test_fractions.py - copied unchanged from r62587, /python/branches/py3k/Lib/test/test_fractions.py python/branches/py3k-ctypes-pep3118/Lib/test/test_future4.py - copied unchanged from r62587, /python/branches/py3k/Lib/test/test_future4.py python/branches/py3k-ctypes-pep3118/Lib/test/test_int_literal.py - copied unchanged from r62587, /python/branches/py3k/Lib/test/test_int_literal.py python/branches/py3k-ctypes-pep3118/Lib/test/test_kqueue.py - copied unchanged from r62587, /python/branches/py3k/Lib/test/test_kqueue.py python/branches/py3k-ctypes-pep3118/Lib/test/test_lib2to3.py - copied unchanged from r62587, /python/branches/py3k/Lib/test/test_lib2to3.py python/branches/py3k-ctypes-pep3118/Lib/test/test_mutex.py - copied unchanged from r62587, /python/branches/py3k/Lib/test/test_mutex.py python/branches/py3k-ctypes-pep3118/Lib/test/test_pkgutil.py - copied unchanged from r62587, /python/branches/py3k/Lib/test/test_pkgutil.py python/branches/py3k-ctypes-pep3118/Lib/test/test_print.py - copied unchanged from r62587, /python/branches/py3k/Lib/test/test_print.py python/branches/py3k-ctypes-pep3118/Lib/test/test_pydoc.py - copied unchanged from r62587, /python/branches/py3k/Lib/test/test_pydoc.py python/branches/py3k-ctypes-pep3118/Lib/test/tokenize_tests-latin1-coding-cookie-and-utf8-bom-sig.txt - copied unchanged from r62587, /python/branches/py3k/Lib/test/tokenize_tests-latin1-coding-cookie-and-utf8-bom-sig.txt python/branches/py3k-ctypes-pep3118/Lib/test/tokenize_tests-no-coding-cookie-and-utf8-bom-sig-only.txt - copied unchanged from r62587, /python/branches/py3k/Lib/test/tokenize_tests-no-coding-cookie-and-utf8-bom-sig-only.txt python/branches/py3k-ctypes-pep3118/Lib/test/tokenize_tests-utf8-coding-cookie-and-no-utf8-bom-sig.txt - copied unchanged from r62587, /python/branches/py3k/Lib/test/tokenize_tests-utf8-coding-cookie-and-no-utf8-bom-sig.txt python/branches/py3k-ctypes-pep3118/Lib/test/tokenize_tests-utf8-coding-cookie-and-utf8-bom-sig.txt - copied unchanged from r62587, /python/branches/py3k/Lib/test/tokenize_tests-utf8-coding-cookie-and-utf8-bom-sig.txt python/branches/py3k-ctypes-pep3118/Misc/RPM/python-3.0.spec - copied unchanged from r62587, /python/branches/py3k/Misc/RPM/python-3.0.spec python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/Makefile.am - copied unchanged from r62587, /python/branches/py3k/Modules/_ctypes/libffi/Makefile.am python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/Makefile.in - copied unchanged from r62587, /python/branches/py3k/Modules/_ctypes/libffi/Makefile.in python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/acinclude.m4 - copied unchanged from r62587, /python/branches/py3k/Modules/_ctypes/libffi/acinclude.m4 python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/configure.host - copied unchanged from r62587, /python/branches/py3k/Modules/_ctypes/libffi/configure.host python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/include/Makefile.am - copied unchanged from r62587, /python/branches/py3k/Modules/_ctypes/libffi/include/Makefile.am python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/include/Makefile.in - copied unchanged from r62587, /python/branches/py3k/Modules/_ctypes/libffi/include/Makefile.in python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/missing - copied unchanged from r62587, /python/branches/py3k/Modules/_ctypes/libffi/missing python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/pa/hpux32.S - copied unchanged from r62587, /python/branches/py3k/Modules/_ctypes/libffi/src/pa/hpux32.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/darwin64.S - copied unchanged from r62587, /python/branches/py3k/Modules/_ctypes/libffi/src/x86/darwin64.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/freebsd.S - copied unchanged from r62587, /python/branches/py3k/Modules/_ctypes/libffi/src/x86/freebsd.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi_osx/ - copied from r62587, /python/branches/py3k/Modules/_ctypes/libffi_osx/ python/branches/py3k-ctypes-pep3118/PC/example_nt/setup.py - copied unchanged from r62587, /python/branches/py3k/PC/example_nt/setup.py python/branches/py3k-ctypes-pep3118/PC/os2emx/python26.def - copied unchanged from r62587, /python/branches/py3k/PC/os2emx/python26.def python/branches/py3k-ctypes-pep3118/PCbuild/_bsddb44.vcproj - copied unchanged from r62587, /python/branches/py3k/PCbuild/_bsddb44.vcproj python/branches/py3k-ctypes-pep3118/PCbuild/_hashlib.vcproj - copied unchanged from r62587, /python/branches/py3k/PCbuild/_hashlib.vcproj python/branches/py3k-ctypes-pep3118/PCbuild/kill_python.c - copied unchanged from r62587, /python/branches/py3k/PCbuild/kill_python.c python/branches/py3k-ctypes-pep3118/PCbuild/kill_python.vcproj - copied unchanged from r62587, /python/branches/py3k/PCbuild/kill_python.vcproj python/branches/py3k-ctypes-pep3118/PCbuild/sqlite3.vcproj - copied unchanged from r62587, /python/branches/py3k/PCbuild/sqlite3.vcproj python/branches/py3k-ctypes-pep3118/Python/_warnings.c - copied unchanged from r62587, /python/branches/py3k/Python/_warnings.c python/branches/py3k-ctypes-pep3118/Python/pymath.c - copied unchanged from r62587, /python/branches/py3k/Python/pymath.c python/branches/py3k-ctypes-pep3118/Tools/buildbot/external-common.bat - copied unchanged from r62587, /python/branches/py3k/Tools/buildbot/external-common.bat python/branches/py3k-ctypes-pep3118/Tools/msi/merge.py - copied unchanged from r62587, /python/branches/py3k/Tools/msi/merge.py python/branches/py3k-ctypes-pep3118/Tools/pybench/With.py - copied unchanged from r62587, /python/branches/py3k/Tools/pybench/With.py python/branches/py3k-ctypes-pep3118/Tools/scripts/2to3 - copied unchanged from r62587, /python/branches/py3k/Tools/scripts/2to3 python/branches/py3k-ctypes-pep3118/Tools/scripts/patchcheck.py - copied unchanged from r62587, /python/branches/py3k/Tools/scripts/patchcheck.py Removed: python/branches/py3k-ctypes-pep3118/Doc/builddoc.bat python/branches/py3k-ctypes-pep3118/Doc/library/dl.rst python/branches/py3k-ctypes-pep3118/Doc/library/rational.rst python/branches/py3k-ctypes-pep3118/Doc/library/userdict.rst python/branches/py3k-ctypes-pep3118/Lib/UserDict.py python/branches/py3k-ctypes-pep3118/Lib/UserList.py python/branches/py3k-ctypes-pep3118/Lib/UserString.py python/branches/py3k-ctypes-pep3118/Lib/rational.py python/branches/py3k-ctypes-pep3118/Lib/test/output/ python/branches/py3k-ctypes-pep3118/Lib/test/test_dl.py python/branches/py3k-ctypes-pep3118/Lib/test/test_hexoct.py python/branches/py3k-ctypes-pep3118/Lib/test/test_rational.py python/branches/py3k-ctypes-pep3118/Lib/test/testall.py python/branches/py3k-ctypes-pep3118/Misc/RPM/python-2.6.spec python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/ffi_darwin.c python/branches/py3k-ctypes-pep3118/Modules/_typesmodule.c python/branches/py3k-ctypes-pep3118/Modules/dlmodule.c python/branches/py3k-ctypes-pep3118/Objects/doubledigits.c python/branches/py3k-ctypes-pep3118/PC/os2emx/python25.def python/branches/py3k-ctypes-pep3118/Python/hypot.c python/branches/py3k-ctypes-pep3118/Python/memmove.c python/branches/py3k-ctypes-pep3118/Python/strerror.c python/branches/py3k-ctypes-pep3118/Tools/buildbot/Makefile python/branches/py3k-ctypes-pep3118/Tools/buildbot/kill_python.bat python/branches/py3k-ctypes-pep3118/Tools/buildbot/kill_python.c python/branches/py3k-ctypes-pep3118/Tools/buildbot/kill_python.mak python/branches/py3k-ctypes-pep3118/Tools/scripts/texcheck.py Modified: python/branches/py3k-ctypes-pep3118/ (props changed) python/branches/py3k-ctypes-pep3118/Demo/classes/Dbm.py python/branches/py3k-ctypes-pep3118/Demo/classes/README python/branches/py3k-ctypes-pep3118/Demo/curses/ncurses.py python/branches/py3k-ctypes-pep3118/Demo/rpc/mountclient.py python/branches/py3k-ctypes-pep3118/Demo/rpc/nfsclient.py python/branches/py3k-ctypes-pep3118/Demo/rpc/rpc.py python/branches/py3k-ctypes-pep3118/Demo/tkinter/guido/ShellWindow.py python/branches/py3k-ctypes-pep3118/Demo/tkinter/guido/paint.py python/branches/py3k-ctypes-pep3118/Doc/ACKS.txt python/branches/py3k-ctypes-pep3118/Doc/Makefile python/branches/py3k-ctypes-pep3118/Doc/README.txt python/branches/py3k-ctypes-pep3118/Doc/bugs.rst python/branches/py3k-ctypes-pep3118/Doc/c-api/arg.rst python/branches/py3k-ctypes-pep3118/Doc/c-api/float.rst python/branches/py3k-ctypes-pep3118/Doc/c-api/import.rst python/branches/py3k-ctypes-pep3118/Doc/c-api/init.rst python/branches/py3k-ctypes-pep3118/Doc/c-api/intro.rst python/branches/py3k-ctypes-pep3118/Doc/c-api/long.rst python/branches/py3k-ctypes-pep3118/Doc/c-api/method.rst python/branches/py3k-ctypes-pep3118/Doc/c-api/module.rst python/branches/py3k-ctypes-pep3118/Doc/c-api/objbuffer.rst python/branches/py3k-ctypes-pep3118/Doc/c-api/set.rst python/branches/py3k-ctypes-pep3118/Doc/c-api/structures.rst python/branches/py3k-ctypes-pep3118/Doc/c-api/sys.rst python/branches/py3k-ctypes-pep3118/Doc/c-api/tuple.rst python/branches/py3k-ctypes-pep3118/Doc/c-api/type.rst python/branches/py3k-ctypes-pep3118/Doc/c-api/typeobj.rst python/branches/py3k-ctypes-pep3118/Doc/c-api/unicode.rst python/branches/py3k-ctypes-pep3118/Doc/c-api/veryhigh.rst python/branches/py3k-ctypes-pep3118/Doc/conf.py python/branches/py3k-ctypes-pep3118/Doc/copyright.rst python/branches/py3k-ctypes-pep3118/Doc/distutils/apiref.rst python/branches/py3k-ctypes-pep3118/Doc/distutils/builtdist.rst python/branches/py3k-ctypes-pep3118/Doc/distutils/examples.rst python/branches/py3k-ctypes-pep3118/Doc/distutils/packageindex.rst python/branches/py3k-ctypes-pep3118/Doc/distutils/setupscript.rst python/branches/py3k-ctypes-pep3118/Doc/distutils/sourcedist.rst python/branches/py3k-ctypes-pep3118/Doc/documenting/markup.rst python/branches/py3k-ctypes-pep3118/Doc/documenting/style.rst python/branches/py3k-ctypes-pep3118/Doc/extending/extending.rst python/branches/py3k-ctypes-pep3118/Doc/extending/newtypes.rst python/branches/py3k-ctypes-pep3118/Doc/extending/windows.rst python/branches/py3k-ctypes-pep3118/Doc/glossary.rst python/branches/py3k-ctypes-pep3118/Doc/howto/advocacy.rst python/branches/py3k-ctypes-pep3118/Doc/howto/curses.rst python/branches/py3k-ctypes-pep3118/Doc/howto/doanddont.rst python/branches/py3k-ctypes-pep3118/Doc/howto/functional.rst python/branches/py3k-ctypes-pep3118/Doc/howto/regex.rst python/branches/py3k-ctypes-pep3118/Doc/howto/sockets.rst python/branches/py3k-ctypes-pep3118/Doc/howto/unicode.rst python/branches/py3k-ctypes-pep3118/Doc/howto/urllib2.rst python/branches/py3k-ctypes-pep3118/Doc/includes/tzinfo-examples.py python/branches/py3k-ctypes-pep3118/Doc/install/index.rst python/branches/py3k-ctypes-pep3118/Doc/library/__future__.rst python/branches/py3k-ctypes-pep3118/Doc/library/_ast.rst python/branches/py3k-ctypes-pep3118/Doc/library/_winreg.rst python/branches/py3k-ctypes-pep3118/Doc/library/aepack.rst python/branches/py3k-ctypes-pep3118/Doc/library/allos.rst python/branches/py3k-ctypes-pep3118/Doc/library/array.rst python/branches/py3k-ctypes-pep3118/Doc/library/asynchat.rst python/branches/py3k-ctypes-pep3118/Doc/library/asyncore.rst python/branches/py3k-ctypes-pep3118/Doc/library/audioop.rst python/branches/py3k-ctypes-pep3118/Doc/library/base64.rst python/branches/py3k-ctypes-pep3118/Doc/library/basehttpserver.rst python/branches/py3k-ctypes-pep3118/Doc/library/bdb.rst python/branches/py3k-ctypes-pep3118/Doc/library/bisect.rst python/branches/py3k-ctypes-pep3118/Doc/library/bz2.rst python/branches/py3k-ctypes-pep3118/Doc/library/calendar.rst python/branches/py3k-ctypes-pep3118/Doc/library/cgihttpserver.rst python/branches/py3k-ctypes-pep3118/Doc/library/chunk.rst python/branches/py3k-ctypes-pep3118/Doc/library/cmath.rst python/branches/py3k-ctypes-pep3118/Doc/library/codecs.rst python/branches/py3k-ctypes-pep3118/Doc/library/collections.rst python/branches/py3k-ctypes-pep3118/Doc/library/configparser.rst python/branches/py3k-ctypes-pep3118/Doc/library/cookie.rst python/branches/py3k-ctypes-pep3118/Doc/library/cookielib.rst python/branches/py3k-ctypes-pep3118/Doc/library/copy_reg.rst python/branches/py3k-ctypes-pep3118/Doc/library/csv.rst python/branches/py3k-ctypes-pep3118/Doc/library/ctypes.rst python/branches/py3k-ctypes-pep3118/Doc/library/curses.rst python/branches/py3k-ctypes-pep3118/Doc/library/datatypes.rst python/branches/py3k-ctypes-pep3118/Doc/library/datetime.rst python/branches/py3k-ctypes-pep3118/Doc/library/decimal.rst python/branches/py3k-ctypes-pep3118/Doc/library/difflib.rst python/branches/py3k-ctypes-pep3118/Doc/library/dis.rst python/branches/py3k-ctypes-pep3118/Doc/library/doctest.rst python/branches/py3k-ctypes-pep3118/Doc/library/easydialogs.rst python/branches/py3k-ctypes-pep3118/Doc/library/email-examples.rst python/branches/py3k-ctypes-pep3118/Doc/library/email.charset.rst python/branches/py3k-ctypes-pep3118/Doc/library/email.generator.rst python/branches/py3k-ctypes-pep3118/Doc/library/email.header.rst python/branches/py3k-ctypes-pep3118/Doc/library/email.message.rst python/branches/py3k-ctypes-pep3118/Doc/library/email.parser.rst python/branches/py3k-ctypes-pep3118/Doc/library/email.util.rst python/branches/py3k-ctypes-pep3118/Doc/library/fcntl.rst python/branches/py3k-ctypes-pep3118/Doc/library/filecmp.rst python/branches/py3k-ctypes-pep3118/Doc/library/fileinput.rst python/branches/py3k-ctypes-pep3118/Doc/library/fnmatch.rst python/branches/py3k-ctypes-pep3118/Doc/library/ftplib.rst python/branches/py3k-ctypes-pep3118/Doc/library/functions.rst python/branches/py3k-ctypes-pep3118/Doc/library/functools.rst python/branches/py3k-ctypes-pep3118/Doc/library/getopt.rst python/branches/py3k-ctypes-pep3118/Doc/library/gettext.rst python/branches/py3k-ctypes-pep3118/Doc/library/gzip.rst python/branches/py3k-ctypes-pep3118/Doc/library/hashlib.rst python/branches/py3k-ctypes-pep3118/Doc/library/heapq.rst python/branches/py3k-ctypes-pep3118/Doc/library/imaplib.rst python/branches/py3k-ctypes-pep3118/Doc/library/imp.rst python/branches/py3k-ctypes-pep3118/Doc/library/index.rst python/branches/py3k-ctypes-pep3118/Doc/library/inspect.rst python/branches/py3k-ctypes-pep3118/Doc/library/itertools.rst python/branches/py3k-ctypes-pep3118/Doc/library/logging.rst python/branches/py3k-ctypes-pep3118/Doc/library/mailbox.rst python/branches/py3k-ctypes-pep3118/Doc/library/marshal.rst python/branches/py3k-ctypes-pep3118/Doc/library/math.rst python/branches/py3k-ctypes-pep3118/Doc/library/mimetools.rst python/branches/py3k-ctypes-pep3118/Doc/library/mimetypes.rst python/branches/py3k-ctypes-pep3118/Doc/library/mmap.rst python/branches/py3k-ctypes-pep3118/Doc/library/modulefinder.rst python/branches/py3k-ctypes-pep3118/Doc/library/msilib.rst python/branches/py3k-ctypes-pep3118/Doc/library/numbers.rst python/branches/py3k-ctypes-pep3118/Doc/library/numeric.rst python/branches/py3k-ctypes-pep3118/Doc/library/operator.rst python/branches/py3k-ctypes-pep3118/Doc/library/optparse.rst python/branches/py3k-ctypes-pep3118/Doc/library/os.path.rst python/branches/py3k-ctypes-pep3118/Doc/library/os.rst python/branches/py3k-ctypes-pep3118/Doc/library/othergui.rst python/branches/py3k-ctypes-pep3118/Doc/library/pdb.rst python/branches/py3k-ctypes-pep3118/Doc/library/pickle.rst python/branches/py3k-ctypes-pep3118/Doc/library/pickletools.rst python/branches/py3k-ctypes-pep3118/Doc/library/pkgutil.rst python/branches/py3k-ctypes-pep3118/Doc/library/platform.rst python/branches/py3k-ctypes-pep3118/Doc/library/plistlib.rst python/branches/py3k-ctypes-pep3118/Doc/library/pprint.rst python/branches/py3k-ctypes-pep3118/Doc/library/profile.rst python/branches/py3k-ctypes-pep3118/Doc/library/py_compile.rst python/branches/py3k-ctypes-pep3118/Doc/library/pyexpat.rst python/branches/py3k-ctypes-pep3118/Doc/library/queue.rst python/branches/py3k-ctypes-pep3118/Doc/library/random.rst python/branches/py3k-ctypes-pep3118/Doc/library/re.rst python/branches/py3k-ctypes-pep3118/Doc/library/robotparser.rst python/branches/py3k-ctypes-pep3118/Doc/library/sched.rst python/branches/py3k-ctypes-pep3118/Doc/library/select.rst python/branches/py3k-ctypes-pep3118/Doc/library/shutil.rst python/branches/py3k-ctypes-pep3118/Doc/library/signal.rst python/branches/py3k-ctypes-pep3118/Doc/library/simplehttpserver.rst python/branches/py3k-ctypes-pep3118/Doc/library/simplexmlrpcserver.rst python/branches/py3k-ctypes-pep3118/Doc/library/smtpd.rst python/branches/py3k-ctypes-pep3118/Doc/library/smtplib.rst python/branches/py3k-ctypes-pep3118/Doc/library/socket.rst python/branches/py3k-ctypes-pep3118/Doc/library/socketserver.rst python/branches/py3k-ctypes-pep3118/Doc/library/sqlite3.rst python/branches/py3k-ctypes-pep3118/Doc/library/ssl.rst python/branches/py3k-ctypes-pep3118/Doc/library/stdtypes.rst python/branches/py3k-ctypes-pep3118/Doc/library/string.rst python/branches/py3k-ctypes-pep3118/Doc/library/stringio.rst python/branches/py3k-ctypes-pep3118/Doc/library/struct.rst python/branches/py3k-ctypes-pep3118/Doc/library/subprocess.rst python/branches/py3k-ctypes-pep3118/Doc/library/sys.rst python/branches/py3k-ctypes-pep3118/Doc/library/tempfile.rst python/branches/py3k-ctypes-pep3118/Doc/library/textwrap.rst python/branches/py3k-ctypes-pep3118/Doc/library/threading.rst python/branches/py3k-ctypes-pep3118/Doc/library/time.rst python/branches/py3k-ctypes-pep3118/Doc/library/tix.rst python/branches/py3k-ctypes-pep3118/Doc/library/tkinter.rst python/branches/py3k-ctypes-pep3118/Doc/library/tokenize.rst python/branches/py3k-ctypes-pep3118/Doc/library/trace.rst python/branches/py3k-ctypes-pep3118/Doc/library/traceback.rst python/branches/py3k-ctypes-pep3118/Doc/library/types.rst python/branches/py3k-ctypes-pep3118/Doc/library/undoc.rst python/branches/py3k-ctypes-pep3118/Doc/library/unicodedata.rst python/branches/py3k-ctypes-pep3118/Doc/library/unittest.rst python/branches/py3k-ctypes-pep3118/Doc/library/unix.rst python/branches/py3k-ctypes-pep3118/Doc/library/urllib.rst python/branches/py3k-ctypes-pep3118/Doc/library/urllib2.rst python/branches/py3k-ctypes-pep3118/Doc/library/urlparse.rst python/branches/py3k-ctypes-pep3118/Doc/library/warnings.rst python/branches/py3k-ctypes-pep3118/Doc/library/weakref.rst python/branches/py3k-ctypes-pep3118/Doc/library/wsgiref.rst python/branches/py3k-ctypes-pep3118/Doc/library/xml.dom.minidom.rst python/branches/py3k-ctypes-pep3118/Doc/library/xml.dom.rst python/branches/py3k-ctypes-pep3118/Doc/library/xml.etree.elementtree.rst python/branches/py3k-ctypes-pep3118/Doc/library/xml.sax.handler.rst python/branches/py3k-ctypes-pep3118/Doc/library/xml.sax.reader.rst python/branches/py3k-ctypes-pep3118/Doc/library/xmlrpclib.rst python/branches/py3k-ctypes-pep3118/Doc/library/zipfile.rst python/branches/py3k-ctypes-pep3118/Doc/library/zipimport.rst python/branches/py3k-ctypes-pep3118/Doc/library/zlib.rst python/branches/py3k-ctypes-pep3118/Doc/license.rst python/branches/py3k-ctypes-pep3118/Doc/reference/compound_stmts.rst python/branches/py3k-ctypes-pep3118/Doc/reference/datamodel.rst python/branches/py3k-ctypes-pep3118/Doc/reference/expressions.rst python/branches/py3k-ctypes-pep3118/Doc/reference/index.rst python/branches/py3k-ctypes-pep3118/Doc/reference/lexical_analysis.rst python/branches/py3k-ctypes-pep3118/Doc/reference/simple_stmts.rst python/branches/py3k-ctypes-pep3118/Doc/tools/sphinxext/ (props changed) python/branches/py3k-ctypes-pep3118/Doc/tools/sphinxext/download.html python/branches/py3k-ctypes-pep3118/Doc/tools/sphinxext/indexcontent.html python/branches/py3k-ctypes-pep3118/Doc/tools/sphinxext/patchlevel.py python/branches/py3k-ctypes-pep3118/Doc/tutorial/appetite.rst python/branches/py3k-ctypes-pep3118/Doc/tutorial/classes.rst python/branches/py3k-ctypes-pep3118/Doc/tutorial/controlflow.rst python/branches/py3k-ctypes-pep3118/Doc/tutorial/datastructures.rst python/branches/py3k-ctypes-pep3118/Doc/tutorial/errors.rst python/branches/py3k-ctypes-pep3118/Doc/tutorial/inputoutput.rst python/branches/py3k-ctypes-pep3118/Doc/tutorial/stdlib.rst python/branches/py3k-ctypes-pep3118/Doc/tutorial/stdlib2.rst python/branches/py3k-ctypes-pep3118/Doc/tutorial/whatnow.rst python/branches/py3k-ctypes-pep3118/Doc/using/cmdline.rst python/branches/py3k-ctypes-pep3118/Doc/using/unix.rst python/branches/py3k-ctypes-pep3118/Doc/using/windows.rst python/branches/py3k-ctypes-pep3118/Doc/whatsnew/2.6.rst python/branches/py3k-ctypes-pep3118/Doc/whatsnew/3.0.rst python/branches/py3k-ctypes-pep3118/Include/Python-ast.h python/branches/py3k-ctypes-pep3118/Include/Python.h python/branches/py3k-ctypes-pep3118/Include/abstract.h python/branches/py3k-ctypes-pep3118/Include/ceval.h python/branches/py3k-ctypes-pep3118/Include/classobject.h python/branches/py3k-ctypes-pep3118/Include/code.h python/branches/py3k-ctypes-pep3118/Include/compile.h python/branches/py3k-ctypes-pep3118/Include/complexobject.h python/branches/py3k-ctypes-pep3118/Include/floatobject.h python/branches/py3k-ctypes-pep3118/Include/frameobject.h python/branches/py3k-ctypes-pep3118/Include/genobject.h python/branches/py3k-ctypes-pep3118/Include/graminit.h python/branches/py3k-ctypes-pep3118/Include/iterobject.h python/branches/py3k-ctypes-pep3118/Include/methodobject.h python/branches/py3k-ctypes-pep3118/Include/object.h python/branches/py3k-ctypes-pep3118/Include/osdefs.h python/branches/py3k-ctypes-pep3118/Include/parsetok.h python/branches/py3k-ctypes-pep3118/Include/patchlevel.h python/branches/py3k-ctypes-pep3118/Include/pyerrors.h python/branches/py3k-ctypes-pep3118/Include/pygetopt.h python/branches/py3k-ctypes-pep3118/Include/pyport.h python/branches/py3k-ctypes-pep3118/Include/pythonrun.h python/branches/py3k-ctypes-pep3118/Include/setobject.h python/branches/py3k-ctypes-pep3118/Include/sysmodule.h python/branches/py3k-ctypes-pep3118/Include/traceback.h python/branches/py3k-ctypes-pep3118/Include/tupleobject.h python/branches/py3k-ctypes-pep3118/Include/unicodeobject.h python/branches/py3k-ctypes-pep3118/LICENSE python/branches/py3k-ctypes-pep3118/Lib/BaseHTTPServer.py python/branches/py3k-ctypes-pep3118/Lib/ConfigParser.py python/branches/py3k-ctypes-pep3118/Lib/DocXMLRPCServer.py python/branches/py3k-ctypes-pep3118/Lib/SimpleHTTPServer.py python/branches/py3k-ctypes-pep3118/Lib/SocketServer.py python/branches/py3k-ctypes-pep3118/Lib/__future__.py python/branches/py3k-ctypes-pep3118/Lib/_abcoll.py python/branches/py3k-ctypes-pep3118/Lib/_strptime.py python/branches/py3k-ctypes-pep3118/Lib/abc.py python/branches/py3k-ctypes-pep3118/Lib/bdb.py python/branches/py3k-ctypes-pep3118/Lib/bsddb/__init__.py python/branches/py3k-ctypes-pep3118/Lib/bsddb/dbobj.py python/branches/py3k-ctypes-pep3118/Lib/bsddb/dbshelve.py python/branches/py3k-ctypes-pep3118/Lib/bsddb/dbtables.py python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_1413192.py python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_associate.py python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_basics.py python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_compare.py python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_cursor_pget_bug.py python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_dbobj.py python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_dbshelve.py python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_dbtables.py python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_env_close.py python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_join.py python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_lock.py python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_misc.py python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_pickle.py python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_recno.py python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_sequence.py python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_thread.py python/branches/py3k-ctypes-pep3118/Lib/calendar.py python/branches/py3k-ctypes-pep3118/Lib/cgi.py python/branches/py3k-ctypes-pep3118/Lib/codecs.py python/branches/py3k-ctypes-pep3118/Lib/collections.py python/branches/py3k-ctypes-pep3118/Lib/compileall.py python/branches/py3k-ctypes-pep3118/Lib/cookielib.py python/branches/py3k-ctypes-pep3118/Lib/copy.py python/branches/py3k-ctypes-pep3118/Lib/csv.py python/branches/py3k-ctypes-pep3118/Lib/ctypes/__init__.py python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/__init__.py python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_arrays.py python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_checkretval.py python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_find.py python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_funcptr.py python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_libc.py python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_numbers.py python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_pep3118.py python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_slicing.py python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_structures.py python/branches/py3k-ctypes-pep3118/Lib/ctypes/util.py python/branches/py3k-ctypes-pep3118/Lib/curses/__init__.py python/branches/py3k-ctypes-pep3118/Lib/curses/wrapper.py python/branches/py3k-ctypes-pep3118/Lib/decimal.py python/branches/py3k-ctypes-pep3118/Lib/distutils/__init__.py python/branches/py3k-ctypes-pep3118/Lib/distutils/bcppcompiler.py python/branches/py3k-ctypes-pep3118/Lib/distutils/ccompiler.py python/branches/py3k-ctypes-pep3118/Lib/distutils/command/bdist.py python/branches/py3k-ctypes-pep3118/Lib/distutils/command/bdist_dumb.py python/branches/py3k-ctypes-pep3118/Lib/distutils/command/bdist_msi.py python/branches/py3k-ctypes-pep3118/Lib/distutils/command/bdist_rpm.py python/branches/py3k-ctypes-pep3118/Lib/distutils/command/bdist_wininst.py python/branches/py3k-ctypes-pep3118/Lib/distutils/command/build.py python/branches/py3k-ctypes-pep3118/Lib/distutils/command/build_ext.py python/branches/py3k-ctypes-pep3118/Lib/distutils/command/build_py.py python/branches/py3k-ctypes-pep3118/Lib/distutils/command/build_scripts.py python/branches/py3k-ctypes-pep3118/Lib/distutils/command/install.py python/branches/py3k-ctypes-pep3118/Lib/distutils/command/install_headers.py python/branches/py3k-ctypes-pep3118/Lib/distutils/command/register.py python/branches/py3k-ctypes-pep3118/Lib/distutils/command/sdist.py python/branches/py3k-ctypes-pep3118/Lib/distutils/core.py python/branches/py3k-ctypes-pep3118/Lib/distutils/filelist.py python/branches/py3k-ctypes-pep3118/Lib/distutils/msvc9compiler.py python/branches/py3k-ctypes-pep3118/Lib/distutils/msvccompiler.py python/branches/py3k-ctypes-pep3118/Lib/distutils/sysconfig.py python/branches/py3k-ctypes-pep3118/Lib/distutils/tests/test_dist.py python/branches/py3k-ctypes-pep3118/Lib/distutils/tests/test_sysconfig.py python/branches/py3k-ctypes-pep3118/Lib/distutils/unixccompiler.py python/branches/py3k-ctypes-pep3118/Lib/distutils/util.py python/branches/py3k-ctypes-pep3118/Lib/dumbdbm.py python/branches/py3k-ctypes-pep3118/Lib/email/base64mime.py python/branches/py3k-ctypes-pep3118/Lib/filecmp.py python/branches/py3k-ctypes-pep3118/Lib/ftplib.py python/branches/py3k-ctypes-pep3118/Lib/glob.py python/branches/py3k-ctypes-pep3118/Lib/gzip.py python/branches/py3k-ctypes-pep3118/Lib/hashlib.py python/branches/py3k-ctypes-pep3118/Lib/heapq.py python/branches/py3k-ctypes-pep3118/Lib/hmac.py python/branches/py3k-ctypes-pep3118/Lib/httplib.py python/branches/py3k-ctypes-pep3118/Lib/idlelib/AutoComplete.py python/branches/py3k-ctypes-pep3118/Lib/idlelib/EditorWindow.py python/branches/py3k-ctypes-pep3118/Lib/idlelib/MultiCall.py python/branches/py3k-ctypes-pep3118/Lib/idlelib/NEWS.txt python/branches/py3k-ctypes-pep3118/Lib/idlelib/PyShell.py python/branches/py3k-ctypes-pep3118/Lib/idlelib/RemoteDebugger.py python/branches/py3k-ctypes-pep3118/Lib/idlelib/ScriptBinding.py python/branches/py3k-ctypes-pep3118/Lib/idlelib/TreeWidget.py python/branches/py3k-ctypes-pep3118/Lib/idlelib/UndoDelegator.py python/branches/py3k-ctypes-pep3118/Lib/idlelib/configDialog.py python/branches/py3k-ctypes-pep3118/Lib/idlelib/configHandler.py python/branches/py3k-ctypes-pep3118/Lib/idlelib/idlever.py python/branches/py3k-ctypes-pep3118/Lib/idlelib/keybindingDialog.py python/branches/py3k-ctypes-pep3118/Lib/idlelib/run.py python/branches/py3k-ctypes-pep3118/Lib/imaplib.py python/branches/py3k-ctypes-pep3118/Lib/inspect.py python/branches/py3k-ctypes-pep3118/Lib/io.py python/branches/py3k-ctypes-pep3118/Lib/lib-tk/Tkinter.py python/branches/py3k-ctypes-pep3118/Lib/lib-tk/tkSimpleDialog.py python/branches/py3k-ctypes-pep3118/Lib/lib-tk/turtle.py python/branches/py3k-ctypes-pep3118/Lib/lib2to3/fixes/ (props changed) python/branches/py3k-ctypes-pep3118/Lib/lib2to3/pgen2/ (props changed) python/branches/py3k-ctypes-pep3118/Lib/lib2to3/tests/ (props changed) python/branches/py3k-ctypes-pep3118/Lib/locale.py python/branches/py3k-ctypes-pep3118/Lib/logging/__init__.py python/branches/py3k-ctypes-pep3118/Lib/logging/handlers.py python/branches/py3k-ctypes-pep3118/Lib/mailbox.py python/branches/py3k-ctypes-pep3118/Lib/ntpath.py python/branches/py3k-ctypes-pep3118/Lib/numbers.py python/branches/py3k-ctypes-pep3118/Lib/opcode.py python/branches/py3k-ctypes-pep3118/Lib/pdb.py python/branches/py3k-ctypes-pep3118/Lib/pickle.py python/branches/py3k-ctypes-pep3118/Lib/pickletools.py python/branches/py3k-ctypes-pep3118/Lib/pkgutil.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/EasyDialogs.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/FrameWork.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/MiniAEFrame.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/PixMapWrapper.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/aepack.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/bgenlocations.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/buildtools.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/findertools.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/gensuitemodule.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/ic.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/CodeWarrior/CodeWarrior_suite.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Standard_Suite.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Explorer/Required_Suite.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Explorer/Web_Browser_Suite.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Finder/Finder_Basics.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Finder/Legacy_suite.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Finder/Standard_Suite.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Netscape/Mozilla_suite.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Netscape/PowerPlant.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Netscape/Required_suite.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Netscape/WorldWideWeb_suite.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/SystemEvents/Standard_Suite.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Terminal/Standard_Suite.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/_builtinSuites/builtin_Suite.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/macostools.py python/branches/py3k-ctypes-pep3118/Lib/plat-mac/videoreader.py python/branches/py3k-ctypes-pep3118/Lib/plat-os2emx/grp.py python/branches/py3k-ctypes-pep3118/Lib/plat-os2emx/pwd.py python/branches/py3k-ctypes-pep3118/Lib/platform.py python/branches/py3k-ctypes-pep3118/Lib/plistlib.py python/branches/py3k-ctypes-pep3118/Lib/pprint.py python/branches/py3k-ctypes-pep3118/Lib/pstats.py python/branches/py3k-ctypes-pep3118/Lib/py_compile.py python/branches/py3k-ctypes-pep3118/Lib/pyclbr.py python/branches/py3k-ctypes-pep3118/Lib/pydoc.py python/branches/py3k-ctypes-pep3118/Lib/random.py python/branches/py3k-ctypes-pep3118/Lib/re.py python/branches/py3k-ctypes-pep3118/Lib/rlcompleter.py python/branches/py3k-ctypes-pep3118/Lib/runpy.py python/branches/py3k-ctypes-pep3118/Lib/shelve.py python/branches/py3k-ctypes-pep3118/Lib/shutil.py python/branches/py3k-ctypes-pep3118/Lib/smtplib.py python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/dbapi.py python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/factory.py python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/hooks.py python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/regression.py python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/transactions.py python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/types.py python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/userfunctions.py python/branches/py3k-ctypes-pep3118/Lib/sre_compile.py python/branches/py3k-ctypes-pep3118/Lib/sre_parse.py python/branches/py3k-ctypes-pep3118/Lib/ssl.py python/branches/py3k-ctypes-pep3118/Lib/stat.py python/branches/py3k-ctypes-pep3118/Lib/subprocess.py python/branches/py3k-ctypes-pep3118/Lib/tarfile.py python/branches/py3k-ctypes-pep3118/Lib/tempfile.py python/branches/py3k-ctypes-pep3118/Lib/test/cjkencodings_test.py python/branches/py3k-ctypes-pep3118/Lib/test/fork_wait.py python/branches/py3k-ctypes-pep3118/Lib/test/list_tests.py python/branches/py3k-ctypes-pep3118/Lib/test/mapping_tests.py python/branches/py3k-ctypes-pep3118/Lib/test/outstanding_bugs.py python/branches/py3k-ctypes-pep3118/Lib/test/pickletester.py python/branches/py3k-ctypes-pep3118/Lib/test/regrtest.py python/branches/py3k-ctypes-pep3118/Lib/test/seq_tests.py python/branches/py3k-ctypes-pep3118/Lib/test/string_tests.py python/branches/py3k-ctypes-pep3118/Lib/test/test___all__.py python/branches/py3k-ctypes-pep3118/Lib/test/test__locale.py python/branches/py3k-ctypes-pep3118/Lib/test/test_abc.py python/branches/py3k-ctypes-pep3118/Lib/test/test_abstract_numbers.py python/branches/py3k-ctypes-pep3118/Lib/test/test_applesingle.py python/branches/py3k-ctypes-pep3118/Lib/test/test_array.py python/branches/py3k-ctypes-pep3118/Lib/test/test_ast.py python/branches/py3k-ctypes-pep3118/Lib/test/test_asynchat.py python/branches/py3k-ctypes-pep3118/Lib/test/test_asyncore.py python/branches/py3k-ctypes-pep3118/Lib/test/test_audioop.py python/branches/py3k-ctypes-pep3118/Lib/test/test_bisect.py python/branches/py3k-ctypes-pep3118/Lib/test/test_bsddb3.py python/branches/py3k-ctypes-pep3118/Lib/test/test_builtin.py python/branches/py3k-ctypes-pep3118/Lib/test/test_bytes.py python/branches/py3k-ctypes-pep3118/Lib/test/test_cProfile.py python/branches/py3k-ctypes-pep3118/Lib/test/test_capi.py python/branches/py3k-ctypes-pep3118/Lib/test/test_cfgparser.py python/branches/py3k-ctypes-pep3118/Lib/test/test_class.py python/branches/py3k-ctypes-pep3118/Lib/test/test_cmath.py python/branches/py3k-ctypes-pep3118/Lib/test/test_cmd.py python/branches/py3k-ctypes-pep3118/Lib/test/test_cmd_line.py python/branches/py3k-ctypes-pep3118/Lib/test/test_code.py python/branches/py3k-ctypes-pep3118/Lib/test/test_codecmaps_hk.py python/branches/py3k-ctypes-pep3118/Lib/test/test_coding.py python/branches/py3k-ctypes-pep3118/Lib/test/test_collections.py python/branches/py3k-ctypes-pep3118/Lib/test/test_compare.py python/branches/py3k-ctypes-pep3118/Lib/test/test_compile.py python/branches/py3k-ctypes-pep3118/Lib/test/test_complex.py python/branches/py3k-ctypes-pep3118/Lib/test/test_contains.py python/branches/py3k-ctypes-pep3118/Lib/test/test_copy.py python/branches/py3k-ctypes-pep3118/Lib/test/test_crypt.py python/branches/py3k-ctypes-pep3118/Lib/test/test_curses.py python/branches/py3k-ctypes-pep3118/Lib/test/test_datetime.py python/branches/py3k-ctypes-pep3118/Lib/test/test_dbm.py python/branches/py3k-ctypes-pep3118/Lib/test/test_decimal.py python/branches/py3k-ctypes-pep3118/Lib/test/test_defaultdict.py python/branches/py3k-ctypes-pep3118/Lib/test/test_deque.py python/branches/py3k-ctypes-pep3118/Lib/test/test_descr.py python/branches/py3k-ctypes-pep3118/Lib/test/test_descrtut.py python/branches/py3k-ctypes-pep3118/Lib/test/test_dict.py python/branches/py3k-ctypes-pep3118/Lib/test/test_dis.py python/branches/py3k-ctypes-pep3118/Lib/test/test_doctest3.txt python/branches/py3k-ctypes-pep3118/Lib/test/test_docxmlrpc.py python/branches/py3k-ctypes-pep3118/Lib/test/test_dummy_threading.py python/branches/py3k-ctypes-pep3118/Lib/test/test_email.py python/branches/py3k-ctypes-pep3118/Lib/test/test_eof.py python/branches/py3k-ctypes-pep3118/Lib/test/test_errno.py python/branches/py3k-ctypes-pep3118/Lib/test/test_extcall.py python/branches/py3k-ctypes-pep3118/Lib/test/test_fcntl.py python/branches/py3k-ctypes-pep3118/Lib/test/test_file.py python/branches/py3k-ctypes-pep3118/Lib/test/test_fileinput.py python/branches/py3k-ctypes-pep3118/Lib/test/test_fileio.py python/branches/py3k-ctypes-pep3118/Lib/test/test_float.py python/branches/py3k-ctypes-pep3118/Lib/test/test_format.py python/branches/py3k-ctypes-pep3118/Lib/test/test_frozen.py python/branches/py3k-ctypes-pep3118/Lib/test/test_ftplib.py python/branches/py3k-ctypes-pep3118/Lib/test/test_funcattrs.py python/branches/py3k-ctypes-pep3118/Lib/test/test_gc.py python/branches/py3k-ctypes-pep3118/Lib/test/test_gdbm.py python/branches/py3k-ctypes-pep3118/Lib/test/test_generators.py python/branches/py3k-ctypes-pep3118/Lib/test/test_genexps.py python/branches/py3k-ctypes-pep3118/Lib/test/test_getargs2.py python/branches/py3k-ctypes-pep3118/Lib/test/test_grammar.py python/branches/py3k-ctypes-pep3118/Lib/test/test_gzip.py python/branches/py3k-ctypes-pep3118/Lib/test/test_heapq.py python/branches/py3k-ctypes-pep3118/Lib/test/test_hmac.py python/branches/py3k-ctypes-pep3118/Lib/test/test_htmlparser.py python/branches/py3k-ctypes-pep3118/Lib/test/test_httplib.py python/branches/py3k-ctypes-pep3118/Lib/test/test_imaplib.py python/branches/py3k-ctypes-pep3118/Lib/test/test_imp.py python/branches/py3k-ctypes-pep3118/Lib/test/test_import.py python/branches/py3k-ctypes-pep3118/Lib/test/test_index.py python/branches/py3k-ctypes-pep3118/Lib/test/test_inspect.py python/branches/py3k-ctypes-pep3118/Lib/test/test_io.py python/branches/py3k-ctypes-pep3118/Lib/test/test_ioctl.py python/branches/py3k-ctypes-pep3118/Lib/test/test_iterlen.py python/branches/py3k-ctypes-pep3118/Lib/test/test_itertools.py python/branches/py3k-ctypes-pep3118/Lib/test/test_largefile.py python/branches/py3k-ctypes-pep3118/Lib/test/test_list.py python/branches/py3k-ctypes-pep3118/Lib/test/test_logging.py python/branches/py3k-ctypes-pep3118/Lib/test/test_long.py python/branches/py3k-ctypes-pep3118/Lib/test/test_mailbox.py python/branches/py3k-ctypes-pep3118/Lib/test/test_math.py python/branches/py3k-ctypes-pep3118/Lib/test/test_metaclass.py python/branches/py3k-ctypes-pep3118/Lib/test/test_minidom.py python/branches/py3k-ctypes-pep3118/Lib/test/test_mmap.py python/branches/py3k-ctypes-pep3118/Lib/test/test_module.py python/branches/py3k-ctypes-pep3118/Lib/test/test_modulefinder.py python/branches/py3k-ctypes-pep3118/Lib/test/test_multibytecodec_support.py python/branches/py3k-ctypes-pep3118/Lib/test/test_nis.py python/branches/py3k-ctypes-pep3118/Lib/test/test_ntpath.py python/branches/py3k-ctypes-pep3118/Lib/test/test_operator.py python/branches/py3k-ctypes-pep3118/Lib/test/test_optparse.py python/branches/py3k-ctypes-pep3118/Lib/test/test_os.py python/branches/py3k-ctypes-pep3118/Lib/test/test_ossaudiodev.py python/branches/py3k-ctypes-pep3118/Lib/test/test_parser.py python/branches/py3k-ctypes-pep3118/Lib/test/test_pep247.py python/branches/py3k-ctypes-pep3118/Lib/test/test_pep263.py python/branches/py3k-ctypes-pep3118/Lib/test/test_pickle.py python/branches/py3k-ctypes-pep3118/Lib/test/test_pickletools.py python/branches/py3k-ctypes-pep3118/Lib/test/test_pkg.py python/branches/py3k-ctypes-pep3118/Lib/test/test_plistlib.py python/branches/py3k-ctypes-pep3118/Lib/test/test_poll.py python/branches/py3k-ctypes-pep3118/Lib/test/test_poplib.py python/branches/py3k-ctypes-pep3118/Lib/test/test_posix.py python/branches/py3k-ctypes-pep3118/Lib/test/test_pprint.py python/branches/py3k-ctypes-pep3118/Lib/test/test_profile.py (contents, props changed) python/branches/py3k-ctypes-pep3118/Lib/test/test_pty.py python/branches/py3k-ctypes-pep3118/Lib/test/test_pyclbr.py python/branches/py3k-ctypes-pep3118/Lib/test/test_queue.py python/branches/py3k-ctypes-pep3118/Lib/test/test_random.py python/branches/py3k-ctypes-pep3118/Lib/test/test_re.py python/branches/py3k-ctypes-pep3118/Lib/test/test_resource.py python/branches/py3k-ctypes-pep3118/Lib/test/test_rfc822.py python/branches/py3k-ctypes-pep3118/Lib/test/test_richcmp.py python/branches/py3k-ctypes-pep3118/Lib/test/test_sax.py python/branches/py3k-ctypes-pep3118/Lib/test/test_scope.py python/branches/py3k-ctypes-pep3118/Lib/test/test_scriptpackages.py python/branches/py3k-ctypes-pep3118/Lib/test/test_select.py python/branches/py3k-ctypes-pep3118/Lib/test/test_set.py python/branches/py3k-ctypes-pep3118/Lib/test/test_sgmllib.py python/branches/py3k-ctypes-pep3118/Lib/test/test_shelve.py python/branches/py3k-ctypes-pep3118/Lib/test/test_shutil.py python/branches/py3k-ctypes-pep3118/Lib/test/test_signal.py python/branches/py3k-ctypes-pep3118/Lib/test/test_site.py python/branches/py3k-ctypes-pep3118/Lib/test/test_smtplib.py python/branches/py3k-ctypes-pep3118/Lib/test/test_socket.py python/branches/py3k-ctypes-pep3118/Lib/test/test_socketserver.py python/branches/py3k-ctypes-pep3118/Lib/test/test_sort.py python/branches/py3k-ctypes-pep3118/Lib/test/test_sqlite.py python/branches/py3k-ctypes-pep3118/Lib/test/test_ssl.py python/branches/py3k-ctypes-pep3118/Lib/test/test_strftime.py python/branches/py3k-ctypes-pep3118/Lib/test/test_strptime.py python/branches/py3k-ctypes-pep3118/Lib/test/test_struct.py python/branches/py3k-ctypes-pep3118/Lib/test/test_structmembers.py python/branches/py3k-ctypes-pep3118/Lib/test/test_subprocess.py python/branches/py3k-ctypes-pep3118/Lib/test/test_sundry.py python/branches/py3k-ctypes-pep3118/Lib/test/test_support.py python/branches/py3k-ctypes-pep3118/Lib/test/test_sys.py python/branches/py3k-ctypes-pep3118/Lib/test/test_tarfile.py python/branches/py3k-ctypes-pep3118/Lib/test/test_telnetlib.py python/branches/py3k-ctypes-pep3118/Lib/test/test_tempfile.py python/branches/py3k-ctypes-pep3118/Lib/test/test_thread.py python/branches/py3k-ctypes-pep3118/Lib/test/test_threading.py python/branches/py3k-ctypes-pep3118/Lib/test/test_timeout.py python/branches/py3k-ctypes-pep3118/Lib/test/test_tokenize.py python/branches/py3k-ctypes-pep3118/Lib/test/test_trace.py python/branches/py3k-ctypes-pep3118/Lib/test/test_tuple.py python/branches/py3k-ctypes-pep3118/Lib/test/test_types.py python/branches/py3k-ctypes-pep3118/Lib/test/test_unicode.py python/branches/py3k-ctypes-pep3118/Lib/test/test_unicode_file.py python/branches/py3k-ctypes-pep3118/Lib/test/test_unpack.py python/branches/py3k-ctypes-pep3118/Lib/test/test_unpack_ex.py python/branches/py3k-ctypes-pep3118/Lib/test/test_urllib.py python/branches/py3k-ctypes-pep3118/Lib/test/test_urllib2.py python/branches/py3k-ctypes-pep3118/Lib/test/test_urllib2_localnet.py python/branches/py3k-ctypes-pep3118/Lib/test/test_urllib2net.py python/branches/py3k-ctypes-pep3118/Lib/test/test_urllibnet.py python/branches/py3k-ctypes-pep3118/Lib/test/test_userdict.py python/branches/py3k-ctypes-pep3118/Lib/test/test_userlist.py python/branches/py3k-ctypes-pep3118/Lib/test/test_userstring.py python/branches/py3k-ctypes-pep3118/Lib/test/test_uu.py python/branches/py3k-ctypes-pep3118/Lib/test/test_warnings.py python/branches/py3k-ctypes-pep3118/Lib/test/test_wave.py python/branches/py3k-ctypes-pep3118/Lib/test/test_weakref.py python/branches/py3k-ctypes-pep3118/Lib/test/test_whichdb.py python/branches/py3k-ctypes-pep3118/Lib/test/test_winsound.py python/branches/py3k-ctypes-pep3118/Lib/test/test_wsgiref.py python/branches/py3k-ctypes-pep3118/Lib/test/test_xml_etree.py python/branches/py3k-ctypes-pep3118/Lib/test/test_xml_etree_c.py python/branches/py3k-ctypes-pep3118/Lib/test/test_xmlrpc.py python/branches/py3k-ctypes-pep3118/Lib/test/test_xmlrpc_net.py python/branches/py3k-ctypes-pep3118/Lib/test/test_zipfile.py python/branches/py3k-ctypes-pep3118/Lib/test/test_zlib.py python/branches/py3k-ctypes-pep3118/Lib/test/testtar.tar python/branches/py3k-ctypes-pep3118/Lib/threading.py python/branches/py3k-ctypes-pep3118/Lib/token.py python/branches/py3k-ctypes-pep3118/Lib/tokenize.py python/branches/py3k-ctypes-pep3118/Lib/trace.py python/branches/py3k-ctypes-pep3118/Lib/types.py python/branches/py3k-ctypes-pep3118/Lib/unittest.py python/branches/py3k-ctypes-pep3118/Lib/urllib.py python/branches/py3k-ctypes-pep3118/Lib/urllib2.py python/branches/py3k-ctypes-pep3118/Lib/warnings.py python/branches/py3k-ctypes-pep3118/Lib/weakref.py python/branches/py3k-ctypes-pep3118/Lib/xml/dom/minidom.py python/branches/py3k-ctypes-pep3118/Lib/xml/sax/expatreader.py python/branches/py3k-ctypes-pep3118/Lib/xmlrpclib.py python/branches/py3k-ctypes-pep3118/Lib/zipfile.py python/branches/py3k-ctypes-pep3118/Mac/BuildScript/build-installer.py python/branches/py3k-ctypes-pep3118/Mac/Demo/PICTbrowse/ICONbrowse.py python/branches/py3k-ctypes-pep3118/Mac/Demo/PICTbrowse/PICTbrowse.py python/branches/py3k-ctypes-pep3118/Mac/Demo/PICTbrowse/PICTbrowse2.py python/branches/py3k-ctypes-pep3118/Mac/Demo/PICTbrowse/cicnbrowse.py python/branches/py3k-ctypes-pep3118/Mac/Demo/PICTbrowse/oldPICTbrowse.py python/branches/py3k-ctypes-pep3118/Mac/Demo/applescript/Disk_Copy/Utility_Events.py python/branches/py3k-ctypes-pep3118/Mac/Demo/example1/dnslookup-1.py python/branches/py3k-ctypes-pep3118/Mac/Demo/example2/dnslookup-2.py python/branches/py3k-ctypes-pep3118/Mac/Demo/imgbrowse/imgbrowse.py python/branches/py3k-ctypes-pep3118/Mac/Demo/imgbrowse/mac_image.py python/branches/py3k-ctypes-pep3118/Mac/Modules/ae/aescan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/ah/ahscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/app/appscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/carbonevt/CarbonEvtscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/cf/cfscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/cg/cgscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/cm/cmscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/ctl/ctlscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/dlg/dlgscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/drag/dragscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/evt/evtscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/file/filescan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/fm/fmscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/folder/folderscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/help/helpscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/ibcarbon/IBCarbonscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/icn/icnscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/launch/launchscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/list/listscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/menu/menuscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/mlte/mltescan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/osa/osascan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/qd/qdscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/qdoffs/qdoffsscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/qt/qtscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/res/resscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/scrap/scrapscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/snd/sndscan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/te/tescan.py python/branches/py3k-ctypes-pep3118/Mac/Modules/win/winscan.py python/branches/py3k-ctypes-pep3118/Mac/Tools/Doc/HelpIndexingTool/Standard_Suite.py python/branches/py3k-ctypes-pep3118/Mac/Tools/Doc/setup.py python/branches/py3k-ctypes-pep3118/Mac/scripts/buildpkg.py python/branches/py3k-ctypes-pep3118/Makefile.pre.in python/branches/py3k-ctypes-pep3118/Misc/ACKS python/branches/py3k-ctypes-pep3118/Misc/HISTORY python/branches/py3k-ctypes-pep3118/Misc/NEWS python/branches/py3k-ctypes-pep3118/Misc/Vim/python.vim python/branches/py3k-ctypes-pep3118/Misc/Vim/syntax_test.py python/branches/py3k-ctypes-pep3118/Misc/Vim/vim_syntax.py python/branches/py3k-ctypes-pep3118/Misc/build.sh python/branches/py3k-ctypes-pep3118/Misc/cheatsheet python/branches/py3k-ctypes-pep3118/Misc/developers.txt python/branches/py3k-ctypes-pep3118/Misc/python-mode.el python/branches/py3k-ctypes-pep3118/Modules/Setup.dist python/branches/py3k-ctypes-pep3118/Modules/_bsddb.c python/branches/py3k-ctypes-pep3118/Modules/_collectionsmodule.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/_ctypes.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/_ctypes_test.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/callbacks.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/callproc.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/cfield.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/ctypes.h python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/LICENSE python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/README python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/aclocal.m4 python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/config.guess python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/config.sub python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/configure python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/configure.ac python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/fficonfig.h.in python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/fficonfig.py.in python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/include/ffi.h.in python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/include/ffi_common.h python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/install-sh python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/alpha/ffi.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/alpha/ffitarget.h python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/alpha/osf.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/arm/ffi.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/arm/ffitarget.h python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/arm/sysv.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/cris/ffi.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/cris/ffitarget.h python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/frv/eabi.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/frv/ffi.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/frv/ffitarget.h python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/ia64/ffi.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/ia64/ffitarget.h python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/ia64/ia64_flags.h python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/ia64/unix.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/m32r/ffi.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/m68k/ffi.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/m68k/ffitarget.h python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/m68k/sysv.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/mips/ffi.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/mips/ffitarget.h python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/mips/n32.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/mips/o32.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/pa/ffi.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/pa/ffitarget.h python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/pa/linux.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/darwin.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/darwin_closure.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/ffi.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/ffi_darwin.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/ffitarget.h python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/linux64.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/linux64_closure.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/ppc_closure.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/sysv.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/prep_cif.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/s390/ffi.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/s390/ffitarget.h python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/s390/sysv.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh/ffi.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh/ffitarget.h python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh/sysv.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh64/ffi.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh64/ffitarget.h python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh64/sysv.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sparc/ffi.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sparc/ffitarget.h python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sparc/v8.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sparc/v9.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/darwin.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/ffi.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/ffi64.c python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/ffitarget.h python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/sysv.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/unix64.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/win32.S python/branches/py3k-ctypes-pep3118/Modules/_ctypes/stgdict.c python/branches/py3k-ctypes-pep3118/Modules/_cursesmodule.c python/branches/py3k-ctypes-pep3118/Modules/_fileio.c python/branches/py3k-ctypes-pep3118/Modules/_heapqmodule.c python/branches/py3k-ctypes-pep3118/Modules/_localemodule.c python/branches/py3k-ctypes-pep3118/Modules/_sqlite/cache.c python/branches/py3k-ctypes-pep3118/Modules/_sqlite/cache.h python/branches/py3k-ctypes-pep3118/Modules/_sqlite/connection.c python/branches/py3k-ctypes-pep3118/Modules/_sqlite/connection.h python/branches/py3k-ctypes-pep3118/Modules/_sqlite/cursor.c python/branches/py3k-ctypes-pep3118/Modules/_sqlite/cursor.h python/branches/py3k-ctypes-pep3118/Modules/_sqlite/microprotocols.h python/branches/py3k-ctypes-pep3118/Modules/_sqlite/module.c python/branches/py3k-ctypes-pep3118/Modules/_sqlite/module.h python/branches/py3k-ctypes-pep3118/Modules/_sqlite/prepare_protocol.h python/branches/py3k-ctypes-pep3118/Modules/_sqlite/row.c python/branches/py3k-ctypes-pep3118/Modules/_sqlite/row.h python/branches/py3k-ctypes-pep3118/Modules/_sqlite/statement.c python/branches/py3k-ctypes-pep3118/Modules/_sqlite/statement.h python/branches/py3k-ctypes-pep3118/Modules/_sqlite/util.c python/branches/py3k-ctypes-pep3118/Modules/_sqlite/util.h python/branches/py3k-ctypes-pep3118/Modules/_ssl.c python/branches/py3k-ctypes-pep3118/Modules/_struct.c python/branches/py3k-ctypes-pep3118/Modules/_testcapimodule.c python/branches/py3k-ctypes-pep3118/Modules/_tkinter.c python/branches/py3k-ctypes-pep3118/Modules/arraymodule.c python/branches/py3k-ctypes-pep3118/Modules/binascii.c python/branches/py3k-ctypes-pep3118/Modules/cStringIO.c python/branches/py3k-ctypes-pep3118/Modules/cjkcodecs/_codecs_hk.c python/branches/py3k-ctypes-pep3118/Modules/cjkcodecs/mappings_hk.h python/branches/py3k-ctypes-pep3118/Modules/cmathmodule.c python/branches/py3k-ctypes-pep3118/Modules/config.c.in python/branches/py3k-ctypes-pep3118/Modules/datetimemodule.c python/branches/py3k-ctypes-pep3118/Modules/dbmmodule.c python/branches/py3k-ctypes-pep3118/Modules/fcntlmodule.c python/branches/py3k-ctypes-pep3118/Modules/gcmodule.c python/branches/py3k-ctypes-pep3118/Modules/gdbmmodule.c python/branches/py3k-ctypes-pep3118/Modules/getpath.c python/branches/py3k-ctypes-pep3118/Modules/itertoolsmodule.c python/branches/py3k-ctypes-pep3118/Modules/main.c python/branches/py3k-ctypes-pep3118/Modules/mathmodule.c python/branches/py3k-ctypes-pep3118/Modules/mmapmodule.c python/branches/py3k-ctypes-pep3118/Modules/operator.c python/branches/py3k-ctypes-pep3118/Modules/posixmodule.c python/branches/py3k-ctypes-pep3118/Modules/python.c python/branches/py3k-ctypes-pep3118/Modules/selectmodule.c python/branches/py3k-ctypes-pep3118/Modules/signalmodule.c python/branches/py3k-ctypes-pep3118/Modules/socketmodule.c python/branches/py3k-ctypes-pep3118/Modules/syslogmodule.c python/branches/py3k-ctypes-pep3118/Modules/timemodule.c python/branches/py3k-ctypes-pep3118/Modules/zlibmodule.c python/branches/py3k-ctypes-pep3118/Objects/abstract.c python/branches/py3k-ctypes-pep3118/Objects/bytesobject.c python/branches/py3k-ctypes-pep3118/Objects/cellobject.c python/branches/py3k-ctypes-pep3118/Objects/classobject.c python/branches/py3k-ctypes-pep3118/Objects/codeobject.c python/branches/py3k-ctypes-pep3118/Objects/complexobject.c python/branches/py3k-ctypes-pep3118/Objects/descrobject.c python/branches/py3k-ctypes-pep3118/Objects/dictobject.c python/branches/py3k-ctypes-pep3118/Objects/floatobject.c python/branches/py3k-ctypes-pep3118/Objects/frameobject.c python/branches/py3k-ctypes-pep3118/Objects/genobject.c python/branches/py3k-ctypes-pep3118/Objects/iterobject.c python/branches/py3k-ctypes-pep3118/Objects/listobject.c python/branches/py3k-ctypes-pep3118/Objects/longobject.c python/branches/py3k-ctypes-pep3118/Objects/methodobject.c python/branches/py3k-ctypes-pep3118/Objects/rangeobject.c python/branches/py3k-ctypes-pep3118/Objects/setobject.c python/branches/py3k-ctypes-pep3118/Objects/stringlib/formatter.h python/branches/py3k-ctypes-pep3118/Objects/stringlib/string_format.h python/branches/py3k-ctypes-pep3118/Objects/stringlib/stringdefs.h python/branches/py3k-ctypes-pep3118/Objects/stringlib/unicodedefs.h python/branches/py3k-ctypes-pep3118/Objects/stringobject.c python/branches/py3k-ctypes-pep3118/Objects/tupleobject.c python/branches/py3k-ctypes-pep3118/Objects/typeobject.c python/branches/py3k-ctypes-pep3118/Objects/unicodeobject.c python/branches/py3k-ctypes-pep3118/PC/VC6/pythoncore.dsp python/branches/py3k-ctypes-pep3118/PC/VS7.1/pythoncore.vcproj python/branches/py3k-ctypes-pep3118/PC/VS8.0/build_ssl.py python/branches/py3k-ctypes-pep3118/PC/VS8.0/build_tkinter.py python/branches/py3k-ctypes-pep3118/PC/VS8.0/pythoncore.vcproj python/branches/py3k-ctypes-pep3118/PC/WinMain.c python/branches/py3k-ctypes-pep3118/PC/_msi.c python/branches/py3k-ctypes-pep3118/PC/_winreg.c python/branches/py3k-ctypes-pep3118/PC/config.c python/branches/py3k-ctypes-pep3118/PC/example_nt/readme.txt python/branches/py3k-ctypes-pep3118/PC/getpathp.c python/branches/py3k-ctypes-pep3118/PC/os2emx/Makefile python/branches/py3k-ctypes-pep3118/PC/os2emx/README.os2emx python/branches/py3k-ctypes-pep3118/PC/os2vacpp/makefile python/branches/py3k-ctypes-pep3118/PC/os2vacpp/makefile.omk python/branches/py3k-ctypes-pep3118/PC/pyconfig.h python/branches/py3k-ctypes-pep3118/PC/python_nt.rc python/branches/py3k-ctypes-pep3118/PC/readme.txt python/branches/py3k-ctypes-pep3118/PC/w9xpopen.c python/branches/py3k-ctypes-pep3118/PCbuild/_bsddb.vcproj python/branches/py3k-ctypes-pep3118/PCbuild/_sqlite3.vcproj python/branches/py3k-ctypes-pep3118/PCbuild/_ssl.vcproj python/branches/py3k-ctypes-pep3118/PCbuild/_tkinter.vcproj python/branches/py3k-ctypes-pep3118/PCbuild/bdist_wininst.vcproj python/branches/py3k-ctypes-pep3118/PCbuild/build.bat python/branches/py3k-ctypes-pep3118/PCbuild/build_ssl.py python/branches/py3k-ctypes-pep3118/PCbuild/build_tkinter.py python/branches/py3k-ctypes-pep3118/PCbuild/debug.vsprops python/branches/py3k-ctypes-pep3118/PCbuild/pcbuild.sln python/branches/py3k-ctypes-pep3118/PCbuild/pyd.vsprops python/branches/py3k-ctypes-pep3118/PCbuild/pyd_d.vsprops python/branches/py3k-ctypes-pep3118/PCbuild/pyproject.vsprops python/branches/py3k-ctypes-pep3118/PCbuild/python.vcproj python/branches/py3k-ctypes-pep3118/PCbuild/pythoncore.vcproj python/branches/py3k-ctypes-pep3118/PCbuild/readme.txt python/branches/py3k-ctypes-pep3118/PCbuild/release.vsprops python/branches/py3k-ctypes-pep3118/PCbuild/rt.bat python/branches/py3k-ctypes-pep3118/PCbuild/x64.vsprops python/branches/py3k-ctypes-pep3118/Parser/Python.asdl python/branches/py3k-ctypes-pep3118/Parser/asdl.py python/branches/py3k-ctypes-pep3118/Parser/asdl_c.py python/branches/py3k-ctypes-pep3118/Parser/parser.c python/branches/py3k-ctypes-pep3118/Parser/parser.h python/branches/py3k-ctypes-pep3118/Parser/parsetok.c python/branches/py3k-ctypes-pep3118/Parser/printgrammar.c python/branches/py3k-ctypes-pep3118/Parser/spark.py python/branches/py3k-ctypes-pep3118/Parser/tokenizer.c python/branches/py3k-ctypes-pep3118/Python/Python-ast.c python/branches/py3k-ctypes-pep3118/Python/ast.c python/branches/py3k-ctypes-pep3118/Python/bltinmodule.c python/branches/py3k-ctypes-pep3118/Python/ceval.c python/branches/py3k-ctypes-pep3118/Python/compile.c python/branches/py3k-ctypes-pep3118/Python/errors.c python/branches/py3k-ctypes-pep3118/Python/frozenmain.c python/branches/py3k-ctypes-pep3118/Python/future.c python/branches/py3k-ctypes-pep3118/Python/getargs.c python/branches/py3k-ctypes-pep3118/Python/getcopyright.c python/branches/py3k-ctypes-pep3118/Python/getopt.c python/branches/py3k-ctypes-pep3118/Python/graminit.c python/branches/py3k-ctypes-pep3118/Python/import.c python/branches/py3k-ctypes-pep3118/Python/marshal.c python/branches/py3k-ctypes-pep3118/Python/mystrtoul.c python/branches/py3k-ctypes-pep3118/Python/peephole.c python/branches/py3k-ctypes-pep3118/Python/pystrcmp.c python/branches/py3k-ctypes-pep3118/Python/pystrtod.c python/branches/py3k-ctypes-pep3118/Python/pythonrun.c python/branches/py3k-ctypes-pep3118/Python/strtod.c python/branches/py3k-ctypes-pep3118/Python/symtable.c python/branches/py3k-ctypes-pep3118/Python/sysmodule.c python/branches/py3k-ctypes-pep3118/Python/traceback.c python/branches/py3k-ctypes-pep3118/README python/branches/py3k-ctypes-pep3118/Tools/ (props changed) python/branches/py3k-ctypes-pep3118/Tools/bgen/bgen/bgenGenerator.py python/branches/py3k-ctypes-pep3118/Tools/buildbot/build-amd64.bat python/branches/py3k-ctypes-pep3118/Tools/buildbot/build.bat python/branches/py3k-ctypes-pep3118/Tools/buildbot/buildmsi.bat python/branches/py3k-ctypes-pep3118/Tools/buildbot/clean-amd64.bat python/branches/py3k-ctypes-pep3118/Tools/buildbot/clean.bat python/branches/py3k-ctypes-pep3118/Tools/buildbot/external-amd64.bat python/branches/py3k-ctypes-pep3118/Tools/buildbot/external.bat python/branches/py3k-ctypes-pep3118/Tools/buildbot/test-amd64.bat python/branches/py3k-ctypes-pep3118/Tools/faqwiz/faqw.py python/branches/py3k-ctypes-pep3118/Tools/i18n/pygettext.py python/branches/py3k-ctypes-pep3118/Tools/modulator/Tkextra.py python/branches/py3k-ctypes-pep3118/Tools/msi/msi.py python/branches/py3k-ctypes-pep3118/Tools/msi/schema.py python/branches/py3k-ctypes-pep3118/Tools/msi/uuids.py python/branches/py3k-ctypes-pep3118/Tools/pybench/Setup.py python/branches/py3k-ctypes-pep3118/Tools/pybench/pybench.py python/branches/py3k-ctypes-pep3118/Tools/pybench/systimes.py python/branches/py3k-ctypes-pep3118/Tools/pynche/ChipViewer.py python/branches/py3k-ctypes-pep3118/Tools/pynche/ColorDB.py python/branches/py3k-ctypes-pep3118/Tools/pynche/TypeinViewer.py python/branches/py3k-ctypes-pep3118/Tools/scripts/ (props changed) python/branches/py3k-ctypes-pep3118/Tools/scripts/checkappend.py python/branches/py3k-ctypes-pep3118/Tools/scripts/finddiv.py python/branches/py3k-ctypes-pep3118/Tools/scripts/logmerge.py python/branches/py3k-ctypes-pep3118/Tools/scripts/nm2def.py python/branches/py3k-ctypes-pep3118/Tools/scripts/pindent.py python/branches/py3k-ctypes-pep3118/Tools/scripts/pysource.py python/branches/py3k-ctypes-pep3118/Tools/scripts/reindent.py python/branches/py3k-ctypes-pep3118/Tools/scripts/xxci.py python/branches/py3k-ctypes-pep3118/Tools/ssl/get-remote-certificate.py python/branches/py3k-ctypes-pep3118/Tools/unicode/gencodec.py python/branches/py3k-ctypes-pep3118/Tools/unicode/makeunicodedata.py python/branches/py3k-ctypes-pep3118/Tools/webchecker/wcgui.py python/branches/py3k-ctypes-pep3118/Tools/webchecker/wsgui.py python/branches/py3k-ctypes-pep3118/configure python/branches/py3k-ctypes-pep3118/configure.in python/branches/py3k-ctypes-pep3118/pyconfig.h.in python/branches/py3k-ctypes-pep3118/setup.py Modified: python/branches/py3k-ctypes-pep3118/Demo/classes/Dbm.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Demo/classes/Dbm.py (original) +++ python/branches/py3k-ctypes-pep3118/Demo/classes/Dbm.py Wed Apr 30 15:57:13 2008 @@ -50,7 +50,7 @@ value = d[key] print('currently:', value) value = eval(input('value: ')) - if value == None: + if value is None: del d[key] else: d[key] = value Modified: python/branches/py3k-ctypes-pep3118/Demo/classes/README ============================================================================== --- python/branches/py3k-ctypes-pep3118/Demo/classes/README (original) +++ python/branches/py3k-ctypes-pep3118/Demo/classes/README Wed Apr 30 15:57:13 2008 @@ -4,7 +4,6 @@ Dates.py Date manipulation package by Tim Peters Dbm.py Wrapper around built-in dbm, supporting arbitrary values Range.py Example of a generator: re-implement built-in range() -Rat.py Rational numbers Rev.py Yield the reverse of a sequence Vec.py A simple vector class bitvec.py A bit-vector class by Jan-Hein B\"uhrman Modified: python/branches/py3k-ctypes-pep3118/Demo/curses/ncurses.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Demo/curses/ncurses.py (original) +++ python/branches/py3k-ctypes-pep3118/Demo/curses/ncurses.py Wed Apr 30 15:57:13 2008 @@ -9,7 +9,7 @@ from curses import panel def wGetchar(win = None): - if win == None: win = stdscr + if win is None: win = stdscr return win.getch() def Getchar(): Modified: python/branches/py3k-ctypes-pep3118/Demo/rpc/mountclient.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Demo/rpc/mountclient.py (original) +++ python/branches/py3k-ctypes-pep3118/Demo/rpc/mountclient.py Wed Apr 30 15:57:13 2008 @@ -100,7 +100,7 @@ # This function is called to cough up a suitable # authentication object for a call to procedure 'proc'. def mkcred(self): - if self.cred == None: + if self.cred is None: self.cred = rpc.AUTH_UNIX, rpc.make_auth_unix_default() return self.cred Modified: python/branches/py3k-ctypes-pep3118/Demo/rpc/nfsclient.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Demo/rpc/nfsclient.py (original) +++ python/branches/py3k-ctypes-pep3118/Demo/rpc/nfsclient.py Wed Apr 30 15:57:13 2008 @@ -129,7 +129,7 @@ self.unpacker = NFSUnpacker('') def mkcred(self): - if self.cred == None: + if self.cred is None: self.cred = rpc.AUTH_UNIX, rpc.make_auth_unix_default() return self.cred @@ -170,7 +170,7 @@ for fileid, name, cookie in entries: list.append((fileid, name)) last_cookie = cookie - if eof or last_cookie == None: + if eof or last_cookie is None: break ra = (ra[0], last_cookie, ra[2]) return list @@ -184,7 +184,7 @@ else: filesys = None from mountclient import UDPMountClient, TCPMountClient mcl = TCPMountClient(host) - if filesys == None: + if filesys is None: list = mcl.Export() for item in list: print(item) Modified: python/branches/py3k-ctypes-pep3118/Demo/rpc/rpc.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Demo/rpc/rpc.py (original) +++ python/branches/py3k-ctypes-pep3118/Demo/rpc/rpc.py Wed Apr 30 15:57:13 2008 @@ -260,13 +260,13 @@ def mkcred(self): # Override this to use more powerful credentials - if self.cred == None: + if self.cred is None: self.cred = (AUTH_NULL, make_auth_null()) return self.cred def mkverf(self): # Override this to use a more powerful verifier - if self.verf == None: + if self.verf is None: self.verf = (AUTH_NULL, make_auth_null()) return self.verf @@ -317,7 +317,7 @@ def bindresvport(sock, host): global last_resv_port_tried FIRST, LAST = 600, 1024 # Range of ports to try - if last_resv_port_tried == None: + if last_resv_port_tried is None: import os last_resv_port_tried = FIRST + os.getpid() % (LAST-FIRST) for i in range(last_resv_port_tried, LAST) + \ @@ -811,7 +811,7 @@ def session(self): call, host_port = self.sock.recvfrom(8192) reply = self.handle(call) - if reply != None: + if reply is not None: self.sock.sendto(reply, host_port) Modified: python/branches/py3k-ctypes-pep3118/Demo/tkinter/guido/ShellWindow.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Demo/tkinter/guido/ShellWindow.py (original) +++ python/branches/py3k-ctypes-pep3118/Demo/tkinter/guido/ShellWindow.py Wed Apr 30 15:57:13 2008 @@ -121,11 +121,7 @@ sys.stderr.write('popen2: bad write dup\n') if os.dup(c2pwrite) != 2: sys.stderr.write('popen2: bad write dup\n') - for i in range(3, MAXFD): - try: - os.close(i) - except: - pass + os.closerange(3, MAXFD) try: os.execvp(prog, args) finally: Modified: python/branches/py3k-ctypes-pep3118/Demo/tkinter/guido/paint.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Demo/tkinter/guido/paint.py (original) +++ python/branches/py3k-ctypes-pep3118/Demo/tkinter/guido/paint.py Wed Apr 30 15:57:13 2008 @@ -50,7 +50,7 @@ def motion(event): if b1 == "down": global xold, yold - if xold != None and yold != None: + if xold is not None and yold is not None: event.widget.create_line(xold,yold,event.x,event.y,smooth=TRUE) # here's where you draw it. smooth. neat. xold = event.x Modified: python/branches/py3k-ctypes-pep3118/Doc/ACKS.txt ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/ACKS.txt (original) +++ python/branches/py3k-ctypes-pep3118/Doc/ACKS.txt Wed Apr 30 15:57:13 2008 @@ -21,6 +21,7 @@ * Chris Barker * Don Bashford * Anthony Baxter + * Alexander Belopolsky * Bennett Benson * Jonathan Black * Robin Boerdijk @@ -144,6 +145,7 @@ * Harri Pasanen * Bo Peng * Tim Peters + * Benjamin Peterson * Christopher Petrilli * Justin D. Pettit * Chris Phoenix @@ -209,3 +211,5 @@ * Moshe Zadka * Milan Zamazal * Cheng Zhang + * Trent Nelson + * Michael Foord Modified: python/branches/py3k-ctypes-pep3118/Doc/Makefile ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/Makefile (original) +++ python/branches/py3k-ctypes-pep3118/Doc/Makefile Wed Apr 30 15:57:13 2008 @@ -8,19 +8,22 @@ SVNROOT = http://svn.python.org/projects SPHINXOPTS = PAPER = +SOURCES = ALLSPHINXOPTS = -b $(BUILDER) -d build/doctrees -D latex_paper_size=$(PAPER) \ - $(SPHINXOPTS) . build/$(BUILDER) + $(SPHINXOPTS) . build/$(BUILDER) $(SOURCES) -.PHONY: help checkout update build html web htmlhelp clean +.PHONY: help checkout update build html web htmlhelp clean coverage help: @echo "Please use \`make ' where is one of" - @echo " html to make standalone HTML files" - @echo " web to make file usable by Sphinx.web" - @echo " htmlhelp to make HTML files and a HTML help project" - @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" - @echo " changes to make an overview over all changed/added/deprecated items" + @echo " html to make standalone HTML files" + @echo " web to make file usable by Sphinx.web" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " changes to make an overview over all changed/added/deprecated items" + @echo " linkcheck to check all external links for integrity" + @echo " coverage to check documentation coverage for library and C API" checkout: @if [ ! -d tools/sphinx ]; then \ @@ -31,6 +34,10 @@ echo "Checking out Docutils..."; \ svn checkout $(SVNROOT)/external/docutils-0.4/docutils tools/docutils; \ fi + @if [ ! -d tools/jinja ]; then \ + echo "Checking out Jinja..."; \ + svn checkout $(SVNROOT)/external/Jinja-1.1/jinja tools/jinja; \ + fi @if [ ! -d tools/pygments ]; then \ echo "Checking out Pygments..."; \ svn checkout $(SVNROOT)/external/Pygments-0.9/pygments tools/pygments; \ @@ -39,6 +46,7 @@ update: checkout svn update tools/sphinx svn update tools/docutils + svn update tools/jinja svn update tools/pygments build: checkout @@ -71,6 +79,20 @@ changes: build @echo "The overview file is in build/changes." +linkcheck: BUILDER = linkcheck +linkcheck: build + @echo "Link check complete; look for any errors in the above output " \ + "or in build/$(BUILDER)/output.txt" + +coverage: BUILDER = coverage +coverage: build + @echo "Coverage finished; see c.txt and python.txt in build/coverage" + +doctest: BUILDER = doctest +doctest: build + @echo "Testing of doctests in the sources finished, look at the " \ + "results in build/doctest/output.txt" + clean: -rm -rf build/* -rm -rf tools/sphinx Modified: python/branches/py3k-ctypes-pep3118/Doc/README.txt ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/README.txt (original) +++ python/branches/py3k-ctypes-pep3118/Doc/README.txt Wed Apr 30 15:57:13 2008 @@ -14,7 +14,7 @@ Building the docs ================= -You need to install Python 2.5.1 or higher (but Python 3.0 is not supported yet); +You need to install Python 2.4 or higher (but Python 3.0 is not supported yet); the toolset used to build the docs are written in Python. The toolset used to build the documentation is called *Sphinx*, it is not included in this tree, but maintained separately in the Python Subversion repository. Also @@ -56,10 +56,17 @@ * "latex", which builds LaTeX source files that can be run with "pdflatex" to produce PDF documents. + * "linkcheck", which checks all external references to see whether they are + broken, redirected or malformed, and outputs this information to stdout + as well as a plain-text (.txt) file. + * "changes", which builds an overview over all versionadded/versionchanged/ deprecated items in the current version. This is meant as a help for the writer of the "What's New" document. + * "coverage", which builds a coverage overview for standard library modules + and C API. + A "make update" updates the Subversion checkouts in `tools/`. @@ -116,7 +123,7 @@ as long as you don't change or remove the copyright notice: ---------------------------------------------------------------------- -Copyright (c) 2000-2007 Python Software Foundation. +Copyright (c) 2000-2008 Python Software Foundation. All rights reserved. Copyright (c) 2000 BeOpen.com. Modified: python/branches/py3k-ctypes-pep3118/Doc/bugs.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/bugs.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/bugs.rst Wed Apr 30 15:57:13 2008 @@ -53,7 +53,7 @@ Article which goes into some detail about how to create a useful bug report. This describes what kind of information is useful and why it is useful. - `Bug Writing Guidelines `_ + `Bug Writing Guidelines `_ Information about writing a good bug report. Some of this is specific to the Mozilla project, but describes general good practices. Deleted: python/branches/py3k-ctypes-pep3118/Doc/builddoc.bat ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/builddoc.bat Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,52 +0,0 @@ - at echo off -setlocal - -set SVNROOT=http://svn.python.org/projects -if "%PYTHON%" EQU "" set PYTHON=python25 - -if "%1" EQU "" goto help -if "%1" EQU "html" goto build -if "%1" EQU "htmlhelp" goto build -if "%1" EQU "web" goto build -if "%1" EQU "webrun" goto webrun -if "%1" EQU "checkout" goto checkout -if "%1" EQU "update" goto update - -:help -echo HELP -echo. -echo builddoc checkout -echo builddoc update -echo builddoc html -echo builddoc htmlhelp -echo builddoc web -echo builddoc webrun -echo. -goto end - -:checkout -svn co %SVNROOT%/doctools/trunk/sphinx tools/sphinx -svn co %SVNROOT%/external/docutils-0.4/docutils tools/docutils -svn co %SVNROOT%/external/Pygments-0.9/pygments tools/pygments -goto end - -:update -svn update tools/sphinx -svn update tools/docutils -svn update tools/pygments -goto end - -:build -if not exist build mkdir build -if not exist build\%1 mkdir build\%1 -if not exist build\doctrees mkdir build\doctrees -cmd /C %PYTHON% tools\sphinx-build.py -b%1 -dbuild\doctrees . build\%1 -if "%1" EQU "htmlhelp" "%ProgramFiles%\HTML Help Workshop\hhc.exe" build\htmlhelp\pydoc.hhp -goto end - -:webrun -set PYTHONPATH=tools -%PYTHON% -m sphinx.web build\web -goto end - -:end Modified: python/branches/py3k-ctypes-pep3118/Doc/c-api/arg.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/c-api/arg.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/c-api/arg.rst Wed Apr 30 15:57:13 2008 @@ -212,7 +212,7 @@ :ctype:`void\*` argument that was passed to the :cfunc:`PyArg_Parse\*` function. The returned *status* should be ``1`` for a successful conversion and ``0`` if the conversion has failed. When the conversion fails, the *converter* function - should raise an exception. + should raise an exception and leave the content of *address* unmodified. ``S`` (string) [PyStringObject \*] Like ``O`` but requires that the Python object is a string object. Raises @@ -284,9 +284,13 @@ units above, where these parameters are used as input values; they should match what is specified for the corresponding format unit in that case. -For the conversion to succeed, the *arg* object must match the format and the -format must be exhausted. On success, the :cfunc:`PyArg_Parse\*` functions -return true, otherwise they return false and raise an appropriate exception. +For the conversion to succeed, the *arg* object must match the format +and the format must be exhausted. On success, the +:cfunc:`PyArg_Parse\*` functions return true, otherwise they return +false and raise an appropriate exception. When the +:cfunc:`PyArg_Parse\*` functions fail due to conversion failure in one +of the format units, the variables at the addresses corresponding to that +and the following format units are left untouched. .. cfunction:: int PyArg_ParseTuple(PyObject *args, const char *format, ...) Modified: python/branches/py3k-ctypes-pep3118/Doc/c-api/float.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/c-api/float.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/c-api/float.rst Wed Apr 30 15:57:13 2008 @@ -72,3 +72,9 @@ .. cfunction:: double PyFloat_GetMin(void) Return the minimum normalized positive float *DBL_MIN* as C :ctype:`double`. + +.. cfunction:: void PyFloat_CompactFreeList(size_t *bc, size_t *bf, size_t *sum) + + Compact the float free list. *bc* is the number of allocated blocks before + blocks are freed, *bf* is the number of freed blocks and *sum* is the number + of remaining objects in the blocks. Modified: python/branches/py3k-ctypes-pep3118/Doc/c-api/import.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/c-api/import.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/c-api/import.rst Wed Apr 30 15:57:13 2008 @@ -134,6 +134,19 @@ ``sys.modules``). Note that this is a per-interpreter variable. +.. cfunction:: PyObject* PyImport_GetImporter(PyObject *path) + + Return an importer object for a :data:`sys.path`/:attr:`pkg.__path__` item + *path*, possibly by fetching it from the :data:`sys.path_importer_cache` + dict. If it wasn't yet cached, traverse :data:`sys.path_hooks` until a hook + is found that can handle the path item. Return ``None`` if no hook could; + this tells our caller it should fall back to the builtin import mechanism. + Cache the result in :data:`sys.path_importer_cache`. Return a new reference + to the importer object. + + .. versionadded:: 2.6 + + .. cfunction:: void _PyImport_Init() Initialize the import mechanism. For internal use only. Modified: python/branches/py3k-ctypes-pep3118/Doc/c-api/init.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/c-api/init.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/c-api/init.rst Wed Apr 30 15:57:13 2008 @@ -161,7 +161,7 @@ haven't been explicitly destroyed at that point. -.. cfunction:: void Py_SetProgramName(char *name) +.. cfunction:: void Py_SetProgramName(wchar_t *name) .. index:: single: Py_Initialize() @@ -170,11 +170,12 @@ This function should be called before :cfunc:`Py_Initialize` is called for the first time, if it is called at all. It tells the interpreter the value - of the ``argv[0]`` argument to the :cfunc:`main` function of the program. + of the ``argv[0]`` argument to the :cfunc:`main` function of the program + (converted to wide characters). This is used by :cfunc:`Py_GetPath` and some other functions below to find the Python run-time libraries relative to the interpreter executable. The default value is ``'python'``. The argument should point to a - zero-terminated character string in static storage whose contents will not + zero-terminated wide character string in static storage whose contents will not change for the duration of the program's execution. No code in the Python interpreter will change the contents of this storage. @@ -188,7 +189,7 @@ value. -.. cfunction:: char* Py_GetPrefix() +.. cfunction:: wchar_t* Py_GetPrefix() Return the *prefix* for installed platform-independent files. This is derived through a number of complicated rules from the program name set with @@ -201,7 +202,7 @@ It is only useful on Unix. See also the next function. -.. cfunction:: char* Py_GetExecPrefix() +.. cfunction:: wchar_t* Py_GetExecPrefix() Return the *exec-prefix* for installed platform-*dependent* files. This is derived through a number of complicated rules from the program name set with @@ -236,7 +237,7 @@ platform. -.. cfunction:: char* Py_GetProgramFullPath() +.. cfunction:: wchar_t* Py_GetProgramFullPath() .. index:: single: Py_SetProgramName() @@ -249,7 +250,7 @@ to Python code as ``sys.executable``. -.. cfunction:: char* Py_GetPath() +.. cfunction:: wchar_t* Py_GetPath() .. index:: triple: module; search; path @@ -342,7 +343,7 @@ ``sys.version``. -.. cfunction:: void PySys_SetArgv(int argc, char **argv) +.. cfunction:: void PySys_SetArgv(int argc, wchar_t **argv) .. index:: single: main() Modified: python/branches/py3k-ctypes-pep3118/Doc/c-api/intro.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/c-api/intro.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/c-api/intro.rst Wed Apr 30 15:57:13 2008 @@ -137,7 +137,7 @@ object type, such as a list, as well as performing any additional finalization that's needed. There's no chance that the reference count can overflow; at least as many bits are used to hold the reference count as there are distinct -memory locations in virtual memory (assuming ``sizeof(long) >= sizeof(char*)``). +memory locations in virtual memory (assuming ``sizeof(Py_ssize_t) >= sizeof(void*)``). Thus, the reference count increment is a simple operation. It is not necessary to increment an object's reference count for every local Modified: python/branches/py3k-ctypes-pep3118/Doc/c-api/long.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/c-api/long.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/c-api/long.rst Wed Apr 30 15:57:13 2008 @@ -190,7 +190,7 @@ .. cfunction:: void* PyLong_AsVoidPtr(PyObject *pylong) - Convert a Python integer *pylong* to a C :ctype:`void` pointer. If *pylong* - cannot be converted, an :exc:`OverflowError` will be raised. This is only - assured to produce a usable :ctype:`void` pointer for values created with - :cfunc:`PyLong_FromVoidPtr`. + Convert a Python integer *pylong* to a C :ctype:`void` pointer. + If *pylong* cannot be converted, an :exc:`OverflowError` will be raised. This + is only assured to produce a usable :ctype:`void` pointer for values created + with :cfunc:`PyLong_FromVoidPtr`. Modified: python/branches/py3k-ctypes-pep3118/Doc/c-api/method.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/c-api/method.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/c-api/method.rst Wed Apr 30 15:57:13 2008 @@ -92,3 +92,9 @@ .. cfunction:: PyObject* PyMethod_GET_SELF(PyObject *meth) Macro version of :cfunc:`PyMethod_Self` which avoids error checking. + + +.. cfunction:: int PyMethod_ClearFreeList(void) + + Clear the free list. Return the total number of freed items. + Modified: python/branches/py3k-ctypes-pep3118/Doc/c-api/module.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/c-api/module.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/c-api/module.rst Wed Apr 30 15:57:13 2008 @@ -18,12 +18,12 @@ is exposed to Python programs as ``types.ModuleType``. -.. cmacro:: int PyModule_Check(PyObject *p) +.. cfunction:: int PyModule_Check(PyObject *p) Return true if *p* is a module object, or a subtype of a module object. -.. cmacro:: int PyModule_CheckExact(PyObject *p) +.. cfunction:: int PyModule_CheckExact(PyObject *p) Return true if *p* is a module object, but not a subtype of :cdata:`PyModule_Type`. @@ -94,7 +94,7 @@ null-terminated. Return ``-1`` on error, ``0`` on success. -.. cmacro:: int PyModule_AddIntMacro(PyObject *module, macro) +.. cfunction:: int PyModule_AddIntMacro(PyObject *module, macro) Add an int constant to *module*. The name and the value are taken from *macro*. For example ``PyModule_AddConstant(module, AF_INET)`` adds the int @@ -102,7 +102,7 @@ Return ``-1`` on error, ``0`` on success. -.. cmacro:: int PyModule_AddStringMacro(PyObject *module, macro) +.. cfunction:: int PyModule_AddStringMacro(PyObject *module, macro) Add a string constant to *module*. Modified: python/branches/py3k-ctypes-pep3118/Doc/c-api/objbuffer.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/c-api/objbuffer.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/c-api/objbuffer.rst Wed Apr 30 15:57:13 2008 @@ -8,7 +8,7 @@ .. cfunction:: int PyObject_AsCharBuffer(PyObject *obj, const char **buffer, Py_ssize_t *buffer_len) - Returns a pointer to a read-only memory location useable as character- based + Returns a pointer to a read-only memory location usable as character-based input. The *obj* argument must support the single-segment character buffer interface. On success, returns ``0``, sets *buffer* to the memory location and *buffer_len* to the buffer length. Returns ``-1`` and sets a :exc:`TypeError` Modified: python/branches/py3k-ctypes-pep3118/Doc/c-api/set.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/c-api/set.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/c-api/set.rst Wed Apr 30 15:57:13 2008 @@ -50,6 +50,15 @@ the constructor functions work with any iterable Python object. +.. cfunction:: int PySet_Check(PyObject *p) + + Return true if *p* is a :class:`set` object or an instance of a subtype. + +.. cfunction:: int PyFrozenSet_Check(PyObject *p) + + Return true if *p* is a :class:`frozenset` object or an instance of a + subtype. + .. cfunction:: int PyAnySet_Check(PyObject *p) Return true if *p* is a :class:`set` object, a :class:`frozenset` object, or an @@ -84,6 +93,11 @@ set on success or *NULL* on failure. Raise :exc:`TypeError` if *iterable* is not actually iterable. + .. versionchanged:: 2.6 + Now guaranteed to return a brand-new :class:`frozenset`. Formerly, + frozensets of zero-length were a singleton. This got in the way of + building-up new frozensets with :meth:`PySet_Add`. + The following functions and macros are available for instances of :class:`set` or :class:`frozenset` or instances of their subtypes. @@ -110,9 +124,6 @@ the *key* is unhashable. Raise :exc:`PyExc_SystemError` if *anyset* is not a :class:`set`, :class:`frozenset`, or an instance of a subtype. -The following functions are available for instances of :class:`set` or its -subtypes but not for instances of :class:`frozenset` or its subtypes. - .. cfunction:: int PySet_Add(PyObject *set, PyObject *key) @@ -122,6 +133,14 @@ Raise a :exc:`SystemError` if *set* is an not an instance of :class:`set` or its subtype. + .. versionchanged:: 2.6 + Now works with instances of :class:`frozenset` or its subtypes. + Like :cfunc:`PyTuple_SetItem` in that it can be used to fill-in the + values of brand new frozensets before they are exposed to other code. + +The following functions are available for instances of :class:`set` or its +subtypes but not for instances of :class:`frozenset` or its subtypes. + .. cfunction:: int PySet_Discard(PyObject *set, PyObject *key) Modified: python/branches/py3k-ctypes-pep3118/Doc/c-api/structures.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/c-api/structures.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/c-api/structures.rst Wed Apr 30 15:57:13 2008 @@ -20,7 +20,7 @@ All object types are extensions of this type. This is a type which contains the information Python needs to treat a pointer to an object as an object. In a - normal "release" build, it contains only the objects reference count and a + normal "release" build, it contains only the object's reference count and a pointer to the corresponding type object. It corresponds to the fields defined by the expansion of the ``PyObject_HEAD`` macro. Modified: python/branches/py3k-ctypes-pep3118/Doc/c-api/sys.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/c-api/sys.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/c-api/sys.rst Wed Apr 30 15:57:13 2008 @@ -84,11 +84,11 @@ Reset :data:`sys.warnoptions` to an empty list. -.. cfunction:: void PySys_AddWarnOption(char *s) +.. cfunction:: void PySys_AddWarnOption(wchar_t *s) Append *s* to :data:`sys.warnoptions`. -.. cfunction:: void PySys_SetPath(char *path) +.. cfunction:: void PySys_SetPath(wchar_t *path) Set :data:`sys.path` to a list object of paths found in *path* which should be a list of paths separated with the platform's search path delimiter Modified: python/branches/py3k-ctypes-pep3118/Doc/c-api/tuple.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/c-api/tuple.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/c-api/tuple.rst Wed Apr 30 15:57:13 2008 @@ -105,3 +105,7 @@ this function. If the object referenced by ``*p`` is replaced, the original ``*p`` is destroyed. On failure, returns ``-1`` and sets ``*p`` to *NULL*, and raises :exc:`MemoryError` or :exc:`SystemError`. + +.. cfunction:: int PyTuple_ClearFreeList(void) + + Clear the free list. Return the total number of freed items. Modified: python/branches/py3k-ctypes-pep3118/Doc/c-api/type.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/c-api/type.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/c-api/type.rst Wed Apr 30 15:57:13 2008 @@ -33,6 +33,11 @@ standard type object. Return false in all other cases. +.. cfunction:: unsigned int PyType_ClearCache(void) + + Clears the internal lookup cache. Return the current version tag. + + .. cfunction:: int PyType_HasFeature(PyObject *o, int feature) Return true if the type object *o* sets the feature *feature*. Type features Modified: python/branches/py3k-ctypes-pep3118/Doc/c-api/typeobj.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/c-api/typeobj.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/c-api/typeobj.rst Wed Apr 30 15:57:13 2008 @@ -560,7 +560,7 @@ The :attr:`tp_traverse` pointer is used by the garbage collector to detect reference cycles. A typical implementation of a :attr:`tp_traverse` function simply calls :cfunc:`Py_VISIT` on each of the instance's members that are Python - objects. For exampe, this is function :cfunc:`local_traverse` from the + objects. For example, this is function :cfunc:`local_traverse` from the :mod:`thread` extension module:: static int @@ -730,8 +730,7 @@ An optional pointer to a function that returns an iterator for the object. Its presence normally signals that the instances of this type are iterable (although - sequences may be iterable without this function, and classic instances always - have this function, even if they don't define an :meth:`__iter__` method). + sequences may be iterable without this function). This function has the same signature as :cfunc:`PyObject_GetIter`. @@ -742,9 +741,7 @@ An optional pointer to a function that returns the next item in an iterator, or raises :exc:`StopIteration` when the iterator is exhausted. Its presence - normally signals that the instances of this type are iterators (although classic - instances always have this function, even if they don't define a - :meth:`__next__` method). + normally signals that the instances of this type are iterators. Iterator types should also define the :attr:`tp_iter` function, and that function should return the iterator instance itself (not a new iterator Modified: python/branches/py3k-ctypes-pep3118/Doc/c-api/unicode.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/c-api/unicode.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/c-api/unicode.rst Wed Apr 30 15:57:13 2008 @@ -83,6 +83,11 @@ Return a pointer to the internal buffer of the object. *o* has to be a :ctype:`PyUnicodeObject` (not checked). + +.. cfunction:: int PyUnicode_ClearFreeList(void) + + Clear the free list. Return the total number of freed items. + Unicode provides many different character properties. The most often needed ones are available through these macros which are mapped to C functions depending on the Python configuration. @@ -331,6 +336,8 @@ .. cfunction:: PyObject* PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size) Create a Unicode object from the :ctype:`wchar_t` buffer *w* of the given size. + Passing -1 as the size indicates that the function must itself compute the length, + using wcslen. Return *NULL* on failure. Modified: python/branches/py3k-ctypes-pep3118/Doc/c-api/veryhigh.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/c-api/veryhigh.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/c-api/veryhigh.rst Wed Apr 30 15:57:13 2008 @@ -25,16 +25,18 @@ the same library that the Python runtime is using. -.. cfunction:: int Py_Main(int argc, char **argv) +.. cfunction:: int Py_Main(int argc, wchar_t **argv) - The main program for the standard interpreter. This is made available for - programs which embed Python. The *argc* and *argv* parameters should be - prepared exactly as those which are passed to a C program's :cfunc:`main` - function. It is important to note that the argument list may be modified (but - the contents of the strings pointed to by the argument list are not). The return - value will be the integer passed to the :func:`sys.exit` function, ``1`` if the - interpreter exits due to an exception, or ``2`` if the parameter list does not - represent a valid Python command line. + The main program for the standard interpreter. This is made + available for programs which embed Python. The *argc* and *argv* + parameters should be prepared exactly as those which are passed to + a C program's :cfunc:`main` function (converted to wchar_t + according to the user's locale). It is important to note that the + argument list may be modified (but the contents of the strings + pointed to by the argument list are not). The return value will be + the integer passed to the :func:`sys.exit` function, ``1`` if the + interpreter exits due to an exception, or ``2`` if the parameter + list does not represent a valid Python command line. .. cfunction:: int PyRun_AnyFile(FILE *fp, const char *filename) Modified: python/branches/py3k-ctypes-pep3118/Doc/conf.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/conf.py (original) +++ python/branches/py3k-ctypes-pep3118/Doc/conf.py Wed Apr 30 15:57:13 2008 @@ -8,11 +8,15 @@ # that aren't pickleable (module imports are okay, they're removed automatically). import sys, os, time -sys.path.append('tools/sphinxext') +sys.path.append(os.path.abspath('tools/sphinxext')) # General configuration # --------------------- +extensions = ['sphinx.ext.refcounting', 'sphinx.ext.coverage', + 'sphinx.ext.doctest', 'pyspecific'] +templates_path = ['tools/sphinxext'] + # General substitutions. project = 'Python' copyright = '1990-%s, Python Software Foundation' % time.strftime('%Y') @@ -36,17 +40,17 @@ today_fmt = '%B %d, %Y' # List of files that shouldn't be included in the build. -unused_files = [ - 'whatsnew/2.0.rst', - 'whatsnew/2.1.rst', - 'whatsnew/2.2.rst', - 'whatsnew/2.3.rst', - 'whatsnew/2.4.rst', - 'whatsnew/2.5.rst', - 'whatsnew/2.6.rst', - 'maclib/scrap.rst', - 'library/xmllib.rst', - 'library/xml.etree.rst', +unused_docs = [ + 'whatsnew/2.0', + 'whatsnew/2.1', + 'whatsnew/2.2', + 'whatsnew/2.3', + 'whatsnew/2.4', + 'whatsnew/2.5', + 'whatsnew/2.6', + 'maclib/scrap', + 'library/xmllib', + 'library/xml.etree', ] # Relative filename of the reference count data file. @@ -71,21 +75,19 @@ # typographically correct entities. html_use_smartypants = True -# Content template for the index page, filename relative to this file. -html_index = 'tools/sphinxext/indexcontent.html' - # Custom sidebar templates, filenames relative to this file. html_sidebars = { - 'index': 'tools/sphinxext/indexsidebar.html', + 'index': 'indexsidebar.html', } # Additional templates that should be rendered to pages. html_additional_pages = { - 'download': 'tools/sphinxext/download.html', + 'download': 'download.html', + 'index': 'indexcontent.html', } # Output file base name for HTML help builder. -htmlhelp_basename = 'pydoc' +htmlhelp_basename = 'python' + release.replace('.', '') # Options for LaTeX output @@ -101,29 +103,29 @@ # (source start file, target name, title, author, document class [howto/manual]). _stdauthor = r'Guido van Rossum\\Fred L. Drake, Jr., editor' latex_documents = [ - ('c-api/index.rst', 'c-api.tex', + ('c-api/index', 'c-api.tex', 'The Python/C API', _stdauthor, 'manual'), - ('distutils/index.rst', 'distutils.tex', + ('distutils/index', 'distutils.tex', 'Distributing Python Modules', _stdauthor, 'manual'), - ('documenting/index.rst', 'documenting.tex', + ('documenting/index', 'documenting.tex', 'Documenting Python', 'Georg Brandl', 'manual'), - ('extending/index.rst', 'extending.tex', + ('extending/index', 'extending.tex', 'Extending and Embedding Python', _stdauthor, 'manual'), - ('install/index.rst', 'install.tex', + ('install/index', 'install.tex', 'Installing Python Modules', _stdauthor, 'manual'), - ('library/index.rst', 'library.tex', + ('library/index', 'library.tex', 'The Python Library Reference', _stdauthor, 'manual'), - ('reference/index.rst', 'reference.tex', + ('reference/index', 'reference.tex', 'The Python Language Reference', _stdauthor, 'manual'), - ('tutorial/index.rst', 'tutorial.tex', + ('tutorial/index', 'tutorial.tex', 'Python Tutorial', _stdauthor, 'manual'), - ('using/index.rst', 'using.tex', + ('using/index', 'using.tex', 'Using Python', _stdauthor, 'manual'), - ('whatsnew/' + version + '.rst', 'whatsnew.tex', + ('whatsnew/' + version, 'whatsnew.tex', 'What\'s New in Python', 'A. M. Kuchling', 'howto'), ] # Collect all HOWTOs individually -latex_documents.extend(('howto/' + fn, 'howto-' + fn[:-4] + '.tex', +latex_documents.extend(('howto/' + fn[:-4], 'howto-' + fn[:-4] + '.tex', 'HOWTO', _stdauthor, 'howto') for fn in os.listdir('howto') if fn.endswith('.rst') and fn != 'index.rst') @@ -137,4 +139,40 @@ ''' # Documents to append as an appendix to all manuals. -latex_appendices = ['glossary.rst', 'about.rst', 'license.rst', 'copyright.rst'] +latex_appendices = ['glossary', 'about', 'license', 'copyright'] + +# Options for the coverage checker +# -------------------------------- + +# The coverage checker will ignore all modules/functions/classes whose names +# match any of the following regexes (using re.match). +coverage_ignore_modules = [ + r'[T|t][k|K]', + r'Tix', + r'distutils.*', +] + +coverage_ignore_functions = [ + 'test($|_)', +] + +coverage_ignore_classes = [ +] + +# Glob patterns for C source files for C API coverage, relative to this directory. +coverage_c_path = [ + '../Include/*.h', +] + +# Regexes to find C items in the source files. +coverage_c_regexes = { + 'cfunction': (r'^PyAPI_FUNC\(.*\)\s+([^_][\w_]+)'), + 'data': (r'^PyAPI_DATA\(.*\)\s+([^_][\w_]+)'), + 'macro': (r'^#define ([^_][\w_]+)\(.*\)[\s|\\]'), +} + +# The coverage checker will ignore all C items whose names match these regexes +# (using re.match) -- the keys must be the same as in coverage_c_regexes. +coverage_ignore_c_items = { +# 'cfunction': [...] +} Modified: python/branches/py3k-ctypes-pep3118/Doc/copyright.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/copyright.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/copyright.rst Wed Apr 30 15:57:13 2008 @@ -4,7 +4,7 @@ Python and this documentation is: -Copyright ?? 2001-2007 Python Software Foundation. All rights reserved. +Copyright ?? 2001-2008 Python Software Foundation. All rights reserved. Copyright ?? 2000 BeOpen.com. All rights reserved. Modified: python/branches/py3k-ctypes-pep3118/Doc/distutils/apiref.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/distutils/apiref.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/distutils/apiref.rst Wed Apr 30 15:57:13 2008 @@ -73,7 +73,7 @@ +--------------------+--------------------------------+-------------------------------------------------------------+ | *classifiers* | A list of categories for the | The list of available | | | package | categorizations is at | - | | | http://cheeseshop.python.org/pypi?:action=list_classifiers. | + | | | http://pypi.python.org/pypi?:action=list_classifiers. | +--------------------+--------------------------------+-------------------------------------------------------------+ | *distclass* | the :class:`Distribution` | A subclass of | | | class to use | :class:`distutils.core.Distribution` | @@ -1820,7 +1820,25 @@ :synopsis: Build the .py/.pyc files of a package -.. % todo +.. class:: build_py(Command) + +.. class:: build_py_2to3(build_py) + + Alternative implementation of build_py which also runs the + 2to3 conversion library on each .py file that is going to be + installed. To use this in a setup.py file for a distribution + that is designed to run with both Python 2.x and 3.x, add:: + + try: + from distutils.command.build_py import build_py_2to3 as build_py + except ImportError: + from distutils.command.build_py import build_py + + to your setup.py, and later:: + + cmdclass = {'build_py':build_py} + + to the invocation of setup(). :mod:`distutils.command.build_scripts` --- Build the scripts of a package Modified: python/branches/py3k-ctypes-pep3118/Doc/distutils/builtdist.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/distutils/builtdist.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/distutils/builtdist.rst Wed Apr 30 15:57:13 2008 @@ -195,7 +195,7 @@ | | or --- & :option:`maintainer` and | | | :option:`maintainer_email` | +------------------------------------------+----------------------------------------------+ -| Copyright | :option:`licence` | +| Copyright | :option:`license` | +------------------------------------------+----------------------------------------------+ | Url | :option:`url` | +------------------------------------------+----------------------------------------------+ @@ -329,6 +329,42 @@ The installer file will be written to the "distribution directory" --- normally :file:`dist/`, but customizable with the :option:`--dist-dir` option. +.. _cross-compile-windows: + +Cross-compiling on Windows +========================== + +Starting with Python 2.6, distutils is capable of cross-compiling between +Windows platforms. In practice, this means that with the correct tools +installed, you can use a 32bit version of Windows to create 64bit extensions +and vice-versa. + +To build for an alternate platform, specify the :option:`--plat-name` option +to the build command. Valid values are currently 'win32', 'win-amd64' and +'win-ia64'. For example, on a 32bit version of Windows, you could execute:: + + python setup.py build --plat-name=win-amd64 + +to build a 64bit version of your extension. The Windows Installers also +support this option, so the command:: + + python setup.py build --plat-name=win-amd64 bdist_wininst + +would create a 64bit installation executable on your 32bit version of Windows. + +To cross-compile, you must download the Python source code and cross-compile +Python itself for the platform you are targetting - it is not possible from a +binary installtion of Python (as the .lib etc file for other platforms are +not included.) In practice, this means the user of a 32 bit operating +system will need to use Visual Studio 2008 to open the +:file:`PCBuild/PCbuild.sln` solution in the Python source tree and build the +"x64" configuration of the 'pythoncore' project before cross-compiling +extensions is possible. + +Note that by default, Visual Studio 2008 does not install 64bit compilers or +tools. You may need to reexecute the Visual Studio setup process and select +these tools (using Control Panel->[Add/Remove] Programs is a convenient way to +check or modify your existing install.) .. _postinstallation-script: Modified: python/branches/py3k-ctypes-pep3118/Doc/distutils/examples.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/distutils/examples.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/distutils/examples.rst Wed Apr 30 15:57:13 2008 @@ -11,7 +11,7 @@ .. seealso:: - `Distutils Cookbook `_ + `Distutils Cookbook `_ Collection of recipes showing how to achieve more control over distutils. Modified: python/branches/py3k-ctypes-pep3118/Doc/distutils/packageindex.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/distutils/packageindex.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/distutils/packageindex.rst Wed Apr 30 15:57:13 2008 @@ -53,13 +53,13 @@ The .pypirc file ================ -The format of the :file:`.pypirc` file is formated as follows:: +The format of the :file:`.pypirc` file is as follows:: [server-login] repository: username: password: -*repository* can be ommitted and defaults to ``http://www.python.org/pypi``. +*repository* can be omitted and defaults to ``http://www.python.org/pypi``. Modified: python/branches/py3k-ctypes-pep3118/Doc/distutils/setupscript.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/distutils/setupscript.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/distutils/setupscript.rst Wed Apr 30 15:57:13 2008 @@ -185,7 +185,7 @@ same base package), use the :option:`ext_package` keyword argument to :func:`setup`. For example, :: - setup(... + setup(..., ext_package='pkg', ext_modules=[Extension('foo', ['foo.c']), Extension('subpkg.bar', ['bar.c'])], @@ -214,7 +214,7 @@ This warning notwithstanding, options to SWIG can be currently passed like this:: - setup(... + setup(..., ext_modules=[Extension('_foo', ['foo.i'], swig_opts=['-modern', '-I../include'])], py_modules=['foo'], @@ -443,7 +443,7 @@ The :option:`scripts` option simply is a list of files to be handled in this way. From the PyXML setup script:: - setup(... + setup(..., scripts=['scripts/xmlproc_parse', 'scripts/xmlproc_val'] ) @@ -499,7 +499,7 @@ :option:`data_files` specifies a sequence of (*directory*, *files*) pairs in the following way:: - setup(... + setup(..., data_files=[('bitmaps', ['bm/b1.gif', 'bm/b2.gif']), ('config', ['cfg/data.cfg']), ('/etc/init.d', ['init-script'])] @@ -578,7 +578,7 @@ (4) These fields should not be used if your package is to be compatible with Python versions prior to 2.2.3 or 2.3. The list is available from the `PyPI website - `_. + `_. 'short string' A single line of text, not more than 200 characters. @@ -611,7 +611,7 @@ :option:`classifiers` are specified in a python list:: - setup(... + setup(..., classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', Modified: python/branches/py3k-ctypes-pep3118/Doc/distutils/sourcedist.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/distutils/sourcedist.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/distutils/sourcedist.rst Wed Apr 30 15:57:13 2008 @@ -122,7 +122,8 @@ * all files in the Distutils "build" tree (default :file:`build/`) -* all files in directories named :file:`RCS`, :file:`CVS` or :file:`.svn` +* all files in directories named :file:`RCS`, :file:`CVS`, :file:`.svn`, + :file:`.hg`, :file:`.git`, :file:`.bzr` or :file:`_darcs` Now we have our complete list of files, which is written to the manifest for future reference, and then used to build the source distribution archive(s). @@ -156,8 +157,9 @@ previous two steps, so it's important that the ``prune`` command in the manifest template comes after the ``recursive-include`` command -#. exclude the entire :file:`build` tree, and any :file:`RCS`, :file:`CVS` and - :file:`.svn` directories +#. exclude the entire :file:`build` tree, and any :file:`RCS`, :file:`CVS`, + :file:`.svn`, :file:`.hg`, :file:`.git`, :file:`.bzr` and :file:`_darcs` + directories Just like in the setup script, file and directory names in the manifest template should always be slash-separated; the Distutils will take care of converting Modified: python/branches/py3k-ctypes-pep3118/Doc/documenting/markup.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/documenting/markup.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/documenting/markup.rst Wed Apr 30 15:57:13 2008 @@ -319,8 +319,8 @@ .. describe:: func The name of a Python function; dotted names may be used. The role text - should include trailing parentheses to enhance readability. The parentheses - are stripped when searching for identifiers. + should not include trailing parentheses to enhance readability. The + parentheses are stripped when searching for identifiers. .. describe:: data @@ -338,7 +338,7 @@ .. describe:: meth The name of a method of an object. The role text should include the type - name, method name and the trailing parentheses. A dotted name may be used. + name and the method name. A dotted name may be used. .. describe:: attr Modified: python/branches/py3k-ctypes-pep3118/Doc/documenting/style.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/documenting/style.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/documenting/style.rst Wed Apr 30 15:57:13 2008 @@ -66,5 +66,5 @@ 1970s. -.. _Apple Publications Style Guide: http://developer.apple.com/documentation/UserExperience/Conceptual/APStyleGuide/AppleStyleGuide2003.pdf +.. _Apple Publications Style Guide: http://developer.apple.com/documentation/UserExperience/Conceptual/APStyleGuide/AppleStyleGuide2006.pdf Modified: python/branches/py3k-ctypes-pep3118/Doc/extending/extending.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/extending/extending.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/extending/extending.rst Wed Apr 30 15:57:13 2008 @@ -826,10 +826,9 @@ interfaces and the ability to disable the detector at runtime. The cycle detector is considered an optional component; though it is included by default, it can be disabled at build time using the :option:`--without-cycle-gc` option -to the :program:`configure` script on Unix platforms (including Mac OS X) or by -removing the definition of ``WITH_CYCLE_GC`` in the :file:`pyconfig.h` header on -other platforms. If the cycle detector is disabled in this way, the :mod:`gc` -module will not be available. +to the :program:`configure` script on Unix platforms (including Mac OS X). If +the cycle detector is disabled in this way, the :mod:`gc` module will not be +available. .. _refcountsinpython: Modified: python/branches/py3k-ctypes-pep3118/Doc/extending/newtypes.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/extending/newtypes.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/extending/newtypes.rst Wed Apr 30 15:57:13 2008 @@ -428,7 +428,7 @@ * when decrementing a reference count in a :attr:`tp_dealloc` handler when garbage-collections is not supported [#]_ -We want to want to expose our instance variables as attributes. There are a +We want to expose our instance variables as attributes. There are a number of ways to do that. The simplest way is to define member definitions:: static PyMemberDef Noddy_members[] = { @@ -616,7 +616,7 @@ Noddy_getseters, /* tp_getset */ -to register out attribute getters and setters. +to register our attribute getters and setters. The last item in a :ctype:`PyGetSetDef` structure is the closure mentioned above. In this case, we aren't using the closure, so we just pass *NULL*. @@ -1538,7 +1538,7 @@ less careful about decrementing their reference counts, however, we accept instances of string subclasses. Even though deallocating normal strings won't call back into our objects, we can't guarantee that deallocating an instance of - a string subclass won't. call back into out objects. + a string subclass won't call back into our objects. .. [#] Even in the third version, we aren't guaranteed to avoid cycles. Instances of string subclasses are allowed and string subclasses could allow cycles even if Modified: python/branches/py3k-ctypes-pep3118/Doc/extending/windows.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/extending/windows.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/extending/windows.rst Wed Apr 30 15:57:13 2008 @@ -179,7 +179,7 @@ MyObject_Type.ob_type = &PyType_Type; -Refer to section 3 of the `Python FAQ `_ for +Refer to section 3 of the `Python FAQ `_ for details on why you must do this. Modified: python/branches/py3k-ctypes-pep3118/Doc/glossary.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/glossary.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/glossary.rst Wed Apr 30 15:57:13 2008 @@ -39,10 +39,6 @@ "intermediate language" is said to run on a "virtual machine" that calls the subroutines corresponding to each bytecode. - classic class - One of the two flavors of classes in earlier Python versions. Since - Python 3.0, there are no classic classes anymore. - complex number An extension of the familiar real number system in which all numbers are expressed as a sum of a real part and an imaginary part. Imaginary @@ -367,8 +363,6 @@ versatile features like :attr:`__slots__`, descriptors, properties, :meth:`__getattribute__`, class methods, and static methods. - More information can be found in :ref:`newstyle`. - positional argument The arguments assigned to local names inside a function or method, determined by the order in which they were given in the call. ``*`` is Modified: python/branches/py3k-ctypes-pep3118/Doc/howto/advocacy.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/howto/advocacy.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/howto/advocacy.rst Wed Apr 30 15:57:13 2008 @@ -160,7 +160,7 @@ don't merge cleanly into the overall design scheme (thus, some fans of Classic C maintain that ANSI C is no longer compact). - (From http://www.catb.org/ esr/jargon/html/C/compact.html) + (From http://www.catb.org/~esr/jargon/html/C/compact.html) In this sense of the word, Python is quite compact, because the language has just a few ideas, which are used in lots of places. Take namespaces, for @@ -174,14 +174,14 @@ This simplicity arises from Python's development history. The language syntax derives from different sources; ABC, a relatively obscure teaching language, is one primary influence, and Modula-3 is another. (For more information about ABC -and Modula-3, consult their respective Web sites at http://www.cwi.nl/ -steven/abc/ and http://www.m3.org.) Other features have come from C, Icon, +and Modula-3, consult their respective Web sites at http://www.cwi.nl/~steven/abc/ +and http://www.m3.org.) Other features have come from C, Icon, Algol-68, and even Perl. Python hasn't really innovated very much, but instead has tried to keep the language small and easy to learn, building on ideas that have been tried in other languages and found useful. Simplicity is a virtue that should not be underestimated. It lets you learn the -language more quickly, and then rapidly write code, code that often works the +language more quickly, and then rapidly write code -- code that often works the first time you run it. @@ -265,8 +265,8 @@ **What are the restrictions on Python's use?** They're practically nonexistent. Consult the :file:`Misc/COPYRIGHT` file in the -source distribution, or http://www.python.org/doc/Copyright.html for the full -language, but it boils down to three conditions. +source distribution, or the section :ref:`history-and-license` for the full +language, but it boils down to three conditions: * You have to leave the copyright notice on the software; if you don't include the source code in a product, you have to put the copyright notice in the @@ -276,7 +276,7 @@ product in any way. * If something goes wrong, you can't sue for damages. Practically all software - licences contain this condition. + licenses contain this condition. Notice that you don't have to provide source code for anything that contains Python or is built with it. Also, the Python interpreter and accompanying @@ -346,7 +346,7 @@ wasn't written commercially. This site presents arguments that show how open source software can have considerable advantages over closed-source software. -http://sunsite.unc.edu/LDP/HOWTO/mini/Advocacy.html +http://www.faqs.org/docs/Linux-mini/Advocacy.html The Linux Advocacy mini-HOWTO was the inspiration for this document, and is also well worth reading for general suggestions on winning acceptance for a new technology, such as Linux or Python. In general, you won't make much progress Modified: python/branches/py3k-ctypes-pep3118/Doc/howto/curses.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/howto/curses.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/howto/curses.rst Wed Apr 30 15:57:13 2008 @@ -1,3 +1,5 @@ +.. _curses-howto: + ********************************** Curses Programming with Python ********************************** @@ -50,7 +52,7 @@ No one has made a Windows port of the curses module. On a Windows platform, try the Console module written by Fredrik Lundh. The Console module provides cursor-addressable text output, plus full support for mouse and keyboard input, -and is available from http://effbot.org/efflib/console. +and is available from http://effbot.org/zone/console-index.htm. The Python curses module @@ -430,5 +432,5 @@ If you write an interesting little program, feel free to contribute it as another demo. We can always use more of them! -The ncurses FAQ: http://dickey.his.com/ncurses/ncurses.faq.html +The ncurses FAQ: http://invisible-island.net/ncurses/ncurses.faq.html Modified: python/branches/py3k-ctypes-pep3118/Doc/howto/doanddont.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/howto/doanddont.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/howto/doanddont.rst Wed Apr 30 15:57:13 2008 @@ -4,7 +4,7 @@ :Author: Moshe Zadka -This document is placed in the public doman. +This document is placed in the public domain. .. topic:: Abstract @@ -81,7 +81,7 @@ This is a "don't" which is much weaker then the previous "don't"s but is still something you should not do if you don't have good reasons to do that. The reason it is usually bad idea is because you suddenly have an object which lives -in two seperate namespaces. When the binding in one namespace changes, the +in two separate namespaces. When the binding in one namespace changes, the binding in the other will not, so there will be a discrepancy between them. This happens when, for example, one module is reloaded, or changes the definition of a function at runtime. Modified: python/branches/py3k-ctypes-pep3118/Doc/howto/functional.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/howto/functional.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/howto/functional.rst Wed Apr 30 15:57:13 2008 @@ -2,7 +2,7 @@ Functional Programming HOWTO ******************************** -:Author: \A. M. Kuchling +:Author: A. M. Kuchling :Release: 0.31 (This is a first draft. Please send comments/error reports/suggestions to @@ -98,6 +98,7 @@ * Composability. * Ease of debugging and testing. + Formal provability ------------------ @@ -133,6 +134,7 @@ proof; maybe there's an error in it, and you wrongly believe you've proved the program correct. + Modularity ---------- @@ -159,7 +161,6 @@ check that the output matches expectations. - Composability ------------- @@ -175,7 +176,6 @@ a few functions specialized for the current task. - Iterators ========= @@ -197,12 +197,12 @@ dictionaries. An object is called an **iterable** object if you can get an iterator for it. -You can experiment with the iteration interface manually:: +You can experiment with the iteration interface manually: >>> L = [1,2,3] >>> it = iter(L) >>> it - + <...iterator object at ...> >>> it.next() 1 >>> it.next() @@ -220,14 +220,15 @@ be an iterator or some object for which ``iter()`` can create an iterator. These two statements are equivalent:: - for i in iter(obj): - print(i) - for i in obj: - print(i) + for i in iter(obj): + print i + + for i in obj: + print i Iterators can be materialized as lists or tuples by using the :func:`list` or -:func:`tuple` constructor functions:: +:func:`tuple` constructor functions: >>> L = [1,2,3] >>> iterator = iter(L) @@ -236,7 +237,7 @@ (1, 2, 3) Sequence unpacking also supports iterators: if you know an iterator will return -N elements, you can unpack them into an N-tuple:: +N elements, you can unpack them into an N-tuple: >>> L = [1,2,3] >>> iterator = iter(L) @@ -269,7 +270,11 @@ iterator. Calling :func:`iter` on a dictionary returns an iterator that will loop over the -dictionary's keys:: +dictionary's keys: + +.. not a doctest since dict ordering varies across Pythons + +:: >>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6, ... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12} @@ -279,11 +284,11 @@ Feb 2 Aug 8 Sep 9 - May 5 + Apr 4 Jun 6 Jul 7 Jan 1 - Apr 4 + May 5 Nov 11 Dec 12 Oct 10 @@ -297,7 +302,7 @@ :meth:`values` or :meth:`items` methods to get an appropriate iterator. The :func:`dict` constructor can accept an iterator that returns a finite stream -of ``(key, value)`` tuples:: +of ``(key, value)`` tuples: >>> L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')] >>> dict(iter(L)) @@ -314,7 +319,7 @@ Sets can take their contents from an iterable and let you iterate over the set's elements:: - S = set((2, 3, 5, 7, 11, 13)) + S = {2, 3, 5, 7, 11, 13} for i in S: print(i) @@ -334,18 +339,18 @@ functional programming language Haskell (http://www.haskell.org). You can strip all the whitespace from a stream of strings with the following code:: - line_list = [' line 1\n', 'line 2 \n', ...] + line_list = [' line 1\n', 'line 2 \n', ...] - # Generator expression -- returns iterator - stripped_iter = (line.strip() for line in line_list) + # Generator expression -- returns iterator + stripped_iter = (line.strip() for line in line_list) - # List comprehension -- returns list - stripped_list = [line.strip() for line in line_list] + # List comprehension -- returns list + stripped_list = [line.strip() for line in line_list] You can select only certain elements by adding an ``"if"`` condition:: - stripped_list = [line.strip() for line in line_list - if line != ""] + stripped_list = [line.strip() for line in line_list + if line != ""] With a list comprehension, you get back a Python list; ``stripped_list`` is a list containing the resulting lines, not an iterator. Generator expressions @@ -378,7 +383,7 @@ parentheses signalling a function call also count. If you want to create an iterator that will be immediately passed to a function you can write:: - obj_total = sum(obj.count for obj in list_all_objects()) + obj_total = sum(obj.count for obj in list_all_objects()) The ``for...in`` clauses contain the sequences to be iterated over. The sequences do not have to be the same length, because they are iterated over from @@ -406,11 +411,14 @@ This means that when there are multiple ``for...in`` clauses but no ``if`` clauses, the length of the resulting output will be equal to the product of the lengths of all the sequences. If you have two lists of length 3, the output -list is 9 elements long:: +list is 9 elements long: - seq1 = 'abc' - seq2 = (1,2,3) - >>> [ (x,y) for x in seq1 for y in seq2] +.. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> seq1 = 'abc' + >>> seq2 = (1,2,3) + >>> [(x,y) for x in seq1 for y in seq2] [('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1), ('c', 2), ('c', 3)] @@ -441,7 +449,9 @@ function? What if you could later resume the function where it left off? This is what generators provide; they can be thought of as resumable functions. -Here's the simplest example of a generator function:: +Here's the simplest example of a generator function: + +.. testcode:: def generate_ints(N): for i in range(N): @@ -459,11 +469,11 @@ suspended and local variables are preserved. On the next call to the generator's ``.next()`` method, the function will resume executing. -Here's a sample usage of the ``generate_ints()`` generator:: +Here's a sample usage of the ``generate_ints()`` generator: >>> gen = generate_ints(3) >>> gen - + >>> gen.next() 0 >>> gen.next() @@ -496,9 +506,7 @@ The test suite included with Python's library, ``test_generators.py``, contains a number of more interesting examples. Here's one generator that implements an -in-order traversal of a tree using generators recursively. - -:: +in-order traversal of a tree using generators recursively. :: # A recursive generator that generates Tree leaves in in-order. def inorder(t): @@ -553,7 +561,7 @@ Here's a simple counter that increments by 1 and allows changing the value of the internal counter. -:: +.. testcode:: def counter (maximum): i = 0 @@ -616,104 +624,95 @@ Let's look in more detail at built-in functions often used with iterators. -Two of Python's built-in functions, :func:`map` and :func:`filter`, are somewhat -obsolete; they duplicate the features of list comprehensions but return actual -lists instead of iterators. +Two of Python's built-in functions, :func:`map` and :func:`filter` duplicate the +features of generator expressions: -``map(f, iterA, iterB, ...)`` returns a list containing ``f(iterA[0], iterB[0]), -f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``. +``map(f, iterA, iterB, ...)`` returns an iterator over the sequence + ``f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``. -:: + >>> def upper(s): + ... return s.upper() - def upper(s): - return s.upper() - map(upper, ['sentence', 'fragment']) => - ['SENTENCE', 'FRAGMENT'] - - [upper(s) for s in ['sentence', 'fragment']] => - ['SENTENCE', 'FRAGMENT'] - -As shown above, you can achieve the same effect with a list comprehension. The -:func:`itertools.imap` function does the same thing but can handle infinite -iterators; it'll be discussed later, in the section on the :mod:`itertools` module. -``filter(predicate, iter)`` returns a list that contains all the sequence -elements that meet a certain condition, and is similarly duplicated by list + >>> map(upper, ['sentence', 'fragment']) + ['SENTENCE', 'FRAGMENT'] + >>> [upper(s) for s in ['sentence', 'fragment']] + ['SENTENCE', 'FRAGMENT'] + +You can of course achieve the same effect with a list comprehension. + +``filter(predicate, iter)`` returns an iterator over all the sequence elements +that meet a certain condition, and is similarly duplicated by list comprehensions. A **predicate** is a function that returns the truth value of some condition; for use with :func:`filter`, the predicate must take a single value. -:: + >>> def is_even(x): + ... return (x % 2) == 0 - def is_even(x): - return (x % 2) == 0 + >>> filter(is_even, range(10)) + [0, 2, 4, 6, 8] - filter(is_even, range(10)) => - [0, 2, 4, 6, 8] -This can also be written as a list comprehension:: +This can also be written as a list comprehension: - >>> [x for x in range(10) if is_even(x)] + >>> list(x for x in range(10) if is_even(x)) [0, 2, 4, 6, 8] -:func:`filter` also has a counterpart in the :mod:`itertools` module, -:func:`itertools.ifilter`, that returns an iterator and can therefore handle -infinite sequences just as :func:`itertools.imap` can. - -``reduce(func, iter, [initial_value])`` doesn't have a counterpart in the -:mod:`itertools` module because it cumulatively performs an operation on all the -iterable's elements and therefore can't be applied to infinite iterables. -``func`` must be a function that takes two elements and returns a single value. -:func:`reduce` takes the first two elements A and B returned by the iterator and -calculates ``func(A, B)``. It then requests the third element, C, calculates -``func(func(A, B), C)``, combines this result with the fourth element returned, -and continues until the iterable is exhausted. If the iterable returns no -values at all, a :exc:`TypeError` exception is raised. If the initial value is -supplied, it's used as a starting point and ``func(initial_value, A)`` is the -first calculation. - -:: - - import operator - reduce(operator.concat, ['A', 'BB', 'C']) => - 'ABBC' - reduce(operator.concat, []) => - TypeError: reduce() of empty sequence with no initial value - reduce(operator.mul, [1,2,3], 1) => - 6 - reduce(operator.mul, [], 1) => - 1 +``functools.reduce(func, iter, [initial_value])`` cumulatively performs an +operation on all the iterable's elements and, therefore, can't be applied to +infinite iterables. ``func`` must be a function that takes two elements and +returns a single value. :func:`functools.reduce` takes the first two elements A +and B returned by the iterator and calculates ``func(A, B)``. It then requests +the third element, C, calculates ``func(func(A, B), C)``, combines this result +with the fourth element returned, and continues until the iterable is exhausted. +If the iterable returns no values at all, a :exc:`TypeError` exception is +raised. If the initial value is supplied, it's used as a starting point and +``func(initial_value, A)`` is the first calculation. :: + + >>> import operator + >>> reduce(operator.concat, ['A', 'BB', 'C']) + 'ABBC' + >>> reduce(operator.concat, []) + Traceback (most recent call last): + ... + TypeError: reduce() of empty sequence with no initial value + >>> reduce(operator.mul, [1,2,3], 1) + 6 + >>> reduce(operator.mul, [], 1) + 1 If you use :func:`operator.add` with :func:`reduce`, you'll add up all the elements of the iterable. This case is so common that there's a special -built-in called :func:`sum` to compute it:: +built-in called :func:`sum` to compute it: - reduce(operator.add, [1,2,3,4], 0) => - 10 - sum([1,2,3,4]) => - 10 - sum([]) => - 0 + >>> reduce(operator.add, [1,2,3,4], 0) + 10 + >>> sum([1,2,3,4]) + 10 + >>> sum([]) + 0 For many uses of :func:`reduce`, though, it can be clearer to just write the obvious :keyword:`for` loop:: - # Instead of: - product = reduce(operator.mul, [1,2,3], 1) + # Instead of: + product = functools.reduce(operator.mul, [1,2,3], 1) - # You can write: - product = 1 - for i in [1,2,3]: - product *= i + # You can write: + product = 1 + for i in [1,2,3]: + product *= i ``enumerate(iter)`` counts off the elements in the iterable, returning 2-tuples -containing the count and each element. - -:: +containing the count and each element. :: - enumerate(['subject', 'verb', 'object']) => - (0, 'subject'), (1, 'verb'), (2, 'object') + >>> for item in enumerate(['subject', 'verb', 'object']): + ... print item + (0, 'subject') + (1, 'verb') + (2, 'object') :func:`enumerate` is often used when looping through a list and recording the indexes at which certain conditions are met:: @@ -723,22 +722,21 @@ if line.strip() == '': print('Blank line at line #%i' % i) + ``sorted(iterable, [cmp=None], [key=None], [reverse=False)`` collects all the elements of the iterable into a list, sorts the list, and returns the sorted result. The ``cmp``, ``key``, and ``reverse`` arguments are passed through to -the constructed list's ``.sort()`` method. - -:: +the constructed list's ``.sort()`` method. :: - import random - # Generate 8 random numbers between [0, 10000) - rand_list = random.sample(range(10000), 8) - rand_list => - [769, 7953, 9828, 6431, 8442, 9878, 6213, 2207] - sorted(rand_list) => - [769, 2207, 6213, 6431, 7953, 8442, 9828, 9878] - sorted(rand_list, reverse=True) => - [9878, 9828, 8442, 7953, 6431, 6213, 2207, 769] + >>> import random + >>> # Generate 8 random numbers between [0, 10000) + >>> rand_list = random.sample(range(10000), 8) + >>> rand_list + [769, 7953, 9828, 6431, 8442, 9878, 6213, 2207] + >>> sorted(rand_list) + [769, 2207, 6213, 6431, 7953, 8442, 9828, 9878] + >>> sorted(rand_list, reverse=True) + [9878, 9828, 8442, 7953, 6431, 6213, 2207, 769] (For a more detailed discussion of sorting, see the Sorting mini-HOWTO in the Python wiki at http://wiki.python.org/moin/HowTo/Sorting.) @@ -746,20 +744,20 @@ The ``any(iter)`` and ``all(iter)`` built-ins look at the truth values of an iterable's contents. :func:`any` returns True if any element in the iterable is a true value, and :func:`all` returns True if all of the elements are true -values:: +values: - any([0,1,0]) => - True - any([0,0,0]) => - False - any([1,1,1]) => - True - all([0,1,0]) => - False - all([0,0,0]) => - False - all([1,1,1]) => - True + >>> any([0,1,0]) + True + >>> any([0,0,0]) + False + >>> any([1,1,1]) + True + >>> all([0,1,0]) + False + >>> all([0,0,0]) + False + >>> all([1,1,1]) + True Small functions and the lambda expression @@ -771,31 +769,31 @@ If there's a Python built-in or a module function that's suitable, you don't need to define a new function at all:: - stripped_lines = [line.strip() for line in lines] - existing_files = filter(os.path.exists, file_list) + stripped_lines = [line.strip() for line in lines] + existing_files = filter(os.path.exists, file_list) If the function you need doesn't exist, you need to write it. One way to write small functions is to use the ``lambda`` statement. ``lambda`` takes a number of parameters and an expression combining these parameters, and creates a small function that returns the value of the expression:: - lowercase = lambda x: x.lower() + lowercase = lambda x: x.lower() - print_assign = lambda name, value: name + '=' + str(value) + print_assign = lambda name, value: name + '=' + str(value) - adder = lambda x, y: x+y + adder = lambda x, y: x+y An alternative is to just use the ``def`` statement and define a function in the usual way:: - def lowercase(x): - return x.lower() + def lowercase(x): + return x.lower() - def print_assign(name, value): - return name + '=' + str(value) + def print_assign(name, value): + return name + '=' + str(value) - def adder(x,y): - return x + y + def adder(x,y): + return x + y Which alternative is preferable? That's a style question; my usual course is to avoid using ``lambda``. @@ -866,24 +864,20 @@ ``itertools.count(n)`` returns an infinite stream of integers, increasing by 1 each time. You can optionally supply the starting number, which defaults to 0:: - itertools.count() => - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... - itertools.count(10) => - 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ... + itertools.count() => + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... + itertools.count(10) => + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ... ``itertools.cycle(iter)`` saves a copy of the contents of a provided iterable and returns a new iterator that returns its elements from first to last. The -new iterator will repeat these elements infinitely. +new iterator will repeat these elements infinitely. :: -:: - - itertools.cycle([1,2,3,4,5]) => - 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ... + itertools.cycle([1,2,3,4,5]) => + 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ... ``itertools.repeat(elem, [n])`` returns the provided element ``n`` times, or -returns the element endlessly if ``n`` is not provided. - -:: +returns the element endlessly if ``n`` is not provided. :: itertools.repeat('abc') => abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ... @@ -892,9 +886,7 @@ ``itertools.chain(iterA, iterB, ...)`` takes an arbitrary number of iterables as input, and returns all the elements of the first iterator, then all the elements -of the second, and so on, until all of the iterables have been exhausted. - -:: +of the second, and so on, until all of the iterables have been exhausted. :: itertools.chain(['a', 'b', 'c'], (1, 2, 3)) => a, b, c, 1, 2, 3 @@ -905,7 +897,7 @@ itertools.izip(['a', 'b', 'c'], (1, 2, 3)) => ('a', 1), ('b', 2), ('c', 3) -It's similiar to the built-in :func:`zip` function, but doesn't construct an +It's similar to the built-in :func:`zip` function, but doesn't construct an in-memory list and exhaust all the input iterators before returning; instead tuples are constructed and returned only if they're requested. (The technical term for this behaviour is `lazy evaluation @@ -913,9 +905,7 @@ This iterator is intended to be used with iterables that are all of the same length. If the iterables are of different lengths, the resulting stream will be -the same length as the shortest iterable. - -:: +the same length as the shortest iterable. :: itertools.izip(['a', 'b'], (1, 2, 3)) => ('a', 1), ('b', 2) @@ -929,9 +919,7 @@ first ``stop`` elements. If you supply a starting index, you'll get ``stop-start`` elements, and if you supply a value for ``step``, elements will be skipped accordingly. Unlike Python's string and list slicing, you can't use -negative values for ``start``, ``stop``, or ``step``. - -:: +negative values for ``start``, ``stop``, or ``step``. :: itertools.islice(range(10), 8) => 0, 1, 2, 3, 4, 5, 6, 7 @@ -945,9 +933,7 @@ If you don't supply a value for ``n``, the default is 2. Replicating iterators requires saving some of the contents of the source iterator, so this can consume significant memory if the iterator is large and one of the new iterators is -consumed more than the others. - -:: +consumed more than the others. :: itertools.tee( itertools.count() ) => iterA, iterB @@ -962,14 +948,7 @@ Calling functions on elements ----------------------------- -Two functions are used for calling other functions on the contents of an -iterable. - -``itertools.imap(f, iterA, iterB, ...)`` returns a stream containing -``f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``:: - - itertools.imap(operator.add, [5, 6, 5], [1, 2, 3]) => - 6, 8, 8 +``itertools.imap(func, iter)`` is the same as built-in :func:`map`. The ``operator`` module contains a set of functions corresponding to Python's operators. Some examples are ``operator.add(a, b)`` (adds two values), @@ -992,14 +971,7 @@ Another group of functions chooses a subset of an iterator's elements based on a predicate. -``itertools.ifilter(predicate, iter)`` returns all the elements for which the -predicate returns true:: - - def is_even(x): - return (x % 2) == 0 - - itertools.ifilter(is_even, itertools.count()) => - 0, 2, 4, 6, 8, 10, 12, 14, ... +``itertools.ifilter(predicate, iter)`` is the same as built-in :func:`filter`. ``itertools.ifilterfalse(predicate, iter)`` is the opposite, returning all elements for which the predicate returns false:: @@ -1117,8 +1089,7 @@ Some of the functions in this module are: -* Math operations: ``add()``, ``sub()``, ``mul()``, ``div()``, ``floordiv()``, - ``abs()``, ... +* Math operations: ``add()``, ``sub()``, ``mul()``, ``floordiv()``, ``abs()``, ... * Logical operations: ``not_()``, ``truth()``. * Bitwise operations: ``and_()``, ``or_()``, ``invert()``. * Comparisons: ``eq()``, ``ne()``, ``lt()``, ``le()``, ``gt()``, and ``ge()``. @@ -1144,87 +1115,76 @@ The ``compose()`` function implements function composition. In other words, it returns a wrapper around the ``outer`` and ``inner`` callables, such that the -return value from ``inner`` is fed directly to ``outer``. That is, - -:: +return value from ``inner`` is fed directly to ``outer``. That is, :: - >>> def add(a, b): - ... return a + b - ... - >>> def double(a): - ... return 2 * a - ... - >>> compose(double, add)(5, 6) - 22 + >>> def add(a, b): + ... return a + b + ... + >>> def double(a): + ... return 2 * a + ... + >>> compose(double, add)(5, 6) + 22 -is equivalent to - -:: +is equivalent to :: - >>> double(add(5, 6)) - 22 + >>> double(add(5, 6)) + 22 The ``unpack`` keyword is provided to work around the fact that Python functions are not always `fully curried `__. By default, it is expected that the ``inner`` function will return a single object and that the ``outer`` function will take a single argument. Setting the ``unpack`` argument causes ``compose`` to expect a tuple from ``inner`` which -will be expanded before being passed to ``outer``. Put simply, +will be expanded before being passed to ``outer``. Put simply, :: -:: - - compose(f, g)(5, 6) + compose(f, g)(5, 6) is equivalent to:: - f(g(5, 6)) + f(g(5, 6)) -while - -:: +while :: - compose(f, g, unpack=True)(5, 6) + compose(f, g, unpack=True)(5, 6) is equivalent to:: - f(*g(5, 6)) + f(*g(5, 6)) Even though ``compose()`` only accepts two functions, it's trivial to build up a -version that will compose any number of functions. We'll use ``reduce()``, +version that will compose any number of functions. We'll use ``functools.reduce()``, ``compose()`` and ``partial()`` (the last of which is provided by both -``functional`` and ``functools``). +``functional`` and ``functools``). :: -:: - - from functional import compose, partial + from functional import compose, partial - multi_compose = partial(reduce, compose) + + multi_compose = partial(reduce, compose) We can also use ``map()``, ``compose()`` and ``partial()`` to craft a version of ``"".join(...)`` that converts its arguments to string:: - from functional import compose, partial + from functional import compose, partial - join = compose("".join, partial(map, str)) + join = compose("".join, partial(map, str)) ``flip(func)`` ``flip()`` wraps the callable in ``func`` and causes it to receive its -non-keyword arguments in reverse order. - -:: +non-keyword arguments in reverse order. :: - >>> def triple(a, b, c): - ... return (a, b, c) - ... - >>> triple(5, 6, 7) - (5, 6, 7) - >>> - >>> flipped_triple = flip(triple) - >>> flipped_triple(5, 6, 7) - (7, 6, 5) + >>> def triple(a, b, c): + ... return (a, b, c) + ... + >>> triple(5, 6, 7) + (5, 6, 7) + >>> + >>> flipped_triple = flip(triple) + >>> flipped_triple(5, 6, 7) + (7, 6, 5) ``foldl(func, start, iterable)`` @@ -1235,35 +1195,34 @@ This means that a call such as:: - foldl(f, 0, [1, 2, 3]) + foldl(f, 0, [1, 2, 3]) is equivalent to:: - f(f(f(0, 1), 2), 3) + f(f(f(0, 1), 2), 3) ``foldl()`` is roughly equivalent to the following recursive function:: - def foldl(func, start, seq): - if len(seq) == 0: - return start + def foldl(func, start, seq): + if len(seq) == 0: + return start - return foldl(func, func(start, seq[0]), seq[1:]) + return foldl(func, func(start, seq[0]), seq[1:]) Speaking of equivalence, the above ``foldl`` call can be expressed in terms of the built-in ``reduce`` like so:: - reduce(f, [1, 2, 3], 0) + reduce(f, [1, 2, 3], 0) We can use ``foldl()``, ``operator.concat()`` and ``partial()`` to write a cleaner, more aesthetically-pleasing version of Python's ``"".join(...)`` idiom:: - from functional import foldl, partial - from operator import concat - - join = partial(foldl, concat, "") + from functional import foldl, partial from operator import concat + + join = partial(foldl, concat, "") Revision History and Acknowledgements Modified: python/branches/py3k-ctypes-pep3118/Doc/howto/regex.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/howto/regex.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/howto/regex.rst Wed Apr 30 15:57:13 2008 @@ -1,3 +1,5 @@ +.. _regex-howto: + **************************** Regular Expression HOWTO **************************** @@ -201,7 +203,7 @@ | | | ``bc``. | +------+-----------+---------------------------------+ | 6 | ``abcb`` | Try ``b`` again. This time | -| | | but the character at the | +| | | the character at the | | | | current position is ``'b'``, so | | | | it succeeds. | +------+-----------+---------------------------------+ @@ -365,8 +367,8 @@ Python distribution. It allows you to enter REs and strings, and displays whether the RE matches or fails. :file:`redemo.py` can be quite useful when trying to debug a complicated RE. Phil Schwartz's `Kodos -`_ is also an interactive tool for -developing and testing RE patterns. +`_ is also an interactive tool for developing and +testing RE patterns. This HOWTO uses the standard Python interpreter for its examples. First, run the Python interpreter, import the :mod:`re` module, and compile a RE:: @@ -497,7 +499,7 @@ the same ones in several locations, then it might be worthwhile to collect all the definitions in one place, in a section of code that compiles all the REs ahead of time. To take an example from the standard library, here's an extract -from :file:`xmllib.py`:: +from the now deprecated :file:`xmllib.py`:: ref = re.compile( ... ) entityref = re.compile( ... ) Modified: python/branches/py3k-ctypes-pep3118/Doc/howto/sockets.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/howto/sockets.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/howto/sockets.rst Wed Apr 30 15:57:13 2008 @@ -354,7 +354,7 @@ reason to do otherwise. In return, you will get three lists. They have the sockets that are actually -readable, writable and in error. Each of these lists is a subset (possbily +readable, writable and in error. Each of these lists is a subset (possibly empty) of the corresponding list you passed in. And if you put a socket in more than one input list, it will only be (at most) in one output list. @@ -368,7 +368,7 @@ If you have a "server" socket, put it in the potential_readers list. If it comes out in the readable list, your ``accept`` will (almost certainly) work. If you have created a new socket to ``connect`` to someone else, put it in the -ptoential_writers list. If it shows up in the writable list, you have a decent +potential_writers list. If it shows up in the writable list, you have a decent chance that it has connected. One very nasty problem with ``select``: if somewhere in those input lists of Modified: python/branches/py3k-ctypes-pep3118/Doc/howto/unicode.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/howto/unicode.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/howto/unicode.rst Wed Apr 30 15:57:13 2008 @@ -216,10 +216,6 @@ to reading the Unicode character tables, available at . -Roman Czyborra wrote another explanation of Unicode's basic principles; it's at -. Czyborra has written a number of -other Unicode-related documentation, available from . - Two other good introductory articles were written by Joel Spolsky and Jason Orendorff . If this introduction didn't make @@ -237,129 +233,83 @@ Now that you've learned the rudiments of Unicode, we can look at Python's Unicode features. +The String Type +--------------- -The Unicode Type ----------------- - -Unicode strings are expressed as instances of the :class:`unicode` type, one of -Python's repertoire of built-in types. It derives from an abstract type called -:class:`basestring`, which is also an ancestor of the :class:`str` type; you can -therefore check if a value is a string type with ``isinstance(value, -basestring)``. Under the hood, Python represents Unicode strings as either 16- -or 32-bit integers, depending on how the Python interpreter was compiled. - -The :func:`unicode` constructor has the signature ``unicode(string[, encoding, -errors])``. All of its arguments should be 8-bit strings. The first argument -is converted to Unicode using the specified encoding; if you leave off the -``encoding`` argument, the ASCII encoding is used for the conversion, so -characters greater than 127 will be treated as errors:: - - >>> unicode('abcdef') - u'abcdef' - >>> s = unicode('abcdef') - >>> type(s) - - >>> unicode('abcdef' + chr(255)) - Traceback (most recent call last): - File "", line 1, in ? - UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 6: - ordinal not in range(128) +Since Python 3.0, the language features a ``str`` type that contain Unicode +characters, meaning any string created using ``"unicode rocks!"``, ``'unicode +rocks!``, or the triple-quoted string syntax is stored as Unicode. + +To insert a Unicode character that is not part ASCII, e.g., any letters with +accents, one can use escape sequences in their string literals as such:: + + >>> "\N{GREEK CAPITAL LETTER DELTA}" # Using the character name + '\u0394' + >>> "\u0394" # Using a 16-bit hex value + '\u0394' + >>> "\U00000394" # Using a 32-bit hex value + '\u0394' + +In addition, one can create a string using the :func:`decode` method of +:class:`bytes`. This method takes an encoding, such as UTF-8, and, optionally, +an *errors* argument. -The ``errors`` argument specifies the response when the input string can't be +The *errors* argument specifies the response when the input string can't be converted according to the encoding's rules. Legal values for this argument are -'strict' (raise a ``UnicodeDecodeError`` exception), 'replace' (add U+FFFD, +'strict' (raise a :exc:`UnicodeDecodeError` exception), 'replace' (add U+FFFD, 'REPLACEMENT CHARACTER'), or 'ignore' (just leave the character out of the Unicode result). The following examples show the differences:: - >>> unicode('\x80abc', errors='strict') + >>> b'\x80abc'.decode("utf-8", "strict") Traceback (most recent call last): File "", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0: ordinal not in range(128) - >>> unicode('\x80abc', errors='replace') - u'\ufffdabc' - >>> unicode('\x80abc', errors='ignore') - u'abc' + >>> b'\x80abc'.decode("utf-8", "replace") + '\ufffdabc' + >>> b'\x80abc'.decode("utf-8", "ignore") + 'abc' -Encodings are specified as strings containing the encoding's name. Python 2.4 +Encodings are specified as strings containing the encoding's name. Python comes with roughly 100 different encodings; see the Python Library Reference at - for a list. Some encodings +:ref:`standard-encodings` for a list. Some encodings have multiple names; for example, 'latin-1', 'iso_8859_1' and '8859' are all synonyms for the same encoding. -One-character Unicode strings can also be created with the :func:`unichr` +One-character Unicode strings can also be created with the :func:`chr` built-in function, which takes integers and returns a Unicode string of length 1 that contains the corresponding code point. The reverse operation is the built-in :func:`ord` function that takes a one-character Unicode string and returns the code point value:: - >>> unichr(40960) - u'\ua000' - >>> ord(u'\ua000') + >>> chr(40960) + '\ua000' + >>> ord('\ua000') 40960 -Instances of the :class:`unicode` type have many of the same methods as the -8-bit string type for operations such as searching and formatting:: - - >>> s = u'Was ever feather so lightly blown to and fro as this multitude?' - >>> s.count('e') - 5 - >>> s.find('feather') - 9 - >>> s.find('bird') - -1 - >>> s.replace('feather', 'sand') - u'Was ever sand so lightly blown to and fro as this multitude?' - >>> s.upper() - u'WAS EVER FEATHER SO LIGHTLY BLOWN TO AND FRO AS THIS MULTITUDE?' - -Note that the arguments to these methods can be Unicode strings or 8-bit -strings. 8-bit strings will be converted to Unicode before carrying out the -operation; Python's default ASCII encoding will be used, so characters greater -than 127 will cause an exception:: +Converting to Bytes +------------------- - >>> s.find('Was\x9f') - Traceback (most recent call last): - File "", line 1, in ? - UnicodeDecodeError: 'ascii' codec can't decode byte 0x9f in position 3: ordinal not in range(128) - >>> s.find(u'Was\x9f') - -1 - -Much Python code that operates on strings will therefore work with Unicode -strings without requiring any changes to the code. (Input and output code needs -more updating for Unicode; more on this later.) - -Another important method is ``.encode([encoding], [errors='strict'])``, which -returns an 8-bit string version of the Unicode string, encoded in the requested -encoding. The ``errors`` parameter is the same as the parameter of the -``unicode()`` constructor, with one additional possibility; as well as 'strict', +Another important str method is ``.encode([encoding], [errors='strict'])``, +which returns a ``bytes`` representation of the Unicode string, encoded in the +requested encoding. The ``errors`` parameter is the same as the parameter of +the :meth:`decode` method, with one additional possibility; as well as 'strict', 'ignore', and 'replace', you can also pass 'xmlcharrefreplace' which uses XML's character references. The following example shows the different results:: - >>> u = unichr(40960) + u'abcd' + unichr(1972) + >>> u = chr(40960) + 'abcd' + chr(1972) >>> u.encode('utf-8') - '\xea\x80\x80abcd\xde\xb4' + b'\xea\x80\x80abcd\xde\xb4' >>> u.encode('ascii') Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character '\ua000' in position 0: ordinal not in range(128) >>> u.encode('ascii', 'ignore') - 'abcd' + b'abcd' >>> u.encode('ascii', 'replace') - '?abcd?' + b'?abcd?' >>> u.encode('ascii', 'xmlcharrefreplace') - 'ꀀabcd޴' - -Python's 8-bit strings have a ``.decode([encoding], [errors])`` method that -interprets the string using the given encoding:: - - >>> u = unichr(40960) + u'abcd' + unichr(1972) # Assemble a string - >>> utf8_version = u.encode('utf-8') # Encode as UTF-8 - >>> type(utf8_version), utf8_version - (, '\xea\x80\x80abcd\xde\xb4') - >>> u2 = utf8_version.decode('utf-8') # Decode using UTF-8 - >>> u == u2 # The two strings match - True + b'ꀀabcd޴' The low-level routines for registering and accessing the available encodings are found in the :mod:`codecs` module. However, the encoding and decoding functions @@ -377,22 +327,14 @@ Unicode Literals in Python Source Code -------------------------------------- -In Python source code, Unicode literals are written as strings prefixed with the -'u' or 'U' character: ``u'abcdefghijk'``. Specific code points can be written -using the ``\u`` escape sequence, which is followed by four hex digits giving -the code point. The ``\U`` escape sequence is similar, but expects 8 hex -digits, not 4. - -Unicode literals can also use the same escape sequences as 8-bit strings, -including ``\x``, but ``\x`` only takes two hex digits so it can't express an -arbitrary code point. Octal escapes can go up to U+01ff, which is octal 777. - -:: - - >>> s = u"a\xac\u1234\u20ac\U00008000" - ^^^^ two-digit hex escape - ^^^^^^ four-digit Unicode escape - ^^^^^^^^^^ eight-digit Unicode escape +In Python source code, specific Unicode code points can be written using the +``\u`` escape sequence, which is followed by four hex digits giving the code +point. The ``\U`` escape sequence is similar, but expects 8 hex digits, not 4:: + + >>> s = "a\xac\u1234\u20ac\U00008000" + ^^^^ two-digit hex escape + ^^^^^ four-digit Unicode escape + ^^^^^^^^^^ eight-digit Unicode escape >>> for c in s: print(ord(c), end=" ") ... 97 172 4660 8364 32768 @@ -400,7 +342,7 @@ Using escape sequences for code points greater than 127 is fine in small doses, but becomes an annoyance if you're using many accented characters, as you would in a program with messages in French or some other accent-using language. You -can also assemble strings using the :func:`unichr` built-in function, but this is +can also assemble strings using the :func:`chr` built-in function, but this is even more tedious. Ideally, you'd want to be able to write literals in your language's natural @@ -408,14 +350,15 @@ which would display the accented characters naturally, and have the right characters used at runtime. -Python supports writing Unicode literals in any encoding, but you have to -declare the encoding being used. This is done by including a special comment as -either the first or second line of the source file:: +Python supports writing Unicode literals in UTF-8 by default, but you can use +(almost) any encoding if you declare the encoding being used. This is done by +including a special comment as either the first or second line of the source +file:: #!/usr/bin/env python # -*- coding: latin-1 -*- - u = u'abcd??' + u = 'abcd??' print(ord(u[-1])) The syntax is inspired by Emacs's notation for specifying variables local to a @@ -424,22 +367,8 @@ them, you must supply the name ``coding`` and the name of your chosen encoding, separated by ``':'``. -If you don't include such a comment, the default encoding used will be ASCII. -Versions of Python before 2.4 were Euro-centric and assumed Latin-1 as a default -encoding for string literals; in Python 2.4, characters greater than 127 still -work but result in a warning. For example, the following program has no -encoding declaration:: - - #!/usr/bin/env python - u = u'abcd??' - print(ord(u[-1])) - -When you run it with Python 2.4, it will output the following warning:: - - amk:~$ python p263.py - sys:1: DeprecationWarning: Non-ASCII character '\xe9' - in file p263.py on line 2, but no encoding declared; - see http://www.python.org/peps/pep-0263.html for details +If you don't include such a comment, the default encoding used will be UTF-8 as +already mentioned. Unicode Properties @@ -457,7 +386,7 @@ import unicodedata - u = unichr(233) + unichr(0x0bf2) + unichr(3972) + unichr(6000) + unichr(13231) + u = chr(233) + chr(0x0bf2) + chr(3972) + chr(6000) + chr(13231) for i, c in enumerate(u): print(i, '%04x' % ord(c), unicodedata.category(c), end=" ") @@ -487,8 +416,8 @@ References ---------- -The Unicode and 8-bit string types are described in the Python library reference -at :ref:`typesseq`. +The ``str`` type is described in the Python library reference at +:ref:`typesseq`. The documentation for the :mod:`unicodedata` module. @@ -496,7 +425,7 @@ Marc-Andr?? Lemburg gave a presentation at EuroPython 2002 titled "Python and Unicode". A PDF version of his slides is available at -, and is an +, and is an excellent overview of the design of Python's Unicode features. @@ -557,7 +486,7 @@ writing:: f = codecs.open('test', encoding='utf-8', mode='w+') - f.write(u'\u4500 blah blah blah\n') + f.write('\u4500 blah blah blah\n') f.seek(0) print(repr(f.readline()[:1])) f.close() @@ -590,7 +519,7 @@ usually just provide the Unicode string as the filename, and it will be automatically converted to the right encoding for you:: - filename = u'filename\u4500abc' + filename = 'filename\u4500abc' f = open(filename, 'w') f.write('blah\n') f.close() @@ -607,7 +536,7 @@ path will return the 8-bit versions of the filenames. For example, assuming the default filesystem encoding is UTF-8, running the following program:: - fn = u'filename\u4500abc' + fn = 'filename\u4500abc' f = open(fn, 'w') f.close() @@ -619,7 +548,7 @@ amk:~$ python t.py ['.svn', 'filename\xe4\x94\x80abc', ...] - [u'.svn', u'filename\u4500abc', ...] + ['.svn', 'filename\u4500abc', ...] The first list contains UTF-8-encoded filenames, and the second list contains the Unicode versions. @@ -683,7 +612,7 @@ The PDF slides for Marc-Andr?? Lemburg's presentation "Writing Unicode-aware Applications in Python" are available at - + and discuss questions of character encodings as well as how to internationalize and localize an application. Modified: python/branches/py3k-ctypes-pep3118/Doc/howto/urllib2.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/howto/urllib2.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/howto/urllib2.rst Wed Apr 30 15:57:13 2008 @@ -8,7 +8,7 @@ There is an French translation of an earlier revision of this HOWTO, available at `urllib2 - Le Manuel manquant - `_. + `_. Modified: python/branches/py3k-ctypes-pep3118/Doc/includes/tzinfo-examples.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/includes/tzinfo-examples.py (original) +++ python/branches/py3k-ctypes-pep3118/Doc/includes/tzinfo-examples.py Wed Apr 30 15:57:13 2008 @@ -87,11 +87,31 @@ dt += timedelta(days_to_go) return dt -# In the US, DST starts at 2am (standard time) on the first Sunday in April. -DSTSTART = datetime(1, 4, 1, 2) -# and ends at 2am (DST time; 1am standard time) on the last Sunday of Oct. -# which is the first Sunday on or after Oct 25. -DSTEND = datetime(1, 10, 25, 1) + +# US DST Rules +# +# This is a simplified (i.e., wrong for a few cases) set of rules for US +# DST start and end times. For a complete and up-to-date set of DST rules +# and timezone definitions, visit the Olson Database (or try pytz): +# http://www.twinsun.com/tz/tz-link.htm +# http://sourceforge.net/projects/pytz/ (might not be up-to-date) +# +# In the US, since 2007, DST starts at 2am (standard time) on the second +# Sunday in March, which is the first Sunday on or after Mar 8. +DSTSTART_2007 = datetime(1, 3, 8, 2) +# and ends at 2am (DST time; 1am standard time) on the first Sunday of Nov. +DSTEND_2007 = datetime(1, 11, 1, 1) +# From 1987 to 2006, DST used to start at 2am (standard time) on the first +# Sunday in April and to end at 2am (DST time; 1am standard time) on the last +# Sunday of October, which is the first Sunday on or after Oct 25. +DSTSTART_1987_2006 = datetime(1, 4, 1, 2) +DSTEND_1987_2006 = datetime(1, 10, 25, 1) +# From 1967 to 1986, DST used to start at 2am (standard time) on the last +# Sunday in April (the one on or after April 24) and to end at 2am (DST time; +# 1am standard time) on the last Sunday of October, which is the first Sunday +# on or after Oct 25. +DSTSTART_1967_1986 = datetime(1, 4, 24, 2) +DSTEND_1967_1986 = DSTEND_1987_2006 class USTimeZone(tzinfo): @@ -122,9 +142,19 @@ return ZERO assert dt.tzinfo is self - # Find first Sunday in April & the last in October. - start = first_sunday_on_or_after(DSTSTART.replace(year=dt.year)) - end = first_sunday_on_or_after(DSTEND.replace(year=dt.year)) + # Find start and end times for US DST. For years before 1967, return + # ZERO for no DST. + if 2006 < dt.year: + dststart, dstend = DSTSTART_2007, DSTEND_2007 + elif 1986 < dt.year < 2007: + dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006 + elif 1966 < dt.year < 1987: + dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986 + else: + return ZERO + + start = first_sunday_on_or_after(dststart.replace(year=dt.year)) + end = first_sunday_on_or_after(dstend.replace(year=dt.year)) # Can't compare naive to aware objects, so strip the timezone from # dt first. Modified: python/branches/py3k-ctypes-pep3118/Doc/install/index.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/install/index.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/install/index.rst Wed Apr 30 15:57:13 2008 @@ -869,10 +869,10 @@ -Borland C++ -^^^^^^^^^^^ +Borland/CodeGear C++ +^^^^^^^^^^^^^^^^^^^^ -This subsection describes the necessary steps to use Distutils with the Borland +This subsection describes the necessary steps to use Distutils with the Borland C++ compiler version 5.5. First you have to know that Borland's object file format (OMF) is different from the format used by the Python version you can download from the Python or ActiveState Web site. (Python is built with @@ -912,7 +912,7 @@ .. seealso:: - `C++Builder Compiler `_ + `C++Builder Compiler `_ Information about the free C++ compiler from Borland, including links to the download pages. @@ -935,9 +935,7 @@ These compilers require some special libraries. This task is more complex than for Borland's C++, because there is no program to convert the library. First you have to create a list of symbols which the Python DLL exports. (You can find -a good program for this task at -http://starship.python.net/crew/kernr/mingw32/Notes.html, see at PExports 0.42h -there.) +a good program for this task at http://www.emmestech.com/software/cygwin/pexports-0.43/download_pexports.html) .. I don't understand what the next line means. --amk .. (inclusive the references on data structures.) @@ -981,9 +979,6 @@ `Building Python modules on MS Windows platform with MinGW `_ Information about building the required libraries for the MinGW environment. - http://pyopengl.sourceforge.net/ftp/win32-stuff/ - Converted import libraries in Cygwin/MinGW and Borland format, and a script to - create the registry entries needed for Distutils to locate the built Python. .. rubric:: Footnotes Modified: python/branches/py3k-ctypes-pep3118/Doc/library/__future__.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/__future__.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/__future__.rst Wed Apr 30 15:57:13 2008 @@ -1,4 +1,3 @@ - :mod:`__future__` --- Future statement definitions ================================================== @@ -22,8 +21,8 @@ Each statement in :file:`__future__.py` is of the form:: - FeatureName = "_Feature(" OptionalRelease "," MandatoryRelease "," - CompilerFlag ")" + FeatureName = _Feature(OptionalRelease, MandatoryRelease, + CompilerFlag) where, normally, *OptionalRelease* is less than *MandatoryRelease*, and both are Modified: python/branches/py3k-ctypes-pep3118/Doc/library/_ast.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/_ast.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/_ast.rst Wed Apr 30 15:57:13 2008 @@ -10,16 +10,16 @@ The ``_ast`` module helps Python applications to process trees of the Python -abstract syntax grammar. The Python compiler currently provides read-only access -to such trees, meaning that applications can only create a tree for a given -piece of Python source code; generating :term:`bytecode` from a (potentially modified) -tree is not supported. The abstract syntax itself might change with each Python -release; this module helps to find out programmatically what the current grammar -looks like. - -An abstract syntax tree can be generated by passing ``_ast.PyCF_ONLY_AST`` as a -flag to the :func:`compile` builtin function. The result will be a tree of -objects whose classes all inherit from ``_ast.AST``. +abstract syntax grammar. The abstract syntax itself might change with each +Python release; this module helps to find out programmatically what the current +grammar looks like. + +An abstract syntax tree can be generated by passing :data:`_ast.PyCF_ONLY_AST` +as a flag to the :func:`compile` builtin function. The result will be a tree of +objects whose classes all inherit from :class:`_ast.AST`. + +A modified abstract syntax tree can be compiled into a Python code object using +the built-in :func:`compile` function. The actual classes are derived from the ``Parser/Python.asdl`` file, which is reproduced below. There is one class defined for each left-hand side symbol in @@ -39,11 +39,37 @@ ``_ast.stmt`` subclasses also have lineno and col_offset attributes. The lineno is the line number of source text (1 indexed so the first line is line 1) and the col_offset is the utf8 byte offset of the first token that generated the -node. The utf8 offset is recorded because the parser uses utf8 internally. +node. The utf8 offset is recorded because the parser uses utf8 internally. If these attributes are marked as optional in the grammar (using a question mark), the value might be ``None``. If the attributes can have zero-or-more values (marked with an asterisk), the values are represented as Python lists. +All possible attributes must be present and have valid values when compiling an +AST with :func:`compile`. + +The constructor of a class ``_ast.T`` parses their arguments as follows: + +* If there are positional arguments, there must be as many as there are items in + ``T._fields``; they will be assigned as attributes of these names. +* If there are keyword arguments, they will set the attributes of the same names + to the given values. + +For example, to create and populate a ``UnaryOp`` node, you could use :: + + node = _ast.UnaryOp() + node.op = _ast.USub() + node.operand = _ast.Num() + node.operand.n = 5 + node.operand.lineno = 0 + node.operand.col_offset = 0 + node.lineno = 0 + node.col_offset = 0 + +or the more compact :: + + node = _ast.UnaryOp(_ast.USub(), _ast.Num(5, lineno=0, col_offset=0), + lineno=0, col_offset=0) + Abstract Grammar Modified: python/branches/py3k-ctypes-pep3118/Doc/library/_winreg.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/_winreg.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/_winreg.rst Wed Apr 30 15:57:13 2008 @@ -138,8 +138,6 @@ >>> ExpandEnvironmentStrings(u"%windir%") u"C:\\Windows" - .. versionadded:: 2.6 - .. function:: FlushKey(key) @@ -437,5 +435,4 @@ will automatically close *key* when control leaves the :keyword:`with` block. - .. versionadded:: 2.6 Modified: python/branches/py3k-ctypes-pep3118/Doc/library/aepack.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/aepack.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/aepack.rst Wed Apr 30 15:57:13 2008 @@ -84,7 +84,3 @@ Module :mod:`aetypes` Python definitions of codes for Apple Event descriptor types. - - `Inside Macintosh: Interapplication Communication `_ - Information about inter-process communications on the Macintosh. - Modified: python/branches/py3k-ctypes-pep3118/Doc/library/allos.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/allos.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/allos.rst Wed Apr 30 15:57:13 2008 @@ -14,6 +14,7 @@ .. toctree:: os.rst + io.rst time.rst optparse.rst getopt.rst Modified: python/branches/py3k-ctypes-pep3118/Doc/library/array.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/array.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/array.rst Wed Apr 30 15:57:13 2008 @@ -3,12 +3,12 @@ =================================================== .. module:: array - :synopsis: Efficient arrays of uniformly typed numeric values. + :synopsis: Space efficient arrays of uniformly typed numeric values. .. index:: single: arrays -This module defines an object type which can efficiently represent an array of +This module defines an object type which can compactly represent an array of basic values: characters, integers, floating point numbers. Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The type is specified at object creation time by using a @@ -183,18 +183,6 @@ returned. -.. method:: array.read(f, n) - - .. deprecated:: 1.5.1 - Use the :meth:`fromfile` method. - - Read *n* items (as machine values) from the file object *f* and append them to - the end of the array. If less than *n* items are available, :exc:`EOFError` is - raised, but the items that were available are still inserted into the array. - *f* must be a real built-in file object; something else with a :meth:`read` - method won't do. - - .. method:: array.remove(x) Remove the first occurrence of *x* from the array. @@ -229,13 +217,6 @@ obtain a unicode string from an array of some other type. -.. method:: array.write(f) - - .. deprecated:: 1.5.1 - Use the :meth:`tofile` method. - - Write all items (as machine values) to the file object *f*. - When an array object is printed or converted to a string, it is represented as ``array(typecode, initializer)``. The *initializer* is omitted if the array is empty, otherwise it is a string if the *typecode* is ``'c'``, otherwise it is a Modified: python/branches/py3k-ctypes-pep3118/Doc/library/asynchat.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/asynchat.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/asynchat.rst Wed Apr 30 15:57:13 2008 @@ -197,10 +197,10 @@ the data no larger than *buffer_size*. -.. method:: simple_producer.more() + .. method:: more() - Produces the next chunk of information from the producer, or returns the - empty string. + Produces the next chunk of information from the producer, or returns the + empty string. .. class:: fifo([list=None]) @@ -212,26 +212,26 @@ producers or data items to be written to the channel. -.. method:: fifo.is_empty() + .. method:: is_empty() - Returns ``True`` if and only if the fifo is empty. + Returns ``True`` if and only if the fifo is empty. -.. method:: fifo.first() + .. method:: first() - Returns the least-recently :meth:`push`\ ed item from the fifo. + Returns the least-recently :meth:`push`\ ed item from the fifo. -.. method:: fifo.push(data) + .. method:: push(data) - Adds the given data (which may be a string or a producer object) to the - producer fifo. + Adds the given data (which may be a string or a producer object) to the + producer fifo. -.. method:: fifo.pop() + .. method:: pop() - If the fifo is not empty, returns ``True, first()``, deleting the popped - item. Returns ``False, None`` for an empty fifo. + If the fifo is not empty, returns ``True, first()``, deleting the popped + item. Returns ``False, None`` for an empty fifo. The :mod:`asynchat` module also defines one utility function, which may be of use in network and textual analysis operations. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/asyncore.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/asyncore.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/asyncore.rst Wed Apr 30 15:57:13 2008 @@ -95,132 +95,132 @@ should be added to the list of channels :cfunc:`select`\ ed or :cfunc:`poll`\ ed for read and write events. -Thus, the set of channel events is larger than the basic socket events. The -full set of methods that can be overridden in your subclass follows: + Thus, the set of channel events is larger than the basic socket events. The + full set of methods that can be overridden in your subclass follows: -.. method:: dispatcher.handle_read() + .. method:: handle_read() - Called when the asynchronous loop detects that a :meth:`read` call on the - channel's socket will succeed. + Called when the asynchronous loop detects that a :meth:`read` call on the + channel's socket will succeed. -.. method:: dispatcher.handle_write() + .. method:: handle_write() - Called when the asynchronous loop detects that a writable socket can be - written. Often this method will implement the necessary buffering for - performance. For example:: + Called when the asynchronous loop detects that a writable socket can be + written. Often this method will implement the necessary buffering for + performance. For example:: - def handle_write(self): - sent = self.send(self.buffer) - self.buffer = self.buffer[sent:] + def handle_write(self): + sent = self.send(self.buffer) + self.buffer = self.buffer[sent:] -.. method:: dispatcher.handle_expt() + .. method:: handle_expt() - Called when there is out of band (OOB) data for a socket connection. This - will almost never happen, as OOB is tenuously supported and rarely used. + Called when there is out of band (OOB) data for a socket connection. This + will almost never happen, as OOB is tenuously supported and rarely used. -.. method:: dispatcher.handle_connect() + .. method:: handle_connect() - Called when the active opener's socket actually makes a connection. Might - send a "welcome" banner, or initiate a protocol negotiation with the remote - endpoint, for example. + Called when the active opener's socket actually makes a connection. Might + send a "welcome" banner, or initiate a protocol negotiation with the + remote endpoint, for example. -.. method:: dispatcher.handle_close() + .. method:: handle_close() - Called when the socket is closed. + Called when the socket is closed. -.. method:: dispatcher.handle_error() + .. method:: handle_error() - Called when an exception is raised and not otherwise handled. The default - version prints a condensed traceback. + Called when an exception is raised and not otherwise handled. The default + version prints a condensed traceback. -.. method:: dispatcher.handle_accept() + .. method:: handle_accept() - Called on listening channels (passive openers) when a connection can be - established with a new remote endpoint that has issued a :meth:`connect` - call for the local endpoint. + Called on listening channels (passive openers) when a connection can be + established with a new remote endpoint that has issued a :meth:`connect` + call for the local endpoint. -.. method:: dispatcher.readable() + .. method:: readable() - Called each time around the asynchronous loop to determine whether a - channel's socket should be added to the list on which read events can - occur. The default method simply returns ``True``, indicating that by - default, all channels will be interested in read events. + Called each time around the asynchronous loop to determine whether a + channel's socket should be added to the list on which read events can + occur. The default method simply returns ``True``, indicating that by + default, all channels will be interested in read events. -.. method:: dispatcher.writable() + .. method:: writable() - Called each time around the asynchronous loop to determine whether a - channel's socket should be added to the list on which write events can - occur. The default method simply returns ``True``, indicating that by - default, all channels will be interested in write events. + Called each time around the asynchronous loop to determine whether a + channel's socket should be added to the list on which write events can + occur. The default method simply returns ``True``, indicating that by + default, all channels will be interested in write events. -In addition, each channel delegates or extends many of the socket methods. -Most of these are nearly identical to their socket partners. + In addition, each channel delegates or extends many of the socket methods. + Most of these are nearly identical to their socket partners. -.. method:: dispatcher.create_socket(family, type) - This is identical to the creation of a normal socket, and will use the same - options for creation. Refer to the :mod:`socket` documentation for - information on creating sockets. + .. method:: create_socket(family, type) + This is identical to the creation of a normal socket, and will use the + same options for creation. Refer to the :mod:`socket` documentation for + information on creating sockets. -.. method:: dispatcher.connect(address) - As with the normal socket object, *address* is a tuple with the first - element the host to connect to, and the second the port number. + .. method:: connect(address) + As with the normal socket object, *address* is a tuple with the first + element the host to connect to, and the second the port number. -.. method:: dispatcher.send(data) - Send *data* to the remote end-point of the socket. + .. method:: send(data) + Send *data* to the remote end-point of the socket. -.. method:: dispatcher.recv(buffer_size) - Read at most *buffer_size* bytes from the socket's remote end-point. - An empty string implies that the channel has been closed from the other - end. + .. method:: recv(buffer_size) + Read at most *buffer_size* bytes from the socket's remote end-point. An + empty string implies that the channel has been closed from the other end. -.. method:: dispatcher.listen(backlog) - Listen for connections made to the socket. The *backlog* argument - specifies the maximum number of queued connections and should be at least - 1; the maximum value is system-dependent (usually 5). + .. method:: listen(backlog) + Listen for connections made to the socket. The *backlog* argument + specifies the maximum number of queued connections and should be at least + 1; the maximum value is system-dependent (usually 5). -.. method:: dispatcher.bind(address) - Bind the socket to *address*. The socket must not already be bound. (The - format of *address* depends on the address family --- see above.) To mark - the socket as re-usable (setting the :const:`SO_REUSEADDR` option), call - the :class:`dispatcher` object's :meth:`set_reuse_addr` method. + .. method:: bind(address) + Bind the socket to *address*. The socket must not already be bound. (The + format of *address* depends on the address family --- see above.) To mark + the socket as re-usable (setting the :const:`SO_REUSEADDR` option), call + the :class:`dispatcher` object's :meth:`set_reuse_addr` method. -.. method:: dispatcher.accept() - Accept a connection. The socket must be bound to an address and listening - for connections. The return value is a pair ``(conn, address)`` where - *conn* is a *new* socket object usable to send and receive data on the - connection, and *address* is the address bound to the socket on the other - end of the connection. + .. method:: accept() + Accept a connection. The socket must be bound to an address and listening + for connections. The return value is a pair ``(conn, address)`` where + *conn* is a *new* socket object usable to send and receive data on the + connection, and *address* is the address bound to the socket on the other + end of the connection. -.. method:: dispatcher.close() - Close the socket. All future operations on the socket object will fail. - The remote end-point will receive no more data (after queued data is - flushed). Sockets are automatically closed when they are - garbage-collected. + .. method:: close() + + Close the socket. All future operations on the socket object will fail. + The remote end-point will receive no more data (after queued data is + flushed). Sockets are automatically closed when they are + garbage-collected. .. _asyncore-example: Modified: python/branches/py3k-ctypes-pep3118/Doc/library/audioop.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/audioop.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/audioop.rst Wed Apr 30 15:57:13 2008 @@ -136,6 +136,18 @@ Convert samples between 1-, 2- and 4-byte formats. + .. note:: + + In some audio formats, such as .WAV files, 16 and 32 bit samples are + signed, but 8 bit samples are unsigned. So when converting to 8 bit wide + samples for these formats, you need to also add 128 to the result:: + + new_frames = audioop.lin2lin(frames, old_width, 1) + new_frames = audioop.bias(new_frames, 1, 128) + + The same, in reverse, has to be applied when converting from 8 to 16 or 32 + bit width samples. + .. function:: lin2ulaw(fragment, width) Modified: python/branches/py3k-ctypes-pep3118/Doc/library/base64.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/base64.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/base64.rst Wed Apr 30 15:57:13 2008 @@ -150,7 +150,7 @@ :func:`encodestring` returns a string containing one or more lines of base64-encoded data always including an extra trailing newline (``'\n'``). -An example usage of the module:: +An example usage of the module: >>> import base64 >>> encoded = base64.b64encode('data to be encoded') Modified: python/branches/py3k-ctypes-pep3118/Doc/library/basehttpserver.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/basehttpserver.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/basehttpserver.rst Wed Apr 30 15:57:13 2008 @@ -34,210 +34,224 @@ .. class:: HTTPServer(server_address, RequestHandlerClass) - This class builds on the :class:`TCPServer` class by storing the server address - as instance variables named :attr:`server_name` and :attr:`server_port`. The - server is accessible by the handler, typically through the handler's - :attr:`server` instance variable. + This class builds on the :class:`TCPServer` class by storing the server + address as instance variables named :attr:`server_name` and + :attr:`server_port`. The server is accessible by the handler, typically + through the handler's :attr:`server` instance variable. .. class:: BaseHTTPRequestHandler(request, client_address, server) This class is used to handle the HTTP requests that arrive at the server. By - itself, it cannot respond to any actual HTTP requests; it must be subclassed to - handle each request method (e.g. GET or POST). :class:`BaseHTTPRequestHandler` - provides a number of class and instance variables, and methods for use by - subclasses. + itself, it cannot respond to any actual HTTP requests; it must be subclassed + to handle each request method (e.g. GET or + POST). :class:`BaseHTTPRequestHandler` provides a number of class and + instance variables, and methods for use by subclasses. - The handler will parse the request and the headers, then call a method specific - to the request type. The method name is constructed from the request. For - example, for the request method ``SPAM``, the :meth:`do_SPAM` method will be - called with no arguments. All of the relevant information is stored in instance - variables of the handler. Subclasses should not need to override or extend the - :meth:`__init__` method. + The handler will parse the request and the headers, then call a method + specific to the request type. The method name is constructed from the + request. For example, for the request method ``SPAM``, the :meth:`do_SPAM` + method will be called with no arguments. All of the relevant information is + stored in instance variables of the handler. Subclasses should not need to + override or extend the :meth:`__init__` method. -:class:`BaseHTTPRequestHandler` has the following instance variables: + :class:`BaseHTTPRequestHandler` has the following instance variables: -.. attribute:: BaseHTTPRequestHandler.client_address + .. attribute:: client_address - Contains a tuple of the form ``(host, port)`` referring to the client's address. + Contains a tuple of the form ``(host, port)`` referring to the client's + address. -.. attribute:: BaseHTTPRequestHandler.command + .. attribute:: command - Contains the command (request type). For example, ``'GET'``. + Contains the command (request type). For example, ``'GET'``. -.. attribute:: BaseHTTPRequestHandler.path + .. attribute:: path - Contains the request path. + Contains the request path. -.. attribute:: BaseHTTPRequestHandler.request_version + .. attribute:: request_version - Contains the version string from the request. For example, ``'HTTP/1.0'``. + Contains the version string from the request. For example, ``'HTTP/1.0'``. -.. attribute:: BaseHTTPRequestHandler.headers + .. attribute:: headers - Holds an instance of the class specified by the :attr:`MessageClass` class - variable. This instance parses and manages the headers in the HTTP request. + Holds an instance of the class specified by the :attr:`MessageClass` class + variable. This instance parses and manages the headers in the HTTP + request. -.. attribute:: BaseHTTPRequestHandler.rfile + .. attribute:: rfile - Contains an input stream, positioned at the start of the optional input data. + Contains an input stream, positioned at the start of the optional input + data. -.. attribute:: BaseHTTPRequestHandler.wfile + .. attribute:: wfile - Contains the output stream for writing a response back to the client. Proper - adherence to the HTTP protocol must be used when writing to this stream. + Contains the output stream for writing a response back to the + client. Proper adherence to the HTTP protocol must be used when writing to + this stream. -:class:`BaseHTTPRequestHandler` has the following class variables: + :class:`BaseHTTPRequestHandler` has the following class variables: -.. attribute:: BaseHTTPRequestHandler.server_version - Specifies the server software version. You may want to override this. The - format is multiple whitespace-separated strings, where each string is of the - form name[/version]. For example, ``'BaseHTTP/0.2'``. + .. attribute:: server_version + Specifies the server software version. You may want to override this. The + format is multiple whitespace-separated strings, where each string is of + the form name[/version]. For example, ``'BaseHTTP/0.2'``. -.. attribute:: BaseHTTPRequestHandler.sys_version - Contains the Python system version, in a form usable by the - :attr:`version_string` method and the :attr:`server_version` class variable. For - example, ``'Python/1.4'``. + .. attribute:: sys_version + Contains the Python system version, in a form usable by the + :attr:`version_string` method and the :attr:`server_version` class + variable. For example, ``'Python/1.4'``. -.. attribute:: BaseHTTPRequestHandler.error_message_format - Specifies a format string for building an error response to the client. It uses - parenthesized, keyed format specifiers, so the format operand must be a - dictionary. The *code* key should be an integer, specifying the numeric HTTP - error code value. *message* should be a string containing a (detailed) error - message of what occurred, and *explain* should be an explanation of the error - code number. Default *message* and *explain* values can found in the *responses* - class variable. + .. attribute:: error_message_format + Specifies a format string for building an error response to the client. It + uses parenthesized, keyed format specifiers, so the format operand must be + a dictionary. The *code* key should be an integer, specifying the numeric + HTTP error code value. *message* should be a string containing a + (detailed) error message of what occurred, and *explain* should be an + explanation of the error code number. Default *message* and *explain* + values can found in the *responses* class variable. -.. attribute:: BaseHTTPRequestHandler.protocol_version - This specifies the HTTP protocol version used in responses. If set to - ``'HTTP/1.1'``, the server will permit HTTP persistent connections; however, - your server *must* then include an accurate ``Content-Length`` header (using - :meth:`send_header`) in all of its responses to clients. For backwards - compatibility, the setting defaults to ``'HTTP/1.0'``. + .. attribute:: error_content_type + Specifies the Content-Type HTTP header of error responses sent to the + client. The default value is ``'text/html'``. -.. attribute:: BaseHTTPRequestHandler.MessageClass - .. index:: single: Message (in module mimetools) + .. attribute:: protocol_version - Specifies a :class:`rfc822.Message`\ -like class to parse HTTP headers. - Typically, this is not overridden, and it defaults to - :class:`mimetools.Message`. + This specifies the HTTP protocol version used in responses. If set to + ``'HTTP/1.1'``, the server will permit HTTP persistent connections; + however, your server *must* then include an accurate ``Content-Length`` + header (using :meth:`send_header`) in all of its responses to clients. + For backwards compatibility, the setting defaults to ``'HTTP/1.0'``. -.. attribute:: BaseHTTPRequestHandler.responses + .. attribute:: MessageClass - This variable contains a mapping of error code integers to two-element tuples - containing a short and long message. For example, ``{code: (shortmessage, - longmessage)}``. The *shortmessage* is usually used as the *message* key in an - error response, and *longmessage* as the *explain* key (see the - :attr:`error_message_format` class variable). + .. index:: single: Message (in module mimetools) -A :class:`BaseHTTPRequestHandler` instance has the following methods: + Specifies a :class:`rfc822.Message`\ -like class to parse HTTP headers. + Typically, this is not overridden, and it defaults to + :class:`mimetools.Message`. -.. method:: BaseHTTPRequestHandler.handle() + .. attribute:: responses - Calls :meth:`handle_one_request` once (or, if persistent connections are - enabled, multiple times) to handle incoming HTTP requests. You should never need - to override it; instead, implement appropriate :meth:`do_\*` methods. + This variable contains a mapping of error code integers to two-element tuples + containing a short and long message. For example, ``{code: (shortmessage, + longmessage)}``. The *shortmessage* is usually used as the *message* key in an + error response, and *longmessage* as the *explain* key (see the + :attr:`error_message_format` class variable). -.. method:: BaseHTTPRequestHandler.handle_one_request() + A :class:`BaseHTTPRequestHandler` instance has the following methods: - This method will parse and dispatch the request to the appropriate :meth:`do_\*` - method. You should never need to override it. + .. method:: handle() -.. method:: BaseHTTPRequestHandler.send_error(code[, message]) + Calls :meth:`handle_one_request` once (or, if persistent connections are + enabled, multiple times) to handle incoming HTTP requests. You should + never need to override it; instead, implement appropriate :meth:`do_\*` + methods. - Sends and logs a complete error reply to the client. The numeric *code* - specifies the HTTP error code, with *message* as optional, more specific text. A - complete set of headers is sent, followed by text composed using the - :attr:`error_message_format` class variable. + .. method:: handle_one_request() -.. method:: BaseHTTPRequestHandler.send_response(code[, message]) + This method will parse and dispatch the request to the appropriate + :meth:`do_\*` method. You should never need to override it. - Sends a response header and logs the accepted request. The HTTP response line is - sent, followed by *Server* and *Date* headers. The values for these two headers - are picked up from the :meth:`version_string` and :meth:`date_time_string` - methods, respectively. + .. method:: send_error(code[, message]) -.. method:: BaseHTTPRequestHandler.send_header(keyword, value) + Sends and logs a complete error reply to the client. The numeric *code* + specifies the HTTP error code, with *message* as optional, more specific text. A + complete set of headers is sent, followed by text composed using the + :attr:`error_message_format` class variable. - Writes a specific HTTP header to the output stream. *keyword* should specify the - header keyword, with *value* specifying its value. + .. method:: send_response(code[, message]) -.. method:: BaseHTTPRequestHandler.end_headers() + Sends a response header and logs the accepted request. The HTTP response + line is sent, followed by *Server* and *Date* headers. The values for + these two headers are picked up from the :meth:`version_string` and + :meth:`date_time_string` methods, respectively. - Sends a blank line, indicating the end of the HTTP headers in the response. + .. method:: send_header(keyword, value) -.. method:: BaseHTTPRequestHandler.log_request([code[, size]]) + Writes a specific HTTP header to the output stream. *keyword* should + specify the header keyword, with *value* specifying its value. - Logs an accepted (successful) request. *code* should specify the numeric HTTP - code associated with the response. If a size of the response is available, then - it should be passed as the *size* parameter. + .. method:: end_headers() -.. method:: BaseHTTPRequestHandler.log_error(...) + Sends a blank line, indicating the end of the HTTP headers in the + response. - Logs an error when a request cannot be fulfilled. By default, it passes the - message to :meth:`log_message`, so it takes the same arguments (*format* and - additional values). + .. method:: log_request([code[, size]]) -.. method:: BaseHTTPRequestHandler.log_message(format, ...) + Logs an accepted (successful) request. *code* should specify the numeric + HTTP code associated with the response. If a size of the response is + available, then it should be passed as the *size* parameter. - Logs an arbitrary message to ``sys.stderr``. This is typically overridden to - create custom error logging mechanisms. The *format* argument is a standard - printf-style format string, where the additional arguments to - :meth:`log_message` are applied as inputs to the formatting. The client address - and current date and time are prefixed to every message logged. + .. method:: log_error(...) -.. method:: BaseHTTPRequestHandler.version_string() + Logs an error when a request cannot be fulfilled. By default, it passes + the message to :meth:`log_message`, so it takes the same arguments + (*format* and additional values). - Returns the server software's version string. This is a combination of the - :attr:`server_version` and :attr:`sys_version` class variables. + .. method:: log_message(format, ...) -.. method:: BaseHTTPRequestHandler.date_time_string([timestamp]) + Logs an arbitrary message to ``sys.stderr``. This is typically overridden + to create custom error logging mechanisms. The *format* argument is a + standard printf-style format string, where the additional arguments to + :meth:`log_message` are applied as inputs to the formatting. The client + address and current date and time are prefixed to every message logged. - Returns the date and time given by *timestamp* (which must be in the format - returned by :func:`time.time`), formatted for a message header. If *timestamp* - is omitted, it uses the current date and time. - The result looks like ``'Sun, 06 Nov 1994 08:49:37 GMT'``. + .. method:: version_string() + Returns the server software's version string. This is a combination of the + :attr:`server_version` and :attr:`sys_version` class variables. -.. method:: BaseHTTPRequestHandler.log_date_time_string() - Returns the current date and time, formatted for logging. + .. method:: date_time_string([timestamp]) + Returns the date and time given by *timestamp* (which must be in the + format returned by :func:`time.time`), formatted for a message header. If + *timestamp* is omitted, it uses the current date and time. -.. method:: BaseHTTPRequestHandler.address_string() + The result looks like ``'Sun, 06 Nov 1994 08:49:37 GMT'``. - Returns the client address, formatted for logging. A name lookup is performed on - the client's IP address. + + .. method:: log_date_time_string() + + Returns the current date and time, formatted for logging. + + + .. method:: address_string() + + Returns the client address, formatted for logging. A name lookup is + performed on the client's IP address. .. seealso:: Modified: python/branches/py3k-ctypes-pep3118/Doc/library/bdb.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/bdb.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/bdb.rst Wed Apr 30 15:57:13 2008 @@ -31,32 +31,35 @@ first line of that function is executed. A conditional breakpoint always counts a hit. -:class:`Breakpoint` instances have the following methods: + :class:`Breakpoint` instances have the following methods: -.. method:: Breakpoint.deleteMe() + .. method:: deleteMe() - Delete the breakpoint from the list associated to a file/line. If it is the - last breakpoint in that position, it also deletes the entry for the - file/line. + Delete the breakpoint from the list associated to a file/line. If it is + the last breakpoint in that position, it also deletes the entry for the + file/line. -.. method:: Breakpoint.enable() - Mark the breakpoint as enabled. + .. method:: enable() -.. method:: Breakpoint.disable() + Mark the breakpoint as enabled. - Mark the breakpoint as disabled. -.. method:: Breakpoint.bpprint([out]) + .. method:: disable() - Print all the information about the breakpoint: + Mark the breakpoint as disabled. - * The breakpoint number. - * If it is temporary or not. - * Its file,line position. - * The condition that causes a break. - * If it must be ignored the next N times. - * The breakpoint hit count. + + .. method:: pprint([out]) + + Print all the information about the breakpoint: + + * The breakpoint number. + * If it is temporary or not. + * Its file,line position. + * The condition that causes a break. + * If it must be ignored the next N times. + * The breakpoint hit count. .. class:: Bdb() @@ -68,247 +71,246 @@ (:class:`pdb.Pdb`) is an example. -The following methods of :class:`Bdb` normally don't need to be overridden. - -.. method:: Bdb.canonic(filename) + The following methods of :class:`Bdb` normally don't need to be overridden. - Auxiliary method for getting a filename in a canonical form, that is, as a - case-normalized (on case-insensitive filesystems) absolute path, stripped - of surrounding angle brackets. + .. method:: canonic(filename) -.. method:: Bdb.reset() + Auxiliary method for getting a filename in a canonical form, that is, as a + case-normalized (on case-insensitive filesystems) absolute path, stripped + of surrounding angle brackets. - Set the :attr:`botframe`, :attr:`stopframe`, :attr:`returnframe` and - :attr:`quitting` attributes with values ready to start debugging. + .. method:: reset() + Set the :attr:`botframe`, :attr:`stopframe`, :attr:`returnframe` and + :attr:`quitting` attributes with values ready to start debugging. -.. method:: Bdb.trace_dispatch(frame, event, arg) + .. method:: trace_dispatch(frame, event, arg) - This function is installed as the trace function of debugged frames. Its - return value is the new trace function (in most cases, that is, itself). + This function is installed as the trace function of debugged frames. Its + return value is the new trace function (in most cases, that is, itself). - The default implementation decides how to dispatch a frame, depending on the - type of event (passed as a string) that is about to be executed. *event* can - be one of the following: + The default implementation decides how to dispatch a frame, depending on + the type of event (passed as a string) that is about to be executed. + *event* can be one of the following: - * ``"line"``: A new line of code is going to be executed. - * ``"call"``: A function is about to be called, or another code block - entered. - * ``"return"``: A function or other code block is about to return. - * ``"exception"``: An exception has occurred. - * ``"c_call"``: A C function is about to be called. - * ``"c_return"``: A C function has returned. - * ``"c_exception"``: A C function has thrown an exception. + * ``"line"``: A new line of code is going to be executed. + * ``"call"``: A function is about to be called, or another code block + entered. + * ``"return"``: A function or other code block is about to return. + * ``"exception"``: An exception has occurred. + * ``"c_call"``: A C function is about to be called. + * ``"c_return"``: A C function has returned. + * ``"c_exception"``: A C function has thrown an exception. - For the Python events, specialized functions (see below) are called. For the - C events, no action is taken. + For the Python events, specialized functions (see below) are called. For + the C events, no action is taken. - The *arg* parameter depends on the previous event. + The *arg* parameter depends on the previous event. - For more information on trace functions, see :ref:`debugger-hooks`. For more - information on code and frame objects, refer to :ref:`types`. + For more information on trace functions, see :ref:`debugger-hooks`. For + more information on code and frame objects, refer to :ref:`types`. -.. method:: Bdb.dispatch_line(frame) + .. method:: dispatch_line(frame) - If the debugger should stop on the current line, invoke the :meth:`user_line` - method (which should be overridden in subclasses). Raise a :exc:`BdbQuit` - exception if the :attr:`Bdb.quitting` flag is set (which can be set from - :meth:`user_line`). Return a reference to the :meth:`trace_dispatch` method - for further tracing in that scope. + If the debugger should stop on the current line, invoke the + :meth:`user_line` method (which should be overridden in subclasses). + Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set + (which can be set from :meth:`user_line`). Return a reference to the + :meth:`trace_dispatch` method for further tracing in that scope. -.. method:: Bdb.dispatch_call(frame, arg) + .. method:: dispatch_call(frame, arg) - If the debugger should stop on this function call, invoke the - :meth:`user_call` method (which should be overridden in subclasses). Raise a - :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set (which can - be set from :meth:`user_call`). Return a reference to the - :meth:`trace_dispatch` method for further tracing in that scope. + If the debugger should stop on this function call, invoke the + :meth:`user_call` method (which should be overridden in subclasses). + Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set + (which can be set from :meth:`user_call`). Return a reference to the + :meth:`trace_dispatch` method for further tracing in that scope. -.. method:: Bdb.dispatch_return(frame, arg) + .. method:: dispatch_return(frame, arg) - If the debugger should stop on this function return, invoke the - :meth:`user_return` method (which should be overridden in subclasses). Raise - a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set (which can - be set from :meth:`user_return`). Return a reference to the - :meth:`trace_dispatch` method for further tracing in that scope. + If the debugger should stop on this function return, invoke the + :meth:`user_return` method (which should be overridden in subclasses). + Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set + (which can be set from :meth:`user_return`). Return a reference to the + :meth:`trace_dispatch` method for further tracing in that scope. -.. method:: Bdb.dispatch_exception(frame, arg) + .. method:: dispatch_exception(frame, arg) - If the debugger should stop at this exception, invokes the - :meth:`user_exception` method (which should be overridden in subclasses). - Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set - (which can be set from :meth:`user_exception`). Return a reference to the - :meth:`trace_dispatch` method for further tracing in that scope. + If the debugger should stop at this exception, invokes the + :meth:`user_exception` method (which should be overridden in subclasses). + Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set + (which can be set from :meth:`user_exception`). Return a reference to the + :meth:`trace_dispatch` method for further tracing in that scope. -Normally derived classes don't override the following methods, but they may if -they want to redefine the definition of stopping and breakpoints. + Normally derived classes don't override the following methods, but they may + if they want to redefine the definition of stopping and breakpoints. -.. method:: Bdb.stop_here(frame) + .. method:: stop_here(frame) - This method checks if the *frame* is somewhere below :attr:`botframe` in the - call stack. :attr:`botframe` is the frame in which debugging started. + This method checks if the *frame* is somewhere below :attr:`botframe` in + the call stack. :attr:`botframe` is the frame in which debugging started. -.. method:: Bdb.break_here(frame) + .. method:: break_here(frame) - This method checks if there is a breakpoint in the filename and line - belonging to *frame* or, at least, in the current function. If the - breakpoint is a temporary one, this method deletes it. + This method checks if there is a breakpoint in the filename and line + belonging to *frame* or, at least, in the current function. If the + breakpoint is a temporary one, this method deletes it. -.. method:: Bdb.break_anywhere(frame) + .. method:: break_anywhere(frame) - This method checks if there is a breakpoint in the filename of the current - frame. + This method checks if there is a breakpoint in the filename of the current + frame. -Derived classes should override these methods to gain control over debugger -operation. + Derived classes should override these methods to gain control over debugger + operation. -.. method:: Bdb.user_call(frame, argument_list) + .. method:: user_call(frame, argument_list) - This method is called from :meth:`dispatch_call` when there is the - possibility that a break might be necessary anywhere inside the called - function. + This method is called from :meth:`dispatch_call` when there is the + possibility that a break might be necessary anywhere inside the called + function. -.. method:: Bdb.user_line(frame) + .. method:: user_line(frame) - This method is called from :meth:`dispatch_line` when either - :meth:`stop_here` or :meth:`break_here` yields True. + This method is called from :meth:`dispatch_line` when either + :meth:`stop_here` or :meth:`break_here` yields True. -.. method:: Bdb.user_return(frame, return_value) + .. method:: user_return(frame, return_value) - This method is called from :meth:`dispatch_return` when :meth:`stop_here` - yields True. + This method is called from :meth:`dispatch_return` when :meth:`stop_here` + yields True. -.. method:: Bdb.user_exception(frame, exc_info) + .. method:: user_exception(frame, exc_info) - This method is called from :meth:`dispatch_exception` when :meth:`stop_here` - yields True. + This method is called from :meth:`dispatch_exception` when + :meth:`stop_here` yields True. -.. method:: Bdb.do_clear(arg) + .. method:: do_clear(arg) - Handle how a breakpoint must be removed when it is a temporary one. + Handle how a breakpoint must be removed when it is a temporary one. - This method must be implemented by derived classes. + This method must be implemented by derived classes. -Derived classes and clients can call the following methods to affect the -stepping state. + Derived classes and clients can call the following methods to affect the + stepping state. -.. method:: Bdb.set_step() + .. method:: set_step() - Stop after one line of code. + Stop after one line of code. -.. method:: Bdb.set_next(frame) + .. method:: set_next(frame) - Stop on the next line in or below the given frame. + Stop on the next line in or below the given frame. -.. method:: Bdb.set_return(frame) + .. method:: set_return(frame) - Stop when returning from the given frame. + Stop when returning from the given frame. -.. method:: Bdb.set_trace([frame]) + .. method:: set_trace([frame]) - Start debugging from *frame*. If *frame* is not specified, debugging starts - from caller's frame. + Start debugging from *frame*. If *frame* is not specified, debugging + starts from caller's frame. -.. method:: Bdb.set_continue() + .. method:: set_continue() - Stop only at breakpoints or when finished. If there are no breakpoints, set - the system trace function to None. + Stop only at breakpoints or when finished. If there are no breakpoints, + set the system trace function to None. -.. method:: Bdb.set_quit() + .. method:: set_quit() - Set the :attr:`quitting` attribute to True. This raises :exc:`BdbQuit` in - the next call to one of the :meth:`dispatch_\*` methods. + Set the :attr:`quitting` attribute to True. This raises :exc:`BdbQuit` in + the next call to one of the :meth:`dispatch_\*` methods. -Derived classes and clients can call the following methods to manipulate -breakpoints. These methods return a string containing an error message if -something went wrong, or ``None`` if all is well. + Derived classes and clients can call the following methods to manipulate + breakpoints. These methods return a string containing an error message if + something went wrong, or ``None`` if all is well. -.. method:: Bdb.set_break(filename, lineno[, temporary=0[, cond[, funcname]]]) + .. method:: set_break(filename, lineno[, temporary=0[, cond[, funcname]]]) - Set a new breakpoint. If the *lineno* line doesn't exist for the *filename* - passed as argument, return an error message. The *filename* should be in - canonical form, as described in the :meth:`canonic` method. + Set a new breakpoint. If the *lineno* line doesn't exist for the + *filename* passed as argument, return an error message. The *filename* + should be in canonical form, as described in the :meth:`canonic` method. -.. method:: Bdb.clear_break(filename, lineno) + .. method:: clear_break(filename, lineno) - Delete the breakpoints in *filename* and *lineno*. If none were set, an - error message is returned. + Delete the breakpoints in *filename* and *lineno*. If none were set, an + error message is returned. -.. method:: Bdb.clear_bpbynumber(arg) + .. method:: clear_bpbynumber(arg) - Delete the breakpoint which has the index *arg* in the - :attr:`Breakpoint.bpbynumber`. If *arg* is not numeric or out of range, - return an error message. + Delete the breakpoint which has the index *arg* in the + :attr:`Breakpoint.bpbynumber`. If *arg* is not numeric or out of range, + return an error message. -.. method:: Bdb.clear_all_file_breaks(filename) + .. method:: clear_all_file_breaks(filename) - Delete all breakpoints in *filename*. If none were set, an error message is - returned. + Delete all breakpoints in *filename*. If none were set, an error message + is returned. -.. method:: Bdb.clear_all_breaks() + .. method:: clear_all_breaks() - Delete all existing breakpoints. + Delete all existing breakpoints. -.. method:: Bdb.get_break(filename, lineno) + .. method:: get_break(filename, lineno) - Check if there is a breakpoint for *lineno* of *filename*. + Check if there is a breakpoint for *lineno* of *filename*. -.. method:: Bdb.get_breaks(filename, lineno) + .. method:: get_breaks(filename, lineno) - Return all breakpoints for *lineno* in *filename*, or an empty list if none - are set. + Return all breakpoints for *lineno* in *filename*, or an empty list if + none are set. -.. method:: Bdb.get_file_breaks(filename) + .. method:: get_file_breaks(filename) - Return all breakpoints in *filename*, or an empty list if none are set. + Return all breakpoints in *filename*, or an empty list if none are set. -.. method:: Bdb.get_all_breaks() + .. method:: get_all_breaks() - Return all breakpoints that are set. + Return all breakpoints that are set. -Derived classes and clients can call the following methods to get a data -structure representing a stack trace. + Derived classes and clients can call the following methods to get a data + structure representing a stack trace. -.. method:: Bdb.get_stack(f, t) + .. method:: get_stack(f, t) - Get a list of records for a frame and all higher (calling) and lower frames, - and the size of the higher part. + Get a list of records for a frame and all higher (calling) and lower + frames, and the size of the higher part. -.. method:: Bdb.format_stack_entry(frame_lineno, [lprefix=': ']) + .. method:: format_stack_entry(frame_lineno, [lprefix=': ']) - Return a string with information about a stack entry, identified by a - ``(frame, lineno)`` tuple: + Return a string with information about a stack entry, identified by a + ``(frame, lineno)`` tuple: - * The canonical form of the filename which contains the frame. - * The function name, or ``""``. - * The input arguments. - * The return value. - * The line of code (if it exists). + * The canonical form of the filename which contains the frame. + * The function name, or ``""``. + * The input arguments. + * The return value. + * The line of code (if it exists). -The following two methods can be called by clients to use a debugger to debug a -:term:`statement`, given as a string. + The following two methods can be called by clients to use a debugger to debug + a :term:`statement`, given as a string. -.. method:: Bdb.run(cmd, [globals, [locals]]) + .. method:: run(cmd, [globals, [locals]]) - Debug a statement executed via the :func:`exec` function. *globals* - defaults to :attr:`__main__.__dict__`, *locals* defaults to *globals*. + Debug a statement executed via the :func:`exec` function. *globals* + defaults to :attr:`__main__.__dict__`, *locals* defaults to *globals*. -.. method:: Bdb.runeval(expr, [globals, [locals]]) + .. method:: runeval(expr, [globals, [locals]]) - Debug an expression executed via the :func:`eval` function. *globals* and - *locals* have the same meaning as in :meth:`run`. + Debug an expression executed via the :func:`eval` function. *globals* and + *locals* have the same meaning as in :meth:`run`. -.. method:: Bdb.runctx(cmd, globals, locals) + .. method:: runctx(cmd, globals, locals) - For backwards compatibility. Calls the :meth:`run` method. + For backwards compatibility. Calls the :meth:`run` method. -.. method:: Bdb.runcall(func, *args, **kwds) + .. method:: runcall(func, *args, **kwds) - Debug a single function call, and return its result. + Debug a single function call, and return its result. Finally, the module defines the following functions: Modified: python/branches/py3k-ctypes-pep3118/Doc/library/bisect.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/bisect.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/bisect.rst Wed Apr 30 15:57:13 2008 @@ -64,7 +64,7 @@ The :func:`bisect` function is generally useful for categorizing numeric data. This example uses :func:`bisect` to look up a letter grade for an exam total (say) based on a set of ordered numeric breakpoints: 85 and up is an 'A', 75..84 -is a 'B', etc. :: +is a 'B', etc. >>> grades = "FEDCBA" >>> breakpoints = [30, 44, 66, 75, 85] Modified: python/branches/py3k-ctypes-pep3118/Doc/library/bz2.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/bz2.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/bz2.rst Wed Apr 30 15:57:13 2008 @@ -44,75 +44,77 @@ .. class:: BZ2File(filename[, mode[, buffering[, compresslevel]]]) - Open a bz2 file. Mode can be either ``'r'`` or ``'w'``, for reading (default) + Open a bz2 file. Mode can be either ``'r'`` or ``'w'``, for reading (default) or writing. When opened for writing, the file will be created if it doesn't - exist, and truncated otherwise. If *buffering* is given, ``0`` means unbuffered, - and larger numbers specify the buffer size; the default is ``0``. If - *compresslevel* is given, it must be a number between ``1`` and ``9``; the - default is ``9``. Add a ``'U'`` to mode to open the file for input with - universal newline support. Any line ending in the input file will be seen as a - ``'\n'`` in Python. Also, a file so opened gains the attribute + exist, and truncated otherwise. If *buffering* is given, ``0`` means + unbuffered, and larger numbers specify the buffer size; the default is + ``0``. If *compresslevel* is given, it must be a number between ``1`` and + ``9``; the default is ``9``. Add a ``'U'`` to mode to open the file for input + with universal newline support. Any line ending in the input file will be + seen as a ``'\n'`` in Python. Also, a file so opened gains the attribute :attr:`newlines`; the value for this attribute is one of ``None`` (no newline - read yet), ``'\r'``, ``'\n'``, ``'\r\n'`` or a tuple containing all the newline - types seen. Universal newlines are available only when reading. Instances - support iteration in the same way as normal :class:`file` instances. + read yet), ``'\r'``, ``'\n'``, ``'\r\n'`` or a tuple containing all the + newline types seen. Universal newlines are available only when + reading. Instances support iteration in the same way as normal :class:`file` + instances. -.. method:: BZ2File.close() + .. method:: close() - Close the file. Sets data attribute :attr:`closed` to true. A closed file cannot - be used for further I/O operations. :meth:`close` may be called more than once - without error. + Close the file. Sets data attribute :attr:`closed` to true. A closed file + cannot be used for further I/O operations. :meth:`close` may be called + more than once without error. -.. method:: BZ2File.read([size]) + .. method:: read([size]) - Read at most *size* uncompressed bytes, returned as a string. If the *size* - argument is negative or omitted, read until EOF is reached. + Read at most *size* uncompressed bytes, returned as a string. If the + *size* argument is negative or omitted, read until EOF is reached. -.. method:: BZ2File.readline([size]) + .. method:: readline([size]) - Return the next line from the file, as a string, retaining newline. A - non-negative *size* argument limits the maximum number of bytes to return (an - incomplete line may be returned then). Return an empty string at EOF. + Return the next line from the file, as a string, retaining newline. A + non-negative *size* argument limits the maximum number of bytes to return + (an incomplete line may be returned then). Return an empty string at EOF. -.. method:: BZ2File.readlines([size]) + .. method:: readlines([size]) - Return a list of lines read. The optional *size* argument, if given, is an - approximate bound on the total number of bytes in the lines returned. + Return a list of lines read. The optional *size* argument, if given, is an + approximate bound on the total number of bytes in the lines returned. -.. method:: BZ2File.seek(offset[, whence]) + .. method:: seek(offset[, whence]) - Move to new file position. Argument *offset* is a byte count. Optional argument - *whence* defaults to ``os.SEEK_SET`` or ``0`` (offset from start of file; offset - should be ``>= 0``); other values are ``os.SEEK_CUR`` or ``1`` (move relative to - current position; offset can be positive or negative), and ``os.SEEK_END`` or - ``2`` (move relative to end of file; offset is usually negative, although many - platforms allow seeking beyond the end of a file). + Move to new file position. Argument *offset* is a byte count. Optional + argument *whence* defaults to ``os.SEEK_SET`` or ``0`` (offset from start + of file; offset should be ``>= 0``); other values are ``os.SEEK_CUR`` or + ``1`` (move relative to current position; offset can be positive or + negative), and ``os.SEEK_END`` or ``2`` (move relative to end of file; + offset is usually negative, although many platforms allow seeking beyond + the end of a file). - Note that seeking of bz2 files is emulated, and depending on the parameters the - operation may be extremely slow. + Note that seeking of bz2 files is emulated, and depending on the + parameters the operation may be extremely slow. -.. method:: BZ2File.tell() + .. method:: tell() - Return the current file position, an integer. + Return the current file position, an integer. -.. method:: BZ2File.write(data) + .. method:: write(data) - Write string *data* to file. Note that due to buffering, :meth:`close` may be - needed before the file on disk reflects the data written. + Write string *data* to file. Note that due to buffering, :meth:`close` may + be needed before the file on disk reflects the data written. -.. method:: BZ2File.writelines(sequence_of_strings) + .. method:: writelines(sequence_of_strings) - Write the sequence of strings to the file. Note that newlines are not added. The - sequence can be any iterable object producing strings. This is equivalent to - calling write() for each string. + Write the sequence of strings to the file. Note that newlines are not + added. The sequence can be any iterable object producing strings. This is + equivalent to calling write() for each string. Sequential (de)compression @@ -125,23 +127,23 @@ .. class:: BZ2Compressor([compresslevel]) Create a new compressor object. This object may be used to compress data - sequentially. If you want to compress data in one shot, use the :func:`compress` - function instead. The *compresslevel* parameter, if given, must be a number - between ``1`` and ``9``; the default is ``9``. + sequentially. If you want to compress data in one shot, use the + :func:`compress` function instead. The *compresslevel* parameter, if given, + must be a number between ``1`` and ``9``; the default is ``9``. -.. method:: BZ2Compressor.compress(data) + .. method:: compress(data) - Provide more data to the compressor object. It will return chunks of compressed - data whenever possible. When you've finished providing data to compress, call - the :meth:`flush` method to finish the compression process, and return what is - left in internal buffers. + Provide more data to the compressor object. It will return chunks of + compressed data whenever possible. When you've finished providing data to + compress, call the :meth:`flush` method to finish the compression process, + and return what is left in internal buffers. -.. method:: BZ2Compressor.flush() + .. method:: flush() - Finish the compression process and return what is left in internal buffers. You - must not use the compressor object after calling this method. + Finish the compression process and return what is left in internal + buffers. You must not use the compressor object after calling this method. .. class:: BZ2Decompressor() @@ -151,12 +153,13 @@ :func:`decompress` function instead. -.. method:: BZ2Decompressor.decompress(data) + .. method:: decompress(data) - Provide more data to the decompressor object. It will return chunks of - decompressed data whenever possible. If you try to decompress data after the end - of stream is found, :exc:`EOFError` will be raised. If any data was found after - the end of stream, it'll be ignored and saved in :attr:`unused_data` attribute. + Provide more data to the decompressor object. It will return chunks of + decompressed data whenever possible. If you try to decompress data after + the end of stream is found, :exc:`EOFError` will be raised. If any data + was found after the end of stream, it'll be ignored and saved in + :attr:`unused_data` attribute. One-shot (de)compression @@ -168,13 +171,13 @@ .. function:: compress(data[, compresslevel]) - Compress *data* in one shot. If you want to compress data sequentially, use an - instance of :class:`BZ2Compressor` instead. The *compresslevel* parameter, if - given, must be a number between ``1`` and ``9``; the default is ``9``. + Compress *data* in one shot. If you want to compress data sequentially, use + an instance of :class:`BZ2Compressor` instead. The *compresslevel* parameter, + if given, must be a number between ``1`` and ``9``; the default is ``9``. .. function:: decompress(data) - Decompress *data* in one shot. If you want to decompress data sequentially, use - an instance of :class:`BZ2Decompressor` instead. + Decompress *data* in one shot. If you want to decompress data sequentially, + use an instance of :class:`BZ2Decompressor` instead. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/calendar.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/calendar.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/calendar.rst Wed Apr 30 15:57:13 2008 @@ -33,74 +33,75 @@ itself. This is the job of subclasses. -:class:`Calendar` instances have the following methods: + :class:`Calendar` instances have the following methods: -.. method:: Calendar.iterweekdays(weekday) + .. method:: iterweekdays(weekday) - Return an iterator for the week day numbers that will be used for one week. The - first number from the iterator will be the same as the number returned by - :meth:`firstweekday`. + Return an iterator for the week day numbers that will be used for one + week. The first value from the iterator will be the same as the value of + the :attr:`firstweekday` property. -.. method:: Calendar.itermonthdates(year, month) + .. method:: itermonthdates(year, month) - Return an iterator for the month *month* (1-12) in the year *year*. This - iterator will return all days (as :class:`datetime.date` objects) for the month - and all days before the start of the month or after the end of the month that - are required to get a complete week. + Return an iterator for the month *month* (1-12) in the year *year*. This + iterator will return all days (as :class:`datetime.date` objects) for the + month and all days before the start of the month or after the end of the + month that are required to get a complete week. -.. method:: Calendar.itermonthdays2(year, month) + .. method:: itermonthdays2(year, month) - Return an iterator for the month *month* in the year *year* similar to - :meth:`itermonthdates`. Days returned will be tuples consisting of a day number - and a week day number. + Return an iterator for the month *month* in the year *year* similar to + :meth:`itermonthdates`. Days returned will be tuples consisting of a day + number and a week day number. -.. method:: Calendar.itermonthdays(year, month) + .. method:: itermonthdays(year, month) - Return an iterator for the month *month* in the year *year* similar to - :meth:`itermonthdates`. Days returned will simply be day numbers. + Return an iterator for the month *month* in the year *year* similar to + :meth:`itermonthdates`. Days returned will simply be day numbers. -.. method:: Calendar.monthdatescalendar(year, month) + .. method:: monthdatescalendar(year, month) - Return a list of the weeks in the month *month* of the *year* as full weeks. - Weeks are lists of seven :class:`datetime.date` objects. + Return a list of the weeks in the month *month* of the *year* as full + weeks. Weeks are lists of seven :class:`datetime.date` objects. -.. method:: Calendar.monthdays2calendar(year, month) + .. method:: monthdays2calendar(year, month) - Return a list of the weeks in the month *month* of the *year* as full weeks. - Weeks are lists of seven tuples of day numbers and weekday numbers. + Return a list of the weeks in the month *month* of the *year* as full + weeks. Weeks are lists of seven tuples of day numbers and weekday + numbers. -.. method:: Calendar.monthdayscalendar(year, month) + .. method:: monthdayscalendar(year, month) - Return a list of the weeks in the month *month* of the *year* as full weeks. - Weeks are lists of seven day numbers. + Return a list of the weeks in the month *month* of the *year* as full + weeks. Weeks are lists of seven day numbers. -.. method:: Calendar.yeardatescalendar(year, month[, width]) + .. method:: yeardatescalendar(year[, width]) - Return the data for the specified year ready for formatting. The return value is - a list of month rows. Each month row contains up to *width* months (defaulting - to 3). Each month contains between 4 and 6 weeks and each week contains 1--7 - days. Days are :class:`datetime.date` objects. + Return the data for the specified year ready for formatting. The return + value is a list of month rows. Each month row contains up to *width* + months (defaulting to 3). Each month contains between 4 and 6 weeks and + each week contains 1--7 days. Days are :class:`datetime.date` objects. -.. method:: Calendar.yeardays2calendar(year, month[, width]) + .. method:: yeardays2calendar(year[, width]) - Return the data for the specified year ready for formatting (similar to - :meth:`yeardatescalendar`). Entries in the week lists are tuples of day numbers - and weekday numbers. Day numbers outside this month are zero. + Return the data for the specified year ready for formatting (similar to + :meth:`yeardatescalendar`). Entries in the week lists are tuples of day + numbers and weekday numbers. Day numbers outside this month are zero. -.. method:: Calendar.yeardayscalendar(year, month[, width]) + .. method:: yeardayscalendar(year[, width]) - Return the data for the specified year ready for formatting (similar to - :meth:`yeardatescalendar`). Entries in the week lists are day numbers. Day - numbers outside this month are zero. + Return the data for the specified year ready for formatting (similar to + :meth:`yeardatescalendar`). Entries in the week lists are day numbers. Day + numbers outside this month are zero. .. class:: TextCalendar([firstweekday]) @@ -108,33 +109,35 @@ This class can be used to generate plain text calendars. -:class:`TextCalendar` instances have the following methods: + :class:`TextCalendar` instances have the following methods: -.. method:: TextCalendar.formatmonth(theyear, themonth[, w[, l]]) + .. method:: formatmonth(theyear, themonth[, w[, l]]) - Return a month's calendar in a multi-line string. If *w* is provided, it - specifies the width of the date columns, which are centered. If *l* is given, it - specifies the number of lines that each week will use. Depends on the first - weekday as set by :func:`setfirstweekday`. + Return a month's calendar in a multi-line string. If *w* is provided, it + specifies the width of the date columns, which are centered. If *l* is + given, it specifies the number of lines that each week will use. Depends + on the first weekday as specified in the constructor or set by the + :meth:`setfirstweekday` method. -.. method:: TextCalendar.prmonth(theyear, themonth[, w[, l]]) + .. method:: prmonth(theyear, themonth[, w[, l]]) - Print a month's calendar as returned by :meth:`formatmonth`. + Print a month's calendar as returned by :meth:`formatmonth`. -.. method:: TextCalendar.formatyear(theyear, themonth[, w[, l[, c[, m]]]]) + .. method:: formatyear(theyear, themonth[, w[, l[, c[, m]]]]) - Return a *m*-column calendar for an entire year as a multi-line string. Optional - parameters *w*, *l*, and *c* are for date column width, lines per week, and - number of spaces between month columns, respectively. Depends on the first - weekday as set by :meth:`setfirstweekday`. The earliest year for which a - calendar can be generated is platform-dependent. + Return a *m*-column calendar for an entire year as a multi-line string. + Optional parameters *w*, *l*, and *c* are for date column width, lines per + week, and number of spaces between month columns, respectively. Depends on + the first weekday as specified in the constructor or set by the + :meth:`setfirstweekday` method. The earliest year for which a calendar + can be generated is platform-dependent. -.. method:: TextCalendar.pryear(theyear[, w[, l[, c[, m]]]]) + .. method:: pryear(theyear[, w[, l[, c[, m]]]]) - Print the calendar for an entire year as returned by :meth:`formatyear`. + Print the calendar for an entire year as returned by :meth:`formatyear`. .. class:: HTMLCalendar([firstweekday]) @@ -142,43 +145,44 @@ This class can be used to generate HTML calendars. -:class:`HTMLCalendar` instances have the following methods: + :class:`HTMLCalendar` instances have the following methods: -.. method:: HTMLCalendar.formatmonth(theyear, themonth[, withyear]) + .. method:: formatmonth(theyear, themonth[, withyear]) - Return a month's calendar as an HTML table. If *withyear* is true the year will - be included in the header, otherwise just the month name will be used. + Return a month's calendar as an HTML table. If *withyear* is true the year + will be included in the header, otherwise just the month name will be + used. -.. method:: HTMLCalendar.formatyear(theyear, themonth[, width]) + .. method:: formatyear(theyear, themonth[, width]) - Return a year's calendar as an HTML table. *width* (defaulting to 3) specifies - the number of months per row. + Return a year's calendar as an HTML table. *width* (defaulting to 3) + specifies the number of months per row. -.. method:: HTMLCalendar.formatyearpage(theyear[, width[, css[, encoding]]]) + .. method:: formatyearpage(theyear[, width[, css[, encoding]]]) - Return a year's calendar as a complete HTML page. *width* (defaulting to 3) - specifies the number of months per row. *css* is the name for the cascading - style sheet to be used. :const:`None` can be passed if no style sheet should be - used. *encoding* specifies the encoding to be used for the output (defaulting to - the system default encoding). + Return a year's calendar as a complete HTML page. *width* (defaulting to + 3) specifies the number of months per row. *css* is the name for the + cascading style sheet to be used. :const:`None` can be passed if no style + sheet should be used. *encoding* specifies the encoding to be used for the + output (defaulting to the system default encoding). .. class:: LocaleTextCalendar([firstweekday[, locale]]) This subclass of :class:`TextCalendar` can be passed a locale name in the - constructor and will return month and weekday names in the specified locale. If - this locale includes an encoding all strings containing month and weekday names - will be returned as unicode. + constructor and will return month and weekday names in the specified + locale. If this locale includes an encoding all strings containing month and + weekday names will be returned as unicode. .. class:: LocaleHTMLCalendar([firstweekday[, locale]]) This subclass of :class:`HTMLCalendar` can be passed a locale name in the - constructor and will return month and weekday names in the specified locale. If - this locale includes an encoding all strings containing month and weekday names - will be returned as unicode. + constructor and will return month and weekday names in the specified + locale. If this locale includes an encoding all strings containing month and + weekday names will be returned as unicode. For simple text calendars this module provides the following functions. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/cgihttpserver.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/cgihttpserver.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/cgihttpserver.rst Wed Apr 30 15:57:13 2008 @@ -43,22 +43,22 @@ and serve the output, instead of serving files, if the request leads to somewhere below the ``cgi_directories`` path. -The :class:`CGIHTTPRequestHandler` defines the following data member: + The :class:`CGIHTTPRequestHandler` defines the following data member: -.. attribute:: CGIHTTPRequestHandler.cgi_directories + .. attribute:: cgi_directories - This defaults to ``['/cgi-bin', '/htbin']`` and describes directories to treat - as containing CGI scripts. + This defaults to ``['/cgi-bin', '/htbin']`` and describes directories to + treat as containing CGI scripts. -The :class:`CGIHTTPRequestHandler` defines the following methods: + The :class:`CGIHTTPRequestHandler` defines the following methods: -.. method:: CGIHTTPRequestHandler.do_POST() + .. method:: do_POST() - This method serves the ``'POST'`` request type, only allowed for CGI scripts. - Error 501, "Can only POST to CGI scripts", is output when trying to POST to a - non-CGI url. + This method serves the ``'POST'`` request type, only allowed for CGI + scripts. Error 501, "Can only POST to CGI scripts", is output when trying + to POST to a non-CGI url. Note that CGI scripts will be run with UID of user nobody, for security reasons. Problems with the CGI script will be translated to error 403. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/chunk.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/chunk.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/chunk.rst Wed Apr 30 15:57:13 2008 @@ -66,62 +66,64 @@ optional argument *inclheader* is true, the size given in the chunk header includes the size of the header. The default value is false. -A :class:`Chunk` object supports the following methods: + A :class:`Chunk` object supports the following methods: -.. method:: Chunk.getname() + .. method:: getname() - Returns the name (ID) of the chunk. This is the first 4 bytes of the chunk. + Returns the name (ID) of the chunk. This is the first 4 bytes of the + chunk. -.. method:: Chunk.getsize() + .. method:: getsize() - Returns the size of the chunk. + Returns the size of the chunk. -.. method:: Chunk.close() + .. method:: close() - Close and skip to the end of the chunk. This does not close the underlying - file. + Close and skip to the end of the chunk. This does not close the + underlying file. -The remaining methods will raise :exc:`IOError` if called after the -:meth:`close` method has been called. + The remaining methods will raise :exc:`IOError` if called after the + :meth:`close` method has been called. -.. method:: Chunk.isatty() + .. method:: isatty() - Returns ``False``. + Returns ``False``. -.. method:: Chunk.seek(pos[, whence]) + .. method:: seek(pos[, whence]) - Set the chunk's current position. The *whence* argument is optional and - defaults to ``0`` (absolute file positioning); other values are ``1`` (seek - relative to the current position) and ``2`` (seek relative to the file's end). - There is no return value. If the underlying file does not allow seek, only - forward seeks are allowed. + Set the chunk's current position. The *whence* argument is optional and + defaults to ``0`` (absolute file positioning); other values are ``1`` + (seek relative to the current position) and ``2`` (seek relative to the + file's end). There is no return value. If the underlying file does not + allow seek, only forward seeks are allowed. -.. method:: Chunk.tell() + .. method:: tell() - Return the current position into the chunk. + Return the current position into the chunk. -.. method:: Chunk.read([size]) + .. method:: read([size]) - Read at most *size* bytes from the chunk (less if the read hits the end of the - chunk before obtaining *size* bytes). If the *size* argument is negative or - omitted, read all data until the end of the chunk. The bytes are returned as a - string object. An empty string is returned when the end of the chunk is - encountered immediately. + Read at most *size* bytes from the chunk (less if the read hits the end of + the chunk before obtaining *size* bytes). If the *size* argument is + negative or omitted, read all data until the end of the chunk. The bytes + are returned as a string object. An empty string is returned when the end + of the chunk is encountered immediately. -.. method:: Chunk.skip() + .. method:: skip() + + Skip to the end of the chunk. All further calls to :meth:`read` for the + chunk will return ``''``. If you are not interested in the contents of + the chunk, this method should be called so that the file points to the + start of the next chunk. - Skip to the end of the chunk. All further calls to :meth:`read` for the chunk - will return ``''``. If you are not interested in the contents of the chunk, - this method should be called so that the file points to the start of the next - chunk. .. rubric:: Footnotes Modified: python/branches/py3k-ctypes-pep3118/Doc/library/cmath.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/cmath.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/cmath.rst Wed Apr 30 15:57:13 2008 @@ -14,8 +14,75 @@ floating-point number, respectively, and the function is then applied to the result of the conversion. -The functions are: +.. note:: + On platforms with hardware and system-level support for signed + zeros, functions involving branch cuts are continuous on *both* + sides of the branch cut: the sign of the zero distinguishes one + side of the branch cut from the other. On platforms that do not + support signed zeros the continuity is as specified below. + + +Complex coordinates +------------------- + +Complex numbers can be expressed by two important coordinate systems. +Python's :class:`complex` type uses rectangular coordinates where a number +on the complex plain is defined by two floats, the real part and the imaginary +part. + +Definition:: + + z = x + 1j * y + + x := real(z) + y := imag(z) + +In engineering the polar coordinate system is popular for complex numbers. In +polar coordinates a complex number is defined by the radius *r* and the phase +angle *??*. The radius *r* is the absolute value of the complex, which can be +viewed as distance from (0, 0). The radius *r* is always 0 or a positive float. +The phase angle *??* is the counter clockwise angle from the positive x axis, +e.g. *1* has the angle *0*, *1j* has the angle *??/2* and *-1* the angle *-??*. + +.. note:: + While :func:`phase` and func:`polar` return *+??* for a negative real they + may return *-??* for a complex with a very small negative imaginary + part, e.g. *-1-1E-300j*. + + +Definition:: + + z = r * exp(1j * ??) + z = r * cis(??) + + r := abs(z) := sqrt(real(z)**2 + imag(z)**2) + phi := phase(z) := atan2(imag(z), real(z)) + cis(??) := cos(??) + 1j * sin(??) + + +.. function:: phase(x) + + Return phase, also known as the argument, of a complex. + + +.. function:: polar(x) + + Convert a :class:`complex` from rectangular coordinates to polar + coordinates. The function returns a tuple with the two elements + *r* and *phi*. *r* is the distance from 0 and *phi* the phase + angle. + + +.. function:: rect(r, phi) + + Convert from polar coordinates to rectangular coordinates and return + a :class:`complex`. + + + +cmath functions +--------------- .. function:: acos(x) @@ -37,30 +104,26 @@ .. function:: asinh(x) - Return the hyperbolic arc sine of *x*. There are two branch cuts, extending - left from ``??1j`` to ``?????j``, both continuous from above. These branch cuts - should be considered a bug to be corrected in a future release. The correct - branch cuts should extend along the imaginary axis, one from ``1j`` up to - ``???j`` and continuous from the right, and one from ``-1j`` down to ``-???j`` - and continuous from the left. + Return the hyperbolic arc sine of *x*. There are two branch cuts: + One extends from ``1j`` along the imaginary axis to ``???j``, + continuous from the right. The other extends from ``-1j`` along + the imaginary axis to ``-???j``, continuous from the left. .. function:: atan(x) Return the arc tangent of *x*. There are two branch cuts: One extends from - ``1j`` along the imaginary axis to ``???j``, continuous from the left. The + ``1j`` along the imaginary axis to ``???j``, continuous from the right. The other extends from ``-1j`` along the imaginary axis to ``-???j``, continuous - from the left. (This should probably be changed so the upper cut becomes - continuous from the other side.) + from the left. .. function:: atanh(x) Return the hyperbolic arc tangent of *x*. There are two branch cuts: One - extends from ``1`` along the real axis to ``???``, continuous from above. The + extends from ``1`` along the real axis to ``???``, continuous from below. The other extends from ``-1`` along the real axis to ``-???``, continuous from - above. (This should probably be changed so the right cut becomes continuous - from the other side.) + above. .. function:: cos(x) @@ -78,6 +141,17 @@ Return the exponential value ``e**x``. +.. function:: isinf(x) + + Return *True* if the real or the imaginary part of x is positive + or negative infinity. + + +.. function:: isnan(x) + + Return *True* if the real or imaginary part of x is not a number (NaN). + + .. function:: log(x[, base]) Returns the logarithm of *x* to the given *base*. If the *base* is not @@ -151,3 +225,4 @@ nothing's sign bit. In Iserles, A., and Powell, M. (eds.), The state of the art in numerical analysis. Clarendon Press (1987) pp165-211. + Modified: python/branches/py3k-ctypes-pep3118/Doc/library/codecs.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/codecs.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/codecs.rst Wed Apr 30 15:57:13 2008 @@ -202,7 +202,8 @@ .. function:: open(filename, mode[, encoding[, errors[, buffering]]]) Open an encoded file using the given *mode* and return a wrapped version - providing transparent encoding/decoding. + providing transparent encoding/decoding. The default file mode is ``'r'`` + meaning to open the file in read mode. .. note:: @@ -210,6 +211,13 @@ i.e. Unicode objects for most built-in codecs. Output is also codec-dependent and will usually be Unicode as well. + .. note:: + + Files are always opened in binary mode, even if no binary mode was + specified. This is done to avoid data loss due to encodings using 8-bit + values. This means that no automatic conversion of ``'\n'`` is done + on reading and writing. + *encoding* specifies the encoding which is to be used for the file. *errors* may be given to define the error handling. It defaults to ``'strict'`` @@ -417,16 +425,16 @@ :func:`register_error`. -.. method:: IncrementalEncoder.encode(object[, final]) + .. method:: encode(object[, final]) - Encodes *object* (taking the current state of the encoder into account) and - returns the resulting encoded object. If this is the last call to :meth:`encode` - *final* must be true (the default is false). + Encodes *object* (taking the current state of the encoder into account) + and returns the resulting encoded object. If this is the last call to + :meth:`encode` *final* must be true (the default is false). -.. method:: IncrementalEncoder.reset() + .. method:: reset() - Reset the encoder to the initial state. + Reset the encoder to the initial state. .. method:: IncrementalEncoder.getstate() @@ -480,41 +488,42 @@ :func:`register_error`. -.. method:: IncrementalDecoder.decode(object[, final]) + .. method:: decode(object[, final]) - Decodes *object* (taking the current state of the decoder into account) and - returns the resulting decoded object. If this is the last call to :meth:`decode` - *final* must be true (the default is false). If *final* is true the decoder must - decode the input completely and must flush all buffers. If this isn't possible - (e.g. because of incomplete byte sequences at the end of the input) it must - initiate error handling just like in the stateless case (which might raise an - exception). + Decodes *object* (taking the current state of the decoder into account) + and returns the resulting decoded object. If this is the last call to + :meth:`decode` *final* must be true (the default is false). If *final* is + true the decoder must decode the input completely and must flush all + buffers. If this isn't possible (e.g. because of incomplete byte sequences + at the end of the input) it must initiate error handling just like in the + stateless case (which might raise an exception). -.. method:: IncrementalDecoder.reset() + .. method:: reset() - Reset the decoder to the initial state. + Reset the decoder to the initial state. -.. method:: IncrementalDecoder.getstate() + .. method:: getstate() - Return the current state of the decoder. This must be a tuple with two items, - the first must be the buffer containing the still undecoded input. The second - must be an integer and can be additional state info. (The implementation should - make sure that ``0`` is the most common additional state info.) If this - additional state info is ``0`` it must be possible to set the decoder to the - state which has no input buffered and ``0`` as the additional state info, so - that feeding the previously buffered input to the decoder returns it to the - previous state without producing any output. (Additional state info that is more - complicated than integers can be converted into an integer by - marshaling/pickling the info and encoding the bytes of the resulting string into - an integer.) + Return the current state of the decoder. This must be a tuple with two + items, the first must be the buffer containing the still undecoded + input. The second must be an integer and can be additional state + info. (The implementation should make sure that ``0`` is the most common + additional state info.) If this additional state info is ``0`` it must be + possible to set the decoder to the state which has no input buffered and + ``0`` as the additional state info, so that feeding the previously + buffered input to the decoder returns it to the previous state without + producing any output. (Additional state info that is more complicated than + integers can be converted into an integer by marshaling/pickling the info + and encoding the bytes of the resulting string into an integer.) -.. method:: IncrementalDecoder.setstate(state) + .. method:: setstate(state) + + Set the state of the encoder to *state*. *state* must be a decoder state + returned by :meth:`getstate`. - Set the state of the encoder to *state*. *state* must be a decoder state - returned by :meth:`getstate`. The :class:`StreamWriter` and :class:`StreamReader` classes provide generic working interfaces which can be used to implement new encoding submodules very @@ -562,24 +571,25 @@ :func:`register_error`. -.. method:: StreamWriter.write(object) + .. method:: write(object) + + Writes the object's contents encoded to the stream. - Writes the object's contents encoded to the stream. + .. method:: writelines(list) -.. method:: StreamWriter.writelines(list) + Writes the concatenated list of strings to the stream (possibly by reusing + the :meth:`write` method). - Writes the concatenated list of strings to the stream (possibly by reusing the - :meth:`write` method). + .. method:: reset() -.. method:: StreamWriter.reset() + Flushes and resets the codec buffers used for keeping state. - Flushes and resets the codec buffers used for keeping state. + Calling this method should ensure that the data on the output is put into + a clean state that allows appending of new fresh data without having to + rescan the whole stream to recover state. - Calling this method should ensure that the data on the output is put into a - clean state that allows appending of new fresh data without having to rescan the - whole stream to recover state. In addition to the above methods, the :class:`StreamWriter` must also inherit all other methods and attributes from the underlying stream. @@ -622,55 +632,59 @@ :func:`register_error`. -.. method:: StreamReader.read([size[, chars, [firstline]]]) + .. method:: read([size[, chars, [firstline]]]) - Decodes data from the stream and returns the resulting object. + Decodes data from the stream and returns the resulting object. - *chars* indicates the number of characters to read from the stream. :func:`read` - will never return more than *chars* characters, but it might return less, if - there are not enough characters available. + *chars* indicates the number of characters to read from the + stream. :func:`read` will never return more than *chars* characters, but + it might return less, if there are not enough characters available. - *size* indicates the approximate maximum number of bytes to read from the stream - for decoding purposes. The decoder can modify this setting as appropriate. The - default value -1 indicates to read and decode as much as possible. *size* is - intended to prevent having to decode huge files in one step. + *size* indicates the approximate maximum number of bytes to read from the + stream for decoding purposes. The decoder can modify this setting as + appropriate. The default value -1 indicates to read and decode as much as + possible. *size* is intended to prevent having to decode huge files in + one step. - *firstline* indicates that it would be sufficient to only return the first line, - if there are decoding errors on later lines. + *firstline* indicates that it would be sufficient to only return the first + line, if there are decoding errors on later lines. - The method should use a greedy read strategy meaning that it should read as much - data as is allowed within the definition of the encoding and the given size, - e.g. if optional encoding endings or state markers are available on the stream, - these should be read too. + The method should use a greedy read strategy meaning that it should read + as much data as is allowed within the definition of the encoding and the + given size, e.g. if optional encoding endings or state markers are + available on the stream, these should be read too. -.. method:: StreamReader.readline([size[, keepends]]) + .. method:: readline([size[, keepends]]) - Read one line from the input stream and return the decoded data. + Read one line from the input stream and return the decoded data. - *size*, if given, is passed as size argument to the stream's :meth:`readline` - method. + *size*, if given, is passed as size argument to the stream's + :meth:`readline` method. - If *keepends* is false line-endings will be stripped from the lines returned. + If *keepends* is false line-endings will be stripped from the lines + returned. -.. method:: StreamReader.readlines([sizehint[, keepends]]) + .. method:: readlines([sizehint[, keepends]]) - Read all lines available on the input stream and return them as a list of lines. + Read all lines available on the input stream and return them as a list of + lines. - Line-endings are implemented using the codec's decoder method and are included - in the list entries if *keepends* is true. + Line-endings are implemented using the codec's decoder method and are + included in the list entries if *keepends* is true. - *sizehint*, if given, is passed as the *size* argument to the stream's - :meth:`read` method. + *sizehint*, if given, is passed as the *size* argument to the stream's + :meth:`read` method. -.. method:: StreamReader.reset() + .. method:: reset() - Resets the codec buffers used for keeping state. + Resets the codec buffers used for keeping state. + + Note that no stream repositioning should take place. This method is + primarily intended to be able to recover from decoding errors. - Note that no stream repositioning should take place. This method is primarily - intended to be able to recover from decoding errors. In addition to the above methods, the :class:`StreamReader` must also inherit all other methods and attributes from the underlying stream. @@ -739,6 +753,7 @@ Error handling is done in the same way as defined for the stream readers and writers. + :class:`StreamRecoder` instances define the combined interfaces of :class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other methods and attributes from the underlying stream. @@ -1010,7 +1025,7 @@ +-----------------+--------------------------------+--------------------------------+ | iso8859_3 | iso-8859-3, latin3, L3 | Esperanto, Maltese | +-----------------+--------------------------------+--------------------------------+ -| iso8859_4 | iso-8859-4, latin4, L4 | Baltic languagues | +| iso8859_4 | iso-8859-4, latin4, L4 | Baltic languages | +-----------------+--------------------------------+--------------------------------+ | iso8859_5 | iso-8859-5, cyrillic | Bulgarian, Byelorussian, | | | | Macedonian, Russian, Serbian | Modified: python/branches/py3k-ctypes-pep3118/Doc/library/collections.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/collections.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/collections.rst Wed Apr 30 15:57:13 2008 @@ -1,72 +1,138 @@ -:mod:`collections` --- High-performance container datatypes -=========================================================== +:mod:`collections` --- Container datatypes +========================================== .. module:: collections - :synopsis: High-performance datatypes + :synopsis: Container datatypes .. moduleauthor:: Raymond Hettinger .. sectionauthor:: Raymond Hettinger +.. testsetup:: * + + from collections import * + import itertools + __name__ = '' This module implements high-performance container datatypes. Currently, there are two datatypes, :class:`deque` and :class:`defaultdict`, and -one datatype factory function, :func:`namedtuple`. Python already -includes built-in containers, :class:`dict`, :class:`list`, -:class:`set`, and :class:`tuple`. In addition, the optional :mod:`bsddb` -module has a :meth:`bsddb.btopen` method that can be used to create in-memory -or file based ordered dictionaries with string keys. - -Future editions of the standard library may include balanced trees and -ordered dictionaries. +one datatype factory function, :func:`namedtuple`. This module also +provides the :class:`UserDict` and :class:`UserList` classes which may +be useful when inheriting directly from :class:`dict` or +:class:`list` isn't convenient. + +The specialized containers provided in this module provide alternatives +to Python's general purpose built-in containers, :class:`dict`, +:class:`list`, :class:`set`, and :class:`tuple`. +Besides the containers provided here, the optional :mod:`bsddb` +module offers the ability to create in-memory or file based ordered +dictionaries with string keys using the :meth:`bsddb.btopen` method. In addition to containers, the collections module provides some ABCs -(abstract base classes) that can be used to test whether -a class provides a particular interface, for example, is it hashable or -a mapping. The ABCs provided include those in the following table: - -===================================== ======================================== -ABC Notes -===================================== ======================================== -:class:`collections.Container` Defines ``__contains__()`` -:class:`collections.Hashable` Defines ``__hash__()`` -:class:`collections.Iterable` Defines ``__iter__()`` -:class:`collections.Iterator` Derived from :class:`Iterable` and in - addition defines ``__next__()`` -:class:`collections.Mapping` Derived from :class:`Container`, - :class:`Iterable`, - and :class:`Sized`, and in addition - defines ``__getitem__()``, ``get()``, - ``__contains__()``, ``__len__()``, - ``__iter__()``, ``keys()``, - ``items()``, and ``values()`` -:class:`collections.MutableMapping` Derived from :class:`Mapping` -:class:`collections.MutableSequence` Derived from :class:`Sequence` -:class:`collections.MutableSet` Derived from :class:`Set` and in - addition defines ``add()``, - ``clear()``, ``discard()``, ``pop()``, - and ``toggle()`` -:class:`collections.Sequence` Derived from :class:`Container`, - :class:`Iterable`, and :class:`Sized`, - and in addition defines - ``__getitem__()`` -:class:`collections.Set` Derived from :class:`Container`, :class:`Iterable`, and :class:`Sized` -:class:`collections.Sized` Defines ``__len__()`` -===================================== ======================================== +(abstract base classes) that can be used to test whether a class +provides a particular interface, for example, is it hashable or +a mapping, and some of them can also be used as mixin classes. + +ABCs - abstract base classes +---------------------------- -.. XXX Have not included them all and the notes are incomplete -.. Deliberately did one row wide to get a neater output +The collections module offers the following ABCs: + +========================= ==================== ====================== ==================================================== +ABC Inherits Abstract Methods Mixin Methods +========================= ==================== ====================== ==================================================== +:class:`Container` ``__contains__`` +:class:`Hashable` ``__hash__`` +:class:`Iterable` ``__iter__`` +:class:`Iterator` :class:`Iterable` ``__next__`` ``__iter__`` +:class:`Sized` ``__len__`` + +:class:`Mapping` :class:`Sized`, ``__getitem__``, ``__contains__``, ``keys``, ``items``, ``values``, + :class:`Iterable`, ``__len__``. and ``get``, ``__eq__``, and ``__ne__`` + :class:`Container` ``__iter__`` + +:class:`MutableMapping` :class:`Mapping` ``__getitem__`` Inherited Mapping methods and + ``__setitem__``, ``pop``, ``popitem``, ``clear``, ``update``, + ``__delitem__``, and ``setdefault`` + ``__iter__``, and + ``__len__`` + +:class:`Sequence` :class:`Sized`, ``__getitem__`` ``__contains__``. ``__iter__``, ``__reversed__``. + :class:`Iterable`, and ``__len__`` ``index``, and ``count`` + :class:`Container` + +:class:`MutableSequnce` :class:`Sequence` ``__getitem__`` Inherited Sequence methods and + ``__delitem__``, ``append``, ``reverse``, ``extend``, ``pop``, + ``insert``, ``remove``, and ``__iadd__`` + and ``__len__`` + +:class:`Set` :class:`Sized`, ``__len__``, ``__le__``, ``__lt__``, ``__eq__``, ``__ne__``, + :class:`Iterable`, ``__iter__``, and ``__gt__``, ``__ge__``, ``__and__``, ``__or__`` + :class:`Container` ``__contains__`` ``__sub__``, ``__xor__``, and ``isdisjoint`` + +:class:`MutableSet` :class:`Set` ``add`` and Inherited Set methods and + ``discard`` ``clear``, ``pop``, ``remove``, ``__ior__``, + ``__iand__``, ``__ixor__``, and ``__isub__`` +========================= ==================== ====================== ==================================================== These ABCs allow us to ask classes or instances if they provide particular functionality, for example:: - from collections import Sized - size = None - if isinstance(myvar, Sized): + if isinstance(myvar, collections.Sized): size = len(myvar) -(For more about ABCs, see the :mod:`abc` module and :pep:`3119`.) +Several of the ABCs are also useful as mixins that make it easier to develop +classes supporting container APIs. For example, to write a class supporting +the full :class:`Set` API, it only necessary to supply the three underlying +abstract methods: :meth:`__contains__`, :meth:`__iter__`, and :meth:`__len__`. +The ABC supplies the remaining methods such as :meth:`__and__` and +:meth:`isdisjoint` :: + + class ListBasedSet(collections.Set): + ''' Alternate set implementation favoring space over speed + and not requiring the set elements to be hashable. ''' + def __init__(self, iterable): + self.elements = lst = [] + for value in iterable: + if value not in lst: + lst.append(value) + def __iter__(self): + return iter(self.elements) + def __contains__(self, value): + return value in self.elements + def __len__(self): + return len(self.elements) + + s1 = ListBasedSet('abcdef') + s2 = ListBasedSet('defghi') + overlap = s1 & s2 # The __and__() method is supported automatically + +Notes on using :class:`Set` and :class:`MutableSet` as a mixin: + +(1) + Since some set operations create new sets, the default mixin methods need + a way to create new instances from an iterable. The class constructor is + assumed to have a signature in the form ``ClassName(iterable)``. + That assumption is factored-out to a single internal classmethod called + :meth:`_from_iterable` which calls ``cls(iterable)`` to produce a new set. + If the :class:`Set` mixin is being used in a class with a different + constructor signature, you will need to override :meth:`from_iterable` + with a classmethod that can construct new instances from + an iterable argument. + +(2) + To override the comparisons (presumably for speed, as the + semantics are fixed), redefine :meth:`__le__` and + then the other operations will automatically follow suit. + +(3) + The :class:`Set` mixin provides a :meth:`_hash` method to compute a hash value + for the set; however, :meth:`__hash__` is not defined because not all sets + are hashable or immutable. To add set hashabilty using mixins, + inherit from both :meth:`Set` and :meth:`Hashable`, then define + ``__hash__ = Set._hash``. +(For more about ABCs, see the :mod:`abc` module and :pep:`3119`.) .. _deque-objects: @@ -100,70 +166,73 @@ where only the most recent activity is of interest. -Deque objects support the following methods: + Deque objects support the following methods: + + .. method:: append(x) -.. method:: deque.append(x) + Add *x* to the right side of the deque. - Add *x* to the right side of the deque. + .. method:: appendleft(x) -.. method:: deque.appendleft(x) + Add *x* to the left side of the deque. - Add *x* to the left side of the deque. + .. method:: clear() -.. method:: deque.clear() + Remove all elements from the deque leaving it with length 0. - Remove all elements from the deque leaving it with length 0. + .. method:: extend(iterable) -.. method:: deque.extend(iterable) + Extend the right side of the deque by appending elements from the iterable + argument. - Extend the right side of the deque by appending elements from the iterable - argument. + .. method:: extendleft(iterable) -.. method:: deque.extendleft(iterable) + Extend the left side of the deque by appending elements from *iterable*. + Note, the series of left appends results in reversing the order of + elements in the iterable argument. - Extend the left side of the deque by appending elements from *iterable*. Note, - the series of left appends results in reversing the order of elements in the - iterable argument. + .. method:: pop() -.. method:: deque.pop() + Remove and return an element from the right side of the deque. If no + elements are present, raises an :exc:`IndexError`. - Remove and return an element from the right side of the deque. If no elements - are present, raises an :exc:`IndexError`. + .. method:: popleft() -.. method:: deque.popleft() + Remove and return an element from the left side of the deque. If no + elements are present, raises an :exc:`IndexError`. - Remove and return an element from the left side of the deque. If no elements are - present, raises an :exc:`IndexError`. + .. method:: remove(value) -.. method:: deque.remove(value) + Removed the first occurrence of *value*. If not found, raises a + :exc:`ValueError`. - Removed the first occurrence of *value*. If not found, raises a - :exc:`ValueError`. + .. method:: rotate(n) -.. method:: deque.rotate(n) + Rotate the deque *n* steps to the right. If *n* is negative, rotate to + the left. Rotating one step to the right is equivalent to: + ``d.appendleft(d.pop())``. - Rotate the deque *n* steps to the right. If *n* is negative, rotate to the - left. Rotating one step to the right is equivalent to: - ``d.appendleft(d.pop())``. In addition to the above, deques support iteration, pickling, ``len(d)``, ``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with the :keyword:`in` operator, and subscript references such as ``d[-1]``. -Example:: +Example: + +.. doctest:: >>> from collections import deque >>> d = deque('ghi') # make a new deque with three items >>> for elem in d: # iterate over the deque's elements - ... print(elem.upper()) + ... print elem.upper() G H I @@ -242,7 +311,7 @@ deque. For example, building a balanced binary tree of nested lists entails reducing -two adjacent nodes into one by grouping them in a list:: +two adjacent nodes into one by grouping them in a list: >>> def maketree(iterable): ... d = deque(iterable) @@ -280,32 +349,34 @@ arguments. -:class:`defaultdict` objects support the following method in addition to the -standard :class:`dict` operations: + :class:`defaultdict` objects support the following method in addition to the + standard :class:`dict` operations: + + .. method:: defaultdict.__missing__(key) -.. method:: defaultdict.__missing__(key) + If the :attr:`default_factory` attribute is ``None``, this raises an + :exc:`KeyError` exception with the *key* as argument. - If the :attr:`default_factory` attribute is ``None``, this raises an - :exc:`KeyError` exception with the *key* as argument. + If :attr:`default_factory` is not ``None``, it is called without arguments + to provide a default value for the given *key*, this value is inserted in + the dictionary for the *key*, and returned. - If :attr:`default_factory` is not ``None``, it is called without arguments to - provide a default value for the given *key*, this value is inserted in the - dictionary for the *key*, and returned. + If calling :attr:`default_factory` raises an exception this exception is + propagated unchanged. - If calling :attr:`default_factory` raises an exception this exception is - propagated unchanged. + This method is called by the :meth:`__getitem__` method of the + :class:`dict` class when the requested key is not found; whatever it + returns or raises is then returned or raised by :meth:`__getitem__`. - This method is called by the :meth:`__getitem__` method of the :class:`dict` - class when the requested key is not found; whatever it returns or raises is then - returned or raised by :meth:`__getitem__`. -:class:`defaultdict` objects support the following instance variable: + :class:`defaultdict` objects support the following instance variable: -.. attribute:: defaultdict.default_factory + .. attribute:: defaultdict.default_factory - This attribute is used by the :meth:`__missing__` method; it is initialized from - the first argument to the constructor, if present, or to ``None``, if absent. + This attribute is used by the :meth:`__missing__` method; it is + initialized from the first argument to the constructor, if present, or to + ``None``, if absent. .. _defaultdict-examples: @@ -314,7 +385,7 @@ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Using :class:`list` as the :attr:`default_factory`, it is easy to group a -sequence of key-value pairs into a dictionary of lists:: +sequence of key-value pairs into a dictionary of lists: >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] >>> d = defaultdict(list) @@ -330,7 +401,7 @@ operation then attaches the value to the new list. When keys are encountered again, the look-up proceeds normally (returning the list for that key) and the :meth:`list.append` operation adds another value to the list. This technique is -simpler and faster than an equivalent technique using :meth:`dict.setdefault`:: +simpler and faster than an equivalent technique using :meth:`dict.setdefault`: >>> d = {} >>> for k, v in s: @@ -341,7 +412,7 @@ Setting the :attr:`default_factory` to :class:`int` makes the :class:`defaultdict` useful for counting (like a bag or multiset in other -languages):: +languages): >>> s = 'mississippi' >>> d = defaultdict(int) @@ -358,7 +429,7 @@ The function :func:`int` which always returns zero is just a special case of constant functions. A faster and more flexible way to create constant functions is to use a lambda function which can supply any constant value (not just -zero):: +zero): >>> def constant_factory(value): ... return lambda: value @@ -368,7 +439,7 @@ 'John ran to ' Setting the :attr:`default_factory` to :class:`set` makes the -:class:`defaultdict` useful for building a dictionary of sets:: +:class:`defaultdict` useful for building a dictionary of sets: >>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)] >>> d = defaultdict(set) @@ -391,7 +462,7 @@ .. function:: namedtuple(typename, fieldnames, [verbose]) Returns a new tuple subclass named *typename*. The new subclass is used to - create tuple-like objects that have fields accessable by attribute lookup as + create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. Instances of the subclass also have a helpful docstring (with typename and fieldnames) and a helpful :meth:`__repr__` method which lists the tuple contents in a ``name=value`` format. @@ -403,7 +474,7 @@ Any valid Python identifier may be used for a fieldname except for names starting with an underscore. Valid identifiers consist of letters, digits, and underscores but do not start with a digit or underscore and cannot be - a :mod:`keyword` such as *class*, *for*, *return*, *global*, *pass*, *print*, + a :mod:`keyword` such as *class*, *for*, *return*, *global*, *pass*, or *raise*. If *verbose* is true, the class definition is printed just before being built. @@ -411,41 +482,44 @@ Named tuple instances do not have per-instance dictionaries, so they are lightweight and require no more memory than regular tuples. -Example:: +Example: + +.. doctest:: + :options: +NORMALIZE_WHITESPACE >>> Point = namedtuple('Point', 'x y', verbose=True) class Point(tuple): 'Point(x, y)' - + __slots__ = () - + _fields = ('x', 'y') - + def __new__(cls, x, y): return tuple.__new__(cls, (x, y)) - + @classmethod - def _make(cls, iterable): + def _make(cls, iterable, new=tuple.__new__, len=len): 'Make a new Point object from a sequence or iterable' - result = tuple.__new__(cls, iterable) + result = new(cls, iterable) if len(result) != 2: raise TypeError('Expected 2 arguments, got %d' % len(result)) return result - + def __repr__(self): return 'Point(x=%r, y=%r)' % self - + def _asdict(t): 'Return a new dict which maps field names to their values' return {'x': t[0], 'y': t[1]} - + def _replace(self, **kwds): 'Return a new Point object replacing specified fields with new values' result = self._make(map(kwds.pop, ('x', 'y'), self)) if kwds: raise ValueError('Got unexpected field names: %r' % kwds.keys()) return result - + x = property(itemgetter(0)) y = property(itemgetter(1)) @@ -455,7 +529,7 @@ >>> x, y = p # unpack like a regular tuple >>> x, y (11, 22) - >>> p.x + p.y # fields also accessable by name + >>> p.x + p.y # fields also accessible by name 33 >>> p # readable __repr__ with a name=value style Point(x=11, y=22) @@ -476,6 +550,16 @@ for emp in map(EmployeeRecord._make, cursor.fetchall()): print(emp.name, emp.title) +Named tuples can also be used to generate enumerated constants: + +.. testcode:: + + def enum(*names): + return namedtuple('Enum', ' '.join(names))(*range(len(names))) + + Status = enum('open', 'pending', 'closed') + assert (0, 1, 2) == (Status.open, Status.pending, Status.closed) + In addition to the methods inherited from tuples, named tuples support three additional methods and one attribute. To prevent conflicts with field names, the method and attribute names start with an underscore. @@ -484,7 +568,7 @@ Class method that makes a new instance from an existing sequence or iterable. -:: +.. doctest:: >>> t = [11, 22] >>> Point._make(t) @@ -492,16 +576,15 @@ .. method:: somenamedtuple._asdict() - Return a new dict which maps field names to their corresponding values: - -:: + Return a new dict which maps field names to their corresponding values:: >>> p._asdict() {'x': 11, 'y': 22} - + .. method:: somenamedtuple._replace(kwargs) - Return a new instance of the named tuple replacing specified fields with new values: + Return a new instance of the named tuple replacing specified fields with new + values: :: @@ -517,7 +600,7 @@ Tuple of strings listing the field names. Useful for introspection and for creating new named tuple types from existing named tuples. -:: +.. doctest:: >>> p._fields # view the field names ('x', 'y') @@ -528,12 +611,12 @@ Pixel(x=11, y=22, red=128, green=255, blue=0) To retrieve a field whose name is stored in a string, use the :func:`getattr` -function:: +function: >>> getattr(p, 'x') 11 -To convert a dictionary to a named tuple, use the double-star-operator [#]_:: +To convert a dictionary to a named tuple, use the double-star-operator [#]_: >>> d = {'x': 11, 'y': 22} >>> Point(**d) @@ -541,7 +624,7 @@ Since a named tuple is a regular Python class, it is easy to add or change functionality with a subclass. Here is how to add a calculated field and -a fixed-width print format:: +a fixed-width print format: >>> class Point(namedtuple('Point', 'x y')): ... __slots__ = () @@ -553,30 +636,20 @@ >>> for p in Point(3, 4), Point(14, 5/7.): ... print(p) - Point: x= 3.000 y= 4.000 hypot= 5.000 Point: x=14.000 y= 0.714 hypot=14.018 -Another use for subclassing is to replace performance critcal methods with -faster versions that bypass error-checking:: - - class Point(namedtuple('Point', 'x y')): - __slots__ = () - _make = classmethod(tuple.__new__) - def _replace(self, _map=map, **kwds): - return self._make(_map(kwds.get, ('x', 'y'), self)) - -The subclasses shown above set ``__slots__`` to an empty tuple. This keeps +The subclass shown above sets ``__slots__`` to an empty tuple. This keeps keep memory requirements low by preventing the creation of instance dictionaries. Subclassing is not useful for adding new, stored fields. Instead, simply -create a new named tuple type from the :attr:`_fields` attribute:: +create a new named tuple type from the :attr:`_fields` attribute: >>> Point3D = namedtuple('Point3D', Point._fields + ('z',)) Default values can be implemented by using :meth:`_replace` to -customize a prototype instance:: +customize a prototype instance: >>> Account = namedtuple('Account', 'owner balance transaction_count') >>> default_account = Account('', 0.0, 0) @@ -586,3 +659,90 @@ .. [#] For information on the double-star-operator see :ref:`tut-unpacking-arguments` and :ref:`calls`. + + + +:class:`UserDict` objects +------------------------- + +The class, :class:`UserDict` acts as a wrapper around dictionary objects. +The need for this class has been partially supplanted by the ability to +subclass directly from :class:`dict`; however, this class can be easier +to work with because the underlying dictionary is accessible as an +attribute. + +.. class:: UserDict([initialdata]) + + Class that simulates a dictionary. The instance's contents are kept in a + regular dictionary, which is accessible via the :attr:`data` attribute of + :class:`UserDict` instances. If *initialdata* is provided, :attr:`data` is + initialized with its contents; note that a reference to *initialdata* will not + be kept, allowing it be used for other purposes. + +In addition to supporting the methods and operations of mappings, +:class:`UserDict` instances provide the following attribute: + +.. attribute:: UserDict.data + + A real dictionary used to store the contents of the :class:`UserDict` class. + + + +:class:`UserList` objects +------------------------- + +This class acts as a wrapper around list objects. It is a useful base class +for your own list-like classes which can inherit from them and override +existing methods or add new ones. In this way, one can add new behaviors to +lists. + +The need for this class has been partially supplanted by the ability to +subclass directly from :class:`list`; however, this class can be easier +to work with because the underlying list is accessible as an attribute. + +.. class:: UserList([list]) + + Class that simulates a list. The instance's contents are kept in a regular + list, which is accessible via the :attr:`data` attribute of :class:`UserList` + instances. The instance's contents are initially set to a copy of *list*, + defaulting to the empty list ``[]``. *list* can be any iterable, for + example a real Python list or a :class:`UserList` object. + +In addition to supporting the methods and operations of mutable sequences, +:class:`UserList` instances provide the following attribute: + +.. attribute:: UserList.data + + A real :class:`list` object used to store the contents of the + :class:`UserList` class. + +**Subclassing requirements:** Subclasses of :class:`UserList` are expect to +offer a constructor which can be called with either no arguments or one +argument. List operations which return a new sequence attempt to create an +instance of the actual implementation class. To do so, it assumes that the +constructor can be called with a single parameter, which is a sequence object +used as a data source. + +If a derived class does not wish to comply with this requirement, all of the +special methods supported by this class will need to be overridden; please +consult the sources for information about the methods which need to be provided +in that case. + +:class:`UserString` objects +--------------------------- + +The class, :class:`UserString` acts as a wrapper around string objects. +The need for this class has been partially supplanted by the ability to +subclass directly from :class:`str`; however, this class can be easier +to work with because the underlying string is accessible as an +attribute. + +.. class:: UserString([sequence]) + + Class that simulates a string or a Unicode string object. The instance's + content is kept in a regular string object, which is accessible via the + :attr:`data` attribute of :class:`UserString` instances. The instance's + contents are initially set to a copy of *sequence*. The *sequence* can + be an instance of :class:`bytes`, :class:`str`, :class:`UserString` (or a + subclass) or an arbitrary sequence which can be converted into a string using + the built-in :func:`str` function. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/configparser.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/configparser.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/configparser.rst Wed Apr 30 15:57:13 2008 @@ -29,18 +29,20 @@ The configuration file consists of sections, led by a ``[section]`` header and followed by ``name: value`` entries, with continuations in the style of -:rfc:`822`; ``name=value`` is also accepted. Note that leading whitespace is -removed from values. The optional values can contain format strings which refer -to other values in the same section, or values in a special ``DEFAULT`` section. -Additional defaults can be provided on initialization and retrieval. Lines -beginning with ``'#'`` or ``';'`` are ignored and may be used to provide -comments. +:rfc:`822` (see section 3.1.1, "LONG HEADER FIELDS"); ``name=value`` is also +accepted. Note that leading whitespace is removed from values. The optional +values can contain format strings which refer to other values in the same +section, or values in a special ``DEFAULT`` section. Additional defaults can be +provided on initialization and retrieval. Lines beginning with ``'#'`` or +``';'`` are ignored and may be used to provide comments. For example:: [My Section] foodir: %(dir)s/whatever dir=frob + long: this value continues + in the next line would resolve the ``%(dir)s`` to the value of ``dir`` (``frob`` in this case). All reference expansions are done on demand. @@ -176,8 +178,9 @@ .. method:: RawConfigParser.add_section(section) Add a section named *section* to the instance. If a section by the given name - already exists, :exc:`DuplicateSectionError` is raised. - + already exists, :exc:`DuplicateSectionError` is raised. If the name + ``DEFAULT`` (or any of it's case-insensitive variants) is passed, + :exc:`ValueError` is raised. .. method:: RawConfigParser.has_section(section) @@ -199,7 +202,7 @@ .. method:: RawConfigParser.read(filenames) Attempt to read and parse a list of filenames, returning a list of filenames - which were successfully parsed. If *filenames* is a string or Unicode string, + which were successfully parsed. If *filenames* is a string, it is treated as a single filename. If a file named in *filenames* cannot be opened, that file will be ignored. This is designed so that you can specify a list of potential configuration file locations (for example, the current @@ -330,8 +333,8 @@ .. method:: SafeConfigParser.set(section, option, value) If the given section exists, set the given option to the specified value; - otherwise raise :exc:`NoSectionError`. *value* must be a string (:class:`str` - or :class:`unicode`); if not, :exc:`TypeError` is raised. + otherwise raise :exc:`NoSectionError`. *value* must be a string; if it is + not, :exc:`TypeError` is raised. Examples @@ -373,12 +376,12 @@ # getint() and getboolean() also do this for their respective types float = config.getfloat('Section1', 'float') int = config.getint('Section1', 'int') - print float + int + print(float + int) # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'. # This is because we are using a RawConfigParser(). if config.getboolean('Section1', 'bool'): - print config.get('Section1', 'foo') + print(config.get('Section1', 'foo')) To get interpolation, you will need to use a :class:`ConfigParser` or :class:`SafeConfigParser`:: @@ -389,13 +392,13 @@ config.read('example.cfg') # Set the third, optional argument of get to 1 if you wish to use raw mode. - print config.get('Section1', 'foo', 0) # -> "Python is fun!" - print config.get('Section1', 'foo', 1) # -> "%(bar)s is %(baz)s!" + print(config.get('Section1', 'foo', 0)) # -> "Python is fun!" + print(config.get('Section1', 'foo', 1)) # -> "%(bar)s is %(baz)s!" # The optional fourth argument is a dict with members that will take # precedence in interpolation. - print config.get('Section1', 'foo', 0, {'bar': 'Documentation', - 'baz': 'evil'}) + print(config.get('Section1', 'foo', 0, {'bar': 'Documentation', + 'baz': 'evil'})) Defaults are available in all three types of ConfigParsers. They are used in interpolation if an option used is not defined elsewhere. :: @@ -406,10 +409,10 @@ config = ConfigParser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'}) config.read('example.cfg') - print config.get('Section1', 'foo') # -> "Python is fun!" + print(config.get('Section1', 'foo')) # -> "Python is fun!" config.remove_option('Section1', 'bar') config.remove_option('Section1', 'baz') - print config.get('Section1', 'foo') # -> "Life is hard!" + print(config.get('Section1', 'foo')) # -> "Life is hard!" The function ``opt_move`` below can be used to move options between sections:: Modified: python/branches/py3k-ctypes-pep3118/Doc/library/cookie.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/cookie.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/cookie.rst Wed Apr 30 15:57:13 2008 @@ -206,7 +206,10 @@ Example ------- -The following example demonstrates how to use the :mod:`Cookie` module. :: +The following example demonstrates how to use the :mod:`Cookie` module. + +.. doctest:: + :options: +NORMALIZE_WHITESPACE >>> import Cookie >>> C = Cookie.SimpleCookie() @@ -215,11 +218,11 @@ >>> C["fig"] = "newton" >>> C["sugar"] = "wafer" >>> print(C) # generate HTTP headers - Set-Cookie: sugar=wafer Set-Cookie: fig=newton - >>> print(C.output()) # same thing Set-Cookie: sugar=wafer + >>> print(C.output()) # same thing Set-Cookie: fig=newton + Set-Cookie: sugar=wafer >>> C = Cookie.SmartCookie() >>> C["rocky"] = "road" >>> C["rocky"]["path"] = "/cookie" @@ -230,8 +233,8 @@ >>> C = Cookie.SmartCookie() >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header) >>> print(C) - Set-Cookie: vienna=finger Set-Cookie: chips=ahoy + Set-Cookie: vienna=finger >>> C = Cookie.SmartCookie() >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";') >>> print(C) Modified: python/branches/py3k-ctypes-pep3118/Doc/library/cookielib.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/cookielib.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/cookielib.rst Wed Apr 30 15:57:13 2008 @@ -117,7 +117,7 @@ Extensions to this module, including a class for reading Microsoft Internet Explorer cookies on Windows. - http://www.netscape.com/newsref/std/cookie_spec.html + http://wp.netscape.com/newsref/std/cookie_spec.html The specification of the original Netscape cookie protocol. Though this is still the dominant protocol, the 'Netscape cookie protocol' implemented by all the major browsers (and :mod:`cookielib`) only bears a passing resemblance to Modified: python/branches/py3k-ctypes-pep3118/Doc/library/copy_reg.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/copy_reg.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/copy_reg.rst Wed Apr 30 15:57:13 2008 @@ -26,11 +26,9 @@ .. function:: pickle(type, function[, constructor]) - Declares that *function* should be used as a "reduction" function for objects of - type *type*; *type* must not be a "classic" class object. (Classic classes are - handled differently; see the documentation for the :mod:`pickle` module for - details.) *function* should return either a string or a tuple containing two or - three elements. + Declares that *function* should be used as a "reduction" function for objects + of type *type*. *function* should return either a string or a tuple + containing two or three elements. The optional *constructor* parameter, if provided, is a callable object which can be used to reconstruct the object when called with the tuple of arguments Modified: python/branches/py3k-ctypes-pep3118/Doc/library/csv.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/csv.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/csv.rst Wed Apr 30 15:57:13 2008 @@ -86,7 +86,7 @@ >>> import csv >>> spamReader = csv.reader(open('eggs.csv'), delimiter=' ', quotechar='|') >>> for row in spamReader: - ... print ', '.join(row) + ... print(', '.join(row)) Spam, Spam, Spam, Spam, Spam, Baked Beans Spam, Lovely Spam, Wonderful Spam @@ -121,7 +121,7 @@ .. function:: register_dialect(name[, dialect][, fmtparam]) - Associate *dialect* with *name*. *name* must be a string or Unicode object. The + Associate *dialect* with *name*. *name* must be a string. The dialect can be specified either by passing a sub-class of :class:`Dialect`, or by *fmtparam* keyword arguments, or both, with keyword arguments overriding parameters of the dialect. For full details about the dialect and formatting @@ -209,19 +209,20 @@ The :class:`Sniffer` class is used to deduce the format of a CSV file. -The :class:`Sniffer` class provides two methods: + The :class:`Sniffer` class provides two methods: -.. method:: Sniffer.sniff(sample[, delimiters=None]) + .. method:: sniff(sample[, delimiters=None]) - Analyze the given *sample* and return a :class:`Dialect` subclass reflecting the - parameters found. If the optional *delimiters* parameter is given, it is - interpreted as a string containing possible valid delimiter characters. + Analyze the given *sample* and return a :class:`Dialect` subclass + reflecting the parameters found. If the optional *delimiters* parameter + is given, it is interpreted as a string containing possible valid + delimiter characters. -.. method:: Sniffer.has_header(sample) + .. method:: has_header(sample) - Analyze the sample text (presumed to be in CSV format) and return :const:`True` - if the first row appears to be a series of column headers. + Analyze the sample text (presumed to be in CSV format) and return + :const:`True` if the first row appears to be a series of column headers. An example for :class:`Sniffer` use:: Modified: python/branches/py3k-ctypes-pep3118/Doc/library/ctypes.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/ctypes.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/ctypes.rst Wed Apr 30 15:57:13 2008 @@ -1441,10 +1441,10 @@ so repeated attribute accesses return the same library each time. -.. method:: LibraryLoader.LoadLibrary(name) + .. method:: LoadLibrary(name) - Load a shared library into the process and return it. This method always - returns a new instance of the library. + Load a shared library into the process and return it. This method always + returns a new instance of the library. These prefabricated library loaders are available: @@ -1501,50 +1501,51 @@ Base class for C callable foreign functions. -Instances of foreign functions are also C compatible data types; they represent -C function pointers. + Instances of foreign functions are also C compatible data types; they + represent C function pointers. -This behavior can be customized by assigning to special attributes of the -foreign function object. + This behavior can be customized by assigning to special attributes of the + foreign function object. -.. attribute:: _FuncPtr.restype + .. attribute:: restype - Assign a ctypes type to specify the result type of the foreign function. Use - ``None`` for ``void`` a function not returning anything. + Assign a ctypes type to specify the result type of the foreign function. + Use ``None`` for ``void`` a function not returning anything. - It is possible to assign a callable Python object that is not a ctypes type, in - this case the function is assumed to return a C ``int``, and the callable will - be called with this integer, allowing to do further processing or error - checking. Using this is deprecated, for more flexible post processing or error - checking use a ctypes data type as :attr:`restype` and assign a callable to the - :attr:`errcheck` attribute. + It is possible to assign a callable Python object that is not a ctypes + type, in this case the function is assumed to return a C ``int``, and the + callable will be called with this integer, allowing to do further + processing or error checking. Using this is deprecated, for more flexible + post processing or error checking use a ctypes data type as + :attr:`restype` and assign a callable to the :attr:`errcheck` attribute. -.. attribute:: _FuncPtr.argtypes + .. attribute:: argtypes - Assign a tuple of ctypes types to specify the argument types that the function - accepts. Functions using the ``stdcall`` calling convention can only be called - with the same number of arguments as the length of this tuple; functions using - the C calling convention accept additional, unspecified arguments as well. + Assign a tuple of ctypes types to specify the argument types that the + function accepts. Functions using the ``stdcall`` calling convention can + only be called with the same number of arguments as the length of this + tuple; functions using the C calling convention accept additional, + unspecified arguments as well. - When a foreign function is called, each actual argument is passed to the - :meth:`from_param` class method of the items in the :attr:`argtypes` tuple, this - method allows to adapt the actual argument to an object that the foreign - function accepts. For example, a :class:`c_char_p` item in the :attr:`argtypes` - tuple will convert a unicode string passed as argument into an byte string using - ctypes conversion rules. + When a foreign function is called, each actual argument is passed to the + :meth:`from_param` class method of the items in the :attr:`argtypes` + tuple, this method allows to adapt the actual argument to an object that + the foreign function accepts. For example, a :class:`c_char_p` item in + the :attr:`argtypes` tuple will convert a unicode string passed as + argument into an byte string using ctypes conversion rules. - New: It is now possible to put items in argtypes which are not ctypes types, but - each item must have a :meth:`from_param` method which returns a value usable as - argument (integer, string, ctypes instance). This allows to define adapters - that can adapt custom objects as function parameters. + New: It is now possible to put items in argtypes which are not ctypes + types, but each item must have a :meth:`from_param` method which returns a + value usable as argument (integer, string, ctypes instance). This allows + to define adapters that can adapt custom objects as function parameters. -.. attribute:: _FuncPtr.errcheck + .. attribute:: errcheck - Assign a Python function or another callable to this attribute. The callable - will be called with three or more arguments: + Assign a Python function or another callable to this attribute. The + callable will be called with three or more arguments: .. function:: callable(result, func, arguments) @@ -1559,9 +1560,9 @@ ``arguments`` is a tuple containing the parameters originally passed to the function call, this allows to specialize the behavior on the arguments used. - The object that this function returns will be returned from the foreign function - call, but it can also check the result value and raise an exception if the - foreign function call failed. + The object that this function returns will be returned from the foreign + function call, but it can also check the result value and raise an exception + if the foreign function call failed. .. exception:: ArgumentError() @@ -1943,57 +1944,58 @@ :attr:`_objects`; this contains other Python objects that need to be kept alive in case the memory block contains pointers. -Common methods of ctypes data types, these are all class methods (to be exact, -they are methods of the :term:`metaclass`): + Common methods of ctypes data types, these are all class methods (to be + exact, they are methods of the :term:`metaclass`): -.. method:: _CData.from_address(address) + .. method:: from_address(address) - This method returns a ctypes type instance using the memory specified by address - which must be an integer. + This method returns a ctypes type instance using the memory specified by + address which must be an integer. -.. method:: _CData.from_param(obj) + .. method:: from_param(obj) - This method adapts obj to a ctypes type. It is called with the actual object - used in a foreign function call, when the type is present in the foreign - functions :attr:`argtypes` tuple; it must return an object that can be used as - function call parameter. + This method adapts obj to a ctypes type. It is called with the actual + object used in a foreign function call, when the type is present in the + foreign functions :attr:`argtypes` tuple; it must return an object that + can be used as function call parameter. - All ctypes data types have a default implementation of this classmethod, - normally it returns ``obj`` if that is an instance of the type. Some types - accept other objects as well. + All ctypes data types have a default implementation of this classmethod, + normally it returns ``obj`` if that is an instance of the type. Some + types accept other objects as well. -.. method:: _CData.in_dll(library, name) + .. method:: in_dll(library, name) - This method returns a ctypes type instance exported by a shared library. *name* - is the name of the symbol that exports the data, *library* is the loaded shared - library. + This method returns a ctypes type instance exported by a shared + library. *name* is the name of the symbol that exports the data, *library* + is the loaded shared library. -Common instance variables of ctypes data types: + Common instance variables of ctypes data types: -.. attribute:: _CData._b_base_ - Sometimes ctypes data instances do not own the memory block they contain, - instead they share part of the memory block of a base object. The - :attr:`_b_base_` read-only member is the root ctypes object that owns the memory - block. + .. attribute:: _b_base_ + Sometimes ctypes data instances do not own the memory block they contain, + instead they share part of the memory block of a base object. The + :attr:`_b_base_` read-only member is the root ctypes object that owns the + memory block. -.. attribute:: _CData._b_needsfree_ - This read-only variable is true when the ctypes data instance has allocated the - memory block itself, false otherwise. + .. attribute:: _b_needsfree_ + This read-only variable is true when the ctypes data instance has + allocated the memory block itself, false otherwise. -.. attribute:: _CData._objects - This member is either ``None`` or a dictionary containing Python objects that - need to be kept alive so that the memory block contents is kept valid. This - object is only exposed for debugging; never modify the contents of this - dictionary. + .. attribute:: _objects + + This member is either ``None`` or a dictionary containing Python objects + that need to be kept alive so that the memory block contents is kept + valid. This object is only exposed for debugging; never modify the + contents of this dictionary. .. _ctypes-fundamental-data-types-2: @@ -2004,24 +2006,26 @@ .. class:: _SimpleCData - This non-public class is the base class of all fundamental ctypes data types. It - is mentioned here because it contains the common attributes of the fundamental - ctypes data types. ``_SimpleCData`` is a subclass of ``_CData``, so it inherits - their methods and attributes. - -Instances have a single attribute: - - -.. attribute:: _SimpleCData.value - - This attribute contains the actual value of the instance. For integer and - pointer types, it is an integer, for character types, it is a single character - string, for character pointer types it is a Python string or unicode string. - - When the ``value`` attribute is retrieved from a ctypes instance, usually a new - object is returned each time. ``ctypes`` does *not* implement original object - return, always a new object is constructed. The same is true for all other - ctypes object instances. + This non-public class is the base class of all fundamental ctypes data + types. It is mentioned here because it contains the common attributes of the + fundamental ctypes data types. ``_SimpleCData`` is a subclass of ``_CData``, + so it inherits their methods and attributes. ctypes data types that are not + and do not contain pointers can now be pickled. + + Instances have a single attribute: + + + .. attribute:: value + + This attribute contains the actual value of the instance. For integer and + pointer types, it is an integer, for character types, it is a single + character string, for character pointer types it is a Python string or + unicode string. + + When the ``value`` attribute is retrieved from a ctypes instance, usually + a new object is returned each time. ``ctypes`` does *not* implement + original object return, always a new object is constructed. The same is + true for all other ctypes object instances. Fundamental data types, when returned as foreign function call results, or, for example, by retrieving structure field members or array items, are transparently @@ -2257,90 +2261,92 @@ Abstract base class for structures in *native* byte order. -Concrete structure and union types must be created by subclassing one of these -types, and at least define a :attr:`_fields_` class variable. ``ctypes`` will -create :term:`descriptor`\s which allow reading and writing the fields by direct -attribute accesses. These are the + Concrete structure and union types must be created by subclassing one of these + types, and at least define a :attr:`_fields_` class variable. ``ctypes`` will + create :term:`descriptor`\s which allow reading and writing the fields by direct + attribute accesses. These are the -.. attribute:: Structure._fields_ + .. attribute:: _fields_ - A sequence defining the structure fields. The items must be 2-tuples or - 3-tuples. The first item is the name of the field, the second item specifies - the type of the field; it can be any ctypes data type. + A sequence defining the structure fields. The items must be 2-tuples or + 3-tuples. The first item is the name of the field, the second item + specifies the type of the field; it can be any ctypes data type. - For integer type fields like :class:`c_int`, a third optional item can be given. - It must be a small positive integer defining the bit width of the field. + For integer type fields like :class:`c_int`, a third optional item can be + given. It must be a small positive integer defining the bit width of the + field. - Field names must be unique within one structure or union. This is not checked, - only one field can be accessed when names are repeated. + Field names must be unique within one structure or union. This is not + checked, only one field can be accessed when names are repeated. - It is possible to define the :attr:`_fields_` class variable *after* the class - statement that defines the Structure subclass, this allows to create data types - that directly or indirectly reference themselves:: + It is possible to define the :attr:`_fields_` class variable *after* the + class statement that defines the Structure subclass, this allows to create + data types that directly or indirectly reference themselves:: - class List(Structure): - pass - List._fields_ = [("pnext", POINTER(List)), - ... - ] + class List(Structure): + pass + List._fields_ = [("pnext", POINTER(List)), + ... + ] - The :attr:`_fields_` class variable must, however, be defined before the type is - first used (an instance is created, ``sizeof()`` is called on it, and so on). - Later assignments to the :attr:`_fields_` class variable will raise an - AttributeError. + The :attr:`_fields_` class variable must, however, be defined before the + type is first used (an instance is created, ``sizeof()`` is called on it, + and so on). Later assignments to the :attr:`_fields_` class variable will + raise an AttributeError. - Structure and union subclass constructors accept both positional and named - arguments. Positional arguments are used to initialize the fields in the same - order as they appear in the :attr:`_fields_` definition, named arguments are - used to initialize the fields with the corresponding name. + Structure and union subclass constructors accept both positional and named + arguments. Positional arguments are used to initialize the fields in the + same order as they appear in the :attr:`_fields_` definition, named + arguments are used to initialize the fields with the corresponding name. - It is possible to defined sub-subclasses of structure types, they inherit the - fields of the base class plus the :attr:`_fields_` defined in the sub-subclass, - if any. + It is possible to defined sub-subclasses of structure types, they inherit + the fields of the base class plus the :attr:`_fields_` defined in the + sub-subclass, if any. -.. attribute:: Structure._pack_ + .. attribute:: _pack_ - An optional small integer that allows to override the alignment of structure - fields in the instance. :attr:`_pack_` must already be defined when - :attr:`_fields_` is assigned, otherwise it will have no effect. + An optional small integer that allows to override the alignment of + structure fields in the instance. :attr:`_pack_` must already be defined + when :attr:`_fields_` is assigned, otherwise it will have no effect. -.. attribute:: Structure._anonymous_ + .. attribute:: _anonymous_ - An optional sequence that lists the names of unnamed (anonymous) fields. - ``_anonymous_`` must be already defined when :attr:`_fields_` is assigned, - otherwise it will have no effect. + An optional sequence that lists the names of unnamed (anonymous) fields. + ``_anonymous_`` must be already defined when :attr:`_fields_` is assigned, + otherwise it will have no effect. - The fields listed in this variable must be structure or union type fields. - ``ctypes`` will create descriptors in the structure type that allows to access - the nested fields directly, without the need to create the structure or union - field. + The fields listed in this variable must be structure or union type fields. + ``ctypes`` will create descriptors in the structure type that allows to + access the nested fields directly, without the need to create the + structure or union field. - Here is an example type (Windows):: + Here is an example type (Windows):: - class _U(Union): - _fields_ = [("lptdesc", POINTER(TYPEDESC)), - ("lpadesc", POINTER(ARRAYDESC)), - ("hreftype", HREFTYPE)] + class _U(Union): + _fields_ = [("lptdesc", POINTER(TYPEDESC)), + ("lpadesc", POINTER(ARRAYDESC)), + ("hreftype", HREFTYPE)] - class TYPEDESC(Structure): - _fields_ = [("u", _U), - ("vt", VARTYPE)] + class TYPEDESC(Structure): + _fields_ = [("u", _U), + ("vt", VARTYPE)] - _anonymous_ = ("u",) + _anonymous_ = ("u",) - The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field specifies - which one of the union fields is valid. Since the ``u`` field is defined as - anonymous field, it is now possible to access the members directly off the - TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc`` are equivalent, but the - former is faster since it does not need to create a temporary union instance:: + The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field + specifies which one of the union fields is valid. Since the ``u`` field + is defined as anonymous field, it is now possible to access the members + directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc`` + are equivalent, but the former is faster since it does not need to create + a temporary union instance:: - td = TYPEDESC() - td.vt = VT_PTR - td.lptdesc = POINTER(some_type) - td.u.lptdesc = POINTER(some_type) + td = TYPEDESC() + td.vt = VT_PTR + td.lptdesc = POINTER(some_type) + td.u.lptdesc = POINTER(some_type) It is possible to defined sub-subclasses of structures, they inherit the fields of the base class. If the subclass definition has a separate :attr:`_fields_` Modified: python/branches/py3k-ctypes-pep3118/Doc/library/curses.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/curses.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/curses.rst Wed Apr 30 15:57:13 2008 @@ -45,9 +45,9 @@ Convenience function to ensure proper terminal setup and resetting on application entry and exit. - `Curses Programming with Python `_ + :ref:`curses-howto` Tutorial material on using curses with Python, by Andrew Kuchling and Eric - Raymond, is available on the Python Web site. + Raymond. The :file:`Demo/curses/` directory in the Python source distribution contains some example programs using the curses bindings provided by this module. @@ -1567,92 +1567,94 @@ containing window, with coordinates ``(0, 0)``. The instance's :attr:`stripspaces` flag is initially on. -:class:`Textbox` objects have the following methods: + :class:`Textbox` objects have the following methods: -.. method:: Textbox.edit([validator]) + .. method:: edit([validator]) - This is the entry point you will normally use. It accepts editing keystrokes - until one of the termination keystrokes is entered. If *validator* is supplied, - it must be a function. It will be called for each keystroke entered with the - keystroke as a parameter; command dispatch is done on the result. This method - returns the window contents as a string; whether blanks in the window are - included is affected by the :attr:`stripspaces` member. - - -.. method:: Textbox.do_command(ch) - - Process a single command keystroke. Here are the supported special keystrokes: - - +------------------+-------------------------------------------+ - | Keystroke | Action | - +==================+===========================================+ - | :kbd:`Control-A` | Go to left edge of window. | - +------------------+-------------------------------------------+ - | :kbd:`Control-B` | Cursor left, wrapping to previous line if | - | | appropriate. | - +------------------+-------------------------------------------+ - | :kbd:`Control-D` | Delete character under cursor. | - +------------------+-------------------------------------------+ - | :kbd:`Control-E` | Go to right edge (stripspaces off) or end | - | | of line (stripspaces on). | - +------------------+-------------------------------------------+ - | :kbd:`Control-F` | Cursor right, wrapping to next line when | - | | appropriate. | - +------------------+-------------------------------------------+ - | :kbd:`Control-G` | Terminate, returning the window contents. | - +------------------+-------------------------------------------+ - | :kbd:`Control-H` | Delete character backward. | - +------------------+-------------------------------------------+ - | :kbd:`Control-J` | Terminate if the window is 1 line, | - | | otherwise insert newline. | - +------------------+-------------------------------------------+ - | :kbd:`Control-K` | If line is blank, delete it, otherwise | - | | clear to end of line. | - +------------------+-------------------------------------------+ - | :kbd:`Control-L` | Refresh screen. | - +------------------+-------------------------------------------+ - | :kbd:`Control-N` | Cursor down; move down one line. | - +------------------+-------------------------------------------+ - | :kbd:`Control-O` | Insert a blank line at cursor location. | - +------------------+-------------------------------------------+ - | :kbd:`Control-P` | Cursor up; move up one line. | - +------------------+-------------------------------------------+ - - Move operations do nothing if the cursor is at an edge where the movement is not - possible. The following synonyms are supported where possible: - - +------------------------+------------------+ - | Constant | Keystroke | - +========================+==================+ - | :const:`KEY_LEFT` | :kbd:`Control-B` | - +------------------------+------------------+ - | :const:`KEY_RIGHT` | :kbd:`Control-F` | - +------------------------+------------------+ - | :const:`KEY_UP` | :kbd:`Control-P` | - +------------------------+------------------+ - | :const:`KEY_DOWN` | :kbd:`Control-N` | - +------------------------+------------------+ - | :const:`KEY_BACKSPACE` | :kbd:`Control-h` | - +------------------------+------------------+ - - All other keystrokes are treated as a command to insert the given character and - move right (with line wrapping). - - -.. method:: Textbox.gather() - - This method returns the window contents as a string; whether blanks in the - window are included is affected by the :attr:`stripspaces` member. - - -.. attribute:: Textbox.stripspaces - - This data member is a flag which controls the interpretation of blanks in the - window. When it is on, trailing blanks on each line are ignored; any cursor - motion that would land the cursor on a trailing blank goes to the end of that - line instead, and trailing blanks are stripped when the window contents are - gathered. + This is the entry point you will normally use. It accepts editing + keystrokes until one of the termination keystrokes is entered. If + *validator* is supplied, it must be a function. It will be called for + each keystroke entered with the keystroke as a parameter; command dispatch + is done on the result. This method returns the window contents as a + string; whether blanks in the window are included is affected by the + :attr:`stripspaces` member. + + + .. method:: do_command(ch) + + Process a single command keystroke. Here are the supported special + keystrokes: + + +------------------+-------------------------------------------+ + | Keystroke | Action | + +==================+===========================================+ + | :kbd:`Control-A` | Go to left edge of window. | + +------------------+-------------------------------------------+ + | :kbd:`Control-B` | Cursor left, wrapping to previous line if | + | | appropriate. | + +------------------+-------------------------------------------+ + | :kbd:`Control-D` | Delete character under cursor. | + +------------------+-------------------------------------------+ + | :kbd:`Control-E` | Go to right edge (stripspaces off) or end | + | | of line (stripspaces on). | + +------------------+-------------------------------------------+ + | :kbd:`Control-F` | Cursor right, wrapping to next line when | + | | appropriate. | + +------------------+-------------------------------------------+ + | :kbd:`Control-G` | Terminate, returning the window contents. | + +------------------+-------------------------------------------+ + | :kbd:`Control-H` | Delete character backward. | + +------------------+-------------------------------------------+ + | :kbd:`Control-J` | Terminate if the window is 1 line, | + | | otherwise insert newline. | + +------------------+-------------------------------------------+ + | :kbd:`Control-K` | If line is blank, delete it, otherwise | + | | clear to end of line. | + +------------------+-------------------------------------------+ + | :kbd:`Control-L` | Refresh screen. | + +------------------+-------------------------------------------+ + | :kbd:`Control-N` | Cursor down; move down one line. | + +------------------+-------------------------------------------+ + | :kbd:`Control-O` | Insert a blank line at cursor location. | + +------------------+-------------------------------------------+ + | :kbd:`Control-P` | Cursor up; move up one line. | + +------------------+-------------------------------------------+ + + Move operations do nothing if the cursor is at an edge where the movement + is not possible. The following synonyms are supported where possible: + + +------------------------+------------------+ + | Constant | Keystroke | + +========================+==================+ + | :const:`KEY_LEFT` | :kbd:`Control-B` | + +------------------------+------------------+ + | :const:`KEY_RIGHT` | :kbd:`Control-F` | + +------------------------+------------------+ + | :const:`KEY_UP` | :kbd:`Control-P` | + +------------------------+------------------+ + | :const:`KEY_DOWN` | :kbd:`Control-N` | + +------------------------+------------------+ + | :const:`KEY_BACKSPACE` | :kbd:`Control-h` | + +------------------------+------------------+ + + All other keystrokes are treated as a command to insert the given + character and move right (with line wrapping). + + + .. method:: gather() + + This method returns the window contents as a string; whether blanks in the + window are included is affected by the :attr:`stripspaces` member. + + + .. attribute:: stripspaces + + This data member is a flag which controls the interpretation of blanks in + the window. When it is on, trailing blanks on each line are ignored; any + cursor motion that would land the cursor on a trailing blank goes to the + end of that line instead, and trailing blanks are stripped when the window + contents are gathered. :mod:`curses.wrapper` --- Terminal handler for curses programs Modified: python/branches/py3k-ctypes-pep3118/Doc/library/datatypes.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/datatypes.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/datatypes.rst Wed Apr 30 15:57:13 2008 @@ -11,8 +11,8 @@ Python also provides some built-in data types, in particular, :class:`dict`, :class:`list`, :class:`set` and :class:`frozenset`, and -:class:`tuple`. The :class:`str` class can be used to handle binary data -and 8-bit text, and the :class:`unicode` class to handle Unicode text. +:class:`tuple`. The :class:`str` class is used to hold +Unicode strings, and the :class:`bytes` class is used to hold binary data. The following modules are documented in this chapter: @@ -29,7 +29,6 @@ mutex.rst queue.rst weakref.rst - userdict.rst types.rst copy.rst pprint.rst Modified: python/branches/py3k-ctypes-pep3118/Doc/library/datetime.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/datetime.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/datetime.rst Wed Apr 30 15:57:13 2008 @@ -157,7 +157,7 @@ :exc:`OverflowError` is raised. Note that normalization of negative values may be surprising at first. For - example, :: + example, >>> from datetime import timedelta >>> d = timedelta(microseconds=-1) @@ -263,7 +263,7 @@ efficient pickling, and in Boolean contexts, a :class:`timedelta` object is considered to be true if and only if it isn't equal to ``timedelta(0)``. -Example usage:: +Example usage: >>> from datetime import timedelta >>> year = timedelta(days=365) @@ -522,14 +522,16 @@ >>> time_to_birthday.days 202 -Example of working with :class:`date`:: +Example of working with :class:`date`: + +.. doctest:: >>> from datetime import date >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001 >>> d datetime.date(2002, 3, 11) >>> t = d.timetuple() - >>> for i in t: + >>> for i in t: # doctest: +SKIP ... print i 2002 # year 3 # month @@ -541,8 +543,8 @@ 70 # 70th day in the year -1 >>> ic = d.isocalendar() - >>> for i in ic: - ... print i # doctest: +SKIP + >>> for i in ic: # doctest: +SKIP + ... print i 2002 # ISO year 11 # ISO week number 1 # ISO day number ( 1 = Monday ) @@ -957,7 +959,7 @@ YYYY-MM-DDTHH:MM:SS+HH:MM The optional argument *sep* (default ``'T'``) is a one-character separator, - placed between the date and time portions of the result. For example, :: + placed between the date and time portions of the result. For example, >>> from datetime import tzinfo, timedelta, datetime >>> class TZ(tzinfo): @@ -987,8 +989,10 @@ Return a string representing the date and time, controlled by an explicit format string. See section :ref:`strftime-behavior`. -Examples of working with datetime objects:: - +Examples of working with datetime objects: + +.. doctest:: + >>> from datetime import datetime, date, time >>> # Using datetime.combine() >>> d = date(2005, 7, 14) @@ -996,9 +1000,9 @@ >>> datetime.combine(d, t) datetime.datetime(2005, 7, 14, 12, 30) >>> # Using datetime.now() or datetime.utcnow() - >>> datetime.now() + >>> datetime.now() # doctest: +SKIP datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1 - >>> datetime.utcnow() + >>> datetime.utcnow() # doctest: +SKIP datetime.datetime(2007, 12, 6, 15, 29, 43, 79060) >>> # Using datetime.strptime() >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") @@ -1006,7 +1010,7 @@ datetime.datetime(2006, 11, 21, 16, 30) >>> # Using datetime.timetuple() to get tuple of all attributes >>> tt = dt.timetuple() - >>> for it in tt: + >>> for it in tt: # doctest: +SKIP ... print it ... 2006 # year @@ -1020,7 +1024,7 @@ -1 # dst - method tzinfo.dst() returned None >>> # Date in ISO format >>> ic = dt.isocalendar() - >>> for it in ic: + >>> for it in ic: # doctest: +SKIP ... print it ... 2006 # ISO year @@ -1030,7 +1034,7 @@ >>> dt.strftime("%A, %d. %B %Y %I:%M%p") 'Tuesday, 21. November 2006 04:30PM' -Using datetime with tzinfo:: +Using datetime with tzinfo: >>> from datetime import timedelta, datetime, tzinfo >>> class GMT1(tzinfo): @@ -1232,7 +1236,7 @@ ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't return ``None`` or a string object. -Example:: +Example: >>> from datetime import time, tzinfo >>> class GMT1(tzinfo): @@ -1486,9 +1490,29 @@ be used, as time objects have no such values. If they're used anyway, ``1900`` is substituted for the year, and ``0`` for the month and day. -For :class:`date` objects, the format codes for hours, minutes, and seconds -should not be used, as :class:`date` objects have no such values. If they're -used anyway, ``0`` is substituted for them. +For :class:`date` objects, the format codes for hours, minutes, seconds, and +microseconds should not be used, as :class:`date` objects have no such +values. If they're used anyway, ``0`` is substituted for them. + +:class:`time` and :class:`datetime` objects support a ``%f`` format code +which expands to the number of microseconds in the object, zero-padded on +the left to six places. + +For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty +strings. + +For an aware object: + +``%z`` + :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or + -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and + MM is a 2-digit string giving the number of UTC offset minutes. For example, if + :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is + replaced with the string ``'-0330'``. + +``%Z`` + If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string. + Otherwise ``%Z`` is replaced by the returned value, which must be a string. The full set of format codes supported varies across platforms, because Python calls the platform C library's :func:`strftime` function, and platform @@ -1521,6 +1545,10 @@ | ``%d`` | Day of the month as a decimal | | | | number [01,31]. | | +-----------+--------------------------------+-------+ +| ``%f`` | Microsecond as a decimal | \(1) | +| | number [0,999999], zero-padded | | +| | on the left | | ++-----------+--------------------------------+-------+ | ``%H`` | Hour (24-hour clock) as a | | | | decimal number [00,23]. | | +-----------+--------------------------------+-------+ @@ -1536,13 +1564,13 @@ | ``%M`` | Minute as a decimal number | | | | [00,59]. | | +-----------+--------------------------------+-------+ -| ``%p`` | Locale's equivalent of either | \(1) | +| ``%p`` | Locale's equivalent of either | \(2) | | | AM or PM. | | +-----------+--------------------------------+-------+ -| ``%S`` | Second as a decimal number | \(2) | +| ``%S`` | Second as a decimal number | \(3) | | | [00,61]. | | +-----------+--------------------------------+-------+ -| ``%U`` | Week number of the year | \(3) | +| ``%U`` | Week number of the year | \(4) | | | (Sunday as the first day of | | | | the week) as a decimal number | | | | [00,53]. All days in a new | | @@ -1553,7 +1581,7 @@ | ``%w`` | Weekday as a decimal number | | | | [0(Sunday),6]. | | +-----------+--------------------------------+-------+ -| ``%W`` | Week number of the year | \(3) | +| ``%W`` | Week number of the year | \(4) | | | (Monday as the first day of | | | | the week) as a decimal number | | | | [00,53]. All days in a new | | @@ -1573,7 +1601,7 @@ | ``%Y`` | Year with century as a decimal | | | | number. | | +-----------+--------------------------------+-------+ -| ``%z`` | UTC offset in the form +HHMM | \(4) | +| ``%z`` | UTC offset in the form +HHMM | \(5) | | | or -HHMM (empty string if the | | | | the object is naive). | | +-----------+--------------------------------+-------+ @@ -1586,17 +1614,22 @@ Notes: (1) + When used with the :func:`strptime` function, the ``%f`` directive + accepts from one to six digits and zero pads on the right. ``%f`` is + an extension to the set of format characters in the C standard. + +(2) When used with the :func:`strptime` function, the ``%p`` directive only affects the output hour field if the ``%I`` directive is used to parse the hour. -(2) +(3) The range really is ``0`` to ``61``; this accounts for leap seconds and the (very rare) double leap seconds. -(3) +(4) When used with the :func:`strptime` function, ``%U`` and ``%W`` are only used in calculations when the day of the week and the year are specified. -(4) +(5) For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is replaced with the string ``'-0330'``. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/decimal.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/decimal.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/decimal.rst Wed Apr 30 15:57:13 2008 @@ -1,6 +1,6 @@ -:mod:`decimal` --- Decimal floating point arithmetic -==================================================== +:mod:`decimal` --- Decimal fixed point and floating point arithmetic +==================================================================== .. module:: decimal :synopsis: Implementation of the General Decimal Arithmetic Specification. @@ -12,10 +12,23 @@ .. moduleauthor:: Tim Peters .. sectionauthor:: Raymond D. Hettinger +.. import modules for testing inline doctests with the Sphinx doctest builder +.. testsetup:: * + + import decimal + import math + from decimal import * + # make sure each group gets a fresh context + setcontext(Context()) The :mod:`decimal` module provides support for decimal floating point arithmetic. It offers several advantages over the :class:`float` datatype: +* Decimal "is based on a floating-point model which was designed with people + in mind, and necessarily has a paramount guiding principle -- computers must + provide an arithmetic that works in the same way as the arithmetic that + people learn at school." -- excerpt from the decimal arithmetic specification. + * Decimal numbers can be represented exactly. In contrast, numbers like :const:`1.1` do not have an exact representation in binary floating point. End users typically would not expect :const:`1.1` to display as @@ -25,7 +38,7 @@ + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result is :const:`5.5511151231257827e-017`. While near to zero, the differences prevent reliable equality testing and differences can accumulate. For this - reason, decimal would be preferred in accounting applications which have strict + reason, decimal is preferred in accounting applications which have strict equality invariants. * The decimal module incorporates a notion of significant places so that ``1.30 @@ -37,19 +50,26 @@ * Unlike hardware based binary floating point, the decimal module has a user alterable precision (defaulting to 28 places) which can be as large as needed for - a given problem:: + a given problem: >>> getcontext().prec = 6 >>> Decimal(1) / Decimal(7) - Decimal("0.142857") + Decimal('0.142857') >>> getcontext().prec = 28 >>> Decimal(1) / Decimal(7) - Decimal("0.1428571428571428571428571429") + Decimal('0.1428571428571428571428571429') * Both binary and decimal floating point are implemented in terms of published standards. While the built-in float type exposes only a modest portion of its capabilities, the decimal module exposes all required parts of the standard. When needed, the programmer has full control over rounding and signal handling. + This includes an option to enforce exact arithmetic by using exceptions + to block any inexact operations. + +* The decimal module was designed to support "without prejudice, both exact + unrounded decimal arithmetic (sometimes called fixed-point arithmetic) + and rounded floating-point arithmetic." -- excerpt from the decimal + arithmetic specification. The module design is centered around three concepts: the decimal number, the context for arithmetic, and signals. @@ -75,7 +95,7 @@ :const:`Overflow`, and :const:`Underflow`. For each signal there is a flag and a trap enabler. When a signal is -encountered, its flag is incremented from zero and, then, if the trap enabler is +encountered, its flag is set to one, then, if the trap enabler is set to one, an exception is raised. Flags are sticky, so the user needs to reset them before monitoring a calculation. @@ -86,7 +106,7 @@ Specification `_. * IEEE standard 854-1987, `Unofficial IEEE 854 Text - `_. + `_. .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -103,8 +123,8 @@ >>> from decimal import * >>> getcontext() Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, - capitals=1, flags=[], traps=[Overflow, InvalidOperation, - DivisionByZero]) + capitals=1, flags=[], traps=[Overflow, DivisionByZero, + InvalidOperation]) >>> getcontext().prec = 7 # Set a new precision @@ -113,51 +133,56 @@ serves as an explicit reminder of the details of the conversion (including representation error). Decimal numbers include special values such as :const:`NaN` which stands for "Not a number", positive and negative -:const:`Infinity`, and :const:`-0`. :: +:const:`Infinity`, and :const:`-0`. >>> Decimal(10) - Decimal("10") - >>> Decimal("3.14") - Decimal("3.14") + Decimal('10') + >>> Decimal('3.14') + Decimal('3.14') >>> Decimal((0, (3, 1, 4), -2)) - Decimal("3.14") + Decimal('3.14') >>> Decimal(str(2.0 ** 0.5)) - Decimal("1.41421356237") - >>> Decimal(2) ** Decimal("0.5") - Decimal("1.414213562373095048801688724") - >>> Decimal("NaN") - Decimal("NaN") - >>> Decimal("-Infinity") - Decimal("-Infinity") + Decimal('1.41421356237') + >>> Decimal(2) ** Decimal('0.5') + Decimal('1.414213562373095048801688724') + >>> Decimal('NaN') + Decimal('NaN') + >>> Decimal('-Infinity') + Decimal('-Infinity') The significance of a new Decimal is determined solely by the number of digits input. Context precision and rounding only come into play during arithmetic -operations. :: +operations. + +.. doctest:: newcontext >>> getcontext().prec = 6 >>> Decimal('3.0') - Decimal("3.0") + Decimal('3.0') >>> Decimal('3.1415926535') - Decimal("3.1415926535") + Decimal('3.1415926535') >>> Decimal('3.1415926535') + Decimal('2.7182818285') - Decimal("5.85987") + Decimal('5.85987') >>> getcontext().rounding = ROUND_UP >>> Decimal('3.1415926535') + Decimal('2.7182818285') - Decimal("5.85988") + Decimal('5.85988') Decimals interact well with much of the rest of Python. Here is a small decimal -floating point flying circus:: +floating point flying circus: + +.. doctest:: + :options: +NORMALIZE_WHITESPACE >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split()) >>> max(data) - Decimal("9.25") + Decimal('9.25') >>> min(data) - Decimal("0.03") + Decimal('0.03') >>> sorted(data) - [Decimal("0.03"), Decimal("1.00"), Decimal("1.34"), Decimal("1.87"), - Decimal("2.35"), Decimal("3.45"), Decimal("9.25")] + [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'), + Decimal('2.35'), Decimal('3.45'), Decimal('9.25')] >>> sum(data) - Decimal("19.29") + Decimal('19.29') >>> a,b,c = data[:3] >>> str(a) '1.34' @@ -168,31 +193,31 @@ >>> int(a) 1 >>> a * 5 - Decimal("6.70") + Decimal('6.70') >>> a * b - Decimal("2.5058") + Decimal('2.5058') >>> c % a - Decimal("0.77") + Decimal('0.77') -And some mathematical functions are also available to Decimal:: +And some mathematical functions are also available to Decimal: >>> Decimal(2).sqrt() - Decimal("1.414213562373095048801688724") + Decimal('1.414213562373095048801688724') >>> Decimal(1).exp() - Decimal("2.718281828459045235360287471") - >>> Decimal("10").ln() - Decimal("2.302585092994045684017991455") - >>> Decimal("10").log10() - Decimal("1") + Decimal('2.718281828459045235360287471') + >>> Decimal('10').ln() + Decimal('2.302585092994045684017991455') + >>> Decimal('10').log10() + Decimal('1') The :meth:`quantize` method rounds a number to a fixed exponent. This method is useful for monetary applications that often round results to a fixed number of -places:: +places: >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN) - Decimal("7.32") + Decimal('7.32') >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP) - Decimal("8") + Decimal('8') As shown above, the :func:`getcontext` function accesses the current context and allows the settings to be changed. This approach meets the needs of most @@ -205,21 +230,24 @@ In accordance with the standard, the :mod:`Decimal` module provides two ready to use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The former is especially useful for debugging because many of the traps are -enabled:: +enabled: + +.. doctest:: newcontext + :options: +NORMALIZE_WHITESPACE >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN) >>> setcontext(myothercontext) >>> Decimal(1) / Decimal(7) - Decimal("0.142857142857142857142857142857142857142857142857142857142857") + Decimal('0.142857142857142857142857142857142857142857142857142857142857') >>> ExtendedContext Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, capitals=1, flags=[], traps=[]) >>> setcontext(ExtendedContext) >>> Decimal(1) / Decimal(7) - Decimal("0.142857143") + Decimal('0.142857143') >>> Decimal(42) / Decimal(0) - Decimal("Infinity") + Decimal('Infinity') >>> setcontext(BasicContext) >>> Decimal(42) / Decimal(0) @@ -236,20 +264,23 @@ >>> setcontext(ExtendedContext) >>> getcontext().clear_flags() >>> Decimal(355) / Decimal(113) - Decimal("3.14159292") + Decimal('3.14159292') >>> getcontext() Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, - capitals=1, flags=[Inexact, Rounded], traps=[]) + capitals=1, flags=[Rounded, Inexact], traps=[]) The *flags* entry shows that the rational approximation to :const:`Pi` was rounded (digits beyond the context precision were thrown away) and that the result is inexact (some of the discarded digits were non-zero). Individual traps are set using the dictionary in the :attr:`traps` field of a -context:: +context: +.. doctest:: newcontext + + >>> setcontext(ExtendedContext) >>> Decimal(1) / Decimal(0) - Decimal("Infinity") + Decimal('Infinity') >>> getcontext().traps[DivisionByZero] = 1 >>> Decimal(1) / Decimal(0) Traceback (most recent call last): @@ -277,7 +308,7 @@ Construct a new :class:`Decimal` object based from *value*. *value* can be an integer, string, tuple, or another :class:`Decimal` - object. If no *value* is given, returns ``Decimal("0")``. If *value* is a + object. If no *value* is given, returns ``Decimal('0')``. If *value* is a string, it should conform to the decimal numeric string syntax after leading and trailing whitespace characters are removed:: @@ -295,11 +326,11 @@ If *value* is a :class:`tuple`, it should have three components, a sign (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))`` - returns ``Decimal("1.414")``. + returns ``Decimal('1.414')``. The *context* precision does not affect how many digits are stored. That is determined exclusively by the number of digits in *value*. For example, - ``Decimal("3.00000")`` records all five zeros even if the context precision is + ``Decimal('3.00000')`` records all five zeros even if the context precision is only three. The purpose of the *context* argument is determining what to do if *value* is a @@ -309,448 +340,394 @@ Once constructed, :class:`Decimal` objects are immutable. - .. versionchanged:: 2.6 - leading and trailing whitespace characters are permitted when - creating a Decimal instance from a string. - -Decimal floating point objects share many properties with the other built-in -numeric types such as :class:`float` and :class:`int`. All of the usual math -operations and special methods apply. Likewise, decimal objects can be copied, -pickled, printed, used as dictionary keys, used as set elements, compared, -sorted, and converted to another type (such as :class:`float` or :class:`int`). - -In addition to the standard numeric properties, decimal floating point objects -also have a number of specialized methods: - - -.. method:: Decimal.adjusted() - - Return the adjusted exponent after shifting out the coefficient's rightmost - digits until only the lead digit remains: ``Decimal("321e+5").adjusted()`` - returns seven. Used for determining the position of the most significant digit - with respect to the decimal point. - - -.. method:: Decimal.as_tuple() - - Return a :term:`named tuple` representation of the number: - ``DecimalTuple(sign, digits, exponent)``. - - .. versionchanged:: 2.6 - Use a named tuple. - - -.. method:: Decimal.canonical() - - Return the canonical encoding of the argument. Currently, the - encoding of a :class:`Decimal` instance is always canonical, so - this operation returns its argument unchanged. - - -.. method:: Decimal.compare(other[, context]) - - Compare the values of two Decimal instances. This operation - behaves in the same way as the usual comparison method - :meth:`__cmp__`, except that :meth:`compare` returns a Decimal - instance rather than an integer, and if either operand is a NaN - then the result is a NaN:: - - a or b is a NaN ==> Decimal("NaN") - a < b ==> Decimal("-1") - a == b ==> Decimal("0") - a > b ==> Decimal("1") - -.. method:: Decimal.compare_signal(other[, context]) - - This operation is identical to the :meth:`compare` method, except - that all NaNs signal. That is, if neither operand is a signaling - NaN then any quiet NaN operand is treated as though it were a - signaling NaN. - - -.. method:: Decimal.compare_total(other) - - Compare two operands using their abstract representation rather - than their numerical value. Similar to the :meth:`compare` method, - but the result gives a total ordering on :class:`Decimal` - instances. Two :class:`Decimal` instances with the same numeric - value but different representations compare unequal in this - ordering:: - - >>> Decimal("12.0").compare_total(Decimal("12")) - Decimal("-1") - - Quiet and signaling NaNs are also included in the total ordering. - The result of this function is ``Decimal("0")`` if both operands - have the same representation, ``Decimal("-1")`` if the first - operand is lower in the total order than the second, and - ``Decimal("1")`` if the first operand is higher in the total order - than the second operand. See the specification for details of the - total order. - + Decimal floating point objects share many properties with the other built-in + numeric types such as :class:`float` and :class:`int`. All of the usual math + operations and special methods apply. Likewise, decimal objects can be + copied, pickled, printed, used as dictionary keys, used as set elements, + compared, sorted, and coerced to another type (such as :class:`float` or + :class:`long`). -.. method:: Decimal.compare_total_mag(other) + In addition to the standard numeric properties, decimal floating point + objects also have a number of specialized methods: - Compare two operands using their abstract representation rather - than their value as in :meth:`compare_total`, but ignoring the sign - of each operand. ``x.compare_total_mag(y)`` is equivalent to - ``x.copy_abs().compare_total(y.copy_abs())``. + .. method:: adjusted() -.. method:: Decimal.copy_abs() + Return the adjusted exponent after shifting out the coefficient's + rightmost digits until only the lead digit remains: + ``Decimal('321e+5').adjusted()`` returns seven. Used for determining the + position of the most significant digit with respect to the decimal point. - Return the absolute value of the argument. This operation is - unaffected by the context and is quiet: no flags are changed and no - rounding is performed. + .. method:: as_tuple() -.. method:: Decimal.copy_negate() + Return a :term:`named tuple` representation of the number: + ``DecimalTuple(sign, digits, exponent)``. - Return the negation of the argument. This operation is unaffected - by the context and is quiet: no flags are changed and no rounding - is performed. + .. method:: canonical() -.. method:: Decimal.copy_sign(other) + Return the canonical encoding of the argument. Currently, the encoding of + a :class:`Decimal` instance is always canonical, so this operation returns + its argument unchanged. - Return a copy of the first operand with the sign set to be the - same as the sign of the second operand. For example:: + .. method:: compare(other[, context]) - >>> Decimal("2.3").copy_sign(Decimal("-1.5")) - Decimal("-2.3") - - This operation is unaffected by the context and is quiet: no flags - are changed and no rounding is performed. + Compare the values of two Decimal instances. This operation behaves in + the same way as the usual comparison method :meth:`__cmp__`, except that + :meth:`compare` returns a Decimal instance rather than an integer, and if + either operand is a NaN then the result is a NaN:: + a or b is a NaN ==> Decimal('NaN') + a < b ==> Decimal('-1') + a == b ==> Decimal('0') + a > b ==> Decimal('1') -.. method:: Decimal.exp([context]) + .. method:: compare_signal(other[, context]) - Return the value of the (natural) exponential function ``e**x`` at the - given number. The result is correctly rounded using the - :const:`ROUND_HALF_EVEN` rounding mode. + This operation is identical to the :meth:`compare` method, except that all + NaNs signal. That is, if neither operand is a signaling NaN then any + quiet NaN operand is treated as though it were a signaling NaN. - >>> Decimal(1).exp() - Decimal("2.718281828459045235360287471") - >>> Decimal(321).exp() - Decimal("2.561702493119680037517373933E+139") - - -.. method:: Decimal.fma(other, third[, context]) - - Fused multiply-add. Return self*other+third with no rounding of - the intermediate product self*other. - - >>> Decimal(2).fma(3, 5) - Decimal("11") - - -.. method:: Decimal.is_canonical() - - Return :const:`True` if the argument is canonical and - :const:`False` otherwise. Currently, a :class:`Decimal` instance - is always canonical, so this operation always returns - :const:`True`. + .. method:: compare_total(other) + Compare two operands using their abstract representation rather than their + numerical value. Similar to the :meth:`compare` method, but the result + gives a total ordering on :class:`Decimal` instances. Two + :class:`Decimal` instances with the same numeric value but different + representations compare unequal in this ordering: -.. method:: is_finite() + >>> Decimal('12.0').compare_total(Decimal('12')) + Decimal('-1') - Return :const:`True` if the argument is a finite number, and - :const:`False` if the argument is an infinity or a NaN. + Quiet and signaling NaNs are also included in the total ordering. The + result of this function is ``Decimal('0')`` if both operands have the same + representation, ``Decimal('-1')`` if the first operand is lower in the + total order than the second, and ``Decimal('1')`` if the first operand is + higher in the total order than the second operand. See the specification + for details of the total order. + .. method:: compare_total_mag(other) -.. method:: is_infinite() + Compare two operands using their abstract representation rather than their + value as in :meth:`compare_total`, but ignoring the sign of each operand. + ``x.compare_total_mag(y)`` is equivalent to + ``x.copy_abs().compare_total(y.copy_abs())``. - Return :const:`True` if the argument is either positive or - negative infinity and :const:`False` otherwise. + .. method:: copy_abs() + Return the absolute value of the argument. This operation is unaffected + by the context and is quiet: no flags are changed and no rounding is + performed. -.. method:: is_nan() + .. method:: copy_negate() - Return :const:`True` if the argument is a (quiet or signaling) - NaN and :const:`False` otherwise. + Return the negation of the argument. This operation is unaffected by the + context and is quiet: no flags are changed and no rounding is performed. + .. method:: copy_sign(other) -.. method:: is_normal() + Return a copy of the first operand with the sign set to be the same as the + sign of the second operand. For example: - Return :const:`True` if the argument is a *normal* finite number. - Return :const:`False` if the argument is zero, subnormal, infinite - or a NaN. + >>> Decimal('2.3').copy_sign(Decimal('-1.5')) + Decimal('-2.3') + This operation is unaffected by the context and is quiet: no flags are + changed and no rounding is performed. -.. method:: is_qnan() + .. method:: exp([context]) - Return :const:`True` if the argument is a quiet NaN, and - :const:`False` otherwise. + Return the value of the (natural) exponential function ``e**x`` at the + given number. The result is correctly rounded using the + :const:`ROUND_HALF_EVEN` rounding mode. + >>> Decimal(1).exp() + Decimal('2.718281828459045235360287471') + >>> Decimal(321).exp() + Decimal('2.561702493119680037517373933E+139') -.. method:: is_signed() + .. method:: fma(other, third[, context]) - Return :const:`True` if the argument has a negative sign and - :const:`False` otherwise. Note that zeros and NaNs can both carry - signs. + Fused multiply-add. Return self*other+third with no rounding of the + intermediate product self*other. + >>> Decimal(2).fma(3, 5) + Decimal('11') -.. method:: is_snan() + .. method:: is_canonical() - Return :const:`True` if the argument is a signaling NaN and - :const:`False` otherwise. + Return :const:`True` if the argument is canonical and :const:`False` + otherwise. Currently, a :class:`Decimal` instance is always canonical, so + this operation always returns :const:`True`. + .. method:: is_finite() -.. method:: is_subnormal() + Return :const:`True` if the argument is a finite number, and + :const:`False` if the argument is an infinity or a NaN. - Return :const:`True` if the argument is subnormal, and - :const:`False` otherwise. + .. method:: is_infinite() + Return :const:`True` if the argument is either positive or negative + infinity and :const:`False` otherwise. -.. method:: is_zero() + .. method:: is_nan() - Return :const:`True` if the argument is a (positive or negative) - zero and :const:`False` otherwise. + Return :const:`True` if the argument is a (quiet or signaling) NaN and + :const:`False` otherwise. + .. method:: is_normal() -.. method:: Decimal.ln([context]) + Return :const:`True` if the argument is a *normal* finite number. Return + :const:`False` if the argument is zero, subnormal, infinite or a NaN. - Return the natural (base e) logarithm of the operand. The result - is correctly rounded using the :const:`ROUND_HALF_EVEN` rounding - mode. + .. method:: is_qnan() + Return :const:`True` if the argument is a quiet NaN, and + :const:`False` otherwise. -.. method:: Decimal.log10([context]) + .. method:: is_signed() - Return the base ten logarithm of the operand. The result is - correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode. + Return :const:`True` if the argument has a negative sign and + :const:`False` otherwise. Note that zeros and NaNs can both carry signs. + .. method:: is_snan() -.. method:: Decimal.logb([context]) + Return :const:`True` if the argument is a signaling NaN and :const:`False` + otherwise. - For a nonzero number, return the adjusted exponent of its operand - as a :class:`Decimal` instance. If the operand is a zero then - ``Decimal("-Infinity")`` is returned and the - :const:`DivisionByZero` flag is raised. If the operand is an - infinity then ``Decimal("Infinity")`` is returned. + .. method:: is_subnormal() + Return :const:`True` if the argument is subnormal, and :const:`False` + otherwise. -.. method:: Decimal.logical_and(other[, context]) + .. method:: is_zero() - :meth:`logical_and` is a logical operation which takes two - *logical operands* (see :ref:`logical_operands_label`). The result - is the digit-wise ``and`` of the two operands. + Return :const:`True` if the argument is a (positive or negative) zero and + :const:`False` otherwise. + .. method:: ln([context]) -.. method:: Decimal.logical_invert(other[, context]) + Return the natural (base e) logarithm of the operand. The result is + correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode. - :meth:`logical_invert` is a logical operation. The argument must - be a *logical operand* (see :ref:`logical_operands_label`). The - result is the digit-wise inversion of the operand. + .. method:: log10([context]) + Return the base ten logarithm of the operand. The result is correctly + rounded using the :const:`ROUND_HALF_EVEN` rounding mode. -.. method:: Decimal.logical_or(other[, context]) + .. method:: logb([context]) - :meth:`logical_or` is a logical operation which takes two *logical - operands* (see :ref:`logical_operands_label`). The result is the - digit-wise ``or`` of the two operands. + For a nonzero number, return the adjusted exponent of its operand as a + :class:`Decimal` instance. If the operand is a zero then + ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag + is raised. If the operand is an infinity then ``Decimal('Infinity')`` is + returned. + .. method:: logical_and(other[, context]) -.. method:: Decimal.logical_xor(other[, context]) + :meth:`logical_and` is a logical operation which takes two *logical + operands* (see :ref:`logical_operands_label`). The result is the + digit-wise ``and`` of the two operands. - :meth:`logical_xor` is a logical operation which takes two - *logical operands* (see :ref:`logical_operands_label`). The result - is the digit-wise exclusive or of the two operands. + .. method:: logical_invert(other[, context]) + :meth:`logical_invert` is a logical operation. The argument must + be a *logical operand* (see :ref:`logical_operands_label`). The + result is the digit-wise inversion of the operand. -.. method:: Decimal.max(other[, context]) + .. method:: logical_or(other[, context]) - Like ``max(self, other)`` except that the context rounding rule is applied - before returning and that :const:`NaN` values are either signaled or ignored - (depending on the context and whether they are signaling or quiet). + :meth:`logical_or` is a logical operation which takes two *logical + operands* (see :ref:`logical_operands_label`). The result is the + digit-wise ``or`` of the two operands. + .. method:: logical_xor(other[, context]) -.. method:: Decimal.max_mag(other[, context]) + :meth:`logical_xor` is a logical operation which takes two *logical + operands* (see :ref:`logical_operands_label`). The result is the + digit-wise exclusive or of the two operands. - Similar to the :meth:`max` method, but the comparison is done using - the absolute values of the operands. + .. method:: max(other[, context]) + Like ``max(self, other)`` except that the context rounding rule is applied + before returning and that :const:`NaN` values are either signaled or + ignored (depending on the context and whether they are signaling or + quiet). -.. method:: Decimal.min(other[, context]) + .. method:: max_mag(other[, context]) - Like ``min(self, other)`` except that the context rounding rule is applied - before returning and that :const:`NaN` values are either signaled or ignored - (depending on the context and whether they are signaling or quiet). + Similar to the :meth:`max` method, but the comparison is done using the + absolute values of the operands. -.. method:: Decimal.min_mag(other[, context]) + .. method:: min(other[, context]) - Similar to the :meth:`min` method, but the comparison is done using - the absolute values of the operands. + Like ``min(self, other)`` except that the context rounding rule is applied + before returning and that :const:`NaN` values are either signaled or + ignored (depending on the context and whether they are signaling or + quiet). + .. method:: min_mag(other[, context]) -.. method:: Decimal.next_minus([context]) + Similar to the :meth:`min` method, but the comparison is done using the + absolute values of the operands. - Return the largest number representable in the given context (or - in the current thread's context if no context is given) that is smaller - than the given operand. + .. method:: next_minus([context]) + Return the largest number representable in the given context (or in the + current thread's context if no context is given) that is smaller than the + given operand. -.. method:: Decimal.next_plus([context]) + .. method:: next_plus([context]) - Return the smallest number representable in the given context (or - in the current thread's context if no context is given) that is - larger than the given operand. + Return the smallest number representable in the given context (or in the + current thread's context if no context is given) that is larger than the + given operand. + .. method:: next_toward(other[, context]) -.. method:: Decimal.next_toward(other[, context]) + If the two operands are unequal, return the number closest to the first + operand in the direction of the second operand. If both operands are + numerically equal, return a copy of the first operand with the sign set to + be the same as the sign of the second operand. - If the two operands are unequal, return the number closest to the - first operand in the direction of the second operand. If both - operands are numerically equal, return a copy of the first operand - with the sign set to be the same as the sign of the second operand. + .. method:: normalize([context]) + Normalize the number by stripping the rightmost trailing zeros and + converting any result equal to :const:`Decimal('0')` to + :const:`Decimal('0e0')`. Used for producing canonical values for members + of an equivalence class. For example, ``Decimal('32.100')`` and + ``Decimal('0.321000e+2')`` both normalize to the equivalent value + ``Decimal('32.1')``. -.. method:: Decimal.normalize([context]) + .. method:: number_class([context]) - Normalize the number by stripping the rightmost trailing zeros and converting - any result equal to :const:`Decimal("0")` to :const:`Decimal("0e0")`. Used for - producing canonical values for members of an equivalence class. For example, - ``Decimal("32.100")`` and ``Decimal("0.321000e+2")`` both normalize to the - equivalent value ``Decimal("32.1")``. + Return a string describing the *class* of the operand. The returned value + is one of the following ten strings. + * ``"-Infinity"``, indicating that the operand is negative infinity. + * ``"-Normal"``, indicating that the operand is a negative normal number. + * ``"-Subnormal"``, indicating that the operand is negative and subnormal. + * ``"-Zero"``, indicating that the operand is a negative zero. + * ``"+Zero"``, indicating that the operand is a positive zero. + * ``"+Subnormal"``, indicating that the operand is positive and subnormal. + * ``"+Normal"``, indicating that the operand is a positive normal number. + * ``"+Infinity"``, indicating that the operand is positive infinity. + * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number). + * ``"sNaN"``, indicating that the operand is a signaling NaN. -.. method:: Decimal.number_class([context]) + .. method:: quantize(exp[, rounding[, context[, watchexp]]]) - Return a string describing the *class* of the operand. The - returned value is one of the following ten strings. + Return a value equal to the first operand after rounding and having the + exponent of the second operand. - * ``"-Infinity"``, indicating that the operand is negative infinity. - * ``"-Normal"``, indicating that the operand is a negative normal number. - * ``"-Subnormal"``, indicating that the operand is negative and subnormal. - * ``"-Zero"``, indicating that the operand is a negative zero. - * ``"+Zero"``, indicating that the operand is a positive zero. - * ``"+Subnormal"``, indicating that the operand is positive and subnormal. - * ``"+Normal"``, indicating that the operand is a positive normal number. - * ``"+Infinity"``, indicating that the operand is positive infinity. - * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number). - * ``"sNaN"``, indicating that the operand is a signaling NaN. + >>> Decimal('1.41421356').quantize(Decimal('1.000')) + Decimal('1.414') + Unlike other operations, if the length of the coefficient after the + quantize operation would be greater than precision, then an + :const:`InvalidOperation` is signaled. This guarantees that, unless there + is an error condition, the quantized exponent is always equal to that of + the right-hand operand. -.. method:: Decimal.quantize(exp[, rounding[, context[, watchexp]]]) + Also unlike other operations, quantize never signals Underflow, even if + the result is subnormal and inexact. - Return a value equal to the first operand after rounding and - having the exponent of the second operand. + If the exponent of the second operand is larger than that of the first + then rounding may be necessary. In this case, the rounding mode is + determined by the ``rounding`` argument if given, else by the given + ``context`` argument; if neither argument is given the rounding mode of + the current thread's context is used. - >>> Decimal("1.41421356").quantize(Decimal("1.000")) - Decimal("1.414") + If *watchexp* is set (default), then an error is returned whenever the + resulting exponent is greater than :attr:`Emax` or less than + :attr:`Etiny`. - Unlike other operations, if the length of the coefficient after the - quantize operation would be greater than precision, then an - :const:`InvalidOperation` is signaled. This guarantees that, unless - there is an error condition, the quantized exponent is always equal - to that of the right-hand operand. + .. method:: radix() - Also unlike other operations, quantize never signals Underflow, - even if the result is subnormal and inexact. + Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal` + class does all its arithmetic. Included for compatibility with the + specification. - If the exponent of the second operand is larger than that of the - first then rounding may be necessary. In this case, the rounding - mode is determined by the ``rounding`` argument if given, else by - the given ``context`` argument; if neither argument is given the - rounding mode of the current thread's context is used. + .. method:: remainder_near(other[, context]) - If *watchexp* is set (default), then an error is returned whenever the - resulting exponent is greater than :attr:`Emax` or less than :attr:`Etiny`. + Compute the modulo as either a positive or negative value depending on + which is closest to zero. For instance, ``Decimal(10).remainder_near(6)`` + returns ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``. -.. method:: Decimal.radix() + If both are equally close, the one chosen will have the same sign as + *self*. - Return ``Decimal(10)``, the radix (base) in which the - :class:`Decimal` class does all its arithmetic. Included for - compatibility with the specification. + .. method:: rotate(other[, context]) + Return the result of rotating the digits of the first operand by an amount + specified by the second operand. The second operand must be an integer in + the range -precision through precision. The absolute value of the second + operand gives the number of places to rotate. If the second operand is + positive then rotation is to the left; otherwise rotation is to the right. + The coefficient of the first operand is padded on the left with zeros to + length precision if necessary. The sign and exponent of the first operand + are unchanged. -.. method:: Decimal.remainder_near(other[, context]) - - Compute the modulo as either a positive or negative value depending on which is - closest to zero. For instance, ``Decimal(10).remainder_near(6)`` returns - ``Decimal("-2")`` which is closer to zero than ``Decimal("4")``. - - If both are equally close, the one chosen will have the same sign as *self*. - -.. method:: Decimal.rotate(other[, context]) - - Return the result of rotating the digits of the first operand by - an amount specified by the second operand. The second operand - must be an integer in the range -precision through precision. The - absolute value of the second operand gives the number of places to - rotate. If the second operand is positive then rotation is to the - left; otherwise rotation is to the right. The coefficient of the - first operand is padded on the left with zeros to length precision - if necessary. The sign and exponent of the first operand are - unchanged. - - -.. method:: Decimal.same_quantum(other[, context]) - - Test whether self and other have the same exponent or whether both are - :const:`NaN`. + .. method:: same_quantum(other[, context]) -.. method:: Decimal.scaleb(other[, context]) + Test whether self and other have the same exponent or whether both are + :const:`NaN`. - Return the first operand with exponent adjusted by the second. - Equivalently, return the first operand multiplied by ``10**other``. - The second operand must be an integer. + .. method:: scaleb(other[, context]) + Return the first operand with exponent adjusted by the second. + Equivalently, return the first operand multiplied by ``10**other``. The + second operand must be an integer. -.. method:: Decimal.shift(other[, context]) + .. method:: shift(other[, context]) - Return the result of shifting the digits of the first operand by - an amount specified by the second operand. The second operand must - be an integer in the range -precision through precision. The - absolute value of the second operand gives the number of places to - shift. If the second operand is positive then the shift is to the - left; otherwise the shift is to the right. Digits shifted into the - coefficient are zeros. The sign and exponent of the first operand - are unchanged. + Return the result of shifting the digits of the first operand by an amount + specified by the second operand. The second operand must be an integer in + the range -precision through precision. The absolute value of the second + operand gives the number of places to shift. If the second operand is + positive then the shift is to the left; otherwise the shift is to the + right. Digits shifted into the coefficient are zeros. The sign and + exponent of the first operand are unchanged. + .. method:: sqrt([context]) -.. method:: Decimal.sqrt([context]) + Return the square root of the argument to full precision. - Return the square root of the argument to full precision. + .. method:: to_eng_string([context]) -.. method:: Decimal.to_eng_string([context]) + Convert to an engineering-type string. - Convert to an engineering-type string. + Engineering notation has an exponent which is a multiple of 3, so there + are up to 3 digits left of the decimal place. For example, converts + ``Decimal('123E+1')`` to ``Decimal('1.23E+3')`` - Engineering notation has an exponent which is a multiple of 3, so there are up - to 3 digits left of the decimal place. For example, converts - ``Decimal('123E+1')`` to ``Decimal("1.23E+3")`` + .. method:: to_integral([rounding[, context]]) -.. method:: Decimal.to_integral([rounding[, context]]) + Identical to the :meth:`to_integral_value` method. The ``to_integral`` + name has been kept for compatibility with older versions. - Identical to the :meth:`to_integral_value` method. The ``to_integral`` - name has been kept for compatibility with older versions. + .. method:: to_integral_exact([rounding[, context]]) -.. method:: Decimal.to_integral_exact([rounding[, context]]) + Round to the nearest integer, signaling :const:`Inexact` or + :const:`Rounded` as appropriate if rounding occurs. The rounding mode is + determined by the ``rounding`` parameter if given, else by the given + ``context``. If neither parameter is given then the rounding mode of the + current context is used. - Round to the nearest integer, signaling - :const:`Inexact` or :const:`Rounded` as appropriate if rounding - occurs. The rounding mode is determined by the ``rounding`` - parameter if given, else by the given ``context``. If neither - parameter is given then the rounding mode of the current context is - used. + .. method:: to_integral_value([rounding[, context]]) + Round to the nearest integer without signaling :const:`Inexact` or + :const:`Rounded`. If given, applies *rounding*; otherwise, uses the + rounding method in either the supplied *context* or the current context. -.. method:: Decimal.to_integral_value([rounding[, context]]) + .. method:: trim() - Round to the nearest integer without signaling :const:`Inexact` or - :const:`Rounded`. If given, applies *rounding*; otherwise, uses the rounding - method in either the supplied *context* or the current context. - - -.. method:: Decimal.trim() - - Return the decimal with *insignificant* trailing zeros removed. - Here, a trailing zero is considered insignificant either if it - follows the decimal point, or if the exponent of the argument (that - is, the last element of the :meth:`as_tuple` representation) is - positive. + Return the decimal with *insignificant* trailing zeros removed. Here, a + trailing zero is considered insignificant either if it follows the decimal + point, or if the exponent of the argument (that is, the last element of + the :meth:`as_tuple` representation) is positive. .. _logical_operands_label: @@ -832,7 +809,7 @@ :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that exceptions are not raised during computations). - Because the trapped are disabled, this context is useful for applications that + Because the traps are disabled, this context is useful for applications that prefer to have result value of :const:`NaN` or :const:`Infinity` instead of raising exceptions. This allows an application to complete a run in the presence of conditions that would otherwise halt the program. @@ -891,148 +868,147 @@ lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`. -The :class:`Context` class defines several general purpose methods as -well as a large number of methods for doing arithmetic directly in a -given context. In addition, for each of the :class:`Decimal` methods -described above (with the exception of the :meth:`adjusted` and -:meth:`as_tuple` methods) there is a corresponding :class:`Context` -method. For example, ``C.exp(x)`` is equivalent to -``x.exp(context=C)``. + The :class:`Context` class defines several general purpose methods as well as + a large number of methods for doing arithmetic directly in a given context. + In addition, for each of the :class:`Decimal` methods described above (with + the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is + a corresponding :class:`Context` method. For example, ``C.exp(x)`` is + equivalent to ``x.exp(context=C)``. -.. method:: Context.clear_flags() - Resets all of the flags to :const:`0`. + .. method:: clear_flags() + Resets all of the flags to :const:`0`. -.. method:: Context.copy() + .. method:: copy() - Return a duplicate of the context. + Return a duplicate of the context. -.. method:: Context.copy_decimal(num) + .. method:: copy_decimal(num) - Return a copy of the Decimal instance num. + Return a copy of the Decimal instance num. -.. method:: Context.create_decimal(num) + .. method:: create_decimal(num) - Creates a new Decimal instance from *num* but using *self* as context. Unlike - the :class:`Decimal` constructor, the context precision, rounding method, flags, - and traps are applied to the conversion. + Creates a new Decimal instance from *num* but using *self* as + context. Unlike the :class:`Decimal` constructor, the context precision, + rounding method, flags, and traps are applied to the conversion. - This is useful because constants are often given to a greater precision than is - needed by the application. Another benefit is that rounding immediately - eliminates unintended effects from digits beyond the current precision. In the - following example, using unrounded inputs means that adding zero to a sum can - change the result:: + This is useful because constants are often given to a greater precision + than is needed by the application. Another benefit is that rounding + immediately eliminates unintended effects from digits beyond the current + precision. In the following example, using unrounded inputs means that + adding zero to a sum can change the result: - >>> getcontext().prec = 3 - >>> Decimal("3.4445") + Decimal("1.0023") - Decimal("4.45") - >>> Decimal("3.4445") + Decimal(0) + Decimal("1.0023") - Decimal("4.44") + .. doctest:: newcontext - This method implements the to-number operation of the IBM - specification. If the argument is a string, no leading or trailing - whitespace is permitted. + >>> getcontext().prec = 3 + >>> Decimal('3.4445') + Decimal('1.0023') + Decimal('4.45') + >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023') + Decimal('4.44') -.. method:: Context.Etiny() + This method implements the to-number operation of the IBM specification. + If the argument is a string, no leading or trailing whitespace is + permitted. - Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent value - for subnormal results. When underflow occurs, the exponent is set to - :const:`Etiny`. + .. method:: Etiny() + Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent + value for subnormal results. When underflow occurs, the exponent is set + to :const:`Etiny`. -.. method:: Context.Etop() - Returns a value equal to ``Emax - prec + 1``. + .. method:: Etop() -The usual approach to working with decimals is to create :class:`Decimal` -instances and then apply arithmetic operations which take place within the -current context for the active thread. An alternative approach is to use context -methods for calculating within a specific context. The methods are similar to -those for the :class:`Decimal` class and are only briefly recounted here. + Returns a value equal to ``Emax - prec + 1``. + The usual approach to working with decimals is to create :class:`Decimal` + instances and then apply arithmetic operations which take place within the + current context for the active thread. An alternative approach is to use + context methods for calculating within a specific context. The methods are + similar to those for the :class:`Decimal` class and are only briefly + recounted here. -.. method:: Context.abs(x) - Returns the absolute value of *x*. + .. method:: abs(x) + Returns the absolute value of *x*. -.. method:: Context.add(x, y) - Return the sum of *x* and *y*. + .. method:: add(x, y) + Return the sum of *x* and *y*. -.. method:: Context.divide(x, y) - Return *x* divided by *y*. + .. method:: divide(x, y) + Return *x* divided by *y*. -.. method:: Context.divide_int(x, y) - Return *x* divided by *y*, truncated to an integer. + .. method:: divide_int(x, y) + Return *x* divided by *y*, truncated to an integer. -.. method:: Context.divmod(x, y) - Divides two numbers and returns the integer part of the result. + .. method:: divmod(x, y) + Divides two numbers and returns the integer part of the result. -.. method:: Context.minus(x) - Minus corresponds to the unary prefix minus operator in Python. + .. method:: minus(x) + Minus corresponds to the unary prefix minus operator in Python. -.. method:: Context.multiply(x, y) - Return the product of *x* and *y*. + .. method:: multiply(x, y) + Return the product of *x* and *y*. -.. method:: Context.plus(x) - Plus corresponds to the unary prefix plus operator in Python. This operation - applies the context precision and rounding, so it is *not* an identity - operation. + .. method:: plus(x) + Plus corresponds to the unary prefix plus operator in Python. This + operation applies the context precision and rounding, so it is *not* an + identity operation. -.. method:: Context.power(x, y[, modulo]) - Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if - given. + .. method:: power(x, y[, modulo]) - With two arguments, compute ``x**y``. If ``x`` is negative then - ``y`` must be integral. The result will be inexact unless ``y`` is - integral and the result is finite and can be expressed exactly in - 'precision' digits. The result should always be correctly rounded, - using the rounding mode of the current thread's context. + Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given. - With three arguments, compute ``(x**y) % modulo``. For the three - argument form, the following restrictions on the arguments hold: + With two arguments, compute ``x**y``. If ``x`` is negative then ``y`` + must be integral. The result will be inexact unless ``y`` is integral and + the result is finite and can be expressed exactly in 'precision' digits. + The result should always be correctly rounded, using the rounding mode of + the current thread's context. - - all three arguments must be integral - - ``y`` must be nonnegative - - at least one of ``x`` or ``y`` must be nonzero - - ``modulo`` must be nonzero and have at most 'precision' digits + With three arguments, compute ``(x**y) % modulo``. For the three argument + form, the following restrictions on the arguments hold: - The result of ``Context.power(x, y, modulo)`` is identical to - the result that would be obtained by computing ``(x**y) % - modulo`` with unbounded precision, but is computed more - efficiently. It is always exact. + - all three arguments must be integral + - ``y`` must be nonnegative + - at least one of ``x`` or ``y`` must be nonzero + - ``modulo`` must be nonzero and have at most 'precision' digits + The result of ``Context.power(x, y, modulo)`` is identical to the result + that would be obtained by computing ``(x**y) % modulo`` with unbounded + precision, but is computed more efficiently. It is always exact. -.. method:: Context.remainder(x, y) + .. method:: remainder(x, y) - Returns the remainder from integer division. + Returns the remainder from integer division. - The sign of the result, if non-zero, is the same as that of the original - dividend. + The sign of the result, if non-zero, is the same as that of the original + dividend. -.. method:: Context.subtract(x, y) + .. method:: subtract(x, y) - Return the difference between *x* and *y*. + Return the difference between *x* and *y*. -.. method:: Context.to_sci_string(x) + .. method:: to_sci_string(x) - Converts a number to a string using scientific notation. + Converts a number to a string using scientific notation. .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -1045,7 +1021,7 @@ Signals represent conditions that arise during computation. Each corresponds to one context flag and one context trap enabler. -The context flag is incremented whenever the condition is encountered. After the +The context flag is set whenever the condition is encountered. After the computation, flags may be checked for informational purposes (for instance, to determine whether a computation was exact). After checking the flags, be sure to clear all flags before starting the next computation. @@ -1111,28 +1087,29 @@ Numerical overflow. - Indicates the exponent is larger than :attr:`Emax` after rounding has occurred. - If not trapped, the result depends on the rounding mode, either pulling inward - to the largest representable finite number or rounding outward to - :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded` are - also signaled. + Indicates the exponent is larger than :attr:`Emax` after rounding has + occurred. If not trapped, the result depends on the rounding mode, either + pulling inward to the largest representable finite number or rounding outward + to :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded` + are also signaled. .. class:: Rounded Rounding occurred though possibly no information was lost. - Signaled whenever rounding discards digits; even if those digits are zero (such - as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns the result - unchanged. This signal is used to detect loss of significant digits. + Signaled whenever rounding discards digits; even if those digits are zero + (such as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns + the result unchanged. This signal is used to detect loss of significant + digits. .. class:: Subnormal Exponent was lower than :attr:`Emin` prior to rounding. - Occurs when an operation result is subnormal (the exponent is too small). If not - trapped, returns the result unchanged. + Occurs when an operation result is subnormal (the exponent is too small). If + not trapped, returns the result unchanged. .. class:: Underflow @@ -1175,7 +1152,9 @@ of nearly offsetting quantities resulting in loss of significance. Knuth provides two instructive examples where rounded floating point arithmetic with insufficient precision causes the breakdown of the associative and distributive -properties of addition:: +properties of addition: + +.. doctest:: newcontext # Examples from Seminumerical Algorithms, Section 4.2.2. >>> from decimal import Decimal, getcontext @@ -1183,31 +1162,33 @@ >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111') >>> (u + v) + w - Decimal("9.5111111") + Decimal('9.5111111') >>> u + (v + w) - Decimal("10") + Decimal('10') >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003') >>> (u*v) + (u*w) - Decimal("0.01") + Decimal('0.01') >>> u * (v+w) - Decimal("0.0060000") + Decimal('0.0060000') The :mod:`decimal` module makes it possible to restore the identities by -expanding the precision sufficiently to avoid loss of significance:: +expanding the precision sufficiently to avoid loss of significance: + +.. doctest:: newcontext >>> getcontext().prec = 20 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111') >>> (u + v) + w - Decimal("9.51111111") + Decimal('9.51111111') >>> u + (v + w) - Decimal("9.51111111") + Decimal('9.51111111') >>> >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003') >>> (u*v) + (u*w) - Decimal("0.0060000") + Decimal('0.0060000') >>> u * (v+w) - Decimal("0.0060000") + Decimal('0.0060000') Special values @@ -1238,6 +1219,19 @@ operation. This is a useful return value when an invalid result needs to interrupt a calculation for special handling. +The behavior of Python's comparison operators can be a little surprising where a +:const:`NaN` is involved. A test for equality where one of the operands is a +quiet or signaling :const:`NaN` always returns :const:`False` (even when doing +``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns +:const:`True`. An attempt to compare two Decimals using any of the ``<``, +``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal +if either operand is a :const:`NaN`, and return :const:`False` if this signal is +not trapped. Note that the General Decimal Arithmetic specification does not +specify the behavior of direct comparisons; these rules for comparisons +involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in +section 5.7). To ensure strict standards-compliance, use the :meth:`compare` +and :meth:`compare-signal` methods instead. + The signed zeros can result from calculations that underflow. They keep the sign that would have resulted if the calculation had been carried out to greater precision. Since their magnitude is zero, both positive and negative zeros are @@ -1247,10 +1241,10 @@ various representations of zero with differing precisions yet equivalent in value. This takes a bit of getting used to. For an eye accustomed to normalized floating point representations, it is not immediately obvious that -the following calculation returns a value equal to zero:: +the following calculation returns a value equal to zero: >>> 1 / Decimal('Infinity') - Decimal("0E-1000000026") + Decimal('0E-1000000026') .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -1324,23 +1318,21 @@ >>> moneyfmt(Decimal(123456789), sep=' ') '123 456 789.00' >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>') - '<.02>' + '<0.02>' """ - q = Decimal((0, (1,), -places)) # 2 places --> '0.01' - sign, digits, exp = value.quantize(q).as_tuple() - assert exp == -places + q = Decimal(10) ** -places # 2 places --> '0.01' + sign, digits, exp = value.quantize(q).as_tuple() result = [] digits = map(str, digits) build, next = result.append, digits.pop if sign: build(trailneg) for i in range(places): - if digits: - build(next()) - else: - build('0') + build(next() if digits else '0') build(dp) + if not digits: + build('0') i = 0 while digits: build(next()) @@ -1349,12 +1341,8 @@ i = 0 build(sep) build(curr) - if sign: - build(neg) - else: - build(pos) - result.reverse() - return ''.join(result) + build(neg if sign else pos) + return ''.join(reversed(result)) def pi(): """Compute Pi to the current precision. @@ -1457,40 +1445,67 @@ Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to minimize typing when using the interactive interpreter? -\A. Some users abbreviate the constructor to just a single letter:: +A. Some users abbreviate the constructor to just a single letter: >>> D = decimal.Decimal >>> D('1.23') + D('3.45') - Decimal("4.68") + Decimal('4.68') Q. In a fixed-point application with two decimal places, some inputs have many places and need to be rounded. Others are not supposed to have excess digits and need to be validated. What methods should be used? A. The :meth:`quantize` method rounds to a fixed number of decimal places. If -the :const:`Inexact` trap is set, it is also useful for validation:: +the :const:`Inexact` trap is set, it is also useful for validation: >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01') >>> # Round to two places - >>> Decimal("3.214").quantize(TWOPLACES) - Decimal("3.21") + >>> Decimal('3.214').quantize(TWOPLACES) + Decimal('3.21') >>> # Validate that a number does not exceed two places - >>> Decimal("3.21").quantize(TWOPLACES, context=Context(traps=[Inexact])) - Decimal("3.21") + >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact])) + Decimal('3.21') - >>> Decimal("3.214").quantize(TWOPLACES, context=Context(traps=[Inexact])) + >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact])) Traceback (most recent call last): ... - Inexact: Changed in rounding + Inexact Q. Once I have valid two place inputs, how do I maintain that invariant throughout an application? -A. Some operations like addition and subtraction automatically preserve fixed -point. Others, like multiplication and division, change the number of decimal -places and need to be followed-up with a :meth:`quantize` step. +A. Some operations like addition, subtraction, and multiplication by an integer +will automatically preserve fixed point. Others operations, like division and +non-integer multiplication, will change the number of decimal places and need to +be followed-up with a :meth:`quantize` step: + + >>> a = Decimal('102.72') # Initial fixed-point values + >>> b = Decimal('3.17') + >>> a + b # Addition preserves fixed-point + Decimal('105.89') + >>> a - b + Decimal('99.55') + >>> a * 42 # So does integer multiplication + Decimal('4314.24') + >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication + Decimal('325.62') + >>> (b / a).quantize(TWOPLACES) # And quantize division + Decimal('0.03') + +In developing fixed-point applications, it is convenient to define functions +to handle the :meth:`quantize` step: + + >>> def mul(x, y, fp=TWOPLACES): + ... return (x * y).quantize(fp) + >>> def div(x, y, fp=TWOPLACES): + ... return (x / y).quantize(fp) + + >>> mul(a, b) # Automatically preserve fixed-point + Decimal('325.62') + >>> div(b, a) + Decimal('0.03') Q. There are many ways to express the same value. The numbers :const:`200`, :const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at @@ -1498,11 +1513,11 @@ canonical value? A. The :meth:`normalize` method maps all equivalent values to a single -representative:: +representative: >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split()) >>> [v.normalize() for v in values] - [Decimal("2E+2"), Decimal("2E+2"), Decimal("2E+2"), Decimal("2E+2")] + [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')] Q. Some decimal values always print with exponential notation. Is there a way to get a non-exponential representation? @@ -1512,44 +1527,48 @@ :const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the original's two-place significance. +If an application does not care about tracking significance, it is easy to +remove the exponent and trailing zeroes, losing significance, but keeping the +value unchanged: + + >>> def remove_exponent(d): + ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize() + + >>> remove_exponent(Decimal('5E+3')) + Decimal('5000') + Q. Is there a way to convert a regular float to a :class:`Decimal`? A. Yes, all binary floating point numbers can be exactly expressed as a Decimal. An exact conversion may take more precision than intuition would -suggest, so trapping :const:`Inexact` will signal a need for more precision:: +suggest, so we trap :const:`Inexact` to signal a need for more precision: + +.. testcode:: + + def float_to_decimal(f): + "Convert a floating point number to a Decimal with no loss of information" + n, d = f.as_integer_ratio() + with localcontext() as ctx: + ctx.traps[Inexact] = True + while True: + try: + return Decimal(n) / Decimal(d) + except Inexact: + ctx.prec += 1 - def floatToDecimal(f): - "Convert a floating point number to a Decimal with no loss of information" - # Transform (exactly) a float to a mantissa (0.5 <= abs(m) < 1.0) and an - # exponent. Double the mantissa until it is an integer. Use the integer - # mantissa and exponent to compute an equivalent Decimal. If this cannot - # be done exactly, then retry with more precision. - - mantissa, exponent = math.frexp(f) - while mantissa != int(mantissa): - mantissa *= 2.0 - exponent -= 1 - mantissa = int(mantissa) - - oldcontext = getcontext() - setcontext(Context(traps=[Inexact])) - try: - while True: - try: - return mantissa * Decimal(2) ** exponent - except Inexact: - getcontext().prec += 1 - finally: - setcontext(oldcontext) +.. doctest:: -Q. Why isn't the :func:`floatToDecimal` routine included in the module? + >>> float_to_decimal(math.pi) + Decimal('3.141592653589793115997963468544185161590576171875') + +Q. Why isn't the :func:`float_to_decimal` routine included in the module? A. There is some question about whether it is advisable to mix binary and decimal floating point. Also, its use requires some care to avoid the -representation issues associated with binary floating point:: +representation issues associated with binary floating point: - >>> floatToDecimal(1.1) - Decimal("1.100000000000000088817841970012523233890533447265625") + >>> float_to_decimal(1.1) + Decimal('1.100000000000000088817841970012523233890533447265625') Q. Within a complex calculation, how can I make sure that I haven't gotten a spurious result because of insufficient precision or rounding anomalies. @@ -1566,24 +1585,28 @@ A. Yes. The principle is that all values are considered to be exact and so is the arithmetic on those values. Only the results are rounded. The advantage for inputs is that "what you type is what you get". A disadvantage is that the -results can look odd if you forget that the inputs haven't been rounded:: +results can look odd if you forget that the inputs haven't been rounded: + +.. doctest:: newcontext >>> getcontext().prec = 3 - >>> Decimal('3.104') + D('2.104') - Decimal("5.21") - >>> Decimal('3.104') + D('0.000') + D('2.104') - Decimal("5.20") + >>> Decimal('3.104') + Decimal('2.104') + Decimal('5.21') + >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104') + Decimal('5.20') The solution is either to increase precision or to force rounding of inputs -using the unary plus operation:: +using the unary plus operation: + +.. doctest:: newcontext >>> getcontext().prec = 3 >>> +Decimal('1.23456789') # unary plus triggers rounding - Decimal("1.23") + Decimal('1.23') Alternatively, inputs can be rounded upon creation using the -:meth:`Context.create_decimal` method:: +:meth:`Context.create_decimal` method: >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678') - Decimal("1.2345") + Decimal('1.2345') Modified: python/branches/py3k-ctypes-pep3118/Doc/library/difflib.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/difflib.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/difflib.rst Wed Apr 30 15:57:13 2008 @@ -1,4 +1,3 @@ - :mod:`difflib` --- Helpers for computing deltas =============================================== @@ -8,7 +7,10 @@ .. sectionauthor:: Tim Peters .. Markup by Fred L. Drake, Jr. +.. testsetup:: + import sys + from difflib import * This module provides classes and functions for comparing sequences. It can be used for example, for comparing files, and can produce difference @@ -144,7 +146,25 @@ expressed in the format returned by :func:`time.ctime`. If not specified, the strings default to blanks. - :file:`Tools/scripts/diff.py` is a command-line front-end for this function. + >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n'] + >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n'] + >>> for line in context_diff(s1, s2, fromfile='before.py', tofile='after.py'): + ... sys.stdout.write(line) # doctest: +NORMALIZE_WHITESPACE + *** before.py + --- after.py + *************** + *** 1,4 **** + ! bacon + ! eggs + ! ham + guido + --- 1,4 ---- + ! python + ! eggy + ! hamster + guido + + See :ref:`difflib-interface` for a more detailed example. .. function:: get_close_matches(word, possibilities[, n][, cutoff]) @@ -160,7 +180,7 @@ Possibilities that don't score at least that similar to *word* are ignored. The best (no more than *n*) matches among the possibilities are returned in a - list, sorted by similarity score, most similar first. :: + list, sorted by similarity score, most similar first. >>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy']) ['apple', 'ape'] @@ -195,7 +215,7 @@ function :func:`IS_CHARACTER_JUNK`, which filters out whitespace characters (a blank or tab; note: bad idea to include newline in this!). - :file:`Tools/scripts/ndiff.py` is a command-line front-end to this function. :: + :file:`Tools/scripts/ndiff.py` is a command-line front-end to this function. >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), ... 'ore\ntree\nemu\n'.splitlines(1)) @@ -219,7 +239,7 @@ lines originating from file 1 or 2 (parameter *which*), stripping off line prefixes. - Example:: + Example: >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), ... 'ore\ntree\nemu\n'.splitlines(1)) @@ -259,7 +279,23 @@ expressed in the format returned by :func:`time.ctime`. If not specified, the strings default to blanks. - :file:`Tools/scripts/diff.py` is a command-line front-end for this function. + + >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n'] + >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n'] + >>> for line in unified_diff(s1, s2, fromfile='before.py', tofile='after.py'): + ... sys.stdout.write(line) # doctest: +NORMALIZE_WHITESPACE + --- before.py + +++ after.py + @@ -1,4 +1,4 @@ + -bacon + -eggs + -ham + +python + +eggy + +hamster + guido + + See :ref:`difflib-interface` for a more detailed example. .. function:: IS_LINE_JUNK(line) @@ -307,172 +343,176 @@ The optional arguments *a* and *b* are sequences to be compared; both default to empty strings. The elements of both sequences must be :term:`hashable`. -:class:`SequenceMatcher` objects have the following methods: + :class:`SequenceMatcher` objects have the following methods: -.. method:: SequenceMatcher.set_seqs(a, b) + .. method:: set_seqs(a, b) - Set the two sequences to be compared. + Set the two sequences to be compared. -:class:`SequenceMatcher` computes and caches detailed information about the -second sequence, so if you want to compare one sequence against many sequences, -use :meth:`set_seq2` to set the commonly used sequence once and call -:meth:`set_seq1` repeatedly, once for each of the other sequences. + :class:`SequenceMatcher` computes and caches detailed information about the + second sequence, so if you want to compare one sequence against many + sequences, use :meth:`set_seq2` to set the commonly used sequence once and + call :meth:`set_seq1` repeatedly, once for each of the other sequences. -.. method:: SequenceMatcher.set_seq1(a) + .. method:: set_seq1(a) - Set the first sequence to be compared. The second sequence to be compared is - not changed. + Set the first sequence to be compared. The second sequence to be compared + is not changed. -.. method:: SequenceMatcher.set_seq2(b) + .. method:: set_seq2(b) - Set the second sequence to be compared. The first sequence to be compared is - not changed. + Set the second sequence to be compared. The first sequence to be compared + is not changed. -.. method:: SequenceMatcher.find_longest_match(alo, ahi, blo, bhi) + .. method:: find_longest_match(alo, ahi, blo, bhi) - Find longest matching block in ``a[alo:ahi]`` and ``b[blo:bhi]``. + Find longest matching block in ``a[alo:ahi]`` and ``b[blo:bhi]``. - If *isjunk* was omitted or ``None``, :meth:`find_longest_match` returns ``(i, j, - k)`` such that ``a[i:i+k]`` is equal to ``b[j:j+k]``, where ``alo <= i <= i+k <= - ahi`` and ``blo <= j <= j+k <= bhi``. For all ``(i', j', k')`` meeting those - conditions, the additional conditions ``k >= k'``, ``i <= i'``, and if ``i == - i'``, ``j <= j'`` are also met. In other words, of all maximal matching blocks, - return one that starts earliest in *a*, and of all those maximal matching blocks - that start earliest in *a*, return the one that starts earliest in *b*. :: + If *isjunk* was omitted or ``None``, :meth:`find_longest_match` returns + ``(i, j, k)`` such that ``a[i:i+k]`` is equal to ``b[j:j+k]``, where ``alo + <= i <= i+k <= ahi`` and ``blo <= j <= j+k <= bhi``. For all ``(i', j', + k')`` meeting those conditions, the additional conditions ``k >= k'``, ``i + <= i'``, and if ``i == i'``, ``j <= j'`` are also met. In other words, of + all maximal matching blocks, return one that starts earliest in *a*, and + of all those maximal matching blocks that start earliest in *a*, return + the one that starts earliest in *b*. - >>> s = SequenceMatcher(None, " abcd", "abcd abcd") - >>> s.find_longest_match(0, 5, 0, 9) - (0, 4, 5) + >>> s = SequenceMatcher(None, " abcd", "abcd abcd") + >>> s.find_longest_match(0, 5, 0, 9) + Match(a=0, b=4, size=5) - If *isjunk* was provided, first the longest matching block is determined as - above, but with the additional restriction that no junk element appears in the - block. Then that block is extended as far as possible by matching (only) junk - elements on both sides. So the resulting block never matches on junk except as - identical junk happens to be adjacent to an interesting match. + If *isjunk* was provided, first the longest matching block is determined + as above, but with the additional restriction that no junk element appears + in the block. Then that block is extended as far as possible by matching + (only) junk elements on both sides. So the resulting block never matches + on junk except as identical junk happens to be adjacent to an interesting + match. - Here's the same example as before, but considering blanks to be junk. That - prevents ``' abcd'`` from matching the ``' abcd'`` at the tail end of the second - sequence directly. Instead only the ``'abcd'`` can match, and matches the - leftmost ``'abcd'`` in the second sequence:: + Here's the same example as before, but considering blanks to be junk. That + prevents ``' abcd'`` from matching the ``' abcd'`` at the tail end of the + second sequence directly. Instead only the ``'abcd'`` can match, and + matches the leftmost ``'abcd'`` in the second sequence: - >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd") - >>> s.find_longest_match(0, 5, 0, 9) - (1, 0, 4) + >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd") + >>> s.find_longest_match(0, 5, 0, 9) + Match(a=1, b=0, size=4) - If no blocks match, this returns ``(alo, blo, 0)``. + If no blocks match, this returns ``(alo, blo, 0)``. - .. versionchanged:: 2.6 This method returns a :term:`named tuple` ``Match(a, b, size)``. -.. method:: SequenceMatcher.get_matching_blocks() + .. method:: get_matching_blocks() - Return list of triples describing matching subsequences. Each triple is of the - form ``(i, j, n)``, and means that ``a[i:i+n] == b[j:j+n]``. The triples are - monotonically increasing in *i* and *j*. + Return list of triples describing matching subsequences. Each triple is of + the form ``(i, j, n)``, and means that ``a[i:i+n] == b[j:j+n]``. The + triples are monotonically increasing in *i* and *j*. - The last triple is a dummy, and has the value ``(len(a), len(b), 0)``. It is - the only triple with ``n == 0``. If ``(i, j, n)`` and ``(i', j', n')`` are - adjacent triples in the list, and the second is not the last triple in the list, - then ``i+n != i'`` or ``j+n != j'``; in other words, adjacent triples always - describe non-adjacent equal blocks. + The last triple is a dummy, and has the value ``(len(a), len(b), 0)``. It + is the only triple with ``n == 0``. If ``(i, j, n)`` and ``(i', j', n')`` + are adjacent triples in the list, and the second is not the last triple in + the list, then ``i+n != i'`` or ``j+n != j'``; in other words, adjacent + triples always describe non-adjacent equal blocks. - .. XXX Explain why a dummy is used! + .. XXX Explain why a dummy is used! - :: + .. doctest:: - >>> s = SequenceMatcher(None, "abxcd", "abcd") - >>> s.get_matching_blocks() - [(0, 0, 2), (3, 2, 2), (5, 4, 0)] + >>> s = SequenceMatcher(None, "abxcd", "abcd") + >>> s.get_matching_blocks() + [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)] -.. method:: SequenceMatcher.get_opcodes() + .. method:: get_opcodes() - Return list of 5-tuples describing how to turn *a* into *b*. Each tuple is of - the form ``(tag, i1, i2, j1, j2)``. The first tuple has ``i1 == j1 == 0``, and - remaining tuples have *i1* equal to the *i2* from the preceding tuple, and, - likewise, *j1* equal to the previous *j2*. + Return list of 5-tuples describing how to turn *a* into *b*. Each tuple is + of the form ``(tag, i1, i2, j1, j2)``. The first tuple has ``i1 == j1 == + 0``, and remaining tuples have *i1* equal to the *i2* from the preceding + tuple, and, likewise, *j1* equal to the previous *j2*. - The *tag* values are strings, with these meanings: + The *tag* values are strings, with these meanings: - +---------------+---------------------------------------------+ - | Value | Meaning | - +===============+=============================================+ - | ``'replace'`` | ``a[i1:i2]`` should be replaced by | - | | ``b[j1:j2]``. | - +---------------+---------------------------------------------+ - | ``'delete'`` | ``a[i1:i2]`` should be deleted. Note that | - | | ``j1 == j2`` in this case. | - +---------------+---------------------------------------------+ - | ``'insert'`` | ``b[j1:j2]`` should be inserted at | - | | ``a[i1:i1]``. Note that ``i1 == i2`` in | - | | this case. | - +---------------+---------------------------------------------+ - | ``'equal'`` | ``a[i1:i2] == b[j1:j2]`` (the sub-sequences | - | | are equal). | - +---------------+---------------------------------------------+ + +---------------+---------------------------------------------+ + | Value | Meaning | + +===============+=============================================+ + | ``'replace'`` | ``a[i1:i2]`` should be replaced by | + | | ``b[j1:j2]``. | + +---------------+---------------------------------------------+ + | ``'delete'`` | ``a[i1:i2]`` should be deleted. Note that | + | | ``j1 == j2`` in this case. | + +---------------+---------------------------------------------+ + | ``'insert'`` | ``b[j1:j2]`` should be inserted at | + | | ``a[i1:i1]``. Note that ``i1 == i2`` in | + | | this case. | + +---------------+---------------------------------------------+ + | ``'equal'`` | ``a[i1:i2] == b[j1:j2]`` (the sub-sequences | + | | are equal). | + +---------------+---------------------------------------------+ - For example:: + For example: - >>> a = "qabxcd" - >>> b = "abycdf" - >>> s = SequenceMatcher(None, a, b) - >>> for tag, i1, i2, j1, j2 in s.get_opcodes(): - ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % - ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))) - delete a[0:1] (q) b[0:0] () - equal a[1:3] (ab) b[0:2] (ab) - replace a[3:4] (x) b[2:3] (y) - equal a[4:6] (cd) b[3:5] (cd) - insert a[6:6] () b[5:6] (f) + >>> a = "qabxcd" + >>> b = "abycdf" + >>> s = SequenceMatcher(None, a, b) + >>> for tag, i1, i2, j1, j2 in s.get_opcodes(): + ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % + ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))) + delete a[0:1] (q) b[0:0] () + equal a[1:3] (ab) b[0:2] (ab) + replace a[3:4] (x) b[2:3] (y) + equal a[4:6] (cd) b[3:5] (cd) + insert a[6:6] () b[5:6] (f) -.. method:: SequenceMatcher.get_grouped_opcodes([n]) + .. method:: get_grouped_opcodes([n]) - Return a :term:`generator` of groups with up to *n* lines of context. + Return a :term:`generator` of groups with up to *n* lines of context. - Starting with the groups returned by :meth:`get_opcodes`, this method splits out - smaller change clusters and eliminates intervening ranges which have no changes. + Starting with the groups returned by :meth:`get_opcodes`, this method + splits out smaller change clusters and eliminates intervening ranges which + have no changes. - The groups are returned in the same format as :meth:`get_opcodes`. + The groups are returned in the same format as :meth:`get_opcodes`. -.. method:: SequenceMatcher.ratio() + .. method:: ratio() - Return a measure of the sequences' similarity as a float in the range [0, 1]. + Return a measure of the sequences' similarity as a float in the range [0, + 1]. - Where T is the total number of elements in both sequences, and M is the number - of matches, this is 2.0\*M / T. Note that this is ``1.0`` if the sequences are - identical, and ``0.0`` if they have nothing in common. + Where T is the total number of elements in both sequences, and M is the + number of matches, this is 2.0\*M / T. Note that this is ``1.0`` if the + sequences are identical, and ``0.0`` if they have nothing in common. - This is expensive to compute if :meth:`get_matching_blocks` or - :meth:`get_opcodes` hasn't already been called, in which case you may want to - try :meth:`quick_ratio` or :meth:`real_quick_ratio` first to get an upper bound. + This is expensive to compute if :meth:`get_matching_blocks` or + :meth:`get_opcodes` hasn't already been called, in which case you may want + to try :meth:`quick_ratio` or :meth:`real_quick_ratio` first to get an + upper bound. -.. method:: SequenceMatcher.quick_ratio() + .. method:: quick_ratio() - Return an upper bound on :meth:`ratio` relatively quickly. + Return an upper bound on :meth:`ratio` relatively quickly. - This isn't defined beyond that it is an upper bound on :meth:`ratio`, and is - faster to compute. + This isn't defined beyond that it is an upper bound on :meth:`ratio`, and + is faster to compute. -.. method:: SequenceMatcher.real_quick_ratio() + .. method:: real_quick_ratio() - Return an upper bound on :meth:`ratio` very quickly. + Return an upper bound on :meth:`ratio` very quickly. - This isn't defined beyond that it is an upper bound on :meth:`ratio`, and is - faster to compute than either :meth:`ratio` or :meth:`quick_ratio`. + This isn't defined beyond that it is an upper bound on :meth:`ratio`, and + is faster to compute than either :meth:`ratio` or :meth:`quick_ratio`. The three methods that return the ratio of matching to total characters can give different results due to differing levels of approximation, although :meth:`quick_ratio` and :meth:`real_quick_ratio` are always at least as large as -:meth:`ratio`:: +:meth:`ratio`: >>> s = SequenceMatcher(None, "abcd", "bcde") >>> s.ratio() @@ -488,7 +528,7 @@ SequenceMatcher Examples ------------------------ -This example compares two strings, considering blanks to be "junk:" :: +This example compares two strings, considering blanks to be "junk:" >>> s = SequenceMatcher(lambda x: x == " ", ... "private Thread currentThread;", @@ -496,19 +536,18 @@ :meth:`ratio` returns a float in [0, 1], measuring the similarity of the sequences. As a rule of thumb, a :meth:`ratio` value over 0.6 means the -sequences are close matches:: +sequences are close matches: >>> print(round(s.ratio(), 3)) 0.866 If you're only interested in where the sequences match, -:meth:`get_matching_blocks` is handy:: +:meth:`get_matching_blocks` is handy: >>> for block in s.get_matching_blocks(): ... print("a[%d] and b[%d] match for %d elements" % block) a[0] and b[0] match for 8 elements - a[8] and b[17] match for 6 elements - a[14] and b[23] match for 15 elements + a[8] and b[17] match for 21 elements a[29] and b[38] match for 0 elements Note that the last tuple returned by :meth:`get_matching_blocks` is always a @@ -516,14 +555,13 @@ tuple element (number of elements matched) is ``0``. If you want to know how to change the first sequence into the second, use -:meth:`get_opcodes`:: +:meth:`get_opcodes`: >>> for opcode in s.get_opcodes(): ... print("%6s a[%d:%d] b[%d:%d]" % opcode) equal a[0:8] b[0:8] insert a[8:8] b[8:17] - equal a[8:14] b[17:23] - equal a[14:29] b[23:38] + equal a[8:29] b[17:38] See also the function :func:`get_close_matches` in this module, which shows how simple code building on :class:`SequenceMatcher` can be used to do useful work. @@ -556,17 +594,17 @@ length 1), and returns true if the character is junk. The default is ``None``, meaning that no character is considered junk. -:class:`Differ` objects are used (deltas generated) via a single method: + :class:`Differ` objects are used (deltas generated) via a single method: -.. method:: Differ.compare(a, b) + .. method:: Differ.compare(a, b) - Compare two sequences of lines, and generate the delta (a sequence of lines). + Compare two sequences of lines, and generate the delta (a sequence of lines). - Each sequence must contain individual single-line strings ending with newlines. - Such sequences can be obtained from the :meth:`readlines` method of file-like - objects. The delta generated also consists of newline-terminated strings, ready - to be printed as-is via the :meth:`writelines` method of a file-like object. + Each sequence must contain individual single-line strings ending with newlines. + Such sequences can be obtained from the :meth:`readlines` method of file-like + objects. The delta generated also consists of newline-terminated strings, ready + to be printed as-is via the :meth:`writelines` method of a file-like object. .. _differ-examples: @@ -576,7 +614,7 @@ This example compares two texts. First we set up the texts, sequences of individual single-line strings ending with newlines (such sequences can also be -obtained from the :meth:`readlines` method of file-like objects):: +obtained from the :meth:`readlines` method of file-like objects): >>> text1 = ''' 1. Beautiful is better than ugly. ... 2. Explicit is better than implicit. @@ -593,7 +631,7 @@ ... 5. Flat is better than nested. ... '''.splitlines(1) -Next we instantiate a Differ object:: +Next we instantiate a Differ object: >>> d = Differ() @@ -601,11 +639,11 @@ filter out line and character "junk." See the :meth:`Differ` constructor for details. -Finally, we compare the two:: +Finally, we compare the two: >>> result = list(d.compare(text1, text2)) -``result`` is a list of strings, so let's pretty-print it:: +``result`` is a list of strings, so let's pretty-print it: >>> from pprint import pprint >>> pprint(result) @@ -613,14 +651,14 @@ '- 2. Explicit is better than implicit.\n', '- 3. Simple is better than complex.\n', '+ 3. Simple is better than complex.\n', - '? ++ \n', + '? ++\n', '- 4. Complex is better than complicated.\n', - '? ^ ---- ^ \n', + '? ^ ---- ^\n', '+ 4. Complicated is better than complex.\n', - '? ++++ ^ ^ \n', + '? ++++ ^ ^\n', '+ 5. Flat is better than nested.\n'] -As a single multi-line string it looks like this:: +As a single multi-line string it looks like this: >>> import sys >>> sys.stdout.writelines(result) @@ -635,3 +673,75 @@ ? ++++ ^ ^ + 5. Flat is better than nested. + +.. _difflib-interface: + +A command-line interface to difflib +----------------------------------- + +This example shows how to use difflib to create a ``diff``-like utility. +It is also contained in the Python source distribution, as +:file:`Tools/scripts/diff.py`. + +.. testcode:: + + """ Command line interface to difflib.py providing diffs in four formats: + + * ndiff: lists every line and highlights interline changes. + * context: highlights clusters of changes in a before/after format. + * unified: highlights clusters of changes in an inline format. + * html: generates side by side comparison with change highlights. + + """ + + import sys, os, time, difflib, optparse + + def main(): + # Configure the option parser + usage = "usage: %prog [options] fromfile tofile" + parser = optparse.OptionParser(usage) + parser.add_option("-c", action="store_true", default=False, + help='Produce a context format diff (default)') + parser.add_option("-u", action="store_true", default=False, + help='Produce a unified format diff') + hlp = 'Produce HTML side by side diff (can use -c and -l in conjunction)' + parser.add_option("-m", action="store_true", default=False, help=hlp) + parser.add_option("-n", action="store_true", default=False, + help='Produce a ndiff format diff') + parser.add_option("-l", "--lines", type="int", default=3, + help='Set number of context lines (default 3)') + (options, args) = parser.parse_args() + + if len(args) == 0: + parser.print_help() + sys.exit(1) + if len(args) != 2: + parser.error("need to specify both a fromfile and tofile") + + n = options.lines + fromfile, tofile = args # as specified in the usage string + + # we're passing these as arguments to the diff function + fromdate = time.ctime(os.stat(fromfile).st_mtime) + todate = time.ctime(os.stat(tofile).st_mtime) + fromlines = open(fromfile, 'U').readlines() + tolines = open(tofile, 'U').readlines() + + if options.u: + diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, + fromdate, todate, n=n) + elif options.n: + diff = difflib.ndiff(fromlines, tolines) + elif options.m: + diff = difflib.HtmlDiff().make_file(fromlines, tolines, fromfile, + tofile, context=options.c, + numlines=n) + else: + diff = difflib.context_diff(fromlines, tolines, fromfile, tofile, + fromdate, todate, n=n) + + # we're using writelines because diff is a generator + sys.stdout.writelines(diff) + + if __name__ == '__main__': + main() Modified: python/branches/py3k-ctypes-pep3118/Doc/library/dis.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/dis.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/dis.rst Wed Apr 30 15:57:13 2008 @@ -412,21 +412,24 @@ .. opcode:: WITH_CLEANUP () - Cleans up the stack when a :keyword:`with` statement block exits. TOS is the - context manager's :meth:`__exit__` bound method. Below that are 1--3 values - indicating how/why the finally clause was entered: - - * SECOND = ``None`` - * (SECOND, THIRD) = (``WHY_{RETURN,CONTINUE}``), retval - * SECOND = ``WHY_*``; no retval below it - * (SECOND, THIRD, FOURTH) = exc_info() - - In the last case, ``TOS(SECOND, THIRD, FOURTH)`` is called, otherwise - ``TOS(None, None, None)``. - - In addition, if the stack represents an exception, *and* the function call - returns a 'true' value, this information is "zapped", to prevent ``END_FINALLY`` - from re-raising the exception. (But non-local gotos should still be resumed.) + Cleans up the stack when a :keyword:`with` statement block exits. On top of + the stack are 1--3 values indicating how/why the finally clause was entered: + + * TOP = ``None`` + * (TOP, SECOND) = (``WHY_{RETURN,CONTINUE}``), retval + * TOP = ``WHY_*``; no retval below it + * (TOP, SECOND, THIRD) = exc_info() + + Under them is EXIT, the context manager's :meth:`__exit__` bound method. + + In the last case, ``EXIT(TOP, SECOND, THIRD)`` is called, otherwise + ``EXIT(None, None, None)``. + + EXIT is removed from the stack, leaving the values above it in the same + order. In addition, if the stack represents an exception, *and* the function + call returns a 'true' value, this information is "zapped", to prevent + ``END_FINALLY`` from re-raising the exception. (But non-local gotos should + still be resumed.) .. XXX explain the WHY stuff! @@ -437,7 +440,7 @@ .. opcode:: STORE_NAME (namei) Implements ``name = TOS``. *namei* is the index of *name* in the attribute - :attr:`co_names` of the code object. The compiler tries to use ``STORE_LOCAL`` + :attr:`co_names` of the code object. The compiler tries to use ``STORE_FAST`` or ``STORE_GLOBAL`` if possible. @@ -525,9 +528,11 @@ .. opcode:: IMPORT_NAME (namei) - Imports the module ``co_names[namei]``. The module object is pushed onto the - stack. The current namespace is not affected: for a proper import statement, a - subsequent ``STORE_FAST`` instruction modifies the namespace. + Imports the module ``co_names[namei]``. TOS and TOS1 are popped and provide + the *fromlist* and *level* arguments of :func:`__import__`. The module + object is pushed onto the stack. The current namespace is not affected: + for a proper import statement, a subsequent ``STORE_FAST`` instruction + modifies the namespace. .. opcode:: IMPORT_FROM (namei) Deleted: python/branches/py3k-ctypes-pep3118/Doc/library/dl.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/dl.rst Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,108 +0,0 @@ - -:mod:`dl` --- Call C functions in shared objects -================================================ - -.. module:: dl - :platform: Unix - :synopsis: Call C functions in shared objects. -.. sectionauthor:: Moshe Zadka - -The :mod:`dl` module defines an interface to the :cfunc:`dlopen` function, which -is the most common interface on Unix platforms for handling dynamically linked -libraries. It allows the program to call arbitrary functions in such a library. - -.. warning:: - - The :mod:`dl` module bypasses the Python type system and error handling. If - used incorrectly it may cause segmentation faults, crashes or other incorrect - behaviour. - -.. note:: - - This module will not work unless ``sizeof(int) == sizeof(long) == sizeof(char - *)`` If this is not the case, :exc:`SystemError` will be raised on import. - -The :mod:`dl` module defines the following function: - - -.. function:: open(name[, mode=RTLD_LAZY]) - - Open a shared object file, and return a handle. Mode signifies late binding - (:const:`RTLD_LAZY`) or immediate binding (:const:`RTLD_NOW`). Default is - :const:`RTLD_LAZY`. Note that some systems do not support :const:`RTLD_NOW`. - - Return value is a :class:`dlobject`. - -The :mod:`dl` module defines the following constants: - - -.. data:: RTLD_LAZY - - Useful as an argument to :func:`open`. - - -.. data:: RTLD_NOW - - Useful as an argument to :func:`open`. Note that on systems which do not - support immediate binding, this constant will not appear in the module. For - maximum portability, use :func:`hasattr` to determine if the system supports - immediate binding. - -The :mod:`dl` module defines the following exception: - - -.. exception:: error - - Exception raised when an error has occurred inside the dynamic loading and - linking routines. - -Example:: - - >>> import dl, time - >>> a=dl.open('/lib/libc.so.6') - >>> a.call('time'), time.time() - (929723914, 929723914.498) - -This example was tried on a Debian GNU/Linux system, and is a good example of -the fact that using this module is usually a bad alternative. - - -.. _dl-objects: - -Dl Objects ----------- - -Dl objects, as returned by :func:`open` above, have the following methods: - - -.. method:: dl.close() - - Free all resources, except the memory. - - -.. method:: dl.sym(name) - - Return the pointer for the function named *name*, as a number, if it exists in - the referenced shared object, otherwise ``None``. This is useful in code like:: - - >>> if a.sym('time'): - ... a.call('time') - ... else: - ... time.time() - - (Note that this function will return a non-zero number, as zero is the *NULL* - pointer) - - -.. method:: dl.call(name[, arg1[, arg2...]]) - - Call the function named *name* in the referenced shared object. The arguments - must be either Python integers, which will be passed as is, Python strings, to - which a pointer will be passed, or ``None``, which will be passed as *NULL*. - Note that strings should only be passed to functions as :ctype:`const char\*`, - as Python will not like its string mutated. - - There must be at most 10 arguments, and arguments not given will be treated as - ``None``. The function's return value must be a C :ctype:`long`, which is a - Python integer. - Modified: python/branches/py3k-ctypes-pep3118/Doc/library/doctest.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/doctest.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/doctest.rst Wed Apr 30 15:57:13 2008 @@ -1113,48 +1113,48 @@ names. -:class:`DocTest` defines the following member variables. They are initialized -by the constructor, and should not be modified directly. + :class:`DocTest` defines the following member variables. They are initialized by + the constructor, and should not be modified directly. -.. attribute:: DocTest.examples + .. attribute:: examples - A list of :class:`Example` objects encoding the individual interactive Python - examples that should be run by this test. + A list of :class:`Example` objects encoding the individual interactive Python + examples that should be run by this test. -.. attribute:: DocTest.globs + .. attribute:: globs - The namespace (aka globals) that the examples should be run in. This is a - dictionary mapping names to values. Any changes to the namespace made by the - examples (such as binding new variables) will be reflected in :attr:`globs` - after the test is run. + The namespace (aka globals) that the examples should be run in. This is a + dictionary mapping names to values. Any changes to the namespace made by the + examples (such as binding new variables) will be reflected in :attr:`globs` + after the test is run. -.. attribute:: DocTest.name + .. attribute:: name - A string name identifying the :class:`DocTest`. Typically, this is the name of - the object or file that the test was extracted from. + A string name identifying the :class:`DocTest`. Typically, this is the name + of the object or file that the test was extracted from. -.. attribute:: DocTest.filename + .. attribute:: filename - The name of the file that this :class:`DocTest` was extracted from; or ``None`` - if the filename is unknown, or if the :class:`DocTest` was not extracted from a - file. + The name of the file that this :class:`DocTest` was extracted from; or + ``None`` if the filename is unknown, or if the :class:`DocTest` was not + extracted from a file. -.. attribute:: DocTest.lineno + .. attribute:: lineno - The line number within :attr:`filename` where this :class:`DocTest` begins, or - ``None`` if the line number is unavailable. This line number is zero-based with - respect to the beginning of the file. + The line number within :attr:`filename` where this :class:`DocTest` begins, or + ``None`` if the line number is unavailable. This line number is zero-based + with respect to the beginning of the file. -.. attribute:: DocTest.docstring + .. attribute:: docstring - The string that the test was extracted from, or 'None' if the string is - unavailable, or if the test was not extracted from a string. + The string that the test was extracted from, or 'None' if the string is + unavailable, or if the test was not extracted from a string. .. _doctest-example: @@ -1170,53 +1170,53 @@ of the same names. -:class:`Example` defines the following member variables. They are initialized -by the constructor, and should not be modified directly. + :class:`Example` defines the following member variables. They are initialized by + the constructor, and should not be modified directly. -.. attribute:: Example.source + .. attribute:: source - A string containing the example's source code. This source code consists of a - single Python statement, and always ends with a newline; the constructor adds a - newline when necessary. + A string containing the example's source code. This source code consists of a + single Python statement, and always ends with a newline; the constructor adds + a newline when necessary. -.. attribute:: Example.want + .. attribute:: want - The expected output from running the example's source code (either from stdout, - or a traceback in case of exception). :attr:`want` ends with a newline unless - no output is expected, in which case it's an empty string. The constructor adds - a newline when necessary. + The expected output from running the example's source code (either from + stdout, or a traceback in case of exception). :attr:`want` ends with a + newline unless no output is expected, in which case it's an empty string. The + constructor adds a newline when necessary. -.. attribute:: Example.exc_msg + .. attribute:: exc_msg - The exception message generated by the example, if the example is expected to - generate an exception; or ``None`` if it is not expected to generate an - exception. This exception message is compared against the return value of - :func:`traceback.format_exception_only`. :attr:`exc_msg` ends with a newline - unless it's ``None``. The constructor adds a newline if needed. + The exception message generated by the example, if the example is expected to + generate an exception; or ``None`` if it is not expected to generate an + exception. This exception message is compared against the return value of + :func:`traceback.format_exception_only`. :attr:`exc_msg` ends with a newline + unless it's ``None``. The constructor adds a newline if needed. -.. attribute:: Example.lineno + .. attribute:: lineno - The line number within the string containing this example where the example - begins. This line number is zero-based with respect to the beginning of the - containing string. + The line number within the string containing this example where the example + begins. This line number is zero-based with respect to the beginning of the + containing string. -.. attribute:: Example.indent + .. attribute:: indent - The example's indentation in the containing string, i.e., the number of space - characters that precede the example's first prompt. + The example's indentation in the containing string, i.e., the number of space + characters that precede the example's first prompt. -.. attribute:: Example.options + .. attribute:: options - A dictionary mapping from option flags to ``True`` or ``False``, which is used - to override default options for this example. Any option flags not contained in - this dictionary are left at their default value (as specified by the - :class:`DocTestRunner`'s :attr:`optionflags`). By default, no options are set. + A dictionary mapping from option flags to ``True`` or ``False``, which is used + to override default options for this example. Any option flags not contained + in this dictionary are left at their default value (as specified by the + :class:`DocTestRunner`'s :attr:`optionflags`). By default, no options are set. .. _doctest-doctestfinder: @@ -1246,44 +1246,44 @@ :meth:`DocTestFinder.find` will include tests for objects with empty docstrings. -:class:`DocTestFinder` defines the following method: + :class:`DocTestFinder` defines the following method: -.. method:: DocTestFinder.find(obj[, name][, module][, globs][, extraglobs]) + .. method:: find(obj[, name][, module][, globs][, extraglobs]) - Return a list of the :class:`DocTest`\ s that are defined by *obj*'s docstring, - or by any of its contained objects' docstrings. + Return a list of the :class:`DocTest`\ s that are defined by *obj*'s + docstring, or by any of its contained objects' docstrings. - The optional argument *name* specifies the object's name; this name will be used - to construct names for the returned :class:`DocTest`\ s. If *name* is not - specified, then ``obj.__name__`` is used. + The optional argument *name* specifies the object's name; this name will be + used to construct names for the returned :class:`DocTest`\ s. If *name* is + not specified, then ``obj.__name__`` is used. - The optional parameter *module* is the module that contains the given object. - If the module is not specified or is None, then the test finder will attempt to - automatically determine the correct module. The object's module is used: + The optional parameter *module* is the module that contains the given object. + If the module is not specified or is None, then the test finder will attempt + to automatically determine the correct module. The object's module is used: - * As a default namespace, if *globs* is not specified. + * As a default namespace, if *globs* is not specified. - * To prevent the DocTestFinder from extracting DocTests from objects that are - imported from other modules. (Contained objects with modules other than - *module* are ignored.) + * To prevent the DocTestFinder from extracting DocTests from objects that are + imported from other modules. (Contained objects with modules other than + *module* are ignored.) - * To find the name of the file containing the object. + * To find the name of the file containing the object. - * To help find the line number of the object within its file. + * To help find the line number of the object within its file. - If *module* is ``False``, no attempt to find the module will be made. This is - obscure, of use mostly in testing doctest itself: if *module* is ``False``, or - is ``None`` but cannot be found automatically, then all objects are considered - to belong to the (non-existent) module, so all contained objects will - (recursively) be searched for doctests. + If *module* is ``False``, no attempt to find the module will be made. This is + obscure, of use mostly in testing doctest itself: if *module* is ``False``, or + is ``None`` but cannot be found automatically, then all objects are considered + to belong to the (non-existent) module, so all contained objects will + (recursively) be searched for doctests. - The globals for each :class:`DocTest` is formed by combining *globs* and - *extraglobs* (bindings in *extraglobs* override bindings in *globs*). A new - shallow copy of the globals dictionary is created for each :class:`DocTest`. If - *globs* is not specified, then it defaults to the module's *__dict__*, if - specified, or ``{}`` otherwise. If *extraglobs* is not specified, then it - defaults to ``{}``. + The globals for each :class:`DocTest` is formed by combining *globs* and + *extraglobs* (bindings in *extraglobs* override bindings in *globs*). A new + shallow copy of the globals dictionary is created for each :class:`DocTest`. + If *globs* is not specified, then it defaults to the module's *__dict__*, if + specified, or ``{}`` otherwise. If *extraglobs* is not specified, then it + defaults to ``{}``. .. _doctest-doctestparser: @@ -1298,32 +1298,32 @@ them to create a :class:`DocTest` object. -:class:`DocTestParser` defines the following methods: + :class:`DocTestParser` defines the following methods: -.. method:: DocTestParser.get_doctest(string, globs, name, filename, lineno) + .. method:: get_doctest(string, globs, name, filename, lineno) - Extract all doctest examples from the given string, and collect them into a - :class:`DocTest` object. + Extract all doctest examples from the given string, and collect them into a + :class:`DocTest` object. - *globs*, *name*, *filename*, and *lineno* are attributes for the new - :class:`DocTest` object. See the documentation for :class:`DocTest` for more - information. + *globs*, *name*, *filename*, and *lineno* are attributes for the new + :class:`DocTest` object. See the documentation for :class:`DocTest` for more + information. -.. method:: DocTestParser.get_examples(string[, name]) + .. method:: get_examples(string[, name]) - Extract all doctest examples from the given string, and return them as a list of - :class:`Example` objects. Line numbers are 0-based. The optional argument - *name* is a name identifying this string, and is only used for error messages. + Extract all doctest examples from the given string, and return them as a list + of :class:`Example` objects. Line numbers are 0-based. The optional argument + *name* is a name identifying this string, and is only used for error messages. -.. method:: DocTestParser.parse(string[, name]) + .. method:: parse(string[, name]) - Divide the given string into examples and intervening text, and return them as a - list of alternating :class:`Example`\ s and strings. Line numbers for the - :class:`Example`\ s are 0-based. The optional argument *name* is a name - identifying this string, and is only used for error messages. + Divide the given string into examples and intervening text, and return them as + a list of alternating :class:`Example`\ s and strings. Line numbers for the + :class:`Example`\ s are 0-based. The optional argument *name* is a name + identifying this string, and is only used for error messages. .. _doctest-doctestrunner: @@ -1366,84 +1366,81 @@ For more information, see section :ref:`doctest-options`. -:class:`DocTestParser` defines the following methods: + :class:`DocTestParser` defines the following methods: -.. method:: DocTestRunner.report_start(out, test, example) + .. method:: report_start(out, test, example) - Report that the test runner is about to process the given example. This method - is provided to allow subclasses of :class:`DocTestRunner` to customize their - output; it should not be called directly. + Report that the test runner is about to process the given example. This method + is provided to allow subclasses of :class:`DocTestRunner` to customize their + output; it should not be called directly. - *example* is the example about to be processed. *test* is the test containing - *example*. *out* is the output function that was passed to - :meth:`DocTestRunner.run`. + *example* is the example about to be processed. *test* is the test + *containing example*. *out* is the output function that was passed to + :meth:`DocTestRunner.run`. -.. method:: DocTestRunner.report_success(out, test, example, got) + .. method:: report_success(out, test, example, got) - Report that the given example ran successfully. This method is provided to - allow subclasses of :class:`DocTestRunner` to customize their output; it should - not be called directly. + Report that the given example ran successfully. This method is provided to + allow subclasses of :class:`DocTestRunner` to customize their output; it + should not be called directly. - *example* is the example about to be processed. *got* is the actual output from - the example. *test* is the test containing *example*. *out* is the output - function that was passed to :meth:`DocTestRunner.run`. + *example* is the example about to be processed. *got* is the actual output + from the example. *test* is the test containing *example*. *out* is the + output function that was passed to :meth:`DocTestRunner.run`. -.. method:: DocTestRunner.report_failure(out, test, example, got) + .. method:: report_failure(out, test, example, got) - Report that the given example failed. This method is provided to allow - subclasses of :class:`DocTestRunner` to customize their output; it should not be - called directly. + Report that the given example failed. This method is provided to allow + subclasses of :class:`DocTestRunner` to customize their output; it should not + be called directly. - *example* is the example about to be processed. *got* is the actual output from - the example. *test* is the test containing *example*. *out* is the output - function that was passed to :meth:`DocTestRunner.run`. + *example* is the example about to be processed. *got* is the actual output + from the example. *test* is the test containing *example*. *out* is the + output function that was passed to :meth:`DocTestRunner.run`. -.. method:: DocTestRunner.report_unexpected_exception(out, test, example, exc_info) + .. method:: report_unexpected_exception(out, test, example, exc_info) - Report that the given example raised an unexpected exception. This method is - provided to allow subclasses of :class:`DocTestRunner` to customize their - output; it should not be called directly. + Report that the given example raised an unexpected exception. This method is + provided to allow subclasses of :class:`DocTestRunner` to customize their + output; it should not be called directly. - *example* is the example about to be processed. *exc_info* is a tuple containing - information about the unexpected exception (as returned by - :func:`sys.exc_info`). *test* is the test containing *example*. *out* is the - output function that was passed to :meth:`DocTestRunner.run`. + *example* is the example about to be processed. *exc_info* is a tuple + containing information about the unexpected exception (as returned by + :func:`sys.exc_info`). *test* is the test containing *example*. *out* is the + output function that was passed to :meth:`DocTestRunner.run`. -.. method:: DocTestRunner.run(test[, compileflags][, out][, clear_globs]) + .. method:: run(test[, compileflags][, out][, clear_globs]) - Run the examples in *test* (a :class:`DocTest` object), and display the results - using the writer function *out*. + Run the examples in *test* (a :class:`DocTest` object), and display the + results using the writer function *out*. - The examples are run in the namespace ``test.globs``. If *clear_globs* is true - (the default), then this namespace will be cleared after the test runs, to help - with garbage collection. If you would like to examine the namespace after the - test completes, then use *clear_globs=False*. + The examples are run in the namespace ``test.globs``. If *clear_globs* is + true (the default), then this namespace will be cleared after the test runs, + to help with garbage collection. If you would like to examine the namespace + after the test completes, then use *clear_globs=False*. - *compileflags* gives the set of flags that should be used by the Python compiler - when running the examples. If not specified, then it will default to the set of - future-import flags that apply to *globs*. + *compileflags* gives the set of flags that should be used by the Python + compiler when running the examples. If not specified, then it will default to + the set of future-import flags that apply to *globs*. - The output of each example is checked using the :class:`DocTestRunner`'s output - checker, and the results are formatted by the :meth:`DocTestRunner.report_\*` - methods. + The output of each example is checked using the :class:`DocTestRunner`'s + output checker, and the results are formatted by the + :meth:`DocTestRunner.report_\*` methods. -.. method:: DocTestRunner.summarize([verbose]) + .. method:: summarize([verbose]) - Print a summary of all the test cases that have been run by this DocTestRunner, - and return a :term:`named tuple` ``TestResults(failed, attempted)``. - - The optional *verbose* argument controls how detailed the summary is. If the - verbosity is not specified, then the :class:`DocTestRunner`'s verbosity is used. - - .. versionchanged:: 2.6 - Use a named tuple. + Print a summary of all the test cases that have been run by this DocTestRunner, + and return a :term:`named tuple` ``TestResults(failed, attempted)``. + The optional *verbose* argument controls how detailed the summary is. If the + verbosity is not specified, then the :class:`DocTestRunner`'s verbosity is + used. .. _doctest-outputchecker: @@ -1460,22 +1457,22 @@ the differences between two outputs. -:class:`OutputChecker` defines the following methods: + :class:`OutputChecker` defines the following methods: -.. method:: OutputChecker.check_output(want, got, optionflags) + .. method:: check_output(want, got, optionflags) - Return ``True`` iff the actual output from an example (*got*) matches the - expected output (*want*). These strings are always considered to match if they - are identical; but depending on what option flags the test runner is using, - several non-exact match types are also possible. See section - :ref:`doctest-options` for more information about option flags. + Return ``True`` iff the actual output from an example (*got*) matches the + expected output (*want*). These strings are always considered to match if + they are identical; but depending on what option flags the test runner is + using, several non-exact match types are also possible. See section + :ref:`doctest-options` for more information about option flags. -.. method:: OutputChecker.output_difference(example, got, optionflags) + .. method:: output_difference(example, got, optionflags) - Return a string describing the differences between the expected output for a - given example (*example*) and the actual output (*got*). *optionflags* is the - set of option flags used to compare *want* and *got*. + Return a string describing the differences between the expected output for a + given example (*example*) and the actual output (*got*). *optionflags* is the + set of option flags used to compare *want* and *got*. .. _doctest-debugging: Modified: python/branches/py3k-ctypes-pep3118/Doc/library/easydialogs.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/easydialogs.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/easydialogs.rst Wed Apr 30 15:57:13 2008 @@ -107,7 +107,7 @@ *actionButtonLabel* is a string to show instead of "Open" in the OK button, *cancelButtonLabel* is a string to show instead of "Cancel" in the cancel button, *wanted* is the type of value wanted as a return: :class:`str`, - :class:`unicode`, :class:`FSSpec`, :class:`FSRef` and subtypes thereof are + :class:`FSSpec`, :class:`FSRef` and subtypes thereof are acceptable. .. index:: single: Navigation Services Modified: python/branches/py3k-ctypes-pep3118/Doc/library/email-examples.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/email-examples.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/email-examples.rst Wed Apr 30 15:57:13 2008 @@ -16,18 +16,23 @@ Here's an example of how to send the entire contents of a directory as an email -message: [1]_ +message: [1]_ .. literalinclude:: ../includes/email-dir.py -And finally, here's an example of how to unpack a MIME message like the one +Here's an example of how to unpack a MIME message like the one above, into a directory of files: .. literalinclude:: ../includes/email-unpack.py +Here's an example of how to create an HTML message with an alternative plain +text version: [2]_ + +.. literalinclude:: ../includes/email-alternative.py + .. rubric:: Footnotes .. [1] Thanks to Matthew Dixon Cowles for the original inspiration and examples. - +.. [2] Contributed by Martin Matejek. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/email.charset.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/email.charset.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/email.charset.rst Wed Apr 30 15:57:13 2008 @@ -38,164 +38,168 @@ will not be encoded, but output text will be converted from the ``euc-jp`` character set to the ``iso-2022-jp`` character set. -:class:`Charset` instances have the following data attributes: + :class:`Charset` instances have the following data attributes: -.. data:: input_charset + .. attribute:: input_charset - The initial character set specified. Common aliases are converted to their - *official* email names (e.g. ``latin_1`` is converted to ``iso-8859-1``). - Defaults to 7-bit ``us-ascii``. + The initial character set specified. Common aliases are converted to + their *official* email names (e.g. ``latin_1`` is converted to + ``iso-8859-1``). Defaults to 7-bit ``us-ascii``. -.. data:: header_encoding + .. attribute:: header_encoding - If the character set must be encoded before it can be used in an email header, - this attribute will be set to ``Charset.QP`` (for quoted-printable), - ``Charset.BASE64`` (for base64 encoding), or ``Charset.SHORTEST`` for the - shortest of QP or BASE64 encoding. Otherwise, it will be ``None``. + If the character set must be encoded before it can be used in an email + header, this attribute will be set to ``Charset.QP`` (for + quoted-printable), ``Charset.BASE64`` (for base64 encoding), or + ``Charset.SHORTEST`` for the shortest of QP or BASE64 encoding. Otherwise, + it will be ``None``. -.. data:: body_encoding + .. attribute:: body_encoding - Same as *header_encoding*, but describes the encoding for the mail message's - body, which indeed may be different than the header encoding. - ``Charset.SHORTEST`` is not allowed for *body_encoding*. + Same as *header_encoding*, but describes the encoding for the mail + message's body, which indeed may be different than the header encoding. + ``Charset.SHORTEST`` is not allowed for *body_encoding*. -.. data:: output_charset + .. attribute:: output_charset - Some character sets must be converted before they can be used in email headers - or bodies. If the *input_charset* is one of them, this attribute will contain - the name of the character set output will be converted to. Otherwise, it will - be ``None``. + Some character sets must be converted before they can be used in email headers + or bodies. If the *input_charset* is one of them, this attribute will + contain the name of the character set output will be converted to. Otherwise, it will + be ``None``. -.. data:: input_codec + .. attribute:: input_codec - The name of the Python codec used to convert the *input_charset* to Unicode. If - no conversion codec is necessary, this attribute will be ``None``. + The name of the Python codec used to convert the *input_charset* to + Unicode. If no conversion codec is necessary, this attribute will be + ``None``. -.. data:: output_codec + .. attribute:: output_codec - The name of the Python codec used to convert Unicode to the *output_charset*. - If no conversion codec is necessary, this attribute will have the same value as - the *input_codec*. + The name of the Python codec used to convert Unicode to the + *output_charset*. If no conversion codec is necessary, this attribute + will have the same value as the *input_codec*. -:class:`Charset` instances also have the following methods: + :class:`Charset` instances also have the following methods: -.. method:: Charset.get_body_encoding() + .. method:: get_body_encoding() - Return the content transfer encoding used for body encoding. + Return the content transfer encoding used for body encoding. - This is either the string ``quoted-printable`` or ``base64`` depending on the - encoding used, or it is a function, in which case you should call the function - with a single argument, the Message object being encoded. The function should - then set the :mailheader:`Content-Transfer-Encoding` header itself to whatever - is appropriate. + This is either the string ``quoted-printable`` or ``base64`` depending on + the encoding used, or it is a function, in which case you should call the + function with a single argument, the Message object being encoded. The + function should then set the :mailheader:`Content-Transfer-Encoding` + header itself to whatever is appropriate. - Returns the string ``quoted-printable`` if *body_encoding* is ``QP``, returns - the string ``base64`` if *body_encoding* is ``BASE64``, and returns the string - ``7bit`` otherwise. + Returns the string ``quoted-printable`` if *body_encoding* is ``QP``, + returns the string ``base64`` if *body_encoding* is ``BASE64``, and + returns the string ``7bit`` otherwise. -.. method:: Charset.convert(s) + .. method:: convert(s) - Convert the string *s* from the *input_codec* to the *output_codec*. + Convert the string *s* from the *input_codec* to the *output_codec*. -.. method:: Charset.to_splittable(s) + .. method:: to_splittable(s) - Convert a possibly multibyte string to a safely splittable format. *s* is the - string to split. + Convert a possibly multibyte string to a safely splittable format. *s* is + the string to split. - Uses the *input_codec* to try and convert the string to Unicode, so it can be - safely split on character boundaries (even for multibyte characters). + Uses the *input_codec* to try and convert the string to Unicode, so it can + be safely split on character boundaries (even for multibyte characters). - Returns the string as-is if it isn't known how to convert *s* to Unicode with - the *input_charset*. + Returns the string as-is if it isn't known how to convert *s* to Unicode + with the *input_charset*. - Characters that could not be converted to Unicode will be replaced with the - Unicode replacement character ``'U+FFFD'``. + Characters that could not be converted to Unicode will be replaced with + the Unicode replacement character ``'U+FFFD'``. -.. method:: Charset.from_splittable(ustr[, to_output]) + .. method:: from_splittable(ustr[, to_output]) - Convert a splittable string back into an encoded string. *ustr* is a Unicode - string to "unsplit". + Convert a splittable string back into an encoded string. *ustr* is a + Unicode string to "unsplit". - This method uses the proper codec to try and convert the string from Unicode - back into an encoded format. Return the string as-is if it is not Unicode, or - if it could not be converted from Unicode. + This method uses the proper codec to try and convert the string from + Unicode back into an encoded format. Return the string as-is if it is not + Unicode, or if it could not be converted from Unicode. - Characters that could not be converted from Unicode will be replaced with an - appropriate character (usually ``'?'``). + Characters that could not be converted from Unicode will be replaced with + an appropriate character (usually ``'?'``). - If *to_output* is ``True`` (the default), uses *output_codec* to convert to an - encoded format. If *to_output* is ``False``, it uses *input_codec*. + If *to_output* is ``True`` (the default), uses *output_codec* to convert + to an encoded format. If *to_output* is ``False``, it uses *input_codec*. -.. method:: Charset.get_output_charset() + .. method:: get_output_charset() - Return the output character set. + Return the output character set. - This is the *output_charset* attribute if that is not ``None``, otherwise it is - *input_charset*. + This is the *output_charset* attribute if that is not ``None``, otherwise + it is *input_charset*. -.. method:: Charset.encoded_header_len() + .. method:: encoded_header_len() - Return the length of the encoded header string, properly calculating for - quoted-printable or base64 encoding. + Return the length of the encoded header string, properly calculating for + quoted-printable or base64 encoding. -.. method:: Charset.header_encode(s[, convert]) + .. method:: header_encode(s[, convert]) - Header-encode the string *s*. + Header-encode the string *s*. - If *convert* is ``True``, the string will be converted from the input charset to - the output charset automatically. This is not useful for multibyte character - sets, which have line length issues (multibyte characters must be split on a - character, not a byte boundary); use the higher-level :class:`Header` class to - deal with these issues (see :mod:`email.header`). *convert* defaults to - ``False``. + If *convert* is ``True``, the string will be converted from the input + charset to the output charset automatically. This is not useful for + multibyte character sets, which have line length issues (multibyte + characters must be split on a character, not a byte boundary); use the + higher-level :class:`Header` class to deal with these issues (see + :mod:`email.header`). *convert* defaults to ``False``. - The type of encoding (base64 or quoted-printable) will be based on the - *header_encoding* attribute. + The type of encoding (base64 or quoted-printable) will be based on the + *header_encoding* attribute. -.. method:: Charset.body_encode(s[, convert]) + .. method:: body_encode(s[, convert]) - Body-encode the string *s*. + Body-encode the string *s*. - If *convert* is ``True`` (the default), the string will be converted from the - input charset to output charset automatically. Unlike :meth:`header_encode`, - there are no issues with byte boundaries and multibyte charsets in email bodies, - so this is usually pretty safe. + If *convert* is ``True`` (the default), the string will be converted from + the input charset to output charset automatically. Unlike + :meth:`header_encode`, there are no issues with byte boundaries and + multibyte charsets in email bodies, so this is usually pretty safe. - The type of encoding (base64 or quoted-printable) will be based on the - *body_encoding* attribute. + The type of encoding (base64 or quoted-printable) will be based on the + *body_encoding* attribute. -The :class:`Charset` class also provides a number of methods to support standard -operations and built-in functions. + The :class:`Charset` class also provides a number of methods to support + standard operations and built-in functions. -.. method:: Charset.__str__() + .. method:: __str__() - Returns *input_charset* as a string coerced to lower case. :meth:`__repr__` is - an alias for :meth:`__str__`. + Returns *input_charset* as a string coerced to lower + case. :meth:`__repr__` is an alias for :meth:`__str__`. -.. method:: Charset.__eq__(other) + .. method:: __eq__(other) - This method allows you to compare two :class:`Charset` instances for equality. + This method allows you to compare two :class:`Charset` instances for + equality. -.. method:: Header.__ne__(other) + .. method:: __ne__(other) - This method allows you to compare two :class:`Charset` instances for inequality. + This method allows you to compare two :class:`Charset` instances for + inequality. The :mod:`email.charset` module also provides the following functions for adding new entries to the global character set, alias, and codec registries: @@ -242,6 +246,6 @@ Add a codec that map characters in the given character set to and from Unicode. *charset* is the canonical name of a character set. *codecname* is the name of a - Python codec, as appropriate for the second argument to the :func:`unicode` - built-in, or to the :meth:`encode` method of a Unicode string. + Python codec, as appropriate for the second argument to the :class:`str`'s + :func:`decode` method Modified: python/branches/py3k-ctypes-pep3118/Doc/library/email.generator.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/email.generator.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/email.generator.rst Wed Apr 30 15:57:13 2008 @@ -44,35 +44,34 @@ :mod:`email.header.Header` class. Set to zero to disable header wrapping. The default is 78, as recommended (but not required) by :rfc:`2822`. -The other public :class:`Generator` methods are: + The other public :class:`Generator` methods are: -.. method:: Generator.flatten(msg[, unixfrom]) + .. method:: flatten(msg[, unixfrom]) - Print the textual representation of the message object structure rooted at *msg* - to the output file specified when the :class:`Generator` instance was created. - Subparts are visited depth-first and the resulting text will be properly MIME - encoded. + Print the textual representation of the message object structure rooted at + *msg* to the output file specified when the :class:`Generator` instance + was created. Subparts are visited depth-first and the resulting text will + be properly MIME encoded. - Optional *unixfrom* is a flag that forces the printing of the envelope header - delimiter before the first :rfc:`2822` header of the root message object. If - the root object has no envelope header, a standard one is crafted. By default, - this is set to ``False`` to inhibit the printing of the envelope delimiter. + Optional *unixfrom* is a flag that forces the printing of the envelope + header delimiter before the first :rfc:`2822` header of the root message + object. If the root object has no envelope header, a standard one is + crafted. By default, this is set to ``False`` to inhibit the printing of + the envelope delimiter. - Note that for subparts, no envelope header is ever printed. + Note that for subparts, no envelope header is ever printed. + .. method:: clone(fp) -.. method:: Generator.clone(fp) + Return an independent clone of this :class:`Generator` instance with the + exact same options. - Return an independent clone of this :class:`Generator` instance with the exact - same options. + .. method:: write(s) - -.. method:: Generator.write(s) - - Write the string *s* to the underlying file object, i.e. *outfp* passed to - :class:`Generator`'s constructor. This provides just enough file-like API for - :class:`Generator` instances to be used in the :func:`print` function. + Write the string *s* to the underlying file object, i.e. *outfp* passed to + :class:`Generator`'s constructor. This provides just enough file-like API + for :class:`Generator` instances to be used in the :func:`print` function. As a convenience, see the methods :meth:`Message.as_string` and ``str(aMessage)``, a.k.a. :meth:`Message.__str__`, which simplify the generation Modified: python/branches/py3k-ctypes-pep3118/Doc/library/email.header.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/email.header.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/email.header.rst Wed Apr 30 15:57:13 2008 @@ -53,8 +53,8 @@ Optional *s* is the initial header value. If ``None`` (the default), the initial header value is not set. You can later append to the header with - :meth:`append` method calls. *s* may be a byte string or a Unicode string, but - see the :meth:`append` documentation for semantics. + :meth:`append` method calls. *s* may be an instance of :class:`bytes` or + :class:`str`, but see the :meth:`append` documentation for semantics. Optional *charset* serves two purposes: it has the same meaning as the *charset* argument to the :meth:`append` method. It also sets the default character set @@ -74,65 +74,66 @@ and is usually either a space or a hard tab character. This character will be prepended to continuation lines. -Optional *errors* is passed straight through to the :meth:`append` method. + Optional *errors* is passed straight through to the :meth:`append` method. -.. method:: Header.append(s[, charset[, errors]]) + .. method:: append(s[, charset[, errors]]) - Append the string *s* to the MIME header. + Append the string *s* to the MIME header. - Optional *charset*, if given, should be a :class:`Charset` instance (see - :mod:`email.charset`) or the name of a character set, which will be converted to - a :class:`Charset` instance. A value of ``None`` (the default) means that the - *charset* given in the constructor is used. + Optional *charset*, if given, should be a :class:`Charset` instance (see + :mod:`email.charset`) or the name of a character set, which will be + converted to a :class:`Charset` instance. A value of ``None`` (the + default) means that the *charset* given in the constructor is used. - *s* may be a byte string or a Unicode string. If it is a byte string (i.e. - ``isinstance(s, str)`` is true), then *charset* is the encoding of that byte - string, and a :exc:`UnicodeError` will be raised if the string cannot be decoded - with that character set. + *s* may be an instance of :class:`bytes` or :class:`str`. If it is an + instance of :class:`bytes`, then *charset* is the encoding of that byte + string, and a :exc:`UnicodeError` will be raised if the string cannot be + decoded with that character set. - If *s* is a Unicode string, then *charset* is a hint specifying the character - set of the characters in the string. In this case, when producing an - :rfc:`2822`\ -compliant header using :rfc:`2047` rules, the Unicode string will - be encoded using the following charsets in order: ``us-ascii``, the *charset* - hint, ``utf-8``. The first character set to not provoke a :exc:`UnicodeError` - is used. + If *s* is an instance of :class:`str`, then *charset* is a hint specifying + the character set of the characters in the string. In this case, when + producing an :rfc:`2822`\ -compliant header using :rfc:`2047` rules, the + Unicode string will be encoded using the following charsets in order: + ``us-ascii``, the *charset* hint, ``utf-8``. The first character set to + not provoke a :exc:`UnicodeError` is used. - Optional *errors* is passed through to any :func:`unicode` or - :func:`ustr.encode` call, and defaults to "strict". + Optional *errors* is passed through to any :func:`encode` or + :func:`ustr.encode` call, and defaults to "strict". -.. method:: Header.encode([splitchars]) + .. method:: encode([splitchars]) - Encode a message header into an RFC-compliant format, possibly wrapping long - lines and encapsulating non-ASCII parts in base64 or quoted-printable encodings. - Optional *splitchars* is a string containing characters to split long ASCII - lines on, in rough support of :rfc:`2822`'s *highest level syntactic breaks*. - This doesn't affect :rfc:`2047` encoded lines. + Encode a message header into an RFC-compliant format, possibly wrapping + long lines and encapsulating non-ASCII parts in base64 or quoted-printable + encodings. Optional *splitchars* is a string containing characters to + split long ASCII lines on, in rough support of :rfc:`2822`'s *highest + level syntactic breaks*. This doesn't affect :rfc:`2047` encoded lines. -The :class:`Header` class also provides a number of methods to support standard -operators and built-in functions. + The :class:`Header` class also provides a number of methods to support + standard operators and built-in functions. -.. method:: Header.__str__() + .. method:: __str__() - A synonym for :meth:`Header.encode`. Useful for ``str(aHeader)``. + A synonym for :meth:`Header.encode`. Useful for ``str(aHeader)``. -.. method:: Header.__unicode__() + .. method:: __unicode__() - A helper for the built-in :func:`unicode` function. Returns the header as a - Unicode string. + A helper for :class:`str`'s :func:`encode` method. Returns the header as + a Unicode string. + .. method:: __eq__(other) -.. method:: Header.__eq__(other) + This method allows you to compare two :class:`Header` instances for + equality. - This method allows you to compare two :class:`Header` instances for equality. + .. method:: __ne__(other) -.. method:: Header.__ne__(other) - - This method allows you to compare two :class:`Header` instances for inequality. + This method allows you to compare two :class:`Header` instances for + inequality. The :mod:`email.header` module also provides the following convenient functions. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/email.message.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/email.message.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/email.message.rst Wed Apr 30 15:57:13 2008 @@ -36,472 +36,489 @@ The constructor takes no arguments. -.. method:: Message.as_string([unixfrom]) + .. method:: as_string([unixfrom]) - Return the entire message flatten as a string. When optional *unixfrom* is - ``True``, the envelope header is included in the returned string. *unixfrom* - defaults to ``False``. + Return the entire message flattened as a string. When optional *unixfrom* + is ``True``, the envelope header is included in the returned string. + *unixfrom* defaults to ``False``. - Note that this method is provided as a convenience and may not always format the - message the way you want. For example, by default it mangles lines that begin - with ``From``. For more flexibility, instantiate a :class:`Generator` instance - and use its :meth:`flatten` method directly. For example:: + Note that this method is provided as a convenience and may not always + format the message the way you want. For example, by default it mangles + lines that begin with ``From``. For more flexibility, instantiate a + :class:`Generator` instance and use its :meth:`flatten` method directly. + For example:: - from cStringIO import StringIO - from email.generator import Generator - fp = StringIO() - g = Generator(fp, mangle_from_=False, maxheaderlen=60) - g.flatten(msg) - text = fp.getvalue() + from cStringIO import StringIO + from email.generator import Generator + fp = StringIO() + g = Generator(fp, mangle_from_=False, maxheaderlen=60) + g.flatten(msg) + text = fp.getvalue() -.. method:: Message.__str__() + .. method:: __str__() - Equivalent to ``as_string(unixfrom=True)``. + Equivalent to ``as_string(unixfrom=True)``. -.. method:: Message.is_multipart() + .. method:: is_multipart() - Return ``True`` if the message's payload is a list of sub-\ :class:`Message` - objects, otherwise return ``False``. When :meth:`is_multipart` returns False, - the payload should be a string object. + Return ``True`` if the message's payload is a list of sub-\ + :class:`Message` objects, otherwise return ``False``. When + :meth:`is_multipart` returns False, the payload should be a string object. -.. method:: Message.set_unixfrom(unixfrom) + .. method:: set_unixfrom(unixfrom) - Set the message's envelope header to *unixfrom*, which should be a string. + Set the message's envelope header to *unixfrom*, which should be a string. -.. method:: Message.get_unixfrom() + .. method:: get_unixfrom() - Return the message's envelope header. Defaults to ``None`` if the envelope - header was never set. + Return the message's envelope header. Defaults to ``None`` if the + envelope header was never set. -.. method:: Message.attach(payload) + .. method:: attach(payload) - Add the given *payload* to the current payload, which must be ``None`` or a list - of :class:`Message` objects before the call. After the call, the payload will - always be a list of :class:`Message` objects. If you want to set the payload to - a scalar object (e.g. a string), use :meth:`set_payload` instead. + Add the given *payload* to the current payload, which must be ``None`` or + a list of :class:`Message` objects before the call. After the call, the + payload will always be a list of :class:`Message` objects. If you want to + set the payload to a scalar object (e.g. a string), use + :meth:`set_payload` instead. -.. method:: Message.get_payload([i[, decode]]) + .. method:: get_payload([i[, decode]]) - Return a reference the current payload, which will be a list of :class:`Message` - objects when :meth:`is_multipart` is ``True``, or a string when - :meth:`is_multipart` is ``False``. If the payload is a list and you mutate the - list object, you modify the message's payload in place. + Return a reference the current payload, which will be a list of + :class:`Message` objects when :meth:`is_multipart` is ``True``, or a + string when :meth:`is_multipart` is ``False``. If the payload is a list + and you mutate the list object, you modify the message's payload in place. - With optional argument *i*, :meth:`get_payload` will return the *i*-th element - of the payload, counting from zero, if :meth:`is_multipart` is ``True``. An - :exc:`IndexError` will be raised if *i* is less than 0 or greater than or equal - to the number of items in the payload. If the payload is a string (i.e. - :meth:`is_multipart` is ``False``) and *i* is given, a :exc:`TypeError` is - raised. + With optional argument *i*, :meth:`get_payload` will return the *i*-th + element of the payload, counting from zero, if :meth:`is_multipart` is + ``True``. An :exc:`IndexError` will be raised if *i* is less than 0 or + greater than or equal to the number of items in the payload. If the + payload is a string (i.e. :meth:`is_multipart` is ``False``) and *i* is + given, a :exc:`TypeError` is raised. - Optional *decode* is a flag indicating whether the payload should be decoded or - not, according to the :mailheader:`Content-Transfer-Encoding` header. When - ``True`` and the message is not a multipart, the payload will be decoded if this - header's value is ``quoted-printable`` or ``base64``. If some other encoding is - used, or :mailheader:`Content-Transfer-Encoding` header is missing, or if the - payload has bogus base64 data, the payload is returned as-is (undecoded). If - the message is a multipart and the *decode* flag is ``True``, then ``None`` is - returned. The default for *decode* is ``False``. + Optional *decode* is a flag indicating whether the payload should be + decoded or not, according to the :mailheader:`Content-Transfer-Encoding` + header. When ``True`` and the message is not a multipart, the payload will + be decoded if this header's value is ``quoted-printable`` or ``base64``. + If some other encoding is used, or :mailheader:`Content-Transfer-Encoding` + header is missing, or if the payload has bogus base64 data, the payload is + returned as-is (undecoded). If the message is a multipart and the + *decode* flag is ``True``, then ``None`` is returned. The default for + *decode* is ``False``. -.. method:: Message.set_payload(payload[, charset]) + .. method:: set_payload(payload[, charset]) - Set the entire message object's payload to *payload*. It is the client's - responsibility to ensure the payload invariants. Optional *charset* sets the - message's default character set; see :meth:`set_charset` for details. + Set the entire message object's payload to *payload*. It is the client's + responsibility to ensure the payload invariants. Optional *charset* sets + the message's default character set; see :meth:`set_charset` for details. + .. method:: set_charset(charset) -.. method:: Message.set_charset(charset) + Set the character set of the payload to *charset*, which can either be a + :class:`Charset` instance (see :mod:`email.charset`), a string naming a + character set, or ``None``. If it is a string, it will be converted to a + :class:`Charset` instance. If *charset* is ``None``, the ``charset`` + parameter will be removed from the :mailheader:`Content-Type` + header. Anything else will generate a :exc:`TypeError`. - Set the character set of the payload to *charset*, which can either be a - :class:`Charset` instance (see :mod:`email.charset`), a string naming a - character set, or ``None``. If it is a string, it will be converted to a - :class:`Charset` instance. If *charset* is ``None``, the ``charset`` parameter - will be removed from the :mailheader:`Content-Type` header. Anything else will - generate a :exc:`TypeError`. + The message will be assumed to be of type :mimetype:`text/\*` encoded with + *charset.input_charset*. It will be converted to *charset.output_charset* + and encoded properly, if needed, when generating the plain text + representation of the message. MIME headers (:mailheader:`MIME-Version`, + :mailheader:`Content-Type`, :mailheader:`Content-Transfer-Encoding`) will + be added as needed. - The message will be assumed to be of type :mimetype:`text/\*` encoded with - *charset.input_charset*. It will be converted to *charset.output_charset* and - encoded properly, if needed, when generating the plain text representation of - the message. MIME headers (:mailheader:`MIME-Version`, - :mailheader:`Content-Type`, :mailheader:`Content-Transfer-Encoding`) will be - added as needed. + .. method:: get_charset() + Return the :class:`Charset` instance associated with the message's + payload. -.. method:: Message.get_charset() + The following methods implement a mapping-like interface for accessing the + message's :rfc:`2822` headers. Note that there are some semantic differences + between these methods and a normal mapping (i.e. dictionary) interface. For + example, in a dictionary there are no duplicate keys, but here there may be + duplicate message headers. Also, in dictionaries there is no guaranteed + order to the keys returned by :meth:`keys`, but in a :class:`Message` object, + headers are always returned in the order they appeared in the original + message, or were added to the message later. Any header deleted and then + re-added are always appended to the end of the header list. - Return the :class:`Charset` instance associated with the message's payload. + These semantic differences are intentional and are biased toward maximal + convenience. -The following methods implement a mapping-like interface for accessing the -message's :rfc:`2822` headers. Note that there are some semantic differences -between these methods and a normal mapping (i.e. dictionary) interface. For -example, in a dictionary there are no duplicate keys, but here there may be -duplicate message headers. Also, in dictionaries there is no guaranteed order -to the keys returned by :meth:`keys`, but in a :class:`Message` object, headers -are always returned in the order they appeared in the original message, or were -added to the message later. Any header deleted and then re-added are always -appended to the end of the header list. + Note that in all cases, any envelope header present in the message is not + included in the mapping interface. -These semantic differences are intentional and are biased toward maximal -convenience. -Note that in all cases, any envelope header present in the message is not -included in the mapping interface. + .. method:: __len__() + Return the total number of headers, including duplicates. -.. method:: Message.__len__() - Return the total number of headers, including duplicates. + .. method:: __contains__(name) + Return true if the message object has a field named *name*. Matching is + done case-insensitively and *name* should not include the trailing colon. + Used for the ``in`` operator, e.g.:: -.. method:: Message.__contains__(name) + if 'message-id' in myMessage: + print('Message-ID:', myMessage['message-id']) - Return true if the message object has a field named *name*. Matching is done - case-insensitively and *name* should not include the trailing colon. Used for - the ``in`` operator, e.g.:: - if 'message-id' in myMessage: - print('Message-ID:', myMessage['message-id']) + .. method:: __getitem__(name) + Return the value of the named header field. *name* should not include the + colon field separator. If the header is missing, ``None`` is returned; a + :exc:`KeyError` is never raised. -.. method:: Message.__getitem__(name) + Note that if the named field appears more than once in the message's + headers, exactly which of those field values will be returned is + undefined. Use the :meth:`get_all` method to get the values of all the + extant named headers. - Return the value of the named header field. *name* should not include the colon - field separator. If the header is missing, ``None`` is returned; a - :exc:`KeyError` is never raised. - Note that if the named field appears more than once in the message's headers, - exactly which of those field values will be returned is undefined. Use the - :meth:`get_all` method to get the values of all the extant named headers. + .. method:: __setitem__(name, val) + Add a header to the message with field name *name* and value *val*. The + field is appended to the end of the message's existing fields. -.. method:: Message.__setitem__(name, val) + Note that this does *not* overwrite or delete any existing header with the same + name. If you want to ensure that the new header is the only one present in the + message with field name *name*, delete the field first, e.g.:: - Add a header to the message with field name *name* and value *val*. The field - is appended to the end of the message's existing fields. + del msg['subject'] + msg['subject'] = 'Python roolz!' - Note that this does *not* overwrite or delete any existing header with the same - name. If you want to ensure that the new header is the only one present in the - message with field name *name*, delete the field first, e.g.:: - del msg['subject'] - msg['subject'] = 'Python roolz!' + .. method:: __delitem__(name) + Delete all occurrences of the field with name *name* from the message's + headers. No exception is raised if the named field isn't present in the headers. -.. method:: Message.__delitem__(name) - Delete all occurrences of the field with name *name* from the message's headers. - No exception is raised if the named field isn't present in the headers. + .. method:: Message.__contains__(name) + Return true if the message contains a header field named *name*, otherwise + return false. -.. method:: Message.__contains__(name) - Return true if the message contains a header field named *name*, otherwise - return false. + .. method:: keys() + Return a list of all the message's header field names. -.. method:: Message.keys() - Return a list of all the message's header field names. + .. method:: values() + Return a list of all the message's field values. -.. method:: Message.values() - Return a list of all the message's field values. + .. method:: items() + Return a list of 2-tuples containing all the message's field headers and + values. -.. method:: Message.items() - Return a list of 2-tuples containing all the message's field headers and values. + .. method:: get(name[, failobj]) + Return the value of the named header field. This is identical to + :meth:`__getitem__` except that optional *failobj* is returned if the + named header is missing (defaults to ``None``). -.. method:: Message.get(name[, failobj]) + Here are some additional useful methods: - Return the value of the named header field. This is identical to - :meth:`__getitem__` except that optional *failobj* is returned if the named - header is missing (defaults to ``None``). -Here are some additional useful methods: + .. method:: get_all(name[, failobj]) + Return a list of all the values for the field named *name*. If there are + no such named headers in the message, *failobj* is returned (defaults to + ``None``). -.. method:: Message.get_all(name[, failobj]) - Return a list of all the values for the field named *name*. If there are no such - named headers in the message, *failobj* is returned (defaults to ``None``). + .. method:: add_header(_name, _value, **_params) + Extended header setting. This method is similar to :meth:`__setitem__` + except that additional header parameters can be provided as keyword + arguments. *_name* is the header field to add and *_value* is the + *primary* value for the header. -.. method:: Message.add_header(_name, _value, **_params) + For each item in the keyword argument dictionary *_params*, the key is + taken as the parameter name, with underscores converted to dashes (since + dashes are illegal in Python identifiers). Normally, the parameter will + be added as ``key="value"`` unless the value is ``None``, in which case + only the key will be added. - Extended header setting. This method is similar to :meth:`__setitem__` except - that additional header parameters can be provided as keyword arguments. *_name* - is the header field to add and *_value* is the *primary* value for the header. + Here's an example:: - For each item in the keyword argument dictionary *_params*, the key is taken as - the parameter name, with underscores converted to dashes (since dashes are - illegal in Python identifiers). Normally, the parameter will be added as - ``key="value"`` unless the value is ``None``, in which case only the key will be - added. + msg.add_header('Content-Disposition', 'attachment', filename='bud.gif') - Here's an example:: + This will add a header that looks like :: - msg.add_header('Content-Disposition', 'attachment', filename='bud.gif') + Content-Disposition: attachment; filename="bud.gif" - This will add a header that looks like :: - Content-Disposition: attachment; filename="bud.gif" + .. method:: replace_header(_name, _value) + Replace a header. Replace the first header found in the message that + matches *_name*, retaining header order and field name case. If no + matching header was found, a :exc:`KeyError` is raised. -.. method:: Message.replace_header(_name, _value) - Replace a header. Replace the first header found in the message that matches - *_name*, retaining header order and field name case. If no matching header was - found, a :exc:`KeyError` is raised. + .. method:: get_content_type() + Return the message's content type. The returned string is coerced to + lower case of the form :mimetype:`maintype/subtype`. If there was no + :mailheader:`Content-Type` header in the message the default type as given + by :meth:`get_default_type` will be returned. Since according to + :rfc:`2045`, messages always have a default type, :meth:`get_content_type` + will always return a value. -.. method:: Message.get_content_type() + :rfc:`2045` defines a message's default type to be :mimetype:`text/plain` + unless it appears inside a :mimetype:`multipart/digest` container, in + which case it would be :mimetype:`message/rfc822`. If the + :mailheader:`Content-Type` header has an invalid type specification, + :rfc:`2045` mandates that the default type be :mimetype:`text/plain`. - Return the message's content type. The returned string is coerced to lower case - of the form :mimetype:`maintype/subtype`. If there was no - :mailheader:`Content-Type` header in the message the default type as given by - :meth:`get_default_type` will be returned. Since according to :rfc:`2045`, - messages always have a default type, :meth:`get_content_type` will always return - a value. - :rfc:`2045` defines a message's default type to be :mimetype:`text/plain` unless - it appears inside a :mimetype:`multipart/digest` container, in which case it - would be :mimetype:`message/rfc822`. If the :mailheader:`Content-Type` header - has an invalid type specification, :rfc:`2045` mandates that the default type be - :mimetype:`text/plain`. + .. method:: get_content_maintype() + Return the message's main content type. This is the :mimetype:`maintype` + part of the string returned by :meth:`get_content_type`. -.. method:: Message.get_content_maintype() - Return the message's main content type. This is the :mimetype:`maintype` part - of the string returned by :meth:`get_content_type`. + .. method:: get_content_subtype() + Return the message's sub-content type. This is the :mimetype:`subtype` + part of the string returned by :meth:`get_content_type`. -.. method:: Message.get_content_subtype() - Return the message's sub-content type. This is the :mimetype:`subtype` part of - the string returned by :meth:`get_content_type`. + .. method:: get_default_type() + Return the default content type. Most messages have a default content + type of :mimetype:`text/plain`, except for messages that are subparts of + :mimetype:`multipart/digest` containers. Such subparts have a default + content type of :mimetype:`message/rfc822`. -.. method:: Message.get_default_type() - Return the default content type. Most messages have a default content type of - :mimetype:`text/plain`, except for messages that are subparts of - :mimetype:`multipart/digest` containers. Such subparts have a default content - type of :mimetype:`message/rfc822`. + .. method:: set_default_type(ctype) + Set the default content type. *ctype* should either be + :mimetype:`text/plain` or :mimetype:`message/rfc822`, although this is not + enforced. The default content type is not stored in the + :mailheader:`Content-Type` header. -.. method:: Message.set_default_type(ctype) - Set the default content type. *ctype* should either be :mimetype:`text/plain` - or :mimetype:`message/rfc822`, although this is not enforced. The default - content type is not stored in the :mailheader:`Content-Type` header. + .. method:: get_params([failobj[, header[, unquote]]]) + Return the message's :mailheader:`Content-Type` parameters, as a list. + The elements of the returned list are 2-tuples of key/value pairs, as + split on the ``'='`` sign. The left hand side of the ``'='`` is the key, + while the right hand side is the value. If there is no ``'='`` sign in + the parameter the value is the empty string, otherwise the value is as + described in :meth:`get_param` and is unquoted if optional *unquote* is + ``True`` (the default). -.. method:: Message.get_params([failobj[, header[, unquote]]]) + Optional *failobj* is the object to return if there is no + :mailheader:`Content-Type` header. Optional *header* is the header to + search instead of :mailheader:`Content-Type`. - Return the message's :mailheader:`Content-Type` parameters, as a list. The - elements of the returned list are 2-tuples of key/value pairs, as split on the - ``'='`` sign. The left hand side of the ``'='`` is the key, while the right - hand side is the value. If there is no ``'='`` sign in the parameter the value - is the empty string, otherwise the value is as described in :meth:`get_param` - and is unquoted if optional *unquote* is ``True`` (the default). - Optional *failobj* is the object to return if there is no - :mailheader:`Content-Type` header. Optional *header* is the header to search - instead of :mailheader:`Content-Type`. + .. method:: get_param(param[, failobj[, header[, unquote]]]) + Return the value of the :mailheader:`Content-Type` header's parameter + *param* as a string. If the message has no :mailheader:`Content-Type` + header or if there is no such parameter, then *failobj* is returned + (defaults to ``None``). -.. method:: Message.get_param(param[, failobj[, header[, unquote]]]) + Optional *header* if given, specifies the message header to use instead of + :mailheader:`Content-Type`. - Return the value of the :mailheader:`Content-Type` header's parameter *param* as - a string. If the message has no :mailheader:`Content-Type` header or if there - is no such parameter, then *failobj* is returned (defaults to ``None``). + Parameter keys are always compared case insensitively. The return value + can either be a string, or a 3-tuple if the parameter was :rfc:`2231` + encoded. When it's a 3-tuple, the elements of the value are of the form + ``(CHARSET, LANGUAGE, VALUE)``. Note that both ``CHARSET`` and + ``LANGUAGE`` can be ``None``, in which case you should consider ``VALUE`` + to be encoded in the ``us-ascii`` charset. You can usually ignore + ``LANGUAGE``. - Optional *header* if given, specifies the message header to use instead of - :mailheader:`Content-Type`. + If your application doesn't care whether the parameter was encoded as in + :rfc:`2231`, you can collapse the parameter value by calling + :func:`email.Utils.collapse_rfc2231_value`, passing in the return value + from :meth:`get_param`. This will return a suitably decoded Unicode + string whn the value is a tuple, or the original string unquoted if it + isn't. For example:: - Parameter keys are always compared case insensitively. The return value can - either be a string, or a 3-tuple if the parameter was :rfc:`2231` encoded. When - it's a 3-tuple, the elements of the value are of the form ``(CHARSET, LANGUAGE, - VALUE)``. Note that both ``CHARSET`` and ``LANGUAGE`` can be ``None``, in which - case you should consider ``VALUE`` to be encoded in the ``us-ascii`` charset. - You can usually ignore ``LANGUAGE``. + rawparam = msg.get_param('foo') + param = email.Utils.collapse_rfc2231_value(rawparam) - If your application doesn't care whether the parameter was encoded as in - :rfc:`2231`, you can collapse the parameter value by calling - :func:`email.Utils.collapse_rfc2231_value`, passing in the return value from - :meth:`get_param`. This will return a suitably decoded Unicode string whn the - value is a tuple, or the original string unquoted if it isn't. For example:: + In any case, the parameter value (either the returned string, or the + ``VALUE`` item in the 3-tuple) is always unquoted, unless *unquote* is set + to ``False``. - rawparam = msg.get_param('foo') - param = email.Utils.collapse_rfc2231_value(rawparam) - In any case, the parameter value (either the returned string, or the ``VALUE`` - item in the 3-tuple) is always unquoted, unless *unquote* is set to ``False``. + .. method:: set_param(param, value[, header[, requote[, charset[, language]]]]) + Set a parameter in the :mailheader:`Content-Type` header. If the + parameter already exists in the header, its value will be replaced with + *value*. If the :mailheader:`Content-Type` header as not yet been defined + for this message, it will be set to :mimetype:`text/plain` and the new + parameter value will be appended as per :rfc:`2045`. -.. method:: Message.set_param(param, value[, header[, requote[, charset[, language]]]]) + Optional *header* specifies an alternative header to + :mailheader:`Content-Type`, and all parameters will be quoted as necessary + unless optional *requote* is ``False`` (the default is ``True``). - Set a parameter in the :mailheader:`Content-Type` header. If the parameter - already exists in the header, its value will be replaced with *value*. If the - :mailheader:`Content-Type` header as not yet been defined for this message, it - will be set to :mimetype:`text/plain` and the new parameter value will be - appended as per :rfc:`2045`. + If optional *charset* is specified, the parameter will be encoded + according to :rfc:`2231`. Optional *language* specifies the RFC 2231 + language, defaulting to the empty string. Both *charset* and *language* + should be strings. - Optional *header* specifies an alternative header to :mailheader:`Content-Type`, - and all parameters will be quoted as necessary unless optional *requote* is - ``False`` (the default is ``True``). - If optional *charset* is specified, the parameter will be encoded according to - :rfc:`2231`. Optional *language* specifies the RFC 2231 language, defaulting to - the empty string. Both *charset* and *language* should be strings. + .. method:: del_param(param[, header[, requote]]) + Remove the given parameter completely from the :mailheader:`Content-Type` + header. The header will be re-written in place without the parameter or + its value. All values will be quoted as necessary unless *requote* is + ``False`` (the default is ``True``). Optional *header* specifies an + alternative to :mailheader:`Content-Type`. -.. method:: Message.del_param(param[, header[, requote]]) - Remove the given parameter completely from the :mailheader:`Content-Type` - header. The header will be re-written in place without the parameter or its - value. All values will be quoted as necessary unless *requote* is ``False`` - (the default is ``True``). Optional *header* specifies an alternative to - :mailheader:`Content-Type`. + .. method:: set_type(type[, header][, requote]) + Set the main type and subtype for the :mailheader:`Content-Type` + header. *type* must be a string in the form :mimetype:`maintype/subtype`, + otherwise a :exc:`ValueError` is raised. -.. method:: Message.set_type(type[, header][, requote]) + This method replaces the :mailheader:`Content-Type` header, keeping all + the parameters in place. If *requote* is ``False``, this leaves the + existing header's quoting as is, otherwise the parameters will be quoted + (the default). - Set the main type and subtype for the :mailheader:`Content-Type` header. *type* - must be a string in the form :mimetype:`maintype/subtype`, otherwise a - :exc:`ValueError` is raised. + An alternative header can be specified in the *header* argument. When the + :mailheader:`Content-Type` header is set a :mailheader:`MIME-Version` + header is also added. - This method replaces the :mailheader:`Content-Type` header, keeping all the - parameters in place. If *requote* is ``False``, this leaves the existing - header's quoting as is, otherwise the parameters will be quoted (the default). - An alternative header can be specified in the *header* argument. When the - :mailheader:`Content-Type` header is set a :mailheader:`MIME-Version` header is - also added. + .. method:: get_filename([failobj]) + Return the value of the ``filename`` parameter of the + :mailheader:`Content-Disposition` header of the message. If the header + does not have a ``filename`` parameter, this method falls back to looking + for the ``name`` parameter. If neither is found, or the header is + missing, then *failobj* is returned. The returned string will always be + unquoted as per :meth:`Utils.unquote`. -.. method:: Message.get_filename([failobj]) - Return the value of the ``filename`` parameter of the - :mailheader:`Content-Disposition` header of the message. If the header does not - have a ``filename`` parameter, this method falls back to looking for the - ``name`` parameter. If neither is found, or the header is missing, then - *failobj* is returned. The returned string will always be unquoted as per - :meth:`Utils.unquote`. + .. method:: get_boundary([failobj]) + Return the value of the ``boundary`` parameter of the + :mailheader:`Content-Type` header of the message, or *failobj* if either + the header is missing, or has no ``boundary`` parameter. The returned + string will always be unquoted as per :meth:`Utils.unquote`. -.. method:: Message.get_boundary([failobj]) - Return the value of the ``boundary`` parameter of the :mailheader:`Content-Type` - header of the message, or *failobj* if either the header is missing, or has no - ``boundary`` parameter. The returned string will always be unquoted as per - :meth:`Utils.unquote`. + .. method:: set_boundary(boundary) + Set the ``boundary`` parameter of the :mailheader:`Content-Type` header to + *boundary*. :meth:`set_boundary` will always quote *boundary* if + necessary. A :exc:`HeaderParseError` is raised if the message object has + no :mailheader:`Content-Type` header. -.. method:: Message.set_boundary(boundary) + Note that using this method is subtly different than deleting the old + :mailheader:`Content-Type` header and adding a new one with the new + boundary via :meth:`add_header`, because :meth:`set_boundary` preserves + the order of the :mailheader:`Content-Type` header in the list of + headers. However, it does *not* preserve any continuation lines which may + have been present in the original :mailheader:`Content-Type` header. - Set the ``boundary`` parameter of the :mailheader:`Content-Type` header to - *boundary*. :meth:`set_boundary` will always quote *boundary* if necessary. A - :exc:`HeaderParseError` is raised if the message object has no - :mailheader:`Content-Type` header. - Note that using this method is subtly different than deleting the old - :mailheader:`Content-Type` header and adding a new one with the new boundary via - :meth:`add_header`, because :meth:`set_boundary` preserves the order of the - :mailheader:`Content-Type` header in the list of headers. However, it does *not* - preserve any continuation lines which may have been present in the original - :mailheader:`Content-Type` header. + .. method:: get_content_charset([failobj]) + Return the ``charset`` parameter of the :mailheader:`Content-Type` header, + coerced to lower case. If there is no :mailheader:`Content-Type` header, or if + that header has no ``charset`` parameter, *failobj* is returned. -.. method:: Message.get_content_charset([failobj]) + Note that this method differs from :meth:`get_charset` which returns the + :class:`Charset` instance for the default encoding of the message body. - Return the ``charset`` parameter of the :mailheader:`Content-Type` header, - coerced to lower case. If there is no :mailheader:`Content-Type` header, or if - that header has no ``charset`` parameter, *failobj* is returned. - Note that this method differs from :meth:`get_charset` which returns the - :class:`Charset` instance for the default encoding of the message body. + .. method:: get_charsets([failobj]) + Return a list containing the character set names in the message. If the + message is a :mimetype:`multipart`, then the list will contain one element + for each subpart in the payload, otherwise, it will be a list of length 1. -.. method:: Message.get_charsets([failobj]) + Each item in the list will be a string which is the value of the + ``charset`` parameter in the :mailheader:`Content-Type` header for the + represented subpart. However, if the subpart has no + :mailheader:`Content-Type` header, no ``charset`` parameter, or is not of + the :mimetype:`text` main MIME type, then that item in the returned list + will be *failobj*. - Return a list containing the character set names in the message. If the message - is a :mimetype:`multipart`, then the list will contain one element for each - subpart in the payload, otherwise, it will be a list of length 1. - Each item in the list will be a string which is the value of the ``charset`` - parameter in the :mailheader:`Content-Type` header for the represented subpart. - However, if the subpart has no :mailheader:`Content-Type` header, no ``charset`` - parameter, or is not of the :mimetype:`text` main MIME type, then that item in - the returned list will be *failobj*. + .. method:: walk() + The :meth:`walk` method is an all-purpose generator which can be used to + iterate over all the parts and subparts of a message object tree, in + depth-first traversal order. You will typically use :meth:`walk` as the + iterator in a ``for`` loop; each iteration returns the next subpart. -.. method:: Message.walk() + Here's an example that prints the MIME type of every part of a multipart + message structure:: - The :meth:`walk` method is an all-purpose generator which can be used to iterate - over all the parts and subparts of a message object tree, in depth-first - traversal order. You will typically use :meth:`walk` as the iterator in a - ``for`` loop; each iteration returns the next subpart. + >>> for part in msg.walk(): + ... print(part.get_content_type()) + multipart/report + text/plain + message/delivery-status + text/plain + text/plain + message/rfc822 - Here's an example that prints the MIME type of every part of a multipart message - structure:: + :class:`Message` objects can also optionally contain two instance attributes, + which can be used when generating the plain text of a MIME message. - >>> for part in msg.walk(): - ... print(part.get_content_type()) - multipart/report - text/plain - message/delivery-status - text/plain - text/plain - message/rfc822 -:class:`Message` objects can also optionally contain two instance attributes, -which can be used when generating the plain text of a MIME message. + .. attribute:: preamble + The format of a MIME document allows for some text between the blank line + following the headers, and the first multipart boundary string. Normally, + this text is never visible in a MIME-aware mail reader because it falls + outside the standard MIME armor. However, when viewing the raw text of + the message, or when viewing the message in a non-MIME aware reader, this + text can become visible. -.. data:: preamble + The *preamble* attribute contains this leading extra-armor text for MIME + documents. When the :class:`Parser` discovers some text after the headers + but before the first boundary string, it assigns this text to the + message's *preamble* attribute. When the :class:`Generator` is writing + out the plain text representation of a MIME message, and it finds the + message has a *preamble* attribute, it will write this text in the area + between the headers and the first boundary. See :mod:`email.parser` and + :mod:`email.generator` for details. - The format of a MIME document allows for some text between the blank line - following the headers, and the first multipart boundary string. Normally, this - text is never visible in a MIME-aware mail reader because it falls outside the - standard MIME armor. However, when viewing the raw text of the message, or when - viewing the message in a non-MIME aware reader, this text can become visible. + Note that if the message object has no preamble, the *preamble* attribute + will be ``None``. - The *preamble* attribute contains this leading extra-armor text for MIME - documents. When the :class:`Parser` discovers some text after the headers but - before the first boundary string, it assigns this text to the message's - *preamble* attribute. When the :class:`Generator` is writing out the plain text - representation of a MIME message, and it finds the message has a *preamble* - attribute, it will write this text in the area between the headers and the first - boundary. See :mod:`email.parser` and :mod:`email.generator` for details. - Note that if the message object has no preamble, the *preamble* attribute will - be ``None``. + .. attribute:: epilogue + The *epilogue* attribute acts the same way as the *preamble* attribute, + except that it contains text that appears between the last boundary and + the end of the message. -.. data:: epilogue + You do not need to set the epilogue to the empty string in order for the + :class:`Generator` to print a newline at the end of the file. - The *epilogue* attribute acts the same way as the *preamble* attribute, except - that it contains text that appears between the last boundary and the end of the - message. - You do not need to set the epilogue to the empty string in order for the - :class:`Generator` to print a newline at the end of the file. + .. attribute:: defects - -.. data:: defects - - The *defects* attribute contains a list of all the problems found when parsing - this message. See :mod:`email.errors` for a detailed description of the - possible parsing defects. + The *defects* attribute contains a list of all the problems found when + parsing this message. See :mod:`email.errors` for a detailed description + of the possible parsing defects. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/email.parser.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/email.parser.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/email.parser.rst Wed Apr 30 15:57:13 2008 @@ -65,20 +65,21 @@ defaults to the :class:`email.message.Message` class. -.. method:: FeedParser.feed(data) + .. method:: feed(data) - Feed the :class:`FeedParser` some more data. *data* should be a string - containing one or more lines. The lines can be partial and the - :class:`FeedParser` will stitch such partial lines together properly. The lines - in the string can have any of the common three line endings, carriage return, - newline, or carriage return and newline (they can even be mixed). + Feed the :class:`FeedParser` some more data. *data* should be a string + containing one or more lines. The lines can be partial and the + :class:`FeedParser` will stitch such partial lines together properly. The + lines in the string can have any of the common three line endings, + carriage return, newline, or carriage return and newline (they can even be + mixed). -.. method:: FeedParser.close() + .. method:: close() - Closing a :class:`FeedParser` completes the parsing of all previously fed data, - and returns the root message object. It is undefined what happens if you feed - more data to a closed :class:`FeedParser`. + Closing a :class:`FeedParser` completes the parsing of all previously fed + data, and returns the root message object. It is undefined what happens + if you feed more data to a closed :class:`FeedParser`. Parser class API @@ -111,33 +112,33 @@ effectively non-strict. You should simply stop passing a *strict* flag to the :class:`Parser` constructor. -The other public :class:`Parser` methods are: + The other public :class:`Parser` methods are: -.. method:: Parser.parse(fp[, headersonly]) + .. method:: parse(fp[, headersonly]) - Read all the data from the file-like object *fp*, parse the resulting text, and - return the root message object. *fp* must support both the :meth:`readline` and - the :meth:`read` methods on file-like objects. + Read all the data from the file-like object *fp*, parse the resulting + text, and return the root message object. *fp* must support both the + :meth:`readline` and the :meth:`read` methods on file-like objects. - The text contained in *fp* must be formatted as a block of :rfc:`2822` style - headers and header continuation lines, optionally preceded by a envelope - header. The header block is terminated either by the end of the data or by a - blank line. Following the header block is the body of the message (which may - contain MIME-encoded subparts). + The text contained in *fp* must be formatted as a block of :rfc:`2822` + style headers and header continuation lines, optionally preceded by a + envelope header. The header block is terminated either by the end of the + data or by a blank line. Following the header block is the body of the + message (which may contain MIME-encoded subparts). - Optional *headersonly* is as with the :meth:`parse` method. + Optional *headersonly* is as with the :meth:`parse` method. + .. method:: parsestr(text[, headersonly]) -.. method:: Parser.parsestr(text[, headersonly]) + Similar to the :meth:`parse` method, except it takes a string object + instead of a file-like object. Calling this method on a string is exactly + equivalent to wrapping *text* in a :class:`StringIO` instance first and + calling :meth:`parse`. - Similar to the :meth:`parse` method, except it takes a string object instead of - a file-like object. Calling this method on a string is exactly equivalent to - wrapping *text* in a :class:`StringIO` instance first and calling :meth:`parse`. - - Optional *headersonly* is a flag specifying whether to stop parsing after - reading the headers or not. The default is ``False``, meaning it parses the - entire contents of the file. + Optional *headersonly* is a flag specifying whether to stop parsing after + reading the headers or not. The default is ``False``, meaning it parses + the entire contents of the file. Since creating a message object structure from a string or a file object is such Modified: python/branches/py3k-ctypes-pep3118/Doc/library/email.util.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/email.util.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/email.util.rst Wed Apr 30 15:57:13 2008 @@ -130,10 +130,10 @@ When a header parameter is encoded in :rfc:`2231` format, :meth:`Message.get_param` may return a 3-tuple containing the character set, language, and value. :func:`collapse_rfc2231_value` turns this into a unicode - string. Optional *errors* is passed to the *errors* argument of the built-in - :func:`unicode` function; it defaults to ``replace``. Optional + string. Optional *errors* is passed to the *errors* argument of :class:`str`'s + :func:`encode` method; it defaults to ``'replace'``. Optional *fallback_charset* specifies the character set to use if the one in the - :rfc:`2231` header is not known by Python; it defaults to ``us-ascii``. + :rfc:`2231` header is not known by Python; it defaults to ``'us-ascii'``. For convenience, if the *value* passed to :func:`collapse_rfc2231_value` is not a tuple, it should be a string and it is returned unquoted. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/fcntl.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/fcntl.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/fcntl.rst Wed Apr 30 15:57:13 2008 @@ -47,9 +47,10 @@ .. function:: ioctl(fd, op[, arg[, mutate_flag]]) This function is identical to the :func:`fcntl` function, except that the - operations are typically defined in the library module :mod:`termios` and the argument handling is even more complicated. + The op parameter is limited to values that can fit in 32-bits. + The parameter *arg* can be one of an integer, absent (treated identically to the integer ``0``), an object supporting the read-only buffer interface (most likely a plain Python string) or an object supporting the read-write buffer interface. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/filecmp.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/filecmp.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/filecmp.rst Wed Apr 30 15:57:13 2008 @@ -66,88 +66,91 @@ 'tags']``. *hide* is a list of names to hide, and defaults to ``[os.curdir, os.pardir]``. -The :class:`dircmp` class provides the following methods: + The :class:`dircmp` class provides the following methods: -.. method:: dircmp.report() + .. method:: report() - Print (to ``sys.stdout``) a comparison between *a* and *b*. + Print (to ``sys.stdout``) a comparison between *a* and *b*. -.. method:: dircmp.report_partial_closure() + .. method:: report_partial_closure() - Print a comparison between *a* and *b* and common immediate subdirectories. + Print a comparison between *a* and *b* and common immediate + subdirectories. -.. method:: dircmp.report_full_closure() + .. method:: report_full_closure() - Print a comparison between *a* and *b* and common subdirectories (recursively). + Print a comparison between *a* and *b* and common subdirectories + (recursively). -The :class:`dircmp` offers a number of interesting attributes that may be used -to get various bits of information about the directory trees being compared. + The :class:`dircmp` offers a number of interesting attributes that may be + used to get various bits of information about the directory trees being + compared. -Note that via :meth:`__getattr__` hooks, all attributes are computed lazily, so -there is no speed penalty if only those attributes which are lightweight to -compute are used. + Note that via :meth:`__getattr__` hooks, all attributes are computed lazily, + so there is no speed penalty if only those attributes which are lightweight + to compute are used. -.. attribute:: dircmp.left_list + .. attribute:: left_list - Files and subdirectories in *a*, filtered by *hide* and *ignore*. + Files and subdirectories in *a*, filtered by *hide* and *ignore*. -.. attribute:: dircmp.right_list + .. attribute:: right_list - Files and subdirectories in *b*, filtered by *hide* and *ignore*. + Files and subdirectories in *b*, filtered by *hide* and *ignore*. -.. attribute:: dircmp.common + .. attribute:: common - Files and subdirectories in both *a* and *b*. + Files and subdirectories in both *a* and *b*. -.. attribute:: dircmp.left_only + .. attribute:: left_only - Files and subdirectories only in *a*. + Files and subdirectories only in *a*. -.. attribute:: dircmp.right_only + .. attribute:: right_only - Files and subdirectories only in *b*. + Files and subdirectories only in *b*. -.. attribute:: dircmp.common_dirs + .. attribute:: common_dirs - Subdirectories in both *a* and *b*. + Subdirectories in both *a* and *b*. -.. attribute:: dircmp.common_files + .. attribute:: common_files - Files in both *a* and *b* + Files in both *a* and *b* -.. attribute:: dircmp.common_funny + .. attribute:: common_funny - Names in both *a* and *b*, such that the type differs between the directories, - or names for which :func:`os.stat` reports an error. + Names in both *a* and *b*, such that the type differs between the + directories, or names for which :func:`os.stat` reports an error. -.. attribute:: dircmp.same_files + .. attribute:: same_files - Files which are identical in both *a* and *b*. + Files which are identical in both *a* and *b*. -.. attribute:: dircmp.diff_files + .. attribute:: diff_files - Files which are in both *a* and *b*, whose contents differ. + Files which are in both *a* and *b*, whose contents differ. -.. attribute:: dircmp.funny_files + .. attribute:: funny_files - Files which are in both *a* and *b*, but could not be compared. + Files which are in both *a* and *b*, but could not be compared. -.. attribute:: dircmp.subdirs + .. attribute:: subdirs - A dictionary mapping names in :attr:`common_dirs` to :class:`dircmp` objects. + A dictionary mapping names in :attr:`common_dirs` to :class:`dircmp` objects. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/fileinput.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/fileinput.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/fileinput.rst Wed Apr 30 15:57:13 2008 @@ -168,9 +168,3 @@ Usage example: ``fi = fileinput.FileInput(openhook=fileinput.hook_encoded("iso-8859-1"))`` - - .. note:: - - With this hook, :class:`FileInput` might return Unicode strings depending on the - specified *encoding*. - Modified: python/branches/py3k-ctypes-pep3118/Doc/library/fnmatch.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/fnmatch.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/fnmatch.rst Wed Apr 30 15:57:13 2008 @@ -70,7 +70,7 @@ Return the shell-style *pattern* converted to a regular expression. - Example:: + Example: >>> import fnmatch, re >>> Modified: python/branches/py3k-ctypes-pep3118/Doc/library/ftplib.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/ftplib.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/ftplib.rst Wed Apr 30 15:57:13 2008 @@ -47,33 +47,34 @@ or passed as None, the global default timeout setting will be used). -.. data:: all_errors + .. attribute:: all_errors - The set of all exceptions (as a tuple) that methods of :class:`FTP` instances - may raise as a result of problems with the FTP connection (as opposed to - programming errors made by the caller). This set includes the four exceptions - listed below as well as :exc:`socket.error` and :exc:`IOError`. + The set of all exceptions (as a tuple) that methods of :class:`FTP` + instances may raise as a result of problems with the FTP connection (as + opposed to programming errors made by the caller). This set includes the + four exceptions listed below as well as :exc:`socket.error` and + :exc:`IOError`. -.. exception:: error_reply + .. exception:: error_reply - Exception raised when an unexpected reply is received from the server. + Exception raised when an unexpected reply is received from the server. -.. exception:: error_temp + .. exception:: error_temp - Exception raised when an error code in the range 400--499 is received. + Exception raised when an error code in the range 400--499 is received. -.. exception:: error_perm + .. exception:: error_perm - Exception raised when an error code in the range 500--599 is received. + Exception raised when an error code in the range 500--599 is received. -.. exception:: error_proto + .. exception:: error_proto - Exception raised when a reply is received from the server that does not begin - with a digit in the range 1--5. + Exception raised when a reply is received from the server that does not + begin with a digit in the range 1--5. .. seealso:: @@ -176,11 +177,12 @@ .. method:: FTP.retrlines(command[, callback]) - Retrieve a file or directory listing in ASCII transfer mode. *command* should be - an appropriate ``RETR`` command (see :meth:`retrbinary`) or a ``LIST`` command - (usually just the string ``'LIST'``). The *callback* function is called for - each line, with the trailing CRLF stripped. The default *callback* prints the - line to ``sys.stdout``. + Retrieve a file or directory listing in ASCII transfer mode. *command* + should be an appropriate ``RETR`` command (see :meth:`retrbinary`) or a + command such as ``LIST``, ``NLST`` or ``MLSD`` (usually just the string + ``'LIST'``). The *callback* function is called for each line, with the + trailing CRLF stripped. The default *callback* prints the line to + ``sys.stdout``. .. method:: FTP.set_pasv(boolean) @@ -190,20 +192,23 @@ it is on by default.) -.. method:: FTP.storbinary(command, file[, blocksize]) +.. method:: FTP.storbinary(command, file[, blocksize, callback]) Store a file in binary transfer mode. *command* should be an appropriate ``STOR`` command: ``"STOR filename"``. *file* is an open file object which is read until EOF using its :meth:`read` method in blocks of size *blocksize* to provide the data to be stored. The *blocksize* argument defaults to 8192. + *callback* is an optional single parameter callable that is called + on each block of data after it is sent. -.. method:: FTP.storlines(command, file) +.. method:: FTP.storlines(command, file[, callback]) Store a file in ASCII transfer mode. *command* should be an appropriate ``STOR`` command (see :meth:`storbinary`). Lines are read until EOF from the open file object *file* using its :meth:`readline` method to provide the data to - be stored. + be stored. *callback* is an optional single parameter callable + that is called on each line after it is sent. .. method:: FTP.transfercmd(cmd[, rest]) Modified: python/branches/py3k-ctypes-pep3118/Doc/library/functions.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/functions.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/functions.rst Wed Apr 30 15:57:13 2008 @@ -1,4 +1,4 @@ - +.. XXX document all delegations to __special__ methods .. _built-in-funcs: Built-in Functions @@ -92,14 +92,6 @@ return False -.. function:: basestring() - - This abstract type is the superclass for :class:`str`. It - cannot be called or instantiated, but it can be used to test whether an object - is an instance of :class:`str` (or a user-defined type inherited from - :class:`basestring`). - - .. function:: bin(x) Convert an integer number to a binary string. The result is a valid Python @@ -129,7 +121,7 @@ different ways: * If it is a *string*, you must also give the *encoding* (and optionally, - *errors*) parameters; :func:`bytearray` then converts the Unicode string to + *errors*) parameters; :func:`bytearray` then converts the string to bytes using :meth:`str.encode`. * If it is an *integer*, the array will have that size and will be @@ -201,21 +193,21 @@ .. function:: compile(source, filename, mode[, flags[, dont_inherit]]) - Compile the *source* into a code object. Code objects can be executed by a call - to :func:`exec` or evaluated by a call to :func:`eval`. The *filename* argument - should give the file from which the code was read; pass some recognizable value - if it wasn't read from a file (``''`` is commonly used). The *mode* - argument specifies what kind of code must be compiled; it can be ``'exec'`` if - *source* consists of a sequence of statements, ``'eval'`` if it consists of a - single expression, or ``'single'`` if it consists of a single interactive - statement (in the latter case, expression statements that evaluate to something - else than ``None`` will be printed). - - When compiling multi-line statements, two caveats apply: line endings must be - represented by a single newline character (``'\n'``), and the input must be - terminated by at least one newline character. If line endings are represented - by ``'\r\n'``, use the string :meth:`replace` method to change them into - ``'\n'``. + Compile the *source* into a code object. Code objects can be + executed by a call to :func:`exec` or evaluated by a call to + :func:`eval`. *source* can either be a string or an AST object. + Refer to the :mod:`_ast` module documentation for information on + how to compile into and from AST objects. + + The *filename* argument should give the file from + which the code was read; pass some recognizable value if it wasn't + read from a file (``''`` is commonly used). The *mode* + argument specifies what kind of code must be compiled; it can be + ``'exec'`` if *source* consists of a sequence of statements, + ``'eval'`` if it consists of a single expression, or ``'single'`` + if it consists of a single interactive statement (in the latter + case, expression statements that evaluate to something else than + ``None`` will be printed). The optional arguments *flags* and *dont_inherit* (which are new in Python 2.2) control which future statements (see :pep:`236`) affect the compilation of @@ -296,13 +288,15 @@ class's attributes, and recursively of the attributes of its class's base classes. - The resulting list is sorted alphabetically. For example:: + The resulting list is sorted alphabetically. For example: >>> import struct - >>> dir() + >>> dir() # doctest: +SKIP ['__builtins__', '__doc__', '__name__', 'struct'] - >>> dir(struct) - ['__doc__', '__name__', 'calcsize', 'error', 'pack', 'unpack'] + >>> dir(struct) # doctest: +NORMALIZE_WHITESPACE + ['Struct', '__builtins__', '__doc__', '__file__', '__name__', + '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', + 'unpack', 'unpack_from'] >>> class Foo(object): ... def __dir__(self): ... return ["kan", "ga", "roo"] @@ -339,10 +333,10 @@ iterator returned by :func:`enumerate` returns a tuple containing a count (from zero) and the corresponding value obtained from iterating over *iterable*. :func:`enumerate` is useful for obtaining an indexed series: ``(0, seq[0])``, - ``(1, seq[1])``, ``(2, seq[2])``, .... For example:: + ``(1, seq[1])``, ``(2, seq[2])``, .... For example: >>> for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter')]: - >>> print(i, season) + ... print(i, season) 0 Spring 1 Summer 2 Fall @@ -364,7 +358,7 @@ propagated. If the *locals* dictionary is omitted it defaults to the *globals* dictionary. If both dictionaries are omitted, the expression is executed in the environment where :func:`eval` is called. The return value is the result of - the evaluated expression. Syntax errors are reported as exceptions. Example:: + the evaluated expression. Syntax errors are reported as exceptions. Example: >>> x = 1 >>> eval('x+1') @@ -415,10 +409,9 @@ .. warning:: The default *locals* act as described for function :func:`locals` below: - modifications to the default *locals* dictionary should not be attempted. Pass - an explicit *locals* dictionary if you need to see effects of the code on - *locals* after function :func:`execfile` returns. :func:`exec` cannot be - used reliably to modify a function's locals. + modifications to the default *locals* dictionary should not be attempted. + Pass an explicit *locals* dictionary if you need to see effects of the + code on *locals* after function :func:`exec` returns. .. function:: filter(function, iterable) @@ -560,18 +553,20 @@ to provide elaborate line editing and history features. -.. function:: int([x[, radix]]) +.. function:: int([number | string[, radix]]) - Convert a string or number to an integer. If the argument is a string, it - must contain a possibly signed number of arbitrary size, possibly embedded in - whitespace. The *radix* parameter gives the base for the conversion (which - is 10 by default) and may be any integer in the range [2, 36], or zero. If - *radix* is zero, the interpretation is the same as for integer literals. If - *radix* is specified and *x* is not a string, :exc:`TypeError` is raised. - Otherwise, the argument may be another integer, a floating point number or - any other object that has an :meth:`__int__` method. Conversion of floating - point numbers to integers truncates (towards zero). If no arguments are - given, returns ``0``. + Convert a number or string to an integer. If no arguments are given, return + ``0``. If a number is given, return ``number.__int__()``. Conversion of + floating point numbers to integers truncates towards zero. A string must be + a base-radix integer literal optionally preceded by '+' or '-' (with no space + in between) and optionally surrounded by whitespace. A base-n literal + consists of the digits 0 to n-1, with 'a' to 'z' (or 'A' to 'Z') having + values 10 to 35. The default radix is 10. The allowed values are 0 and 2-36. + Base-2, -8, and -16 literals can be optionally prefixed with ``0b``/``0B``, + ``0o``/``0O``, or ``0x``/``0X``, as with integer literals in code. Radix 0 + means to interpret exactly as a code literal, so that the actual radix is 2, + 8, 10, or 16, and so that ``int('010', 0)`` is not legal, while + ``int('010')`` is, as well as ``int('010', 8)``. The integer type is described in :ref:`typesnumeric`. @@ -624,10 +619,7 @@ returns ``['a', 'b', 'c']`` and ``list( (1, 2, 3) )`` returns ``[1, 2, 3]``. If no argument is given, returns a new empty list, ``[]``. - :class:`list` is a mutable sequence type, as documented in - :ref:`typesseq`. For other containers see the built in :class:`dict`, - :class:`set`, and :class:`tuple` classes, and the :mod:`collections` module. - + :class:`list` is a mutable sequence type, as documented in :ref:`typesseq`. .. function:: locals() @@ -679,7 +671,7 @@ .. function:: next(iterator[, default]) - Retrieve the next item from the *iterable* by calling its :meth:`__next__` + Retrieve the next item from the *iterator* by calling its :meth:`__next__` method. If *default* is given, it is returned if the iterator is exhausted, otherwise :exc:`StopIteration` is raised. @@ -703,94 +695,89 @@ :meth:`__index__` method that returns an integer. -.. function:: open(filename[, mode='r'[, buffering=None[, encoding=None[, errors=None[, newline=None[, closefd=True]]]]]]) +.. function:: open(file[, mode='r'[, buffering=None[, encoding=None[, errors=None[, newline=None[, closefd=True]]]]]]) - Open a file, returning an object of the :class:`file` type described in - section :ref:`bltin-file-objects`. If the file cannot be opened, - :exc:`IOError` is raised. When opening a file, it's preferable to use - :func:`open` instead of invoking the :class:`file` constructor directly. + Open a file. If the file cannot be opened, :exc:`IOError` is raised. - *filename* is either a string giving the name (and the path if the - file isn't in the current working directory) of the file to be - opened; or an integer file descriptor of the file to be wrapped. (If - a file descriptor is given, it is closed when the returned I/O object - is closed, unless *closefd* is set to ``False``.) + *file* is either a string giving the name (and the path if the file isn't in + the current working directory) of the file to be opened or an integer file + descriptor of the file to be wrapped. (If a file descriptor is given, it is + closed when the returned I/O object is closed, unless *closefd* is set to + ``False``.) *mode* is an optional string that specifies the mode in which the file is - opened. It defaults to ``'r'`` which means open for reading in text mode. - Other common values are ``'w'`` for writing (truncating the file if - it already exists), and ``'a'`` for appending (which on *some* Unix - systems means that *all* writes append to the end of the file - regardless of the current seek position). In text mode, if *encoding* - is not specified the encoding used is platform dependent. (For reading - and writing raw bytes use binary mode and leave *encoding* - unspecified.) The available modes are: - - * 'r' open for reading (default) - * 'w' open for writing, truncating the file first - * 'a' open for writing, appending to the end if the file exists - * 'b' binary mode - * 't' text mode (default) - * '+' open the file for updating (implies both reading and writing) - * 'U' universal newline mode (for backwards compatibility; - unnecessary in new code) - - The most commonly-used values of *mode* are ``'r'`` for reading, ``'w'`` for - writing (truncating the file if it already exists), and ``'a'`` for appending - (which on *some* Unix systems means that *all* writes append to the end of the - file regardless of the current seek position). If *mode* is omitted, it - defaults to ``'r'``. The default is to use text mode, which may convert - ``'\n'`` characters to a platform-specific representation on writing and back - on reading. Thus, when opening a binary file, you should append ``'b'`` to - the *mode* value to open the file in binary mode, which will improve - portability. (Appending ``'b'`` is useful even on systems that don't treat - binary and text files differently, where it serves as documentation.) See below - for more possible values of *mode*. + opened. It defaults to ``'r'`` which means open for reading in text mode. + Other common values are ``'w'`` for writing (truncating the file if it + already exists), and ``'a'`` for appending (which on *some* Unix systems, + means that *all* writes append to the end of the file regardless of the + current seek position). In text mode, if *encoding* is not specified the + encoding used is platform dependent. (For reading and writing raw bytes use + binary mode and leave *encoding* unspecified.) The available modes are: + + ========= =============================================================== + Character Meaning + --------- --------------------------------------------------------------- + ``'r'`` open for reading (default) + ``'w'`` open for writing, truncating the file first + ``'a'`` open for writing, appending to the end of the file if it exists + ``'b'`` binary mode + ``'t'`` text mode (default) + ``'+'`` open a disk file for updating (reading and writing) + ``'U'`` universal newline mode (for backwards compatibility; unneeded + for new code) + ========= =============================================================== + + The default mode is ``'rt'`` (open for reading text). For binary random + access, the mode ``'w+b'`` opens and truncates the file to 0 bytes, while + ``'r+b'`` opens the file without truncation. Python distinguishes between files opened in binary and text modes, even when the underlying operating system doesn't. Files opened in binary mode (appending ``'b'`` to the *mode* argument) return contents as - ``bytes`` objects without any decoding. In text mode (the default, - or when ``'t'`` is appended to the *mode* argument) the contents of + ``bytes`` objects without any decoding. In text mode (the default, or when + ``'t'`` is appended to the *mode* argument) the contents of the file are returned as strings, the bytes having been first decoded using a platform-dependent encoding or using the specified *encoding* if given. - *buffering* is an optional integer used to set the buffering policy. By - default full buffering is on. Pass 0 to switch buffering off (only - allowed in binary mode), 1 to set line buffering, and an integer > 1 - for full buffering. + *buffering* is an optional integer used to set the buffering policy. By + default full buffering is on. Pass 0 to switch buffering off (only allowed in + binary mode), 1 to set line buffering, and an integer > 1 for full buffering. - *encoding* is an optional string that specifies the file's encoding when - reading or writing in text mode---this argument should not be used in - binary mode. The default encoding is platform dependent, but any encoding - supported by Python can be used. (See the :mod:`codecs` module for - the list of supported encodings.) + *encoding* is the name of the encoding used to decode or encode the file. + This should only be used in text mode. The default encoding is platform + dependent, but any encoding supported by Python can be passed. See the + :mod:`codecs` module for the list of supported encodings. *errors* is an optional string that specifies how encoding errors are to be - handled---this argument should not be used in binary mode. Pass - ``'strict'`` to raise a :exc:`ValueError` exception if there is an encoding - error (the default of ``None`` has the same effect), or pass ``'ignore'`` - to ignore errors. (Note that ignoring encoding errors can lead to - data loss.) See the documentation for :func:`codecs.register` for a - list of the permitted encoding error strings. - - *newline* is an optional string that specifies the newline character(s). - When reading, if *newline* is ``None``, universal newlines mode is enabled. - Lines read in univeral newlines mode can end in ``'\n'``, ``'\r'``, - or ``'\r\n'``, and these are translated into ``'\n'``. If *newline* - is ``''``, universal newline mode is enabled, but line endings are - not translated. If any other string is given, lines are assumed to be - terminated by that string, and no translating is done. When writing, - if *newline* is ``None``, any ``'\n'`` characters written are - translated to the system default line separator, :attr:`os.linesep`. - If *newline* is ``''``, no translation takes place. If *newline* is - any of the other standard values, any ``'\n'`` characters written are - translated to the given string. - - *closefd* is an optional Boolean which specifies whether to keep the - underlying file descriptor open. It must be ``True`` (the default) if - a filename is given. + handled---this argument should not be used in binary mode. Pass ``'strict'`` + to raise a :exc:`ValueError` exception if there is an encoding error (the + default of ``None`` has the same effect), or pass ``'ignore'`` to ignore + errors. (Note that ignoring encoding errors can lead to data loss.) See the + documentation for :func:`codecs.register` for a list of the permitted + encoding error strings. + + *newline* controls how universal newlines works (it only applies to text + mode). It can be ``None``, ``''``, ``'\n'``, ``'\r'``, and ``'\r\n'``. It + works as follows: + + * On input, if *newline* is ``None``, universal newlines mode is enabled. + Lines in the input can end in ``'\n'``, ``'\r'``, or ``'\r\n'``, and these + are translated into ``'\n'`` before being returned to the caller. If it is + ``''``, universal newline mode is enabled, but line endings are returned to + the caller untranslated. If it has any of the other legal values, input + lines are only terminated by the given string, and the line ending is + returned to the caller untranslated. + + * On output, if *newline* is ``None``, any ``'\n'`` characters written are + translated to the system default line separator, :data:`os.linesep`. If + *newline* is ``''``, no translation takes place. If *newline* is any of + the other legal values, any ``'\n'`` characters written are translated to + the given string. + + If *closefd* is ``False``, the underlying file descriptor will be kept open + when the file is closed. This does not work when a file name is given and + must be ``True`` in that case. .. index:: single: line-buffered I/O @@ -801,20 +788,21 @@ single: text mode module: sys - See also the file handling modules, such as, - :mod:`fileinput`, :mod:`os`, :mod:`os.path`, :mod:`tempfile`, and - :mod:`shutil`. + See also the file handling modules, such as, :mod:`fileinput`, :mod:`io` + (where :func:`open()` is declared), :mod:`os`, :mod:`os.path`, + :mod:`tempfile`, and :mod:`shutil`. + +.. XXX works for bytes too, but should it? .. function:: ord(c) Given a string of length one, return an integer representing the Unicode code - point of the character when the argument is a unicode object, or the value of - the byte when the argument is an 8-bit string. For example, ``ord('a')`` returns - the integer ``97``, ``ord(u'\u2020')`` returns ``8224``. This is the inverse of - :func:`chr` for 8-bit strings and of :func:`unichr` for unicode objects. If a - unicode argument is given and Python was built with UCS2 Unicode, then the - character's code point must be in the range [0..65535] inclusive; otherwise the - string length is two, and a :exc:`TypeError` will be raised. + point of the character. For example, ``ord('a')`` returns the integer ``97`` + and ``ord('\u2020')`` returns ``8224``. This is the inverse of :func:`chr`. + + If the argument length is not one, a :exc:`TypeError` will be raised. (If + Python was built with UCS2 Unicode, then the character's code point must be + in the range [0..65535] inclusive; otherwise the string length is two!) .. function:: pow(x, y[, z]) @@ -838,6 +826,22 @@ accidents.) +.. function:: print([object, ...][, sep=' '][, end='\n'][, file=sys.stdout]) + + Print *object*\(s) to the stream *file*, separated by *sep* and followed by + *end*. *sep*, *end* and *file*, if present, must be given as keyword + arguments. + + All non-keyword arguments are converted to strings like :func:`str` does and + written to the stream, separated by *sep* and followed by *end*. Both *sep* + and *end* must be strings; they can also be ``None``, which means to use the + default values. If no *object* is given, :func:`print` will just write + *end*. + + The *file* argument must be an object with a ``write(string)`` method; if it + is not present or ``None``, :data:`sys.stdout` will be used. + + .. function:: property([fget[, fset[, fdel[, doc]]]]) Return a property attribute. @@ -873,15 +877,15 @@ .. XXX does accept objects with __index__ too .. function:: range([start,] stop[, step]) - This is a versatile function to create iterators containing arithmetic - progressions. It is most often used in :keyword:`for` loops. The arguments - must be integers. If the *step* argument is omitted, it defaults to ``1``. - If the *start* argument is omitted, it defaults to ``0``. The full form - returns an iterator of plain integers ``[start, start + step, start + 2 * - step, ...]``. If *step* is positive, the last element is the largest ``start - + i * step`` less than *stop*; if *step* is negative, the last element is the - smallest ``start + i * step`` greater than *stop*. *step* must not be zero - (or else :exc:`ValueError` is raised). Example:: + This is a versatile function to create lists containing arithmetic progressions. + It is most often used in :keyword:`for` loops. The arguments must be plain + integers. If the *step* argument is omitted, it defaults to ``1``. If the + *start* argument is omitted, it defaults to ``0``. The full form returns a list + of plain integers ``[start, start + step, start + 2 * step, ...]``. If *step* + is positive, the last element is the largest ``start + i * step`` less than + *stop*; if *step* is negative, the last element is the smallest ``start + i * + step`` greater than *stop*. *step* must not be zero (or else :exc:`ValueError` + is raised). Example: >>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] @@ -901,11 +905,13 @@ .. function:: repr(object) - Return a string containing a printable representation of an object. This is the - same value yielded by conversions (reverse quotes). It is sometimes useful to be - able to access this operation as an ordinary function. For many types, this - function makes an attempt to return a string that would yield an object with the - same value when passed to :func:`eval`. + Return a string containing a printable representation of an object. For many + types, this function makes an attempt to return a string that would yield an + object with the same value when passed to :func:`eval`, otherwise the + representation is a string enclosed in angle brackets that contains the name + of the type of the object together with additional information often + including the name and address of the object. A class can control what this + function returns for its instances by defining a :meth:`__repr__` method. .. function:: reversed(seq) @@ -932,9 +938,6 @@ Return a new set, optionally with elements are taken from *iterable*. The set type is described in :ref:`types-set`. - For other containers see the built in :class:`dict`, :class:`list`, and - :class:`tuple` classes, and the :mod:`collections` module. - .. function:: setattr(object, name, value) @@ -959,19 +962,11 @@ ``a[start:stop:step]`` or ``a[start:stop, i]``. -.. function:: sorted(iterable[, cmp[, key[, reverse]]]) +.. function:: sorted(iterable[, key[, reverse]]) Return a new sorted list from the items in *iterable*. - The optional arguments *cmp*, *key*, and *reverse* have the same meaning as - those for the :meth:`list.sort` method (described in section - :ref:`typesseq-mutable`). - - *cmp* specifies a custom comparison function of two arguments (iterable - elements) which should return a negative, zero or positive number depending on - whether the first argument is considered smaller than, equal to, or larger than - the second argument: ``cmp=lambda x,y: cmp(x.lower(), y.lower())``. The default - value is ``None``. + Has two optional arguments which must be specified as keyword arguments. *key* specifies a function of one argument that is used to extract a comparison key from each list element: ``key=str.lower``. The default value is ``None``. @@ -979,11 +974,6 @@ *reverse* is a boolean value. If set to ``True``, then the list elements are sorted as if each comparison were reversed. - In general, the *key* and *reverse* conversion processes are much faster than - specifying an equivalent *cmp* function. This is because *cmp* is called - multiple times for each list element while *key* and *reverse* touch each - element only once. - .. function:: staticmethod(function) @@ -1049,31 +1039,31 @@ sequence of strings is by calling ``''.join(sequence)``. -.. function:: super(type[, object-or-type]) +.. function:: super([type[, object-or-type]]) - .. XXX need to document PEP "new super" + .. XXX updated as per http://www.artima.com/weblogs/viewpost.jsp?thread=208549 but needs checking - Return the superclass of *type*. If the second argument is omitted the super - object returned is unbound. If the second argument is an object, - ``isinstance(obj, type)`` must be true. If the second argument is a type, + Return the superclass of *type*. + + Calling :func:`super()` without arguments is equivalent to + ``super(this_class, first_arg)``. If called with one + argument the super object returned is unbound. If called with two + arguments and the second argument is an object, ``isinstance(obj, + type)`` must be true. If the second argument is a type, ``issubclass(type2, type)`` must be true. A typical use for calling a cooperative superclass method is:: class C(B): - def meth(self, arg): - super(C, self).meth(arg) + def method(self, arg): + super().method(arg) # This does the same thing as: super(C, self).method(arg) Note that :func:`super` is implemented as part of the binding process for - explicit dotted attribute lookups such as ``super(C, self).__getitem__(name)``. + explicit dotted attribute lookups such as ``super().__getitem__(name)``. Accordingly, :func:`super` is undefined for implicit lookups using statements or - operators such as ``super(C, self)[name]``. - - -.. function:: trunc(x) - - Return the :class:`Real` value *x* truncated to an :class:`Integral` (usually - a long integer). Delegates to ``x.__trunc__()``. + operators such as ``super()[name]``. Also, :func:`super` is not + limited to use inside methods: under the hood it searches the stack + frame for the class (``__class__``) and the first argument. .. function:: tuple([iterable]) @@ -1085,9 +1075,7 @@ 3])`` returns ``(1, 2, 3)``. If no argument is given, returns a new empty tuple, ``()``. - :class:`tuple` is an immutable sequence type, as documented in - :ref:`typesseq`. For other containers see the built in :class:`dict`, - :class:`list`, and :class:`set` classes, and the :mod:`collections` module. + :class:`tuple` is an immutable sequence type, as documented in :ref:`typesseq`. .. function:: type(object) @@ -1108,12 +1096,12 @@ :noindex: Return a new type object. This is essentially a dynamic form of the - :keyword:`class` statement. The *name* string is the class name and becomes - the :attr:`__name__` attribute; the *bases* tuple itemizes the base classes - and becomes the :attr:`__bases__` attribute; and the *dict* dictionary is the - namespace containing definitions for class body and becomes the - :attr:`__dict__` attribute. For example, the following two statements create - identical :class:`type` objects:: + :keyword:`class` statement. The *name* string is the class name and becomes the + :attr:`__name__` attribute; the *bases* tuple itemizes the base classes and + becomes the :attr:`__bases__` attribute; and the *dict* dictionary is the + namespace containing definitions for class body and becomes the :attr:`__dict__` + attribute. For example, the following two statements create identical + :class:`type` objects: >>> class X(object): ... a = 1 @@ -1130,20 +1118,30 @@ the effects on the corresponding symbol table are undefined. [#]_ -.. function:: zip([iterable, ...]) +.. function:: zip(*iterables) + + Make an iterator that aggregates elements from each of the iterables. - This function returns an iterator of tuples, where the *i*-th tuple contains + Returns an iterator of tuples, where the *i*-th tuple contains the *i*-th element from each of the argument sequences or iterables. The - iterator stops when the shortest argument sequence is exhausted. When there - are multiple arguments which are all of the same length, :func:`zip` is - similar to :func:`map` with an initial argument of ``None``. With a single - sequence argument, it returns an iterator of 1-tuples. With no arguments, it - returns an empty iterator. + iterator stops when the shortest input iterable is exhausted. With a single + iterable argument, it returns an iterator of 1-tuples. With no arguments, + it returns an empty iterator. Equivalent to:: + + def zip(*iterables): + # zip('ABCD', 'xy') --> Ax By + iterables = map(iter, iterables) + while iterables: + result = [it.next() for it in iterables] + yield tuple(result) The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using ``zip(*[iter(s)]*n)``. + :func:`zip` should only be used with unequal length inputs when you don't + care about trailing, unmatched values from the longer iterables. If those + values are important, use :func:`itertools.zip_longest` instead. .. rubric:: Footnotes Modified: python/branches/py3k-ctypes-pep3118/Doc/library/functools.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/functools.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/functools.rst Wed Apr 30 15:57:13 2008 @@ -15,13 +15,6 @@ The :mod:`functools` module defines the following functions: - -.. function:: reduce(function, iterable[, initializer]) - - This is the same function as :func:`reduce`. It is made available in this module - to allow writing code more forward-compatible with Python 3. - - .. function:: partial(func[,*args][, **keywords]) Return a new :class:`partial` object which when called will behave like *func* @@ -44,15 +37,16 @@ some portion of a function's arguments and/or keywords resulting in a new object with a simplified signature. For example, :func:`partial` can be used to create a callable that behaves like the :func:`int` function where the *base* argument - defaults to two:: + defaults to two: + >>> from functools import partial >>> basetwo = partial(int, base=2) >>> basetwo.__doc__ = 'Convert base 2 string to an int.' >>> basetwo('10010') 18 -.. function:: reduce(function, sequence[, initializer]) +.. function:: reduce(function, iterable[, initializer]) Apply *function* of two arguments cumulatively to the items of *sequence*, from left to right, so as to reduce the sequence to a single value. For example, @@ -87,8 +81,9 @@ This is a convenience function for invoking ``partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)`` as a function decorator - when defining a wrapper function. For example:: + when defining a wrapper function. For example: + >>> from functools import wraps >>> def my_decorator(f): ... @wraps(f) ... def wrapper(*args, **kwds): Modified: python/branches/py3k-ctypes-pep3118/Doc/library/getopt.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/getopt.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/getopt.rst Wed Apr 30 15:57:13 2008 @@ -77,7 +77,7 @@ Alias for :exc:`GetoptError`; for backward compatibility. -An example using only Unix style options:: +An example using only Unix style options: >>> import getopt >>> args = '-a -b -cfoo -d bar a1 a2'.split() @@ -89,7 +89,7 @@ >>> args ['a1', 'a2'] -Using long option names is equally easy:: +Using long option names is equally easy: >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2' >>> args = s.split() @@ -98,8 +98,7 @@ >>> optlist, args = getopt.getopt(args, 'x', [ ... 'condition=', 'output-file=', 'testing']) >>> optlist - [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', - '')] + [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')] >>> args ['a1', 'a2'] Modified: python/branches/py3k-ctypes-pep3118/Doc/library/gettext.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/gettext.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/gettext.rst Wed Apr 30 15:57:13 2008 @@ -136,9 +136,9 @@ greater convenience than the GNU :program:`gettext` API. It is the recommended way of localizing your Python applications and modules. :mod:`gettext` defines a "translations" class which implements the parsing of GNU :file:`.mo` format -files, and has methods for returning either standard 8-bit strings or Unicode -strings. Instances of this "translations" class can also install themselves in -the built-in namespace as the function :func:`_`. +files, and has methods for returning strings. Instances of this "translations" +class can also install themselves in the built-in namespace as the function +:func:`_`. .. function:: find(domain[, localedir[, languages[, all]]]) @@ -218,7 +218,7 @@ are the methods of :class:`NullTranslations`: -.. method:: NullTranslations.__init__([fp]) +.. class:: NullTranslations([fp]) Takes an optional file object *fp*, which is ignored by the base class. Initializes "protected" instance variables *_info* and *_charset* which are set @@ -227,106 +227,107 @@ ``None``. -.. method:: NullTranslations._parse(fp) + .. method:: _parse(fp) - No-op'd in the base class, this method takes file object *fp*, and reads the - data from the file, initializing its message catalog. If you have an - unsupported message catalog file format, you should override this method to - parse your format. + No-op'd in the base class, this method takes file object *fp*, and reads + the data from the file, initializing its message catalog. If you have an + unsupported message catalog file format, you should override this method + to parse your format. -.. method:: NullTranslations.add_fallback(fallback) + .. method:: add_fallback(fallback) - Add *fallback* as the fallback object for the current translation object. A - translation object should consult the fallback if it cannot provide a - translation for a given message. + Add *fallback* as the fallback object for the current translation + object. A translation object should consult the fallback if it cannot provide a + translation for a given message. -.. method:: NullTranslations.gettext(message) + .. method:: gettext(message) - If a fallback has been set, forward :meth:`gettext` to the fallback. Otherwise, - return the translated message. Overridden in derived classes. + If a fallback has been set, forward :meth:`gettext` to the + fallback. Otherwise, return the translated message. Overridden in derived + classes. -.. method:: NullTranslations.lgettext(message) + .. method:: lgettext(message) - If a fallback has been set, forward :meth:`lgettext` to the fallback. Otherwise, - return the translated message. Overridden in derived classes. + If a fallback has been set, forward :meth:`lgettext` to the + fallback. Otherwise, return the translated message. Overridden in derived + classes. + .. method:: ugettext(message) -.. method:: NullTranslations.ugettext(message) + If a fallback has been set, forward :meth:`ugettext` to the + fallback. Otherwise, return the translated message as a string. Overridden + in derived classes. - If a fallback has been set, forward :meth:`ugettext` to the fallback. Otherwise, - return the translated message as a Unicode string. Overridden in derived - classes. + .. method:: ngettext(singular, plural, n) -.. method:: NullTranslations.ngettext(singular, plural, n) + If a fallback has been set, forward :meth:`ngettext` to the + fallback. Otherwise, return the translated message. Overridden in derived + classes. - If a fallback has been set, forward :meth:`ngettext` to the fallback. Otherwise, - return the translated message. Overridden in derived classes. + .. method:: lngettext(singular, plural, n) + If a fallback has been set, forward :meth:`ngettext` to the + fallback. Otherwise, return the translated message. Overridden in derived + classes. -.. method:: NullTranslations.lngettext(singular, plural, n) + .. method:: ungettext(singular, plural, n) - If a fallback has been set, forward :meth:`ngettext` to the fallback. Otherwise, - return the translated message. Overridden in derived classes. + If a fallback has been set, forward :meth:`ungettext` to the fallback. + Otherwise, return the translated message as a string. Overridden in + derived classes. + .. method:: info() -.. method:: NullTranslations.ungettext(singular, plural, n) + Return the "protected" :attr:`_info` variable. - If a fallback has been set, forward :meth:`ungettext` to the fallback. - Otherwise, return the translated message as a Unicode string. Overridden in - derived classes. + .. method:: charset() -.. method:: NullTranslations.info() + Return the "protected" :attr:`_charset` variable. - Return the "protected" :attr:`_info` variable. + .. method:: output_charset() -.. method:: NullTranslations.charset() + Return the "protected" :attr:`_output_charset` variable, which defines the + encoding used to return translated messages. - Return the "protected" :attr:`_charset` variable. + .. method:: set_output_charset(charset) -.. method:: NullTranslations.output_charset() + Change the "protected" :attr:`_output_charset` variable, which defines the + encoding used to return translated messages. - Return the "protected" :attr:`_output_charset` variable, which defines the - encoding used to return translated messages. + .. method:: install([unicode [, names]]) -.. method:: NullTranslations.set_output_charset(charset) + If the *unicode* flag is false, this method installs :meth:`self.gettext` + into the built-in namespace, binding it to ``_``. If *unicode* is true, + it binds :meth:`self.ugettext` instead. By default, *unicode* is false. - Change the "protected" :attr:`_output_charset` variable, which defines the - encoding used to return translated messages. + If the *names* parameter is given, it must be a sequence containing the + names of functions you want to install in the builtin namespace in + addition to :func:`_`. Supported names are ``'gettext'`` (bound to + :meth:`self.gettext` or :meth:`self.ugettext` according to the *unicode* + flag), ``'ngettext'`` (bound to :meth:`self.ngettext` or + :meth:`self.ungettext` according to the *unicode* flag), ``'lgettext'`` + and ``'lngettext'``. + Note that this is only one way, albeit the most convenient way, to make + the :func:`_` function available to your application. Because it affects + the entire application globally, and specifically the built-in namespace, + localized modules should never install :func:`_`. Instead, they should use + this code to make :func:`_` available to their module:: -.. method:: NullTranslations.install([unicode [, names]]) + import gettext + t = gettext.translation('mymodule', ...) + _ = t.gettext - If the *unicode* flag is false, this method installs :meth:`self.gettext` into - the built-in namespace, binding it to ``_``. If *unicode* is true, it binds - :meth:`self.ugettext` instead. By default, *unicode* is false. - - If the *names* parameter is given, it must be a sequence containing the names of - functions you want to install in the builtin namespace in addition to :func:`_`. - Supported names are ``'gettext'`` (bound to :meth:`self.gettext` or - :meth:`self.ugettext` according to the *unicode* flag), ``'ngettext'`` (bound to - :meth:`self.ngettext` or :meth:`self.ungettext` according to the *unicode* - flag), ``'lgettext'`` and ``'lngettext'``. - - Note that this is only one way, albeit the most convenient way, to make the - :func:`_` function available to your application. Because it affects the entire - application globally, and specifically the built-in namespace, localized modules - should never install :func:`_`. Instead, they should use this code to make - :func:`_` available to their module:: - - import gettext - t = gettext.translation('mymodule', ...) - _ = t.gettext - - This puts :func:`_` only in the module's global namespace and so only affects - calls within this module. + This puts :func:`_` only in the module's global namespace and so only + affects calls within this module. The :class:`GNUTranslations` class @@ -347,8 +348,8 @@ ``None`` if not found. If the charset encoding is specified, then all message ids and message strings read from the catalog are converted to Unicode using this encoding. The :meth:`ugettext` method always returns a Unicode, while the -:meth:`gettext` returns an encoded 8-bit string. For the message id arguments -of both methods, either Unicode strings or 8-bit strings containing only +:meth:`gettext` returns an encoded bytestring. For the message id arguments +of both methods, either Unicode strings or bytestrings containing only US-ASCII characters are acceptable. Note that the Unicode version of the methods (i.e. :meth:`ugettext` and :meth:`ungettext`) are the recommended interface to use for internationalized Python programs. @@ -366,7 +367,7 @@ .. method:: GNUTranslations.gettext(message) Look up the *message* id in the catalog and return the corresponding message - string, as an 8-bit string encoded with the catalog's charset encoding, if + string, as a bytestring encoded with the catalog's charset encoding, if known. If there is no entry in the catalog for the *message* id, and a fallback has been set, the look up is forwarded to the fallback's :meth:`gettext` method. Otherwise, the *message* id is returned. @@ -382,7 +383,7 @@ .. method:: GNUTranslations.ugettext(message) Look up the *message* id in the catalog and return the corresponding message - string, as a Unicode string. If there is no entry in the catalog for the + string, as a string. If there is no entry in the catalog for the *message* id, and a fallback has been set, the look up is forwarded to the fallback's :meth:`ugettext` method. Otherwise, the *message* id is returned. @@ -391,7 +392,7 @@ Do a plural-forms lookup of a message id. *singular* is used as the message id for purposes of lookup in the catalog, while *n* is used to determine which - plural form to use. The returned message string is an 8-bit string encoded with + plural form to use. The returned message string is a bytestring encoded with the catalog's charset encoding, if known. If the message id is not found in the catalog, and a fallback is specified, the @@ -410,7 +411,7 @@ Do a plural-forms lookup of a message id. *singular* is used as the message id for purposes of lookup in the catalog, while *n* is used to determine which - plural form to use. The returned message string is a Unicode string. + plural form to use. The returned message string is a string. If the message id is not found in the catalog, and a fallback is specified, the request is forwarded to the fallback's :meth:`ungettext` method. Otherwise, Modified: python/branches/py3k-ctypes-pep3118/Doc/library/gzip.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/gzip.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/gzip.rst Wed Apr 30 15:57:13 2008 @@ -1,19 +1,22 @@ - :mod:`gzip` --- Support for :program:`gzip` files ================================================= .. module:: gzip :synopsis: Interfaces for gzip compression and decompression using file objects. +This module provides a simple interface to compress and decompress files just +like the GNU programs :program:`gzip` and :program:`gunzip` would. + +The data compression is provided by the :mod:``zlib`` module. -The data compression provided by the ``zlib`` module is compatible with that -used by the GNU compression program :program:`gzip`. Accordingly, the -:mod:`gzip` module provides the :class:`GzipFile` class to read and write +The :mod:`gzip` module provides the :class:`GzipFile` class which is modeled +after Python's File Object. The :class:`GzipFile` class reads and writes :program:`gzip`\ -format files, automatically compressing or decompressing the -data so it looks like an ordinary file object. Note that additional file -formats which can be decompressed by the :program:`gzip` and :program:`gunzip` -programs, such as those produced by :program:`compress` and :program:`pack`, -are not supported by this module. +data so that it looks like an ordinary file object. + +Note that additional file formats which can be decompressed by the +:program:`gzip` and :program:`gunzip` programs, such as those produced by +:program:`compress` and :program:`pack`, are not supported by this module. For other archive formats, see the :mod:`bz2`, :mod:`zipfile`, and :mod:`tarfile` modules. @@ -63,6 +66,36 @@ *compresslevel* defaults to ``9``. +.. _gzip-usage-examples: + +Examples of usage +----------------- + +Example of how to read a compressed file:: + + import gzip + f = gzip.open('/home/joe/file.txt.gz', 'rb') + file_content = f.read() + f.close() + +Example of how to create a compressed GZIP file:: + + import gzip + content = "Lots of content here" + f = gzip.open('/home/joe/file.txt.gz', 'wb') + f.write(content) + f.close() + +Example of how to GZIP compress an existing file:: + + import gzip + f_in = open('/home/joe/file.txt', 'rb') + f_out = gzip.open('/home/joe/file.txt.gz', 'wb') + f_out.writelines(f_in) + f_out.close() + f_in.close() + + .. seealso:: Module :mod:`zlib` Modified: python/branches/py3k-ctypes-pep3118/Doc/library/hashlib.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/hashlib.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/hashlib.rst Wed Apr 30 15:57:13 2008 @@ -19,6 +19,10 @@ "message digest" are interchangeable. Older algorithms were called message digests. The modern term is secure hash. +.. note:: + If you want the adler32 or crc32 hash functions they are available in + the :mod:`zlib` module. + .. warning:: Some algorithms have known hash collision weaknesses, see the FAQ at the end. @@ -57,7 +61,7 @@ >>> m.block_size 64 -More condensed:: +More condensed: >>> hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest() b'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2' @@ -67,7 +71,7 @@ hashes as well as any other algorithms that your OpenSSL library may offer. The named constructors are much faster than :func:`new` and should be preferred. -Using :func:`new` with an algorithm provided by OpenSSL:: +Using :func:`new` with an algorithm provided by OpenSSL: >>> h = hashlib.new('ripemd160') >>> h.update(b"Nobody inspects the spammish repetition") Modified: python/branches/py3k-ctypes-pep3118/Doc/library/heapq.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/heapq.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/heapq.rst Wed Apr 30 15:57:13 2008 @@ -44,6 +44,13 @@ invariant. If the heap is empty, :exc:`IndexError` is raised. +.. function:: heappushpop(heap, item) + + Push *item* on the heap, then pop and return the smallest item from the + *heap*. The combined action runs more efficiently than :func:`heappush` + followed by a separate call to :func:`heappop`. + + .. function:: heapify(x) Transform list *x* into a heap, in-place, in linear time. @@ -61,7 +68,7 @@ if item > heap[0]: item = heapreplace(heap, item) -Example of use:: +Example of use: >>> from heapq import heappush, heappop >>> heap = [] @@ -78,7 +85,6 @@ >>> data.sort() >>> data == ordered True - >>> The module also offers three general purpose functions based on heaps. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/imaplib.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/imaplib.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/imaplib.rst Wed Apr 30 15:57:13 2008 @@ -116,7 +116,7 @@ Documents describing the protocol, and sources and binaries for servers implementing it, can all be found at the University of Washington's *IMAP - Information Center* (http://www.cac.washington.edu/imap/). + Information Center* (http://www.washington.edu/imap/). .. _imap4-objects: Modified: python/branches/py3k-ctypes-pep3118/Doc/library/imp.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/imp.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/imp.rst Wed Apr 30 15:57:13 2008 @@ -185,6 +185,19 @@ continue to use the old class definition. The same is true for derived classes. +.. function:: acquire_lock() + + Acquires the interpreter's import lock for the current thread. This lock should + be used by import hooks to ensure thread-safety when importing modules. On + platforms without threads, this function does nothing. + + +.. function:: release_lock() + + Release the interpreter's import lock. On platforms without threads, this + function does nothing. + + The following constants with integer values, defined in this module, are used to indicate the search result of :func:`find_module`. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/index.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/index.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/index.rst Wed Apr 30 15:57:13 2008 @@ -31,8 +31,9 @@ optional components. In addition to the standard library, there is a growing collection of -over 2500 additional components available from the `Python Package Index -`_. +several thousand components (from individual programs and modules to +packages and entire application development frameworks), available from +the `Python Package Index `_. .. toctree:: Modified: python/branches/py3k-ctypes-pep3118/Doc/library/inspect.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/inspect.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/inspect.rst Wed Apr 30 15:57:13 2008 @@ -26,7 +26,7 @@ ----------------- The :func:`getmembers` function retrieves the members of an object such as a -class or module. The eleven functions whose names begin with "is" are mainly +class or module. The sixteen functions whose names begin with "is" are mainly provided as convenient choices for the second argument to :func:`getmembers`. They also help you determine when you can expect to find the following special attributes: @@ -229,6 +229,16 @@ Return true if the object is a Python function or unnamed (:term:`lambda`) function. +.. function:: isgeneratorfunction(object) + + Return true if the object is a Python generator function. + + +.. function:: isgenerator(object) + + Return true if the object is a generator. + + .. function:: istraceback(object) Return true if the object is a traceback. @@ -253,6 +263,10 @@ Return true if the object is a user-defined or built-in function or method. +.. function:: isabstract(object) + + Return true if the object is an abstract base class. + .. function:: ismethoddescriptor(object) Modified: python/branches/py3k-ctypes-pep3118/Doc/library/itertools.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/itertools.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/itertools.rst Wed Apr 30 15:57:13 2008 @@ -8,6 +8,11 @@ .. sectionauthor:: Raymond Hettinger +.. testsetup:: + + from itertools import * + + This module implements a number of :term:`iterator` building blocks inspired by constructs from the Haskell and SML programming languages. Each has been recast in a form suitable for Python. @@ -22,9 +27,8 @@ to construct more specialized tools succinctly and efficiently in pure Python. For instance, SML provides a tabulation tool: ``tabulate(f)`` which produces a -sequence ``f(0), f(1), ...``. This toolbox provides :func:`imap` and -:func:`count` which can be combined to form ``imap(f, count())`` and produce an -equivalent result. +sequence ``f(0), f(1), ...``. But, this effect can be achieved in Python +by combining :func:`map` and :func:`count` to form ``map(f, count())``. Likewise, the functional tools are designed to work well with the high-speed functions provided by the :mod:`operator` module. @@ -69,19 +73,78 @@ Equivalent to:: def chain(*iterables): + # chain('ABC', 'DEF') --> A B C D E F for it in iterables: for element in it: yield element +.. function:: itertools.chain.from_iterable(iterable) + + Alternate constructor for :func:`chain`. Gets chained inputs from a + single iterable argument that is evaluated lazily. Equivalent to:: + + @classmethod + def from_iterable(iterables): + # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F + for it in iterables: + for element in it: + yield element + + +.. function:: combinations(iterable, r) + + Return *r* length subsequences of elements from the input *iterable*. + + Combinations are emitted in lexicographic sort order. So, if the + input *iterable* is sorted, the combination tuples will be produced + in sorted order. + + Elements are treated as unique based on their position, not on their + value. So if the input elements are unique, there will be no repeat + values in each combination. + + Equivalent to:: + + def combinations(iterable, r): + # combinations('ABCD', 2) --> AB AC AD BC BD CD + # combinations(range(4), 3) --> 012 013 023 123 + pool = tuple(iterable) + n = len(pool) + indices = range(r) + yield tuple(pool[i] for i in indices) + while 1: + for i in reversed(range(r)): + if indices[i] != i + n - r: + break + else: + return + indices[i] += 1 + for j in range(i+1, r): + indices[j] = indices[j-1] + 1 + yield tuple(pool[i] for i in indices) + + The code for :func:`combinations` can be also expressed as a subsequence + of :func:`permutations` after filtering entries where the elements are not + in sorted order (according to their position in the input pool):: + + def combinations(iterable, r): + pool = tuple(iterable) + n = len(pool) + for indices in permutations(range(n), r): + if sorted(indices) == list(indices): + yield tuple(pool[i] for i in indices) + + .. function:: count([n]) Make an iterator that returns consecutive integers starting with *n*. If not - specified *n* defaults to zero. Often used as an argument to :func:`imap` to - generate consecutive data points. Also, used with :func:`izip` to add sequence + specified *n* defaults to zero. Often used as an argument to :func:`map` to + generate consecutive data points. Also, used with :func:`zip` to add sequence numbers. Equivalent to:: def count(n=0): + # count(10) --> 10 11 12 13 14 ... while True: yield n n += 1 @@ -94,6 +157,7 @@ indefinitely. Equivalent to:: def cycle(iterable): + # cycle('ABCD') --> A B C D A B C D A B C D ... saved = [] for element in iterable: yield element @@ -114,6 +178,7 @@ start-up time. Equivalent to:: def dropwhile(predicate, iterable): + # dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1 iterable = iter(iterable) for x in iterable: if not predicate(x): @@ -152,6 +217,8 @@ :func:`groupby` is equivalent to:: class groupby(object): + # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B + # [(list(g)) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D def __init__(self, iterable, key=None): if key is None: key = lambda x: x @@ -173,27 +240,14 @@ self.currkey = self.keyfunc(self.currvalue) -.. function:: ifilter(predicate, iterable) - - Make an iterator that filters elements from iterable returning only those for - which the predicate is ``True``. If *predicate* is ``None``, return the items - that are true. Equivalent to:: - - def ifilter(predicate, iterable): - if predicate is None: - predicate = bool - for x in iterable: - if predicate(x): - yield x - - -.. function:: ifilterfalse(predicate, iterable) +.. function:: filterfalse(predicate, iterable) Make an iterator that filters elements from iterable returning only those for which the predicate is ``False``. If *predicate* is ``None``, return the items that are false. Equivalent to:: - def ifilterfalse(predicate, iterable): + def filterfalse(predicate, iterable): + # filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8 if predicate is None: predicate = bool for x in iterable: @@ -201,21 +255,6 @@ yield x -.. function:: imap(function, *iterables) - - Make an iterator that computes the function using arguments from each of the - iterables. Equivalent to:: - - def imap(function, *iterables): - iterables = [iter(it) for it in iterables) - while True: - args = [next(it) for it in iterables] - if function is None: - yield tuple(args) - else: - yield function(*args) - - .. function:: islice(iterable, [start,] stop [, step]) Make an iterator that returns selected elements from the iterable. If *start* is @@ -229,8 +268,12 @@ multi-line report may list a name field on every third line). Equivalent to:: def islice(iterable, *args): + # islice('ABCDEFG', 2) --> A B + # islice('ABCDEFG', 2, 4) --> C D + # islice('ABCDEFG', 2, None) --> C D E F G + # islice('ABCDEFG', 0, None, 2) --> A C E G s = slice(*args) - it = iter(range(s.start or 0, s.stop or sys.maxsize, s.step or 1)) + it = range(s.start or 0, s.stop or sys.maxsize, s.step or 1) nexti = next(it) for i, element in enumerate(iterable): if i == nexti: @@ -241,60 +284,122 @@ then the step defaults to one. -.. function:: izip(*iterables) - - Make an iterator that aggregates elements from each of the iterables. Like - :func:`zip` except that it returns an iterator instead of a list. Used for - lock-step iteration over several iterables at a time. Equivalent to:: - - def izip(*iterables): - iterables = map(iter, iterables) - while iterables: - result = [next(it) for it in iterables] - yield tuple(result) - - When no iterables are specified, return a zero length iterator. - - The left-to-right evaluation order of the iterables is guaranteed. This - makes possible an idiom for clustering a data series into n-length groups - using ``izip(*[iter(s)]*n)``. - - :func:`izip` should only be used with unequal length inputs when you don't - care about trailing, unmatched values from the longer iterables. If those - values are important, use :func:`izip_longest` instead. - - -.. function:: izip_longest(*iterables[, fillvalue]) +.. function:: zip_longest(*iterables[, fillvalue]) Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with *fillvalue*. Iteration continues until the longest iterable is exhausted. Equivalent to:: - def izip_longest(*args, **kwds): - fillvalue = kwds.get('fillvalue') + def zip_longest(*args, fillvalue=None): + # zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D- def sentinel(counter = ([fillvalue]*(len(args)-1)).pop): yield counter() # yields the fillvalue, or raises IndexError fillers = repeat(fillvalue) iters = [chain(it, sentinel(), fillers) for it in args] try: - for tup in izip(*iters): + for tup in zip(*iters): yield tup except IndexError: pass - If one of the iterables is potentially infinite, then the :func:`izip_longest` + If one of the iterables is potentially infinite, then the :func:`zip_longest` function should be wrapped with something that limits the number of calls (for example :func:`islice` or :func:`takewhile`). +.. function:: permutations(iterable[, r]) + + Return successive *r* length permutations of elements in the *iterable*. + + If *r* is not specified or is ``None``, then *r* defaults to the length + of the *iterable* and all possible full-length permutations + are generated. + + Permutations are emitted in lexicographic sort order. So, if the + input *iterable* is sorted, the permutation tuples will be produced + in sorted order. + + Elements are treated as unique based on their position, not on their + value. So if the input elements are unique, there will be no repeat + values in each permutation. + + Equivalent to:: + + def permutations(iterable, r=None): + # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC + # permutations(range(3)) --> 012 021 102 120 201 210 + pool = tuple(iterable) + n = len(pool) + r = n if r is None else r + indices = range(n) + cycles = range(n, n-r, -1) + yield tuple(pool[i] for i in indices[:r]) + while n: + for i in reversed(range(r)): + cycles[i] -= 1 + if cycles[i] == 0: + indices[i:] = indices[i+1:] + indices[i:i+1] + cycles[i] = n - i + else: + j = cycles[i] + indices[i], indices[-j] = indices[-j], indices[i] + yield tuple(pool[i] for i in indices[:r]) + break + else: + return + + The code for :func:`permutations` can be also expressed as a subsequence of + :func:`product`, filtered to exclude entries with repeated elements (those + from the same position in the input pool):: + + def permutations(iterable, r=None): + pool = tuple(iterable) + n = len(pool) + r = n if r is None else r + for indices in product(range(n), repeat=r): + if len(set(indices)) == r: + yield tuple(pool[i] for i in indices) + + +.. function:: product(*iterables[, repeat]) + + Cartesian product of input iterables. + + Equivalent to nested for-loops in a generator expression. For example, + ``product(A, B)`` returns the same as ``((x,y) for x in A for y in B)``. + + The nested loops cycle like an odometer with the rightmost element advancing + on every iteration. This pattern creates a lexicographic ordering so that if + the input's iterables are sorted, the product tuples are emitted in sorted + order. + + To compute the product of an iterable with itself, specify the number of + repetitions with the optional *repeat* keyword argument. For example, + ``product(A, repeat=4)`` means the same as ``product(A, A, A, A)``. + + This function is equivalent to the following code, except that the + actual implementation does not build up intermediate results in memory:: + + def product(*args, repeat=1): + # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy + # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 + pools = map(tuple, args) * repeat + result = [[]] + for pool in pools: + result = [x+[y] for x in result for y in pool] + for prod in result: + yield tuple(prod) + + .. function:: repeat(object[, times]) Make an iterator that returns *object* over and over again. Runs indefinitely - unless the *times* argument is specified. Used as argument to :func:`imap` for - invariant parameters to the called function. Also used with :func:`izip` to + unless the *times* argument is specified. Used as argument to :func:`map` for + invariant parameters to the called function. Also used with :func:`zip` to create an invariant part of a tuple record. Equivalent to:: def repeat(object, times=None): + # repeat(10, 3) --> 10 10 10 if times is None: while True: yield object @@ -306,19 +411,16 @@ .. function:: starmap(function, iterable) Make an iterator that computes the function using arguments obtained from - the iterable. Used instead of :func:`imap` when argument parameters are already + the iterable. Used instead of :func:`map` when argument parameters are already grouped in tuples from a single iterable (the data has been "pre-zipped"). The - difference between :func:`imap` and :func:`starmap` parallels the distinction + difference between :func:`map` and :func:`starmap` parallels the distinction between ``function(a,b)`` and ``function(*c)``. Equivalent to:: def starmap(function, iterable): + # starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000 for args in iterable: yield function(*args) - .. versionchanged:: 2.6 - Previously, :func:`starmap` required the function arguments to be tuples. - Now, any iterable is allowed. - .. function:: takewhile(predicate, iterable) @@ -326,6 +428,7 @@ predicate is true. Equivalent to:: def takewhile(predicate, iterable): + # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4 for x in iterable: if predicate(x): yield x @@ -365,35 +468,9 @@ -------- The following examples show common uses for each tool and demonstrate ways they -can be combined. :: +can be combined. - >>> amounts = [120.15, 764.05, 823.14] - >>> for checknum, amount in izip(count(1200), amounts): - ... print('Check %d is for $%.2f' % (checknum, amount)) - ... - Check 1200 is for $120.15 - Check 1201 is for $764.05 - Check 1202 is for $823.14 - - >>> import operator - >>> for cube in imap(operator.pow, range(1,5), repeat(3)): - ... print(cube) - ... - 1 - 8 - 27 - 64 - - >>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', - ... '', 'martin', '', 'walter', '', 'mark'] - >>> for name in islice(reportlines, 3, None, 2): - ... print(name.title()) - ... - Alex - Laura - Martin - Walter - Mark +.. doctest:: # Show a dictionary sorted and grouped by value >>> from operator import itemgetter @@ -436,43 +513,48 @@ kept small by linking the tools together in a functional style which helps eliminate temporary variables. High speed is retained by preferring "vectorized" building blocks over the use of for-loops and :term:`generator`\s -which incur interpreter overhead. :: +which incur interpreter overhead. + +.. testcode:: def take(n, seq): return list(islice(seq, n)) def enumerate(iterable): - return izip(count(), iterable) + return zip(count(), iterable) def tabulate(function): "Return function(0), function(1), ..." - return imap(function, count()) + return map(function, count()) + + def items(mapping): + return zip(mapping.keys(), mapping.values()) def nth(iterable, n): "Returns the nth item or raise StopIteration" - return islice(iterable, n, None).next() + return next(islice(iterable, n, None)) def all(seq, pred=None): "Returns True if pred(x) is true for every element in the iterable" - for elem in ifilterfalse(pred, seq): + for elem in filterfalse(pred, seq): return False return True def any(seq, pred=None): "Returns True if pred(x) is true for at least one element in the iterable" - for elem in ifilter(pred, seq): + for elem in filter(pred, seq): return True return False def no(seq, pred=None): "Returns True if pred(x) is false for every element in the iterable" - for elem in ifilter(pred, seq): + for elem in filter(pred, seq): return False return True def quantify(seq, pred=None): "Count how many times the predicate is true in the sequence" - return sum(imap(pred, seq)) + return sum(map(pred, seq)) def padnone(seq): """Returns the sequence elements and then returns None indefinitely. @@ -483,13 +565,13 @@ def ncycles(seq, n): "Returns the sequence elements n times" - return chain(*repeat(seq, n)) + return chain.from_iterable(repeat(seq, n)) def dotproduct(vec1, vec2): - return sum(imap(operator.mul, vec1, vec2)) + return sum(map(operator.mul, vec1, vec2)) def flatten(listOfLists): - return list(chain(*listOfLists)) + return list(chain.from_iterable(listOfLists)) def repeatfunc(func, times=None, *args): """Repeat calls to func with specified arguments. @@ -498,18 +580,43 @@ """ if times is None: return starmap(func, repeat(args)) - else: - return starmap(func, repeat(args, times)) + return starmap(func, repeat(args, times)) def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) - next(b, None) - return izip(a, b) + for elem in b: + break + return zip(a, b) - def grouper(n, iterable, padvalue=None): + def grouper(n, iterable, fillvalue=None): "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')" - return izip(*[chain(iterable, repeat(padvalue, n-1))]*n) - + args = [iter(iterable)] * n + return zip_longest(*args, fillvalue=fillvalue) + def roundrobin(*iterables): + "roundrobin('abc', 'd', 'ef') --> 'a', 'd', 'e', 'b', 'f', 'c'" + # Recipe credited to George Sakkis + pending = len(iterables) + nexts = cycle(iter(it).__next__ for it in iterables) + while pending: + try: + for next in nexts: + yield next() + except StopIteration: + pending -= 1 + nexts = cycle(islice(nexts, pending)) + + def powerset(iterable): + "powerset('ab') --> set([]), set(['a']), set(['b']), set(['a', 'b'])" + # Recipe credited to Eric Raymond + pairs = [(2**i, x) for i, x in enumerate(iterable)] + for n in xrange(2**len(pairs)): + yield set(x for m, x in pairs if m&n) + + def compress(data, selectors): + "compress('abcdef', [1,0,1,0,1,1]) --> a c e f" + for d, s in zip(data, selectors): + if s: + yield d Modified: python/branches/py3k-ctypes-pep3118/Doc/library/logging.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/logging.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/logging.rst Wed Apr 30 15:57:13 2008 @@ -41,7 +41,7 @@ It is, of course, possible to log messages with different verbosity levels or to different destinations. Support for writing log messages to files, HTTP GET/POST locations, email via SMTP, generic sockets, or OS-specific logging -mechnisms are all supported by the standard module. You can also create your +mechanisms are all supported by the standard module. You can also create your own log destination class if you have special requirements not met by any of the built-in classes. @@ -95,7 +95,7 @@ logfiles = glob.glob('%s*' % LOG_FILENAME) for filename in logfiles: - print filename + print(filename) The result should be 6 separate files, each with part of the log history for the application:: @@ -243,8 +243,8 @@ little more verbose for logging messages than using the log level convenience methods listed above, but this is how to log at custom log levels. -:func:`getLogger` returns a reference to a logger instance with a name of name -if a name is provided, or root if not. The names are period-separated +:func:`getLogger` returns a reference to a logger instance with the specified +if it it is provided, or ``root`` if not. The names are period-separated hierarchical structures. Multiple calls to :func:`getLogger` with the same name will return a reference to the same logger object. Loggers that are further down in the hierarchical list are children of loggers higher up in the list. @@ -265,7 +265,7 @@ with an :func:`addHandler` method. As an example scenario, an application may want to send all log messages to a log file, all log messages of error or higher to stdout, and all messages of critical to an email address. This scenario -requires three individual handlers where each hander is responsible for sending +requires three individual handlers where each handler is responsible for sending messages of a specific severity to a specific location. The standard library includes quite a few handler types; this tutorial uses only @@ -296,7 +296,7 @@ ^^^^^^^^^^ Formatter objects configure the final order, structure, and contents of the log -message. Unlike the base logging.Handler class, application code may +message. Unlike the base :class:`logging.Handler` class, application code may instantiate formatter classes, although you could likely subclass the formatter if your application needs special behavior. The constructor takes two optional arguments: a message format string and a date format string. If there is no @@ -724,7 +724,8 @@ .. function:: shutdown() Informs the logging system to perform an orderly shutdown by flushing and - closing all handlers. + closing all handlers. This should be called at application exit and no + further use of the logging system should be made after this call. .. function:: setLoggerClass(klass) @@ -1239,10 +1240,6 @@ 2008-01-18 14:49:54,033 d.e.f WARNING IP: 192.168.0.1 User: sheila A message at WARNING level with 2 parameters 2008-01-18 14:49:54,033 d.e.f WARNING IP: 127.0.0.1 User: jim A message at WARNING level with 2 parameters -.. versionadded:: 2.6 - -The :class:`LoggerAdapter` class was not present in previous versions. - .. _network-logging: @@ -1494,19 +1491,19 @@ will be used. -.. method:: StreamHandler.emit(record) + .. method:: emit(record) - If a formatter is specified, it is used to format the record. The record is then - written to the stream with a trailing newline. If exception information is - present, it is formatted using :func:`traceback.print_exception` and appended to - the stream. + If a formatter is specified, it is used to format the record. The record + is then written to the stream with a trailing newline. If exception + information is present, it is formatted using + :func:`traceback.print_exception` and appended to the stream. -.. method:: StreamHandler.flush() + .. method:: flush() - Flushes the stream by calling its :meth:`flush` method. Note that the - :meth:`close` method is inherited from :class:`Handler` and so does nothing, so - an explicit :meth:`flush` call may be needed at times. + Flushes the stream by calling its :meth:`flush` method. Note that the + :meth:`close` method is inherited from :class:`Handler` and so does + nothing, so an explicit :meth:`flush` call may be needed at times. FileHandler @@ -1526,14 +1523,14 @@ first call to :meth:`emit`. By default, the file grows indefinitely. -.. method:: FileHandler.close() + .. method:: close() - Closes the file. + Closes the file. -.. method:: FileHandler.emit(record) + .. method:: emit(record) - Outputs the record to the file. + Outputs the record to the file. WatchedFileHandler @@ -1566,11 +1563,11 @@ first call to :meth:`emit`. By default, the file grows indefinitely. -.. method:: WatchedFileHandler.emit(record) + .. method:: emit(record) - Outputs the record to the file, but first checks to see if the file has changed. - If it has, the existing stream is flushed and closed and the file opened again, - before outputting the record to the file. + Outputs the record to the file, but first checks to see if the file has + changed. If it has, the existing stream is flushed and closed and the + file opened again, before outputting the record to the file. RotatingFileHandler @@ -1602,14 +1599,15 @@ :file:`app.log.2`, :file:`app.log.3` etc. respectively. -.. method:: RotatingFileHandler.doRollover() + .. method:: doRollover() - Does a rollover, as described above. + Does a rollover, as described above. -.. method:: RotatingFileHandler.emit(record) + .. method:: emit(record) - Outputs the record to the file, catering for rollover as described previously. + Outputs the record to the file, catering for rollover as described + previously. TimedRotatingFileHandler @@ -1630,37 +1628,39 @@ You can use the *when* to specify the type of *interval*. The list of possible values is, note that they are not case sensitive: - +----------+-----------------------+ - | Value | Type of interval | - +==========+=======================+ - | S | Seconds | - +----------+-----------------------+ - | M | Minutes | - +----------+-----------------------+ - | H | Hours | - +----------+-----------------------+ - | D | Days | - +----------+-----------------------+ - | W | Week day (0=Monday) | - +----------+-----------------------+ - | midnight | Roll over at midnight | - +----------+-----------------------+ - - If *backupCount* is non-zero, the system will save old log files by appending - extensions to the filename. The extensions are date-and-time based, using the - strftime format ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on - the rollover interval. At most *backupCount* files will be kept, and if more - would be created when rollover occurs, the oldest one is deleted. + +----------------+-----------------------+ + | Value | Type of interval | + +================+=======================+ + | ``'S'`` | Seconds | + +----------------+-----------------------+ + | ``'M'`` | Minutes | + +----------------+-----------------------+ + | ``'H'`` | Hours | + +----------------+-----------------------+ + | ``'D'`` | Days | + +----------------+-----------------------+ + | ``'W'`` | Week day (0=Monday) | + +----------------+-----------------------+ + | ``'midnight'`` | Roll over at midnight | + +----------------+-----------------------+ + + The system will save old log files by appending extensions to the filename. + The extensions are date-and-time based, using the strftime format + ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the + rollover interval. If *backupCount* is nonzero, at most *backupCount* files + will be kept, and if more would be created when rollover occurs, the oldest + one is deleted. The deletion logic uses the interval to determine which + files to delete, so changing the interval may leave old files lying around. -.. method:: TimedRotatingFileHandler.doRollover() + .. method:: doRollover() - Does a rollover, as described above. + Does a rollover, as described above. -.. method:: TimedRotatingFileHandler.emit(record) + .. method:: emit(record) - Outputs the record to the file, catering for rollover as described above. + Outputs the record to the file, catering for rollover as described above. SocketHandler @@ -1676,43 +1676,44 @@ communicate with a remote machine whose address is given by *host* and *port*. -.. method:: SocketHandler.close() + .. method:: close() - Closes the socket. + Closes the socket. -.. method:: SocketHandler.emit() + .. method:: emit() - Pickles the record's attribute dictionary and writes it to the socket in binary - format. If there is an error with the socket, silently drops the packet. If the - connection was previously lost, re-establishes the connection. To unpickle the - record at the receiving end into a :class:`LogRecord`, use the - :func:`makeLogRecord` function. + Pickles the record's attribute dictionary and writes it to the socket in + binary format. If there is an error with the socket, silently drops the + packet. If the connection was previously lost, re-establishes the + connection. To unpickle the record at the receiving end into a + :class:`LogRecord`, use the :func:`makeLogRecord` function. -.. method:: SocketHandler.handleError() + .. method:: handleError() - Handles an error which has occurred during :meth:`emit`. The most likely cause - is a lost connection. Closes the socket so that we can retry on the next event. + Handles an error which has occurred during :meth:`emit`. The most likely + cause is a lost connection. Closes the socket so that we can retry on the + next event. -.. method:: SocketHandler.makeSocket() + .. method:: makeSocket() - This is a factory method which allows subclasses to define the precise type of - socket they want. The default implementation creates a TCP socket - (:const:`socket.SOCK_STREAM`). + This is a factory method which allows subclasses to define the precise + type of socket they want. The default implementation creates a TCP socket + (:const:`socket.SOCK_STREAM`). -.. method:: SocketHandler.makePickle(record) + .. method:: makePickle(record) - Pickles the record's attribute dictionary in binary format with a length prefix, - and returns it ready for transmission across the socket. + Pickles the record's attribute dictionary in binary format with a length + prefix, and returns it ready for transmission across the socket. -.. method:: SocketHandler.send(packet) + .. method:: send(packet) - Send a pickled string *packet* to the socket. This function allows for partial - sends which can happen when the network is busy. + Send a pickled string *packet* to the socket. This function allows for + partial sends which can happen when the network is busy. DatagramHandler @@ -1729,23 +1730,23 @@ communicate with a remote machine whose address is given by *host* and *port*. -.. method:: DatagramHandler.emit() + .. method:: emit() - Pickles the record's attribute dictionary and writes it to the socket in binary - format. If there is an error with the socket, silently drops the packet. To - unpickle the record at the receiving end into a :class:`LogRecord`, use the - :func:`makeLogRecord` function. + Pickles the record's attribute dictionary and writes it to the socket in + binary format. If there is an error with the socket, silently drops the + packet. To unpickle the record at the receiving end into a + :class:`LogRecord`, use the :func:`makeLogRecord` function. -.. method:: DatagramHandler.makeSocket() + .. method:: makeSocket() - The factory method of :class:`SocketHandler` is here overridden to create a UDP - socket (:const:`socket.SOCK_DGRAM`). + The factory method of :class:`SocketHandler` is here overridden to create + a UDP socket (:const:`socket.SOCK_DGRAM`). -.. method:: DatagramHandler.send(s) + .. method:: send(s) - Send a pickled string to a socket. + Send a pickled string to a socket. SysLogHandler @@ -1767,22 +1768,22 @@ :const:`LOG_USER` is used. -.. method:: SysLogHandler.close() + .. method:: close() - Closes the socket to the remote host. + Closes the socket to the remote host. -.. method:: SysLogHandler.emit(record) + .. method:: emit(record) - The record is formatted, and then sent to the syslog server. If exception - information is present, it is *not* sent to the server. + The record is formatted, and then sent to the syslog server. If exception + information is present, it is *not* sent to the server. -.. method:: SysLogHandler.encodePriority(facility, priority) + .. method:: encodePriority(facility, priority) - Encodes the facility and priority into an integer. You can pass in strings or - integers - if strings are passed, internal mapping dictionaries are used to - convert them to integers. + Encodes the facility and priority into an integer. You can pass in strings + or integers - if strings are passed, internal mapping dictionaries are + used to convert them to integers. NTEventLogHandler @@ -1810,45 +1811,45 @@ defaults to ``'Application'``. -.. method:: NTEventLogHandler.close() + .. method:: close() - At this point, you can remove the application name from the registry as a source - of event log entries. However, if you do this, you will not be able to see the - events as you intended in the Event Log Viewer - it needs to be able to access - the registry to get the .dll name. The current version does not do this (in fact - it doesn't do anything). + At this point, you can remove the application name from the registry as a + source of event log entries. However, if you do this, you will not be able + to see the events as you intended in the Event Log Viewer - it needs to be + able to access the registry to get the .dll name. The current version does + not do this (in fact it doesn't do anything). -.. method:: NTEventLogHandler.emit(record) + .. method:: emit(record) - Determines the message ID, event category and event type, and then logs the - message in the NT event log. + Determines the message ID, event category and event type, and then logs + the message in the NT event log. -.. method:: NTEventLogHandler.getEventCategory(record) + .. method:: getEventCategory(record) - Returns the event category for the record. Override this if you want to specify - your own categories. This version returns 0. + Returns the event category for the record. Override this if you want to + specify your own categories. This version returns 0. -.. method:: NTEventLogHandler.getEventType(record) + .. method:: getEventType(record) - Returns the event type for the record. Override this if you want to specify your - own types. This version does a mapping using the handler's typemap attribute, - which is set up in :meth:`__init__` to a dictionary which contains mappings for - :const:`DEBUG`, :const:`INFO`, :const:`WARNING`, :const:`ERROR` and - :const:`CRITICAL`. If you are using your own levels, you will either need to - override this method or place a suitable dictionary in the handler's *typemap* - attribute. + Returns the event type for the record. Override this if you want to + specify your own types. This version does a mapping using the handler's + typemap attribute, which is set up in :meth:`__init__` to a dictionary + which contains mappings for :const:`DEBUG`, :const:`INFO`, + :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using + your own levels, you will either need to override this method or place a + suitable dictionary in the handler's *typemap* attribute. -.. method:: NTEventLogHandler.getMessageID(record) + .. method:: getMessageID(record) - Returns the message ID for the record. If you are using your own messages, you - could do this by having the *msg* passed to the logger being an ID rather than a - format string. Then, in here, you could use a dictionary lookup to get the - message ID. This version returns 1, which is the base message ID in - :file:`win32service.pyd`. + Returns the message ID for the record. If you are using your own messages, + you could do this by having the *msg* passed to the logger being an ID + rather than a format string. Then, in here, you could use a dictionary + lookup to get the message ID. This version returns 1, which is the base + message ID in :file:`win32service.pyd`. SMTPHandler @@ -1868,15 +1869,15 @@ can specify a (username, password) tuple for the *credentials* argument. -.. method:: SMTPHandler.emit(record) + .. method:: emit(record) - Formats the record and sends it to the specified addressees. + Formats the record and sends it to the specified addressees. -.. method:: SMTPHandler.getSubject(record) + .. method:: getSubject(record) - If you want to specify a subject line which is record-dependent, override this - method. + If you want to specify a subject line which is record-dependent, override + this method. MemoryHandler @@ -1899,22 +1900,22 @@ Initializes the handler with a buffer of the specified capacity. -.. method:: BufferingHandler.emit(record) + .. method:: emit(record) - Appends the record to the buffer. If :meth:`shouldFlush` returns true, calls - :meth:`flush` to process the buffer. + Appends the record to the buffer. If :meth:`shouldFlush` returns true, + calls :meth:`flush` to process the buffer. -.. method:: BufferingHandler.flush() + .. method:: flush() - You can override this to implement custom flushing behavior. This version just - zaps the buffer to empty. + You can override this to implement custom flushing behavior. This version + just zaps the buffer to empty. -.. method:: BufferingHandler.shouldFlush(record) + .. method:: shouldFlush(record) - Returns true if the buffer is up to capacity. This method can be overridden to - implement custom flushing strategies. + Returns true if the buffer is up to capacity. This method can be + overridden to implement custom flushing strategies. .. class:: MemoryHandler(capacity[, flushLevel [, target]]) @@ -1925,25 +1926,27 @@ set using :meth:`setTarget` before this handler does anything useful. -.. method:: MemoryHandler.close() + .. method:: close() - Calls :meth:`flush`, sets the target to :const:`None` and clears the buffer. + Calls :meth:`flush`, sets the target to :const:`None` and clears the + buffer. -.. method:: MemoryHandler.flush() + .. method:: flush() - For a :class:`MemoryHandler`, flushing means just sending the buffered records - to the target, if there is one. Override if you want different behavior. + For a :class:`MemoryHandler`, flushing means just sending the buffered + records to the target, if there is one. Override if you want different + behavior. -.. method:: MemoryHandler.setTarget(target) + .. method:: setTarget(target) - Sets the target handler for this handler. + Sets the target handler for this handler. -.. method:: MemoryHandler.shouldFlush(record) + .. method:: shouldFlush(record) - Checks for buffer full or a record at the *flushLevel* or higher. + Checks for buffer full or a record at the *flushLevel* or higher. HTTPHandler @@ -1962,9 +1965,9 @@ *method* is specified, ``GET`` is used. -.. method:: HTTPHandler.emit(record) + .. method:: emit(record) - Sends the record to the Web server as an URL-encoded dictionary. + Sends the record to the Web server as an URL-encoded dictionary. .. _formatter-objects: @@ -2049,38 +2052,42 @@ is used. -.. method:: Formatter.format(record) + .. method:: format(record) - The record's attribute dictionary is used as the operand to a string formatting - operation. Returns the resulting string. Before formatting the dictionary, a - couple of preparatory steps are carried out. The *message* attribute of the - record is computed using *msg* % *args*. If the formatting string contains - ``'(asctime)'``, :meth:`formatTime` is called to format the event time. If there - is exception information, it is formatted using :meth:`formatException` and - appended to the message. Note that the formatted exception information is cached - in attribute *exc_text*. This is useful because the exception information can - be pickled and sent across the wire, but you should be careful if you have more - than one :class:`Formatter` subclass which customizes the formatting of exception - information. In this case, you will have to clear the cached value after a - formatter has done its formatting, so that the next formatter to handle the event - doesn't use the cached value but recalculates it afresh. - - -.. method:: Formatter.formatTime(record[, datefmt]) - - This method should be called from :meth:`format` by a formatter which wants to - make use of a formatted time. This method can be overridden in formatters to - provide for any specific requirement, but the basic behavior is as follows: if - *datefmt* (a string) is specified, it is used with :func:`time.strftime` to - format the creation time of the record. Otherwise, the ISO8601 format is used. - The resulting string is returned. - - -.. method:: Formatter.formatException(exc_info) - - Formats the specified exception information (a standard exception tuple as - returned by :func:`sys.exc_info`) as a string. This default implementation just - uses :func:`traceback.print_exception`. The resulting string is returned. + The record's attribute dictionary is used as the operand to a string + formatting operation. Returns the resulting string. Before formatting the + dictionary, a couple of preparatory steps are carried out. The *message* + attribute of the record is computed using *msg* % *args*. If the + formatting string contains ``'(asctime)'``, :meth:`formatTime` is called + to format the event time. If there is exception information, it is + formatted using :meth:`formatException` and appended to the message. Note + that the formatted exception information is cached in attribute + *exc_text*. This is useful because the exception information can be + pickled and sent across the wire, but you should be careful if you have + more than one :class:`Formatter` subclass which customizes the formatting + of exception information. In this case, you will have to clear the cached + value after a formatter has done its formatting, so that the next + formatter to handle the event doesn't use the cached value but + recalculates it afresh. + + + .. method:: formatTime(record[, datefmt]) + + This method should be called from :meth:`format` by a formatter which + wants to make use of a formatted time. This method can be overridden in + formatters to provide for any specific requirement, but the basic behavior + is as follows: if *datefmt* (a string) is specified, it is used with + :func:`time.strftime` to format the creation time of the + record. Otherwise, the ISO8601 format is used. The resulting string is + returned. + + + .. method:: formatException(exc_info) + + Formats the specified exception information (a standard exception tuple as + returned by :func:`sys.exc_info`) as a string. This default implementation + just uses :func:`traceback.print_exception`. The resulting string is + returned. Filter Objects @@ -2101,10 +2108,11 @@ through the filter. If no name is specified, allows every event. -.. method:: Filter.filter(record) + .. method:: filter(record) - Is the specified record to be logged? Returns zero for no, nonzero for yes. If - deemed appropriate, the record may be modified in-place by this method. + Is the specified record to be logged? Returns zero for no, nonzero for + yes. If deemed appropriate, the record may be modified in-place by this + method. LogRecord Objects @@ -2132,16 +2140,15 @@ specified, it defaults to ``None``. -.. method:: LogRecord.getMessage() + .. method:: getMessage() + + Returns the message for this :class:`LogRecord` instance after merging any + user-supplied arguments with the message. - Returns the message for this :class:`LogRecord` instance after merging any - user-supplied arguments with the message. LoggerAdapter Objects --------------------- -.. versionadded:: 2.6 - :class:`LoggerAdapter` instances are used to conveniently pass contextual information into logging calls. For a usage example , see the section on `adding contextual information to your logging output`__. @@ -2153,13 +2160,13 @@ Returns an instance of :class:`LoggerAdapter` initialized with an underlying :class:`Logger` instance and a dict-like object. -.. method:: LoggerAdapter.process(msg, kwargs) + .. method:: process(msg, kwargs) - Modifies the message and/or keyword arguments passed to a logging call in - order to insert contextual information. This implementation takes the - object passed as *extra* to the constructor and adds it to *kwargs* using - key 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the - (possibly modified) versions of the arguments passed in. + Modifies the message and/or keyword arguments passed to a logging call in + order to insert contextual information. This implementation takes the object + passed as *extra* to the constructor and adds it to *kwargs* using key + 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the + (possibly modified) versions of the arguments passed in. In addition to the above, :class:`LoggerAdapter` supports all the logging methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`, @@ -2428,13 +2435,13 @@ HOST = 'localhost' PORT = 9999 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - print "connecting..." + print("connecting...") s.connect((HOST, PORT)) - print "sending config..." + print("sending config...") s.send(struct.pack(">L", len(data_to_send))) s.send(data_to_send) s.close() - print "complete" + print("complete") More examples Modified: python/branches/py3k-ctypes-pep3118/Doc/library/mailbox.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/mailbox.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/mailbox.rst Wed Apr 30 15:57:13 2008 @@ -32,237 +32,243 @@ A mailbox, which may be inspected and modified. -The :class:`Mailbox` class defines an interface and is not intended to be -instantiated. Instead, format-specific subclasses should inherit from -:class:`Mailbox` and your code should instantiate a particular subclass. + The :class:`Mailbox` class defines an interface and is not intended to be + instantiated. Instead, format-specific subclasses should inherit from + :class:`Mailbox` and your code should instantiate a particular subclass. + + The :class:`Mailbox` interface is dictionary-like, with small keys + corresponding to messages. Keys are issued by the :class:`Mailbox` instance + with which they will be used and are only meaningful to that :class:`Mailbox` + instance. A key continues to identify a message even if the corresponding + message is modified, such as by replacing it with another message. + + Messages may be added to a :class:`Mailbox` instance using the set-like + method :meth:`add` and removed using a ``del`` statement or the set-like + methods :meth:`remove` and :meth:`discard`. + + :class:`Mailbox` interface semantics differ from dictionary semantics in some + noteworthy ways. Each time a message is requested, a new representation + (typically a :class:`Message` instance) is generated based upon the current + state of the mailbox. Similarly, when a message is added to a + :class:`Mailbox` instance, the provided message representation's contents are + copied. In neither case is a reference to the message representation kept by + the :class:`Mailbox` instance. + + The default :class:`Mailbox` iterator iterates over message representations, + not keys as the default dictionary iterator does. Moreover, modification of a + mailbox during iteration is safe and well-defined. Messages added to the + mailbox after an iterator is created will not be seen by the + iterator. Messages removed from the mailbox before the iterator yields them + will be silently skipped, though using a key from an iterator may result in a + :exc:`KeyError` exception if the corresponding message is subsequently + removed. -The :class:`Mailbox` interface is dictionary-like, with small keys corresponding -to messages. Keys are issued by the :class:`Mailbox` instance with which they -will be used and are only meaningful to that :class:`Mailbox` instance. A key -continues to identify a message even if the corresponding message is modified, -such as by replacing it with another message. - -Messages may be added to a :class:`Mailbox` instance using the set-like method -:meth:`add` and removed using a ``del`` statement or the set-like methods -:meth:`remove` and :meth:`discard`. - -:class:`Mailbox` interface semantics differ from dictionary semantics in some -noteworthy ways. Each time a message is requested, a new representation -(typically a :class:`Message` instance) is generated based upon the current -state of the mailbox. Similarly, when a message is added to a :class:`Mailbox` -instance, the provided message representation's contents are copied. In neither -case is a reference to the message representation kept by the :class:`Mailbox` -instance. - -The default :class:`Mailbox` iterator iterates over message representations, not -keys as the default dictionary iterator does. Moreover, modification of a -mailbox during iteration is safe and well-defined. Messages added to the mailbox -after an iterator is created will not be seen by the iterator. Messages removed -from the mailbox before the iterator yields them will be silently skipped, -though using a key from an iterator may result in a :exc:`KeyError` exception if -the corresponding message is subsequently removed. - -.. warning:: + .. warning:: - Be very cautious when modifying mailboxes that might be simultaneously changed - by some other process. The safest mailbox format to use for such tasks is - Maildir; try to avoid using single-file formats such as mbox for concurrent - writing. If you're modifying a mailbox, you *must* lock it by calling the - :meth:`lock` and :meth:`unlock` methods *before* reading any messages in the - file or making any changes by adding or deleting a message. Failing to lock the - mailbox runs the risk of losing messages or corrupting the entire mailbox. + Be very cautious when modifying mailboxes that might be simultaneously + changed by some other process. The safest mailbox format to use for such + tasks is Maildir; try to avoid using single-file formats such as mbox for + concurrent writing. If you're modifying a mailbox, you *must* lock it by + calling the :meth:`lock` and :meth:`unlock` methods *before* reading any + messages in the file or making any changes by adding or deleting a + message. Failing to lock the mailbox runs the risk of losing messages or + corrupting the entire mailbox. -:class:`Mailbox` instances have the following methods: + :class:`Mailbox` instances have the following methods: -.. method:: Mailbox.add(message) + .. method:: add(message) - Add *message* to the mailbox and return the key that has been assigned to it. + Add *message* to the mailbox and return the key that has been assigned to + it. - Parameter *message* may be a :class:`Message` instance, an - :class:`email.Message.Message` instance, a string, or a file-like object (which - should be open in text mode). If *message* is an instance of the appropriate - format-specific :class:`Message` subclass (e.g., if it's an :class:`mboxMessage` - instance and this is an :class:`mbox` instance), its format-specific information - is used. Otherwise, reasonable defaults for format-specific information are - used. + Parameter *message* may be a :class:`Message` instance, an + :class:`email.Message.Message` instance, a string, or a file-like object + (which should be open in text mode). If *message* is an instance of the + appropriate format-specific :class:`Message` subclass (e.g., if it's an + :class:`mboxMessage` instance and this is an :class:`mbox` instance), its + format-specific information is used. Otherwise, reasonable defaults for + format-specific information are used. -.. method:: Mailbox.remove(key) - Mailbox.__delitem__(key) - Mailbox.discard(key) + .. method:: remove(key) + __delitem__(key) + discard(key) - Delete the message corresponding to *key* from the mailbox. + Delete the message corresponding to *key* from the mailbox. - If no such message exists, a :exc:`KeyError` exception is raised if the method - was called as :meth:`remove` or :meth:`__delitem__` but no exception is raised - if the method was called as :meth:`discard`. The behavior of :meth:`discard` may - be preferred if the underlying mailbox format supports concurrent modification - by other processes. + If no such message exists, a :exc:`KeyError` exception is raised if the + method was called as :meth:`remove` or :meth:`__delitem__` but no + exception is raised if the method was called as :meth:`discard`. The + behavior of :meth:`discard` may be preferred if the underlying mailbox + format supports concurrent modification by other processes. -.. method:: Mailbox.__setitem__(key, message) + .. method:: __setitem__(key, message) - Replace the message corresponding to *key* with *message*. Raise a - :exc:`KeyError` exception if no message already corresponds to *key*. + Replace the message corresponding to *key* with *message*. Raise a + :exc:`KeyError` exception if no message already corresponds to *key*. - As with :meth:`add`, parameter *message* may be a :class:`Message` instance, an - :class:`email.Message.Message` instance, a string, or a file-like object (which - should be open in text mode). If *message* is an instance of the appropriate - format-specific :class:`Message` subclass (e.g., if it's an :class:`mboxMessage` - instance and this is an :class:`mbox` instance), its format-specific information - is used. Otherwise, the format-specific information of the message that - currently corresponds to *key* is left unchanged. + As with :meth:`add`, parameter *message* may be a :class:`Message` + instance, an :class:`email.Message.Message` instance, a string, or a + file-like object (which should be open in text mode). If *message* is an + instance of the appropriate format-specific :class:`Message` subclass + (e.g., if it's an :class:`mboxMessage` instance and this is an + :class:`mbox` instance), its format-specific information is + used. Otherwise, the format-specific information of the message that + currently corresponds to *key* is left unchanged. -.. method:: Mailbox.iterkeys() - Mailbox.keys() + .. method:: iterkeys() + keys() - Return an iterator over all keys if called as :meth:`iterkeys` or return a list - of keys if called as :meth:`keys`. + Return an iterator over all keys if called as :meth:`iterkeys` or return a + list of keys if called as :meth:`keys`. -.. method:: Mailbox.itervalues() - Mailbox.__iter__() - Mailbox.values() + .. method:: itervalues() + __iter__() + values() - Return an iterator over representations of all messages if called as - :meth:`itervalues` or :meth:`__iter__` or return a list of such representations - if called as :meth:`values`. The messages are represented as instances of the - appropriate format-specific :class:`Message` subclass unless a custom message - factory was specified when the :class:`Mailbox` instance was initialized. + Return an iterator over representations of all messages if called as + :meth:`itervalues` or :meth:`__iter__` or return a list of such + representations if called as :meth:`values`. The messages are represented + as instances of the appropriate format-specific :class:`Message` subclass + unless a custom message factory was specified when the :class:`Mailbox` + instance was initialized. - .. note:: + .. note:: - The behavior of :meth:`__iter__` is unlike that of dictionaries, which iterate - over keys. + The behavior of :meth:`__iter__` is unlike that of dictionaries, which + iterate over keys. -.. method:: Mailbox.iteritems() - Mailbox.items() + .. method:: iteritems() + items() - Return an iterator over (*key*, *message*) pairs, where *key* is a key and - *message* is a message representation, if called as :meth:`iteritems` or return - a list of such pairs if called as :meth:`items`. The messages are represented as - instances of the appropriate format-specific :class:`Message` subclass unless a - custom message factory was specified when the :class:`Mailbox` instance was - initialized. + Return an iterator over (*key*, *message*) pairs, where *key* is a key and + *message* is a message representation, if called as :meth:`iteritems` or + return a list of such pairs if called as :meth:`items`. The messages are + represented as instances of the appropriate format-specific + :class:`Message` subclass unless a custom message factory was specified + when the :class:`Mailbox` instance was initialized. -.. method:: Mailbox.get(key[, default=None]) - Mailbox.__getitem__(key) + .. method:: get(key[, default=None]) + __getitem__(key) - Return a representation of the message corresponding to *key*. If no such - message exists, *default* is returned if the method was called as :meth:`get` - and a :exc:`KeyError` exception is raised if the method was called as - :meth:`__getitem__`. The message is represented as an instance of the - appropriate format-specific :class:`Message` subclass unless a custom message - factory was specified when the :class:`Mailbox` instance was initialized. + Return a representation of the message corresponding to *key*. If no such + message exists, *default* is returned if the method was called as + :meth:`get` and a :exc:`KeyError` exception is raised if the method was + called as :meth:`__getitem__`. The message is represented as an instance + of the appropriate format-specific :class:`Message` subclass unless a + custom message factory was specified when the :class:`Mailbox` instance + was initialized. -.. method:: Mailbox.get_message(key) + .. method:: get_message(key) - Return a representation of the message corresponding to *key* as an instance of - the appropriate format-specific :class:`Message` subclass, or raise a - :exc:`KeyError` exception if no such message exists. + Return a representation of the message corresponding to *key* as an + instance of the appropriate format-specific :class:`Message` subclass, or + raise a :exc:`KeyError` exception if no such message exists. -.. method:: Mailbox.get_string(key) + .. method:: get_string(key) - Return a string representation of the message corresponding to *key*, or raise a - :exc:`KeyError` exception if no such message exists. + Return a string representation of the message corresponding to *key*, or + raise a :exc:`KeyError` exception if no such message exists. -.. method:: Mailbox.get_file(key) + .. method:: get_file(key) - Return a file-like representation of the message corresponding to *key*, or - raise a :exc:`KeyError` exception if no such message exists. The file-like - object behaves as if open in binary mode. This file should be closed once it is - no longer needed. + Return a file-like representation of the message corresponding to *key*, + or raise a :exc:`KeyError` exception if no such message exists. The + file-like object behaves as if open in binary mode. This file should be + closed once it is no longer needed. - .. note:: + .. note:: - Unlike other representations of messages, file-like representations are not - necessarily independent of the :class:`Mailbox` instance that created them or of - the underlying mailbox. More specific documentation is provided by each - subclass. + Unlike other representations of messages, file-like representations are + not necessarily independent of the :class:`Mailbox` instance that + created them or of the underlying mailbox. More specific documentation + is provided by each subclass. -.. method:: Mailbox.__contains__(key) + .. method:: __contains__(key) - Return ``True`` if *key* corresponds to a message, ``False`` otherwise. + Return ``True`` if *key* corresponds to a message, ``False`` otherwise. -.. method:: Mailbox.__len__() + .. method:: __len__() - Return a count of messages in the mailbox. + Return a count of messages in the mailbox. -.. method:: Mailbox.clear() + .. method:: clear() - Delete all messages from the mailbox. + Delete all messages from the mailbox. -.. method:: Mailbox.pop(key[, default]) + .. method:: pop(key[, default]) - Return a representation of the message corresponding to *key* and delete the - message. If no such message exists, return *default* if it was supplied or else - raise a :exc:`KeyError` exception. The message is represented as an instance of - the appropriate format-specific :class:`Message` subclass unless a custom - message factory was specified when the :class:`Mailbox` instance was - initialized. + Return a representation of the message corresponding to *key* and delete + the message. If no such message exists, return *default* if it was + supplied or else raise a :exc:`KeyError` exception. The message is + represented as an instance of the appropriate format-specific + :class:`Message` subclass unless a custom message factory was specified + when the :class:`Mailbox` instance was initialized. -.. method:: Mailbox.popitem() + .. method:: popitem() - Return an arbitrary (*key*, *message*) pair, where *key* is a key and *message* - is a message representation, and delete the corresponding message. If the - mailbox is empty, raise a :exc:`KeyError` exception. The message is represented - as an instance of the appropriate format-specific :class:`Message` subclass - unless a custom message factory was specified when the :class:`Mailbox` instance - was initialized. + Return an arbitrary (*key*, *message*) pair, where *key* is a key and + *message* is a message representation, and delete the corresponding + message. If the mailbox is empty, raise a :exc:`KeyError` exception. The + message is represented as an instance of the appropriate format-specific + :class:`Message` subclass unless a custom message factory was specified + when the :class:`Mailbox` instance was initialized. -.. method:: Mailbox.update(arg) + .. method:: update(arg) - Parameter *arg* should be a *key*-to-*message* mapping or an iterable of (*key*, - *message*) pairs. Updates the mailbox so that, for each given *key* and - *message*, the message corresponding to *key* is set to *message* as if by using - :meth:`__setitem__`. As with :meth:`__setitem__`, each *key* must already - correspond to a message in the mailbox or else a :exc:`KeyError` exception will - be raised, so in general it is incorrect for *arg* to be a :class:`Mailbox` - instance. + Parameter *arg* should be a *key*-to-*message* mapping or an iterable of + (*key*, *message*) pairs. Updates the mailbox so that, for each given + *key* and *message*, the message corresponding to *key* is set to + *message* as if by using :meth:`__setitem__`. As with :meth:`__setitem__`, + each *key* must already correspond to a message in the mailbox or else a + :exc:`KeyError` exception will be raised, so in general it is incorrect + for *arg* to be a :class:`Mailbox` instance. - .. note:: + .. note:: - Unlike with dictionaries, keyword arguments are not supported. + Unlike with dictionaries, keyword arguments are not supported. -.. method:: Mailbox.flush() + .. method:: flush() - Write any pending changes to the filesystem. For some :class:`Mailbox` - subclasses, changes are always written immediately and :meth:`flush` does - nothing, but you should still make a habit of calling this method. + Write any pending changes to the filesystem. For some :class:`Mailbox` + subclasses, changes are always written immediately and :meth:`flush` does + nothing, but you should still make a habit of calling this method. -.. method:: Mailbox.lock() + .. method:: lock() - Acquire an exclusive advisory lock on the mailbox so that other processes know - not to modify it. An :exc:`ExternalClashError` is raised if the lock is not - available. The particular locking mechanisms used depend upon the mailbox - format. You should *always* lock the mailbox before making any modifications - to its contents. + Acquire an exclusive advisory lock on the mailbox so that other processes + know not to modify it. An :exc:`ExternalClashError` is raised if the lock + is not available. The particular locking mechanisms used depend upon the + mailbox format. You should *always* lock the mailbox before making any + modifications to its contents. -.. method:: Mailbox.unlock() + .. method:: unlock() - Release the lock on the mailbox, if any. + Release the lock on the mailbox, if any. -.. method:: Mailbox.close() + .. method:: close() - Flush the mailbox, unlock it if necessary, and close any open files. For some - :class:`Mailbox` subclasses, this method does nothing. + Flush the mailbox, unlock it if necessary, and close any open files. For + some :class:`Mailbox` subclasses, this method does nothing. .. _mailbox-maildir: @@ -285,113 +291,115 @@ instance that behaves like instances of other :class:`Mailbox` subclasses, set *factory* to ``None``. -Maildir is a directory-based mailbox format invented for the qmail mail transfer -agent and now widely supported by other programs. Messages in a Maildir mailbox -are stored in separate files within a common directory structure. This design -allows Maildir mailboxes to be accessed and modified by multiple unrelated -programs without data corruption, so file locking is unnecessary. - -Maildir mailboxes contain three subdirectories, namely: :file:`tmp`, -:file:`new`, and :file:`cur`. Messages are created momentarily in the -:file:`tmp` subdirectory and then moved to the :file:`new` subdirectory to -finalize delivery. A mail user agent may subsequently move the message to the -:file:`cur` subdirectory and store information about the state of the message in -a special "info" section appended to its file name. + Maildir is a directory-based mailbox format invented for the qmail mail + transfer agent and now widely supported by other programs. Messages in a + Maildir mailbox are stored in separate files within a common directory + structure. This design allows Maildir mailboxes to be accessed and modified + by multiple unrelated programs without data corruption, so file locking is + unnecessary. + + Maildir mailboxes contain three subdirectories, namely: :file:`tmp`, + :file:`new`, and :file:`cur`. Messages are created momentarily in the + :file:`tmp` subdirectory and then moved to the :file:`new` subdirectory to + finalize delivery. A mail user agent may subsequently move the message to the + :file:`cur` subdirectory and store information about the state of the message + in a special "info" section appended to its file name. + + Folders of the style introduced by the Courier mail transfer agent are also + supported. Any subdirectory of the main mailbox is considered a folder if + ``'.'`` is the first character in its name. Folder names are represented by + :class:`Maildir` without the leading ``'.'``. Each folder is itself a Maildir + mailbox but should not contain other folders. Instead, a logical nesting is + indicated using ``'.'`` to delimit levels, e.g., "Archived.2005.07". -Folders of the style introduced by the Courier mail transfer agent are also -supported. Any subdirectory of the main mailbox is considered a folder if -``'.'`` is the first character in its name. Folder names are represented by -:class:`Maildir` without the leading ``'.'``. Each folder is itself a Maildir -mailbox but should not contain other folders. Instead, a logical nesting is -indicated using ``'.'`` to delimit levels, e.g., "Archived.2005.07". + .. note:: -.. note:: + The Maildir specification requires the use of a colon (``':'``) in certain + message file names. However, some operating systems do not permit this + character in file names, If you wish to use a Maildir-like format on such + an operating system, you should specify another character to use + instead. The exclamation point (``'!'``) is a popular choice. For + example:: - The Maildir specification requires the use of a colon (``':'``) in certain - message file names. However, some operating systems do not permit this character - in file names, If you wish to use a Maildir-like format on such an operating - system, you should specify another character to use instead. The exclamation - point (``'!'``) is a popular choice. For example:: + import mailbox + mailbox.Maildir.colon = '!' - import mailbox - mailbox.Maildir.colon = '!' + The :attr:`colon` attribute may also be set on a per-instance basis. - The :attr:`colon` attribute may also be set on a per-instance basis. + :class:`Maildir` instances have all of the methods of :class:`Mailbox` in + addition to the following: -:class:`Maildir` instances have all of the methods of :class:`Mailbox` in -addition to the following: + .. method:: list_folders() -.. method:: Maildir.list_folders() + Return a list of the names of all folders. - Return a list of the names of all folders. + .. method:: .et_folder(folder) -.. method:: Maildir.get_folder(folder) + Return a :class:`Maildir` instance representing the folder whose name is + *folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder + does not exist. - Return a :class:`Maildir` instance representing the folder whose name is - *folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder does not - exist. + .. method:: add_folder(folder) -.. method:: Maildir.add_folder(folder) + Create a folder whose name is *folder* and return a :class:`Maildir` + instance representing it. - Create a folder whose name is *folder* and return a :class:`Maildir` instance - representing it. + .. method:: remove_folder(folder) -.. method:: Maildir.remove_folder(folder) + Delete the folder whose name is *folder*. If the folder contains any + messages, a :exc:`NotEmptyError` exception will be raised and the folder + will not be deleted. - Delete the folder whose name is *folder*. If the folder contains any messages, a - :exc:`NotEmptyError` exception will be raised and the folder will not be - deleted. + .. method:: clean() -.. method:: Maildir.clean() + Delete temporary files from the mailbox that have not been accessed in the + last 36 hours. The Maildir specification says that mail-reading programs + should do this occasionally. - Delete temporary files from the mailbox that have not been accessed in the last - 36 hours. The Maildir specification says that mail-reading programs should do - this occasionally. + Some :class:`Mailbox` methods implemented by :class:`Maildir` deserve special + remarks: -Some :class:`Mailbox` methods implemented by :class:`Maildir` deserve special -remarks: + .. method:: add(message) + __setitem__(key, message) + update(arg) -.. method:: Maildir.add(message) - Maildir.__setitem__(key, message) - Maildir.update(arg) + .. warning:: - .. warning:: + These methods generate unique file names based upon the current process + ID. When using multiple threads, undetected name clashes may occur and + cause corruption of the mailbox unless threads are coordinated to avoid + using these methods to manipulate the same mailbox simultaneously. - These methods generate unique file names based upon the current process ID. When - using multiple threads, undetected name clashes may occur and cause corruption - of the mailbox unless threads are coordinated to avoid using these methods to - manipulate the same mailbox simultaneously. + .. method:: flush() -.. method:: Maildir.flush() + All changes to Maildir mailboxes are immediately applied, so this method + does nothing. - All changes to Maildir mailboxes are immediately applied, so this method does - nothing. + .. method:: lock() + unlock() -.. method:: Maildir.lock() - Maildir.unlock() + Maildir mailboxes do not support (or require) locking, so these methods do + nothing. - Maildir mailboxes do not support (or require) locking, so these methods do - nothing. + .. method:: close() -.. method:: Maildir.close() + :class:`Maildir` instances do not keep any open files and the underlying + mailboxes do not support locking, so this method does nothing. - :class:`Maildir` instances do not keep any open files and the underlying - mailboxes do not support locking, so this method does nothing. + .. method:: get_file(key) -.. method:: Maildir.get_file(key) - - Depending upon the host platform, it may not be possible to modify or remove the - underlying message while the returned file remains open. + Depending upon the host platform, it may not be possible to modify or + remove the underlying message while the returned file remains open. .. seealso:: @@ -403,7 +411,7 @@ Notes on Maildir by its inventor. Includes an updated name-creation scheme and details on "info" semantics. - `maildir man page from Courier `_ + `maildir man page from Courier `_ Another specification of the format. Describes a common extension for supporting folders. @@ -423,33 +431,34 @@ representation. If *create* is ``True``, the mailbox is created if it does not exist. -The mbox format is the classic format for storing mail on Unix systems. All -messages in an mbox mailbox are stored in a single file with the beginning of -each message indicated by a line whose first five characters are "From ". + The mbox format is the classic format for storing mail on Unix systems. All + messages in an mbox mailbox are stored in a single file with the beginning of + each message indicated by a line whose first five characters are "From ". -Several variations of the mbox format exist to address perceived shortcomings in -the original. In the interest of compatibility, :class:`mbox` implements the -original format, which is sometimes referred to as :dfn:`mboxo`. This means that -the :mailheader:`Content-Length` header, if present, is ignored and that any -occurrences of "From " at the beginning of a line in a message body are -transformed to ">From " when storing the message, although occurences of ">From -" are not transformed to "From " when reading the message. + Several variations of the mbox format exist to address perceived shortcomings in + the original. In the interest of compatibility, :class:`mbox` implements the + original format, which is sometimes referred to as :dfn:`mboxo`. This means that + the :mailheader:`Content-Length` header, if present, is ignored and that any + occurrences of "From " at the beginning of a line in a message body are + transformed to ">From " when storing the message, although occurrences of ">From + " are not transformed to "From " when reading the message. -Some :class:`Mailbox` methods implemented by :class:`mbox` deserve special -remarks: + Some :class:`Mailbox` methods implemented by :class:`mbox` deserve special + remarks: -.. method:: mbox.get_file(key) + .. method:: get_file(key) - Using the file after calling :meth:`flush` or :meth:`close` on the :class:`mbox` - instance may yield unpredictable results or raise an exception. + Using the file after calling :meth:`flush` or :meth:`close` on the + :class:`mbox` instance may yield unpredictable results or raise an + exception. -.. method:: mbox.lock() - mbox.unlock() + .. method:: lock() + unlock() - Three locking mechanisms are used---dot locking and, if available, the - :cfunc:`flock` and :cfunc:`lockf` system calls. + Three locking mechanisms are used---dot locking and, if available, the + :cfunc:`flock` and :cfunc:`lockf` system calls. .. seealso:: @@ -460,7 +469,7 @@ `mbox man page from tin `_ Another specification of the format, with details on locking. - `Configuring Netscape Mail on Unix: Why The Content-Length Format is Bad `_ + `Configuring Netscape Mail on Unix: Why The Content-Length Format is Bad `_ An argument for using the original mbox format rather than a variation. `"mbox" is a family of several mutually incompatible mailbox formats `_ @@ -482,106 +491,109 @@ representation. If *create* is ``True``, the mailbox is created if it does not exist. -MH is a directory-based mailbox format invented for the MH Message Handling -System, a mail user agent. Each message in an MH mailbox resides in its own -file. An MH mailbox may contain other MH mailboxes (called :dfn:`folders`) in -addition to messages. Folders may be nested indefinitely. MH mailboxes also -support :dfn:`sequences`, which are named lists used to logically group messages -without moving them to sub-folders. Sequences are defined in a file called -:file:`.mh_sequences` in each folder. + MH is a directory-based mailbox format invented for the MH Message Handling + System, a mail user agent. Each message in an MH mailbox resides in its own + file. An MH mailbox may contain other MH mailboxes (called :dfn:`folders`) in + addition to messages. Folders may be nested indefinitely. MH mailboxes also + support :dfn:`sequences`, which are named lists used to logically group + messages without moving them to sub-folders. Sequences are defined in a file + called :file:`.mh_sequences` in each folder. -The :class:`MH` class manipulates MH mailboxes, but it does not attempt to -emulate all of :program:`mh`'s behaviors. In particular, it does not modify and -is not affected by the :file:`context` or :file:`.mh_profile` files that are -used by :program:`mh` to store its state and configuration. + The :class:`MH` class manipulates MH mailboxes, but it does not attempt to + emulate all of :program:`mh`'s behaviors. In particular, it does not modify + and is not affected by the :file:`context` or :file:`.mh_profile` files that + are used by :program:`mh` to store its state and configuration. -:class:`MH` instances have all of the methods of :class:`Mailbox` in addition to -the following: + :class:`MH` instances have all of the methods of :class:`Mailbox` in addition + to the following: -.. method:: MH.list_folders() + .. method:: list_folders() - Return a list of the names of all folders. + Return a list of the names of all folders. -.. method:: MH.get_folder(folder) + .. method:: get_folder(folder) - Return an :class:`MH` instance representing the folder whose name is *folder*. A - :exc:`NoSuchMailboxError` exception is raised if the folder does not exist. + Return an :class:`MH` instance representing the folder whose name is + *folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder + does not exist. -.. method:: MH.add_folder(folder) + .. method:: add_folder(folder) - Create a folder whose name is *folder* and return an :class:`MH` instance - representing it. + Create a folder whose name is *folder* and return an :class:`MH` instance + representing it. -.. method:: MH.remove_folder(folder) + .. method:: remove_folder(folder) - Delete the folder whose name is *folder*. If the folder contains any messages, a - :exc:`NotEmptyError` exception will be raised and the folder will not be - deleted. + Delete the folder whose name is *folder*. If the folder contains any + messages, a :exc:`NotEmptyError` exception will be raised and the folder + will not be deleted. -.. method:: MH.get_sequences() + .. method:: get_sequences() - Return a dictionary of sequence names mapped to key lists. If there are no - sequences, the empty dictionary is returned. + Return a dictionary of sequence names mapped to key lists. If there are no + sequences, the empty dictionary is returned. -.. method:: MH.set_sequences(sequences) + .. method:: set_sequences(sequences) - Re-define the sequences that exist in the mailbox based upon *sequences*, a - dictionary of names mapped to key lists, like returned by :meth:`get_sequences`. + Re-define the sequences that exist in the mailbox based upon *sequences*, + a dictionary of names mapped to key lists, like returned by + :meth:`get_sequences`. -.. method:: MH.pack() + .. method:: pack() - Rename messages in the mailbox as necessary to eliminate gaps in numbering. - Entries in the sequences list are updated correspondingly. + Rename messages in the mailbox as necessary to eliminate gaps in + numbering. Entries in the sequences list are updated correspondingly. - .. note:: + .. note:: - Already-issued keys are invalidated by this operation and should not be - subsequently used. + Already-issued keys are invalidated by this operation and should not be + subsequently used. -Some :class:`Mailbox` methods implemented by :class:`MH` deserve special -remarks: + Some :class:`Mailbox` methods implemented by :class:`MH` deserve special + remarks: -.. method:: MH.remove(key) - MH.__delitem__(key) - MH.discard(key) + .. method:: remove(key) + __delitem__(key) + discard(key) - These methods immediately delete the message. The MH convention of marking a - message for deletion by prepending a comma to its name is not used. + These methods immediately delete the message. The MH convention of marking + a message for deletion by prepending a comma to its name is not used. -.. method:: MH.lock() - MH.unlock() + .. method:: lock() + unlock() - Three locking mechanisms are used---dot locking and, if available, the - :cfunc:`flock` and :cfunc:`lockf` system calls. For MH mailboxes, locking the - mailbox means locking the :file:`.mh_sequences` file and, only for the duration - of any operations that affect them, locking individual message files. + Three locking mechanisms are used---dot locking and, if available, the + :cfunc:`flock` and :cfunc:`lockf` system calls. For MH mailboxes, locking + the mailbox means locking the :file:`.mh_sequences` file and, only for the + duration of any operations that affect them, locking individual message + files. -.. method:: MH.get_file(key) + .. method:: get_file(key) - Depending upon the host platform, it may not be possible to remove the - underlying message while the returned file remains open. + Depending upon the host platform, it may not be possible to remove the + underlying message while the returned file remains open. -.. method:: MH.flush() + .. method:: flush() - All changes to MH mailboxes are immediately applied, so this method does - nothing. + All changes to MH mailboxes are immediately applied, so this method does + nothing. -.. method:: MH.close() + .. method:: close() - :class:`MH` instances do not keep any open files, so this method is equivelant - to :meth:`unlock`. + :class:`MH` instances do not keep any open files, so this method is + equivalent to :meth:`unlock`. .. seealso:: @@ -609,54 +621,56 @@ representation. If *create* is ``True``, the mailbox is created if it does not exist. -Babyl is a single-file mailbox format used by the Rmail mail user agent included -with Emacs. The beginning of a message is indicated by a line containing the two -characters Control-Underscore (``'\037'``) and Control-L (``'\014'``). The end -of a message is indicated by the start of the next message or, in the case of -the last message, a line containing a Control-Underscore (``'\037'``) -character. - -Messages in a Babyl mailbox have two sets of headers, original headers and -so-called visible headers. Visible headers are typically a subset of the -original headers that have been reformatted or abridged to be more -attractive. Each message in a Babyl mailbox also has an accompanying list of -:dfn:`labels`, or short strings that record extra information about the message, -and a list of all user-defined labels found in the mailbox is kept in the Babyl -options section. + Babyl is a single-file mailbox format used by the Rmail mail user agent + included with Emacs. The beginning of a message is indicated by a line + containing the two characters Control-Underscore (``'\037'``) and Control-L + (``'\014'``). The end of a message is indicated by the start of the next + message or, in the case of the last message, a line containing a + Control-Underscore (``'\037'``) character. -:class:`Babyl` instances have all of the methods of :class:`Mailbox` in addition -to the following: + Messages in a Babyl mailbox have two sets of headers, original headers and + so-called visible headers. Visible headers are typically a subset of the + original headers that have been reformatted or abridged to be more + attractive. Each message in a Babyl mailbox also has an accompanying list of + :dfn:`labels`, or short strings that record extra information about the + message, and a list of all user-defined labels found in the mailbox is kept + in the Babyl options section. + :class:`Babyl` instances have all of the methods of :class:`Mailbox` in + addition to the following: -.. method:: Babyl.get_labels() - Return a list of the names of all user-defined labels used in the mailbox. + .. method:: get_labels() - .. note:: + Return a list of the names of all user-defined labels used in the mailbox. - The actual messages are inspected to determine which labels exist in the mailbox - rather than consulting the list of labels in the Babyl options section, but the - Babyl section is updated whenever the mailbox is modified. + .. note:: -Some :class:`Mailbox` methods implemented by :class:`Babyl` deserve special -remarks: + The actual messages are inspected to determine which labels exist in + the mailbox rather than consulting the list of labels in the Babyl + options section, but the Babyl section is updated whenever the mailbox + is modified. + Some :class:`Mailbox` methods implemented by :class:`Babyl` deserve special + remarks: -.. method:: Babyl.get_file(key) - In Babyl mailboxes, the headers of a message are not stored contiguously with - the body of the message. To generate a file-like representation, the headers and - body are copied together into a :class:`StringIO` instance (from the - :mod:`StringIO` module), which has an API identical to that of a file. As a - result, the file-like object is truly independent of the underlying mailbox but - does not save memory compared to a string representation. + .. method:: get_file(key) + In Babyl mailboxes, the headers of a message are not stored contiguously + with the body of the message. To generate a file-like representation, the + headers and body are copied together into a :class:`StringIO` instance + (from the :mod:`StringIO` module), which has an API identical to that of a + file. As a result, the file-like object is truly independent of the + underlying mailbox but does not save memory compared to a string + representation. -.. method:: Babyl.lock() - Babyl.unlock() - Three locking mechanisms are used---dot locking and, if available, the - :cfunc:`flock` and :cfunc:`lockf` system calls. + .. method:: lock() + unlock() + + Three locking mechanisms are used---dot locking and, if available, the + :cfunc:`flock` and :cfunc:`lockf` system calls. .. seealso:: @@ -664,7 +678,7 @@ `Format of Version 5 Babyl Files `_ A specification of the Babyl format. - `Reading Mail with Rmail `_ + `Reading Mail with Rmail `_ The Rmail manual, with some information on Babyl semantics. @@ -683,30 +697,31 @@ representation. If *create* is ``True``, the mailbox is created if it does not exist. -MMDF is a single-file mailbox format invented for the Multichannel Memorandum -Distribution Facility, a mail transfer agent. Each message is in the same form -as an mbox message but is bracketed before and after by lines containing four -Control-A (``'\001'``) characters. As with the mbox format, the beginning of -each message is indicated by a line whose first five characters are "From ", but -additional occurrences of "From " are not transformed to ">From " when storing -messages because the extra message separator lines prevent mistaking such -occurrences for the starts of subsequent messages. + MMDF is a single-file mailbox format invented for the Multichannel Memorandum + Distribution Facility, a mail transfer agent. Each message is in the same + form as an mbox message but is bracketed before and after by lines containing + four Control-A (``'\001'``) characters. As with the mbox format, the + beginning of each message is indicated by a line whose first five characters + are "From ", but additional occurrences of "From " are not transformed to + ">From " when storing messages because the extra message separator lines + prevent mistaking such occurrences for the starts of subsequent messages. -Some :class:`Mailbox` methods implemented by :class:`MMDF` deserve special -remarks: + Some :class:`Mailbox` methods implemented by :class:`MMDF` deserve special + remarks: -.. method:: MMDF.get_file(key) + .. method:: get_file(key) - Using the file after calling :meth:`flush` or :meth:`close` on the :class:`MMDF` - instance may yield unpredictable results or raise an exception. + Using the file after calling :meth:`flush` or :meth:`close` on the + :class:`MMDF` instance may yield unpredictable results or raise an + exception. -.. method:: MMDF.lock() - MMDF.unlock() + .. method:: lock() + unlock() - Three locking mechanisms are used---dot locking and, if available, the - :cfunc:`flock` and :cfunc:`lockf` system calls. + Three locking mechanisms are used---dot locking and, if available, the + :cfunc:`flock` and :cfunc:`lockf` system calls. .. seealso:: @@ -737,21 +752,21 @@ or a file, it should contain an :rfc:`2822`\ -compliant message, which is read and parsed. -The format-specific state and behaviors offered by subclasses vary, but in -general it is only the properties that are not specific to a particular mailbox -that are supported (although presumably the properties are specific to a -particular mailbox format). For example, file offsets for single-file mailbox -formats and file names for directory-based mailbox formats are not retained, -because they are only applicable to the original mailbox. But state such as -whether a message has been read by the user or marked as important is retained, -because it applies to the message itself. - -There is no requirement that :class:`Message` instances be used to represent -messages retrieved using :class:`Mailbox` instances. In some situations, the -time and memory required to generate :class:`Message` representations might not -not acceptable. For such situations, :class:`Mailbox` instances also offer -string and file-like representations, and a custom message factory may be -specified when a :class:`Mailbox` instance is initialized. + The format-specific state and behaviors offered by subclasses vary, but in + general it is only the properties that are not specific to a particular + mailbox that are supported (although presumably the properties are specific + to a particular mailbox format). For example, file offsets for single-file + mailbox formats and file names for directory-based mailbox formats are not + retained, because they are only applicable to the original mailbox. But state + such as whether a message has been read by the user or marked as important is + retained, because it applies to the message itself. + + There is no requirement that :class:`Message` instances be used to represent + messages retrieved using :class:`Mailbox` instances. In some situations, the + time and memory required to generate :class:`Message` representations might + not not acceptable. For such situations, :class:`Mailbox` instances also + offer string and file-like representations, and a custom message factory may + be specified when a :class:`Mailbox` instance is initialized. .. _mailbox-maildirmessage: @@ -765,106 +780,109 @@ A message with Maildir-specific behaviors. Parameter *message* has the same meaning as with the :class:`Message` constructor. -Typically, a mail user agent application moves all of the messages in the -:file:`new` subdirectory to the :file:`cur` subdirectory after the first time -the user opens and closes the mailbox, recording that the messages are old -whether or not they've actually been read. Each message in :file:`cur` has an -"info" section added to its file name to store information about its state. -(Some mail readers may also add an "info" section to messages in :file:`new`.) -The "info" section may take one of two forms: it may contain "2," followed by a -list of standardized flags (e.g., "2,FR") or it may contain "1," followed by -so-called experimental information. Standard flags for Maildir messages are as -follows: - -+------+---------+--------------------------------+ -| Flag | Meaning | Explanation | -+======+=========+================================+ -| D | Draft | Under composition | -+------+---------+--------------------------------+ -| F | Flagged | Marked as important | -+------+---------+--------------------------------+ -| P | Passed | Forwarded, resent, or bounced | -+------+---------+--------------------------------+ -| R | Replied | Replied to | -+------+---------+--------------------------------+ -| S | Seen | Read | -+------+---------+--------------------------------+ -| T | Trashed | Marked for subsequent deletion | -+------+---------+--------------------------------+ - -:class:`MaildirMessage` instances offer the following methods: - - -.. method:: MaildirMessage.get_subdir() - - Return either "new" (if the message should be stored in the :file:`new` - subdirectory) or "cur" (if the message should be stored in the :file:`cur` - subdirectory). + Typically, a mail user agent application moves all of the messages in the + :file:`new` subdirectory to the :file:`cur` subdirectory after the first time + the user opens and closes the mailbox, recording that the messages are old + whether or not they've actually been read. Each message in :file:`cur` has an + "info" section added to its file name to store information about its state. + (Some mail readers may also add an "info" section to messages in + :file:`new`.) The "info" section may take one of two forms: it may contain + "2," followed by a list of standardized flags (e.g., "2,FR") or it may + contain "1," followed by so-called experimental information. Standard flags + for Maildir messages are as follows: - .. note:: + +------+---------+--------------------------------+ + | Flag | Meaning | Explanation | + +======+=========+================================+ + | D | Draft | Under composition | + +------+---------+--------------------------------+ + | F | Flagged | Marked as important | + +------+---------+--------------------------------+ + | P | Passed | Forwarded, resent, or bounced | + +------+---------+--------------------------------+ + | R | Replied | Replied to | + +------+---------+--------------------------------+ + | S | Seen | Read | + +------+---------+--------------------------------+ + | T | Trashed | Marked for subsequent deletion | + +------+---------+--------------------------------+ + + :class:`MaildirMessage` instances offer the following methods: - A message is typically moved from :file:`new` to :file:`cur` after its mailbox - has been accessed, whether or not the message is has been read. A message - ``msg`` has been read if ``"S" in msg.get_flags()`` is ``True``. + .. method:: get_subdir() -.. method:: MaildirMessage.set_subdir(subdir) + Return either "new" (if the message should be stored in the :file:`new` + subdirectory) or "cur" (if the message should be stored in the :file:`cur` + subdirectory). - Set the subdirectory the message should be stored in. Parameter *subdir* must be - either "new" or "cur". + .. note:: + A message is typically moved from :file:`new` to :file:`cur` after its + mailbox has been accessed, whether or not the message is has been + read. A message ``msg`` has been read if ``"S" in msg.get_flags()`` is + ``True``. -.. method:: MaildirMessage.get_flags() - Return a string specifying the flags that are currently set. If the message - complies with the standard Maildir format, the result is the concatenation in - alphabetical order of zero or one occurrence of each of ``'D'``, ``'F'``, - ``'P'``, ``'R'``, ``'S'``, and ``'T'``. The empty string is returned if no flags - are set or if "info" contains experimental semantics. + .. method:: set_subdir(subdir) + Set the subdirectory the message should be stored in. Parameter *subdir* + must be either "new" or "cur". -.. method:: MaildirMessage.set_flags(flags) - Set the flags specified by *flags* and unset all others. + .. method:: get_flags() + Return a string specifying the flags that are currently set. If the + message complies with the standard Maildir format, the result is the + concatenation in alphabetical order of zero or one occurrence of each of + ``'D'``, ``'F'``, ``'P'``, ``'R'``, ``'S'``, and ``'T'``. The empty string + is returned if no flags are set or if "info" contains experimental + semantics. -.. method:: MaildirMessage.add_flag(flag) - Set the flag(s) specified by *flag* without changing other flags. To add more - than one flag at a time, *flag* may be a string of more than one character. The - current "info" is overwritten whether or not it contains experimental - information rather than flags. + .. method:: set_flags(flags) + Set the flags specified by *flags* and unset all others. -.. method:: MaildirMessage.remove_flag(flag) - Unset the flag(s) specified by *flag* without changing other flags. To remove - more than one flag at a time, *flag* maybe a string of more than one character. - If "info" contains experimental information rather than flags, the current - "info" is not modified. + .. method:: add_flag(flag) + Set the flag(s) specified by *flag* without changing other flags. To add + more than one flag at a time, *flag* may be a string of more than one + character. The current "info" is overwritten whether or not it contains + experimental information rather than flags. -.. method:: MaildirMessage.get_date() - Return the delivery date of the message as a floating-point number representing - seconds since the epoch. + .. method:: remove_flag(flag) + Unset the flag(s) specified by *flag* without changing other flags. To + remove more than one flag at a time, *flag* maybe a string of more than + one character. If "info" contains experimental information rather than + flags, the current "info" is not modified. -.. method:: MaildirMessage.set_date(date) - Set the delivery date of the message to *date*, a floating-point number - representing seconds since the epoch. + .. method:: get_date() + Return the delivery date of the message as a floating-point number + representing seconds since the epoch. -.. method:: MaildirMessage.get_info() - Return a string containing the "info" for a message. This is useful for - accessing and modifying "info" that is experimental (i.e., not a list of flags). + .. method:: set_date(date) + Set the delivery date of the message to *date*, a floating-point number + representing seconds since the epoch. -.. method:: MaildirMessage.set_info(info) - Set "info" to *info*, which should be a string. + .. method:: get_info() + + Return a string containing the "info" for a message. This is useful for + accessing and modifying "info" that is experimental (i.e., not a list of + flags). + + + .. method:: set_info(info) + + Set "info" to *info*, which should be a string. When a :class:`MaildirMessage` instance is created based upon an :class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status` @@ -930,78 +948,81 @@ A message with mbox-specific behaviors. Parameter *message* has the same meaning as with the :class:`Message` constructor. -Messages in an mbox mailbox are stored together in a single file. The sender's -envelope address and the time of delivery are typically stored in a line -beginning with "From " that is used to indicate the start of a message, though -there is considerable variation in the exact format of this data among mbox -implementations. Flags that indicate the state of the message, such as whether -it has been read or marked as important, are typically stored in -:mailheader:`Status` and :mailheader:`X-Status` headers. + Messages in an mbox mailbox are stored together in a single file. The + sender's envelope address and the time of delivery are typically stored in a + line beginning with "From " that is used to indicate the start of a message, + though there is considerable variation in the exact format of this data among + mbox implementations. Flags that indicate the state of the message, such as + whether it has been read or marked as important, are typically stored in + :mailheader:`Status` and :mailheader:`X-Status` headers. -Conventional flags for mbox messages are as follows: + Conventional flags for mbox messages are as follows: -+------+----------+--------------------------------+ -| Flag | Meaning | Explanation | -+======+==========+================================+ -| R | Read | Read | -+------+----------+--------------------------------+ -| O | Old | Previously detected by MUA | -+------+----------+--------------------------------+ -| D | Deleted | Marked for subsequent deletion | -+------+----------+--------------------------------+ -| F | Flagged | Marked as important | -+------+----------+--------------------------------+ -| A | Answered | Replied to | -+------+----------+--------------------------------+ + +------+----------+--------------------------------+ + | Flag | Meaning | Explanation | + +======+==========+================================+ + | R | Read | Read | + +------+----------+--------------------------------+ + | O | Old | Previously detected by MUA | + +------+----------+--------------------------------+ + | D | Deleted | Marked for subsequent deletion | + +------+----------+--------------------------------+ + | F | Flagged | Marked as important | + +------+----------+--------------------------------+ + | A | Answered | Replied to | + +------+----------+--------------------------------+ -The "R" and "O" flags are stored in the :mailheader:`Status` header, and the -"D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The -flags and headers typically appear in the order mentioned. + The "R" and "O" flags are stored in the :mailheader:`Status` header, and the + "D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The + flags and headers typically appear in the order mentioned. -:class:`mboxMessage` instances offer the following methods: + :class:`mboxMessage` instances offer the following methods: -.. method:: mboxMessage.get_from() + .. method:: get_from() - Return a string representing the "From " line that marks the start of the - message in an mbox mailbox. The leading "From " and the trailing newline are - excluded. + Return a string representing the "From " line that marks the start of the + message in an mbox mailbox. The leading "From " and the trailing newline + are excluded. -.. method:: mboxMessage.set_from(from_[, time_=None]) + .. method:: set_from(from_[, time_=None]) - Set the "From " line to *from_*, which should be specified without a leading - "From " or trailing newline. For convenience, *time_* may be specified and will - be formatted appropriately and appended to *from_*. If *time_* is specified, it - should be a :class:`struct_time` instance, a tuple suitable for passing to - :meth:`time.strftime`, or ``True`` (to use :meth:`time.gmtime`). + Set the "From " line to *from_*, which should be specified without a + leading "From " or trailing newline. For convenience, *time_* may be + specified and will be formatted appropriately and appended to *from_*. If + *time_* is specified, it should be a :class:`struct_time` instance, a + tuple suitable for passing to :meth:`time.strftime`, or ``True`` (to use + :meth:`time.gmtime`). -.. method:: mboxMessage.get_flags() + .. method:: get_flags() - Return a string specifying the flags that are currently set. If the message - complies with the conventional format, the result is the concatenation in the - following order of zero or one occurrence of each of ``'R'``, ``'O'``, ``'D'``, - ``'F'``, and ``'A'``. + Return a string specifying the flags that are currently set. If the + message complies with the conventional format, the result is the + concatenation in the following order of zero or one occurrence of each of + ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. -.. method:: mboxMessage.set_flags(flags) + .. method:: set_flags(flags) - Set the flags specified by *flags* and unset all others. Parameter *flags* - should be the concatenation in any order of zero or more occurrences of each of - ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. + Set the flags specified by *flags* and unset all others. Parameter *flags* + should be the concatenation in any order of zero or more occurrences of + each of ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. -.. method:: mboxMessage.add_flag(flag) + .. method:: add_flag(flag) - Set the flag(s) specified by *flag* without changing other flags. To add more - than one flag at a time, *flag* may be a string of more than one character. + Set the flag(s) specified by *flag* without changing other flags. To add + more than one flag at a time, *flag* may be a string of more than one + character. -.. method:: mboxMessage.remove_flag(flag) + .. method:: remove_flag(flag) - Unset the flag(s) specified by *flag* without changing other flags. To remove - more than one flag at a time, *flag* maybe a string of more than one character. + Unset the flag(s) specified by *flag* without changing other flags. To + remove more than one flag at a time, *flag* maybe a string of more than + one character. When an :class:`mboxMessage` instance is created based upon a :class:`MaildirMessage` instance, a "From " line is generated based upon the @@ -1081,43 +1102,43 @@ A message with MH-specific behaviors. Parameter *message* has the same meaning as with the :class:`Message` constructor. -MH messages do not support marks or flags in the traditional sense, but they do -support sequences, which are logical groupings of arbitrary messages. Some mail -reading programs (although not the standard :program:`mh` and :program:`nmh`) -use sequences in much the same way flags are used with other formats, as -follows: + MH messages do not support marks or flags in the traditional sense, but they + do support sequences, which are logical groupings of arbitrary messages. Some + mail reading programs (although not the standard :program:`mh` and + :program:`nmh`) use sequences in much the same way flags are used with other + formats, as follows: -+----------+------------------------------------------+ -| Sequence | Explanation | -+==========+==========================================+ -| unseen | Not read, but previously detected by MUA | -+----------+------------------------------------------+ -| replied | Replied to | -+----------+------------------------------------------+ -| flagged | Marked as important | -+----------+------------------------------------------+ + +----------+------------------------------------------+ + | Sequence | Explanation | + +==========+==========================================+ + | unseen | Not read, but previously detected by MUA | + +----------+------------------------------------------+ + | replied | Replied to | + +----------+------------------------------------------+ + | flagged | Marked as important | + +----------+------------------------------------------+ -:class:`MHMessage` instances offer the following methods: + :class:`MHMessage` instances offer the following methods: -.. method:: MHMessage.get_sequences() + .. method:: get_sequences() - Return a list of the names of sequences that include this message. + Return a list of the names of sequences that include this message. -.. method:: MHMessage.set_sequences(sequences) + .. method:: set_sequences(sequences) - Set the list of sequences that include this message. + Set the list of sequences that include this message. -.. method:: MHMessage.add_sequence(sequence) + .. method:: add_sequence(sequence) - Add *sequence* to the list of sequences that include this message. + Add *sequence* to the list of sequences that include this message. -.. method:: MHMessage.remove_sequence(sequence) + .. method:: remove_sequence(sequence) - Remove *sequence* from the list of sequences that include this message. + Remove *sequence* from the list of sequences that include this message. When an :class:`MHMessage` instance is created based upon a :class:`MaildirMessage` instance, the following conversions take place: @@ -1171,79 +1192,79 @@ A message with Babyl-specific behaviors. Parameter *message* has the same meaning as with the :class:`Message` constructor. -Certain message labels, called :dfn:`attributes`, are defined by convention to -have special meanings. The attributes are as follows: + Certain message labels, called :dfn:`attributes`, are defined by convention + to have special meanings. The attributes are as follows: -+-----------+------------------------------------------+ -| Label | Explanation | -+===========+==========================================+ -| unseen | Not read, but previously detected by MUA | -+-----------+------------------------------------------+ -| deleted | Marked for subsequent deletion | -+-----------+------------------------------------------+ -| filed | Copied to another file or mailbox | -+-----------+------------------------------------------+ -| answered | Replied to | -+-----------+------------------------------------------+ -| forwarded | Forwarded | -+-----------+------------------------------------------+ -| edited | Modified by the user | -+-----------+------------------------------------------+ -| resent | Resent | -+-----------+------------------------------------------+ + +-----------+------------------------------------------+ + | Label | Explanation | + +===========+==========================================+ + | unseen | Not read, but previously detected by MUA | + +-----------+------------------------------------------+ + | deleted | Marked for subsequent deletion | + +-----------+------------------------------------------+ + | filed | Copied to another file or mailbox | + +-----------+------------------------------------------+ + | answered | Replied to | + +-----------+------------------------------------------+ + | forwarded | Forwarded | + +-----------+------------------------------------------+ + | edited | Modified by the user | + +-----------+------------------------------------------+ + | resent | Resent | + +-----------+------------------------------------------+ -By default, Rmail displays only visible headers. The :class:`BabylMessage` -class, though, uses the original headers because they are more complete. Visible -headers may be accessed explicitly if desired. + By default, Rmail displays only visible headers. The :class:`BabylMessage` + class, though, uses the original headers because they are more + complete. Visible headers may be accessed explicitly if desired. -:class:`BabylMessage` instances offer the following methods: + :class:`BabylMessage` instances offer the following methods: -.. method:: BabylMessage.get_labels() + .. method:: get_labels() - Return a list of labels on the message. + Return a list of labels on the message. -.. method:: BabylMessage.set_labels(labels) + .. method:: set_labels(labels) - Set the list of labels on the message to *labels*. + Set the list of labels on the message to *labels*. -.. method:: BabylMessage.add_label(label) + .. method:: add_label(label) - Add *label* to the list of labels on the message. + Add *label* to the list of labels on the message. -.. method:: BabylMessage.remove_label(label) + .. method:: remove_label(label) - Remove *label* from the list of labels on the message. + Remove *label* from the list of labels on the message. -.. method:: BabylMessage.get_visible() + .. method:: get_visible() - Return an :class:`Message` instance whose headers are the message's visible - headers and whose body is empty. + Return an :class:`Message` instance whose headers are the message's + visible headers and whose body is empty. -.. method:: BabylMessage.set_visible(visible) + .. method:: set_visible(visible) - Set the message's visible headers to be the same as the headers in *message*. - Parameter *visible* should be a :class:`Message` instance, an - :class:`email.Message.Message` instance, a string, or a file-like object (which - should be open in text mode). + Set the message's visible headers to be the same as the headers in + *message*. Parameter *visible* should be a :class:`Message` instance, an + :class:`email.Message.Message` instance, a string, or a file-like object + (which should be open in text mode). -.. method:: BabylMessage.update_visible() + .. method:: update_visible() - When a :class:`BabylMessage` instance's original headers are modified, the - visible headers are not automatically modified to correspond. This method - updates the visible headers as follows: each visible header with a corresponding - original header is set to the value of the original header, each visible header - without a corresponding original header is removed, and any of - :mailheader:`Date`, :mailheader:`From`, :mailheader:`Reply-To`, - :mailheader:`To`, :mailheader:`CC`, and :mailheader:`Subject` that are present - in the original headers but not the visible headers are added to the visible - headers. + When a :class:`BabylMessage` instance's original headers are modified, the + visible headers are not automatically modified to correspond. This method + updates the visible headers as follows: each visible header with a + corresponding original header is set to the value of the original header, + each visible header without a corresponding original header is removed, + and any of :mailheader:`Date`, :mailheader:`From`, :mailheader:`Reply-To`, + :mailheader:`To`, :mailheader:`CC`, and :mailheader:`Subject` that are + present in the original headers but not the visible headers are added to + the visible headers. When a :class:`BabylMessage` instance is created based upon a :class:`MaildirMessage` instance, the following conversions take place: @@ -1299,77 +1320,80 @@ A message with MMDF-specific behaviors. Parameter *message* has the same meaning as with the :class:`Message` constructor. -As with message in an mbox mailbox, MMDF messages are stored with the sender's -address and the delivery date in an initial line beginning with "From ". -Likewise, flags that indicate the state of the message are typically stored in -:mailheader:`Status` and :mailheader:`X-Status` headers. + As with message in an mbox mailbox, MMDF messages are stored with the + sender's address and the delivery date in an initial line beginning with + "From ". Likewise, flags that indicate the state of the message are + typically stored in :mailheader:`Status` and :mailheader:`X-Status` headers. -Conventional flags for MMDF messages are identical to those of mbox message and -are as follows: + Conventional flags for MMDF messages are identical to those of mbox message + and are as follows: -+------+----------+--------------------------------+ -| Flag | Meaning | Explanation | -+======+==========+================================+ -| R | Read | Read | -+------+----------+--------------------------------+ -| O | Old | Previously detected by MUA | -+------+----------+--------------------------------+ -| D | Deleted | Marked for subsequent deletion | -+------+----------+--------------------------------+ -| F | Flagged | Marked as important | -+------+----------+--------------------------------+ -| A | Answered | Replied to | -+------+----------+--------------------------------+ + +------+----------+--------------------------------+ + | Flag | Meaning | Explanation | + +======+==========+================================+ + | R | Read | Read | + +------+----------+--------------------------------+ + | O | Old | Previously detected by MUA | + +------+----------+--------------------------------+ + | D | Deleted | Marked for subsequent deletion | + +------+----------+--------------------------------+ + | F | Flagged | Marked as important | + +------+----------+--------------------------------+ + | A | Answered | Replied to | + +------+----------+--------------------------------+ -The "R" and "O" flags are stored in the :mailheader:`Status` header, and the -"D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The -flags and headers typically appear in the order mentioned. + The "R" and "O" flags are stored in the :mailheader:`Status` header, and the + "D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The + flags and headers typically appear in the order mentioned. -:class:`MMDFMessage` instances offer the following methods, which are identical -to those offered by :class:`mboxMessage`: + :class:`MMDFMessage` instances offer the following methods, which are + identical to those offered by :class:`mboxMessage`: -.. method:: MMDFMessage.get_from() + .. method:: get_from() - Return a string representing the "From " line that marks the start of the - message in an mbox mailbox. The leading "From " and the trailing newline are - excluded. + Return a string representing the "From " line that marks the start of the + message in an mbox mailbox. The leading "From " and the trailing newline + are excluded. -.. method:: MMDFMessage.set_from(from_[, time_=None]) + .. method:: set_from(from_[, time_=None]) - Set the "From " line to *from_*, which should be specified without a leading - "From " or trailing newline. For convenience, *time_* may be specified and will - be formatted appropriately and appended to *from_*. If *time_* is specified, it - should be a :class:`struct_time` instance, a tuple suitable for passing to - :meth:`time.strftime`, or ``True`` (to use :meth:`time.gmtime`). + Set the "From " line to *from_*, which should be specified without a + leading "From " or trailing newline. For convenience, *time_* may be + specified and will be formatted appropriately and appended to *from_*. If + *time_* is specified, it should be a :class:`struct_time` instance, a + tuple suitable for passing to :meth:`time.strftime`, or ``True`` (to use + :meth:`time.gmtime`). -.. method:: MMDFMessage.get_flags() + .. method:: get_flags() - Return a string specifying the flags that are currently set. If the message - complies with the conventional format, the result is the concatenation in the - following order of zero or one occurrence of each of ``'R'``, ``'O'``, ``'D'``, - ``'F'``, and ``'A'``. + Return a string specifying the flags that are currently set. If the + message complies with the conventional format, the result is the + concatenation in the following order of zero or one occurrence of each of + ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. -.. method:: MMDFMessage.set_flags(flags) + .. method:: set_flags(flags) - Set the flags specified by *flags* and unset all others. Parameter *flags* - should be the concatenation in any order of zero or more occurrences of each of - ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. + Set the flags specified by *flags* and unset all others. Parameter *flags* + should be the concatenation in any order of zero or more occurrences of + each of ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. -.. method:: MMDFMessage.add_flag(flag) + .. method:: add_flag(flag) - Set the flag(s) specified by *flag* without changing other flags. To add more - than one flag at a time, *flag* may be a string of more than one character. + Set the flag(s) specified by *flag* without changing other flags. To add + more than one flag at a time, *flag* may be a string of more than one + character. -.. method:: MMDFMessage.remove_flag(flag) + .. method:: remove_flag(flag) - Unset the flag(s) specified by *flag* without changing other flags. To remove - more than one flag at a time, *flag* maybe a string of more than one character. + Unset the flag(s) specified by *flag* without changing other flags. To + remove more than one flag at a time, *flag* maybe a string of more than + one character. When an :class:`MMDFMessage` instance is created based upon a :class:`MaildirMessage` instance, a "From " line is generated based upon the @@ -1445,25 +1469,25 @@ The following exception classes are defined in the :mod:`mailbox` module: -.. class:: Error() +.. exception:: Error() The based class for all other module-specific exceptions. -.. class:: NoSuchMailboxError() +.. exception:: NoSuchMailboxError() Raised when a mailbox is expected but is not found, such as when instantiating a :class:`Mailbox` subclass with a path that does not exist (and with the *create* parameter set to ``False``), or when opening a folder that does not exist. -.. class:: NotEmptyErrorError() +.. exception:: NotEmptyErrorError() Raised when a mailbox is not empty but is expected to be, such as when deleting a folder that contains messages. -.. class:: ExternalClashError() +.. exception:: ExternalClashError() Raised when some mailbox-related condition beyond the control of the program causes it to be unable to proceed, such as when failing to acquire a lock that @@ -1471,7 +1495,7 @@ already exists. -.. class:: FormatError() +.. exception:: FormatError() Raised when the data in a file cannot be parsed, such as when an :class:`MH` instance attempts to read a corrupted :file:`.mh_sequences` file. @@ -1540,10 +1564,6 @@ :class:`UnixMailbox` except that individual messages are separated by only ``From`` lines. - For more information, see `Configuring Netscape Mail on Unix: Why the - Content-Length Format is Bad - `_. - .. class:: PortableUnixMailbox(fp[, factory]) @@ -1629,7 +1649,7 @@ destination = mailbox.MH('~/Mail') destination.lock() for message in mailbox.Babyl('~/RMAIL'): - destination.add(MHMessage(message)) + destination.add(mailbox.MHMessage(message)) destination.flush() destination.unlock() @@ -1643,7 +1663,7 @@ list_names = ('python-list', 'python-dev', 'python-bugs') - boxes = dict((name, mailbox.mbox('~/email/%s' % name)) for name in list_names) + boxes = {name: mailbox.mbox('~/email/%s' % name) for name in list_names} inbox = mailbox.Maildir('~/Maildir', factory=None) for key in inbox.iterkeys(): Modified: python/branches/py3k-ctypes-pep3118/Doc/library/marshal.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/marshal.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/marshal.rst Wed Apr 30 15:57:13 2008 @@ -38,7 +38,7 @@ Not all Python object types are supported; in general, only objects whose value is independent from a particular invocation of Python can be written and read by this module. The following types are supported: ``None``, integers, -floating point numbers, strings, Unicode objects, tuples, lists, sets, +floating point numbers, strings, bytes, bytearrays, tuples, lists, sets, dictionaries, and code objects, where it should be understood that tuples, lists and dictionaries are only supported as long as the values contained therein are themselves supported; and recursive lists and dictionaries should not be written Modified: python/branches/py3k-ctypes-pep3118/Doc/library/math.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/math.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/math.rst Wed Apr 30 15:57:13 2008 @@ -26,9 +26,9 @@ .. function:: ceil(x) - Return the ceiling of *x* as a float, the smallest integer value greater than - or equal to *x*. If *x* is not a float, delegates to ``x.__ceil__()``, which - should return an :class:`Integral` value. + Return the ceiling of *x*, the smallest integer greater than or equal to *x*. + If *x* is not a float, delegates to ``x.__ceil__()``, which should return an + :class:`Integral` value. .. function:: copysign(x, y) @@ -44,9 +44,9 @@ .. function:: floor(x) - Return the floor of *x* as a float, the largest integer value less than or - equal to *x*. If *x* is not a float, delegates to ``x.__floor__()``, which - should return an :class:`Integral` value. + Return the floor of *x*, the largest integer less than or equal to *x*. + If *x* is not a float, delegates to ``x.__floor__()``, which should return an + :class:`Integral` value. .. function:: fmod(x, y) @@ -96,6 +96,13 @@ Return the fractional and integer parts of *x*. Both results carry the sign of *x*, and both are floats. + +.. function:: trunc(x) + + Return the :class:`Real` value *x* truncated to an :class:`Integral` (usually + a long integer). Delegates to ``x.__trunc__()``. + + Note that :func:`frexp` and :func:`modf` have a different call/return pattern than their C equivalents: they take a single argument and return a pair of values, rather than returning their second return value through an 'output @@ -109,7 +116,6 @@ Power and logarithmic functions: - .. function:: exp(x) Return ``e**x``. @@ -121,6 +127,12 @@ return the natural logarithm of *x* (that is, the logarithm to base *e*). +.. function:: log1p(x) + + Return the natural logarithm of *1+x* (base *e*). The + result is calculated in a way which is accurate for *x* near zero. + + .. function:: log10(x) Return the base-10 logarithm of *x*. @@ -128,7 +140,12 @@ .. function:: pow(x, y) - Return ``x**y``. + Return ``x`` raised to the power ``y``. Exceptional cases follow + Annex 'F' of the C99 standard as far as possible. In particular, + ``pow(1.0, x)`` and ``pow(x, 0.0)`` always return ``1.0``, even + when ``x`` is a zero or a NaN. If both ``x`` and ``y`` are finite, + ``x`` is negative, and ``y`` is not an integer then ``pow(x, y)`` + is undefined, and raises :exc:`ValueError`. .. function:: sqrt(x) @@ -198,6 +215,21 @@ Hyperbolic functions: +.. function:: acosh(x) + + Return the inverse hyperbolic cosine of *x*. + + +.. function:: asinh(x) + + Return the inverse hyperbolic sine of *x*. + + +.. function:: atanh(x) + + Return the inverse hyperbolic tangent of *x*. + + .. function:: cosh(x) Return the hyperbolic cosine of *x*. @@ -212,6 +244,8 @@ Return the hyperbolic tangent of *x*. + + The module also defines two mathematical constants: @@ -224,6 +258,7 @@ The mathematical constant *e*. + .. note:: The :mod:`math` module consists mostly of thin wrappers around the platform C @@ -237,9 +272,17 @@ :exc:`OverflowError` isn't defined, and in cases where ``math.log(0)`` raises :exc:`OverflowError`, ``math.log(0L)`` may raise :exc:`ValueError` instead. + All functions return a quiet *NaN* if at least one of the args is *NaN*. + Signaling *NaN*s raise an exception. The exception type still depends on the + platform and libm implementation. It's usually :exc:`ValueError` for *EDOM* + and :exc:`OverflowError` for errno *ERANGE*. + + ..versionchanged:: 2.6 + In earlier versions of Python the outcome of an operation with NaN as + input depended on platform and libm implementation. + .. seealso:: Module :mod:`cmath` Complex number versions of many of these functions. - Modified: python/branches/py3k-ctypes-pep3118/Doc/library/mimetools.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/mimetools.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/mimetools.rst Wed Apr 30 15:57:13 2008 @@ -73,7 +73,7 @@ Module :mod:`multifile` Support for reading files which contain distinct parts, such as MIME data. - http://www.cs.uu.nl/wais/html/na-dir/mail/mime-faq/.html + http://faqs.cs.uu.nl/na-dir/mail/mime-faq/.html The MIME Frequently Asked Questions document. For an overview of MIME, see the answer to question 1.1 in Part 1 of this document. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/mimetypes.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/mimetypes.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/mimetypes.rst Wed Apr 30 15:57:13 2008 @@ -41,7 +41,7 @@ Optional *strict* is a flag specifying whether the list of known MIME types is limited to only the official types `registered with IANA - `_ are recognized. + `_ are recognized. When *strict* is true (the default), only the IANA types are supported; when *strict* is false, some additional non-standard but commonly used MIME types are also recognized. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/mmap.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/mmap.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/mmap.rst Wed Apr 30 15:57:13 2008 @@ -8,54 +8,55 @@ Memory-mapped file objects behave like both strings and like file objects. Unlike normal string objects, however, these are mutable. You can use mmap -objects in most places where strings are expected; for example, you can use the -:mod:`re` module to search through a memory-mapped file. Since they're mutable, -you can change a single character by doing ``obj[index] = 'a'``, or change a -substring by assigning to a slice: ``obj[i1:i2] = '...'``. You can also read -and write data starting at the current file position, and :meth:`seek` through -the file to different positions. - -A memory-mapped file is created by the :class:`mmap` constructor, which is different -on Unix and on Windows. In either case you must provide a file descriptor for a -file opened for update. If you wish to map an existing Python file object, use -its :meth:`fileno` method to obtain the correct value for the *fileno* -parameter. Otherwise, you can open the file using the :func:`os.open` function, -which returns a file descriptor directly (the file still needs to be closed when -done). +objects in most places where strings are expected; for example, you can use +the :mod:`re` module to search through a memory-mapped file. Since they're +mutable, you can change a single character by doing ``obj[index] = 'a'``, or +change a substring by assigning to a slice: ``obj[i1:i2] = '...'``. You can +also read and write data starting at the current file position, and +:meth:`seek` through the file to different positions. + +A memory-mapped file is created by the :class:`mmap` constructor, which is +different on Unix and on Windows. In either case you must provide a file +descriptor for a file opened for update. If you wish to map an existing Python +file object, use its :meth:`fileno` method to obtain the correct value for the +*fileno* parameter. Otherwise, you can open the file using the +:func:`os.open` function, which returns a file descriptor directly (the file +still needs to be closed when done). For both the Unix and Windows versions of the constructor, *access* may be specified as an optional keyword parameter. *access* accepts one of three -values: :const:`ACCESS_READ`, :const:`ACCESS_WRITE`, or :const:`ACCESS_COPY` to -specify readonly, write-through or copy-on-write memory respectively. *access* -can be used on both Unix and Windows. If *access* is not specified, Windows -mmap returns a write-through mapping. The initial memory values for all three -access types are taken from the specified file. Assignment to an -:const:`ACCESS_READ` memory map raises a :exc:`TypeError` exception. Assignment -to an :const:`ACCESS_WRITE` memory map affects both memory and the underlying -file. Assignment to an :const:`ACCESS_COPY` memory map affects memory but does -not update the underlying file. +values: :const:`ACCESS_READ`, :const:`ACCESS_WRITE`, or :const:`ACCESS_COPY` +to specify read-only, write-through or copy-on-write memory respectively. +*access* can be used on both Unix and Windows. If *access* is not specified, +Windows mmap returns a write-through mapping. The initial memory values for +all three access types are taken from the specified file. Assignment to an +:const:`ACCESS_READ` memory map raises a :exc:`TypeError` exception. +Assignment to an :const:`ACCESS_WRITE` memory map affects both memory and the +underlying file. Assignment to an :const:`ACCESS_COPY` memory map affects +memory but does not update the underlying file. To map anonymous memory, -1 should be passed as the fileno along with the length. .. class:: mmap(fileno, length[, tagname[, access[, offset]]]) - **(Windows version)** Maps *length* bytes from the file specified by the file - handle *fileno*, and creates a mmap object. If *length* is larger than the - current size of the file, the file is extended to contain *length* bytes. If - *length* is ``0``, the maximum length of the map is the current size of the - file, except that if the file is empty Windows raises an exception (you cannot - create an empty mapping on Windows). - - *tagname*, if specified and not ``None``, is a string giving a tag name for the - mapping. Windows allows you to have many different mappings against the same - file. If you specify the name of an existing tag, that tag is opened, otherwise - a new tag of this name is created. If this parameter is omitted or ``None``, - the mapping is created without a name. Avoiding the use of the tag parameter - will assist in keeping your code portable between Unix and Windows. - - *offset* may be specified as a non-negative integer offset. mmap references will - be relative to the offset from the beginning of the file. *offset* defaults to 0. - *offset* must be a multiple of the ALLOCATIONGRANULARITY. + **(Windows version)** Maps *length* bytes from the file specified by the + file handle *fileno*, and creates a mmap object. If *length* is larger + than the current size of the file, the file is extended to contain *length* + bytes. If *length* is ``0``, the maximum length of the map is the current + size of the file, except that if the file is empty Windows raises an + exception (you cannot create an empty mapping on Windows). + + *tagname*, if specified and not ``None``, is a string giving a tag name for + the mapping. Windows allows you to have many different mappings against + the same file. If you specify the name of an existing tag, that tag is + opened, otherwise a new tag of this name is created. If this parameter is + omitted or ``None``, the mapping is created without a name. Avoiding the + use of the tag parameter will assist in keeping your code portable between + Unix and Windows. + + *offset* may be specified as a non-negative integer offset. mmap references + will be relative to the offset from the beginning of the file. *offset* + defaults to 0. *offset* must be a multiple of the ALLOCATIONGRANULARITY. .. class:: mmap(fileno, length[, flags[, prot[, access[, offset]]]]) @@ -63,26 +64,29 @@ **(Unix version)** Maps *length* bytes from the file specified by the file descriptor *fileno*, and returns a mmap object. If *length* is ``0``, the - maximum length of the map will be the current size of the file when :class:`mmap` - is called. + maximum length of the map will be the current size of the file when + :class:`mmap` is called. *flags* specifies the nature of the mapping. :const:`MAP_PRIVATE` creates a - private copy-on-write mapping, so changes to the contents of the mmap object - will be private to this process, and :const:`MAP_SHARED` creates a mapping - that's shared with all other processes mapping the same areas of the file. The - default value is :const:`MAP_SHARED`. - - *prot*, if specified, gives the desired memory protection; the two most useful - values are :const:`PROT_READ` and :const:`PROT_WRITE`, to specify that the pages - may be read or written. *prot* defaults to :const:`PROT_READ \| PROT_WRITE`. - - *access* may be specified in lieu of *flags* and *prot* as an optional keyword - parameter. It is an error to specify both *flags*, *prot* and *access*. See - the description of *access* above for information on how to use this parameter. - - *offset* may be specified as a non-negative integer offset. mmap references will - be relative to the offset from the beginning of the file. *offset* defaults to 0. - *offset* must be a multiple of the PAGESIZE or ALLOCATIONGRANULARITY. + private copy-on-write mapping, so changes to the contents of the mmap + object will be private to this process, and :const:`MAP_SHARED` creates a + mapping that's shared with all other processes mapping the same areas of + the file. The default value is :const:`MAP_SHARED`. + + *prot*, if specified, gives the desired memory protection; the two most + useful values are :const:`PROT_READ` and :const:`PROT_WRITE`, to specify + that the pages may be read or written. *prot* defaults to + :const:`PROT_READ \| PROT_WRITE`. + + *access* may be specified in lieu of *flags* and *prot* as an optional + keyword parameter. It is an error to specify both *flags*, *prot* and + *access*. See the description of *access* above for information on how to + use this parameter. + + *offset* may be specified as a non-negative integer offset. mmap references + will be relative to the offset from the beginning of the file. *offset* + defaults to 0. *offset* must be a multiple of the PAGESIZE or + ALLOCATIONGRANULARITY. This example shows a simple way of using :class:`mmap`:: @@ -127,105 +131,111 @@ map.close() -Memory-mapped file objects support the following methods: + Memory-mapped file objects support the following methods: -.. method:: mmap.close() + .. method:: close() - Close the file. Subsequent calls to other methods of the object will result in - an exception being raised. + Close the file. Subsequent calls to other methods of the object will + result in an exception being raised. -.. method:: mmap.find(string[, start[, end]]) + .. method:: find(string[, start[, end]]) - Returns the lowest index in the object where the substring *string* is found, - such that *string* is contained in the range [*start*, *end*]. Optional - arguments *start* and *end* are interpreted as in slice notation. - Returns ``-1`` on failure. + Returns the lowest index in the object where the substring *string* is + found, such that *string* is contained in the range [*start*, *end*]. + Optional arguments *start* and *end* are interpreted as in slice notation. + Returns ``-1`` on failure. -.. method:: mmap.flush([offset, size]) + .. method:: flush([offset, size]) - Flushes changes made to the in-memory copy of a file back to disk. Without use - of this call there is no guarantee that changes are written back before the - object is destroyed. If *offset* and *size* are specified, only changes to the - given range of bytes will be flushed to disk; otherwise, the whole extent of the - mapping is flushed. + Flushes changes made to the in-memory copy of a file back to disk. Without + use of this call there is no guarantee that changes are written back before + the object is destroyed. If *offset* and *size* are specified, only + changes to the given range of bytes will be flushed to disk; otherwise, the + whole extent of the mapping is flushed. + **(Windows version)** A nonzero value returned indicates success; zero + indicates failure. -.. method:: mmap.move(dest, src, count) + **(Unix version)** A zero value is returned to indicate success. An + exception is raised when the call failed. - Copy the *count* bytes starting at offset *src* to the destination index *dest*. - If the mmap was created with :const:`ACCESS_READ`, then calls to move will throw - a :exc:`TypeError` exception. + .. method:: move(dest, src, count) -.. method:: mmap.read(num) + Copy the *count* bytes starting at offset *src* to the destination index + *dest*. If the mmap was created with :const:`ACCESS_READ`, then calls to + move will throw a :exc:`TypeError` exception. - Return a string containing up to *num* bytes starting from the current file - position; the file position is updated to point after the bytes that were - returned. + .. method:: read(num) -.. method:: mmap.read_byte() + Return a string containing up to *num* bytes starting from the current + file position; the file position is updated to point after the bytes that + were returned. - Returns a string of length 1 containing the character at the current file - position, and advances the file position by 1. + .. method:: read_byte() -.. method:: mmap.readline() + Returns a string of length 1 containing the character at the current file + position, and advances the file position by 1. - Returns a single line, starting at the current file position and up to the next - newline. + .. method:: readline() -.. method:: mmap.resize(newsize) + Returns a single line, starting at the current file position and up to the + next newline. - Resizes the map and the underlying file, if any. If the mmap was created with - :const:`ACCESS_READ` or :const:`ACCESS_COPY`, resizing the map will throw a - :exc:`TypeError` exception. + .. method:: resize(newsize) -.. method:: mmap.rfind(string[, start[, end]]) + Resizes the map and the underlying file, if any. If the mmap was created + with :const:`ACCESS_READ` or :const:`ACCESS_COPY`, resizing the map will + throw a :exc:`TypeError` exception. - Returns the highest index in the object where the substring *string* is - found, such that *string* is contained in the range [*start*, - *end*]. Optional arguments *start* and *end* are interpreted as in slice - notation. Returns ``-1`` on failure. + .. method:: rfind(string[, start[, end]]) -.. method:: mmap.seek(pos[, whence]) + Returns the highest index in the object where the substring *string* is + found, such that *string* is contained in the range [*start*, *end*]. + Optional arguments *start* and *end* are interpreted as in slice notation. + Returns ``-1`` on failure. - Set the file's current position. *whence* argument is optional and defaults to - ``os.SEEK_SET`` or ``0`` (absolute file positioning); other values are - ``os.SEEK_CUR`` or ``1`` (seek relative to the current position) and - ``os.SEEK_END`` or ``2`` (seek relative to the file's end). + .. method:: seek(pos[, whence]) -.. method:: mmap.size() + Set the file's current position. *whence* argument is optional and + defaults to ``os.SEEK_SET`` or ``0`` (absolute file positioning); other + values are ``os.SEEK_CUR`` or ``1`` (seek relative to the current + position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's end). - Return the length of the file, which can be larger than the size of the - memory-mapped area. + .. method:: size() -.. method:: mmap.tell() + Return the length of the file, which can be larger than the size of the + memory-mapped area. - Returns the current position of the file pointer. + .. method:: tell() -.. method:: mmap.write(string) + Returns the current position of the file pointer. - Write the bytes in *string* into memory at the current position of the file - pointer; the file position is updated to point after the bytes that were - written. If the mmap was created with :const:`ACCESS_READ`, then writing to it - will throw a :exc:`TypeError` exception. + .. method:: write(string) -.. method:: mmap.write_byte(byte) + Write the bytes in *string* into memory at the current position of the + file pointer; the file position is updated to point after the bytes that + were written. If the mmap was created with :const:`ACCESS_READ`, then + writing to it will throw a :exc:`TypeError` exception. - Write the single-character string *byte* into memory at the current position of - the file pointer; the file position is advanced by ``1``. If the mmap was - created with :const:`ACCESS_READ`, then writing to it will throw a - :exc:`TypeError` exception. + + .. method:: write_byte(byte) + + Write the single-character string *byte* into memory at the current + position of the file pointer; the file position is advanced by ``1``. If + the mmap was created with :const:`ACCESS_READ`, then writing to it will + throw a :exc:`TypeError` exception. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/modulefinder.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/modulefinder.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/modulefinder.rst Wed Apr 30 15:57:13 2008 @@ -38,13 +38,77 @@ be replaced in module paths. -.. method:: ModuleFinder.report() + .. method:: report() - Print a report to standard output that lists the modules imported by the script - and their paths, as well as modules that are missing or seem to be missing. + Print a report to standard output that lists the modules imported by the + script and their paths, as well as modules that are missing or seem to be + missing. + .. method:: run_script(pathname) -.. method:: ModuleFinder.run_script(pathname) + Analyze the contents of the *pathname* file, which must contain Python + code. + + .. attribute:: modules + + A dictionary mapping module names to modules. See + :ref:`modulefinder-example` + + +.. _modulefinder-example: + +Example usage of :class:`ModuleFinder` +-------------------------------------- + +The script that is going to get analyzed later on (bacon.py):: + + import re, itertools + + try: + import baconhameggs + except ImportError: + pass + + try: + import guido.python.ham + except ImportError: + pass + + +The script that will output the report of bacon.py:: + + from modulefinder import ModuleFinder + + finder = ModuleFinder() + finder.run_script('bacon.py') + + print 'Loaded modules:' + for name, mod in finder.modules.iteritems(): + print '%s: ' % name, + print ','.join(mod.globalnames.keys()[:3]) + + print '-'*50 + print 'Modules not imported:' + print '\n'.join(finder.badmodules.iterkeys()) + +Sample output (may vary depending on the architecture):: + + Loaded modules: + _types: + copy_reg: _inverted_registry,_slotnames,__all__ + sre_compile: isstring,_sre,_optimize_unicode + _sre: + sre_constants: REPEAT_ONE,makedict,AT_END_LINE + sys: + re: __module__,finditer,_expand + itertools: + __main__: re,itertools,baconhameggs + sre_parse: __getslice__,_PATTERNENDERS,SRE_FLAG_UNICODE + array: + types: __module__,IntType,TypeType + --------------------------------------------------- + Modules not imported: + guido.python.ham + baconhameggs - Analyze the contents of the *pathname* file, which must contain Python code. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/msilib.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/msilib.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/msilib.rst Wed Apr 30 15:57:13 2008 @@ -65,7 +65,7 @@ .. function:: init_database(name, schema, ProductName, ProductCode, ProductVersion, Manufacturer) - Create and return a new database *name*, initialize it with *schema*, and set + Create and return a new database *name*, initialize it with *schema*, and set the properties *ProductName*, *ProductCode*, *ProductVersion*, and *Manufacturer*. @@ -77,13 +77,20 @@ function returns. -.. function:: add_data(database, records) +.. function:: add_data(database, table, records) - Add all *records* to *database*. *records* should be a list of tuples, each one - containing all fields of a record according to the schema of the table. For - optional fields, ``None`` can be passed. + Add all *records* to the table named *table* in *database*. - Field values can be integers, strings, or instances of the Binary class. + The *table* argument must be one of the predefined tables in the MSI schema, + e.g. ``'Feature'``, ``'File'``, ``'Component'``, ``'Dialog'``, ``'Control'``, + etc. + + *records* should be a list of tuples, each one containing all fields of a + record according to the schema of the table. For optional fields, + ``None`` can be passed. + + Field values can be int or long numbers, strings, or instances of the Binary + class. .. class:: Binary(filename) @@ -311,19 +318,20 @@ *name* is the name of the CAB file in the MSI file. -.. method:: CAB.append(full, file, logical) + .. method:: append(full, file, logical) - Add the file with the pathname *full* to the CAB file, under the name *logical*. - If there is already a file named *logical*, a new file name is created. + Add the file with the pathname *full* to the CAB file, under the name + *logical*. If there is already a file named *logical*, a new file name is + created. - Return the index of the file in the CAB file, and the new name of the file - inside the CAB file. + Return the index of the file in the CAB file, and the new name of the file + inside the CAB file. -.. method:: CAB.commit(database) + .. method:: commit(database) - Generate a CAB file, add it as a stream to the MSI file, put it into the - ``Media`` table, and remove the generated file from the disk. + Generate a CAB file, add it as a stream to the MSI file, put it into the + ``Media`` table, and remove the generated file from the disk. .. _msi-directory: @@ -344,33 +352,33 @@ the default flags that new components get. -.. method:: Directory.start_component([component[, feature[, flags[, keyfile[, uuid]]]]]) + .. method:: start_component([component[, feature[, flags[, keyfile[, uuid]]]]]) - Add an entry to the Component table, and make this component the current - component for this directory. If no component name is given, the directory name - is used. If no *feature* is given, the current feature is used. If no *flags* - are given, the directory's default flags are used. If no *keyfile* is given, the - KeyPath is left null in the Component table. + Add an entry to the Component table, and make this component the current + component for this directory. If no component name is given, the directory + name is used. If no *feature* is given, the current feature is used. If no + *flags* are given, the directory's default flags are used. If no *keyfile* + is given, the KeyPath is left null in the Component table. -.. method:: Directory.add_file(file[, src[, version[, language]]]) + .. method:: add_file(file[, src[, version[, language]]]) - Add a file to the current component of the directory, starting a new one if - there is no current component. By default, the file name in the source and the - file table will be identical. If the *src* file is specified, it is interpreted - relative to the current directory. Optionally, a *version* and a *language* can - be specified for the entry in the File table. + Add a file to the current component of the directory, starting a new one + if there is no current component. By default, the file name in the source + and the file table will be identical. If the *src* file is specified, it + is interpreted relative to the current directory. Optionally, a *version* + and a *language* can be specified for the entry in the File table. -.. method:: Directory.glob(pattern[, exclude]) + .. method:: glob(pattern[, exclude]) - Add a list of files to the current component as specified in the glob pattern. - Individual files can be excluded in the *exclude* list. + Add a list of files to the current component as specified in the glob + pattern. Individual files can be excluded in the *exclude* list. -.. method:: Directory.remove_pyc() + .. method:: remove_pyc() - Remove ``.pyc``/``.pyo`` files on uninstall. + Remove ``.pyc``/``.pyo`` files on uninstall. .. seealso:: @@ -394,11 +402,11 @@ :class:`Directory`. -.. method:: Feature.set_current() + .. method:: set_current() - Make this feature the current feature of :mod:`msilib`. New components are - automatically added to the default feature, unless a feature is explicitly - specified. + Make this feature the current feature of :mod:`msilib`. New components are + automatically added to the default feature, unless a feature is explicitly + specified. .. seealso:: @@ -421,19 +429,19 @@ belongs to, and *name* is the control's name. -.. method:: Control.event(event, argument[, condition=1[, ordering]]) + .. method:: event(event, argument[, condition=1[, ordering]]) - Make an entry into the ``ControlEvent`` table for this control. + Make an entry into the ``ControlEvent`` table for this control. -.. method:: Control.mapping(event, attribute) + .. method:: mapping(event, attribute) - Make an entry into the ``EventMapping`` table for this control. + Make an entry into the ``EventMapping`` table for this control. -.. method:: Control.condition(action, condition) + .. method:: condition(action, condition) - Make an entry into the ``ControlCondition`` table for this control. + Make an entry into the ``ControlCondition`` table for this control. .. class:: RadioButtonGroup(dlg, name, property) @@ -442,11 +450,11 @@ that gets set when a radio button is selected. -.. method:: RadioButtonGroup.add(name, x, y, width, height, text [, value]) + .. method:: add(name, x, y, width, height, text [, value]) - Add a radio button named *name* to the group, at the coordinates *x*, *y*, - *width*, *height*, and with the label *text*. If *value* is omitted, it defaults - to *name*. + Add a radio button named *name* to the group, at the coordinates *x*, *y*, + *width*, *height*, and with the label *text*. If *value* is omitted, it + defaults to *name*. .. class:: Dialog(db, name, x, y, w, h, attr, title, first, default, cancel) @@ -456,42 +464,43 @@ default, and cancel controls. -.. method:: Dialog.control(name, type, x, y, width, height, attributes, property, text, control_next, help) + .. method:: control(name, type, x, y, width, height, attributes, property, text, control_next, help) - Return a new :class:`Control` object. An entry in the ``Control`` table is made - with the specified parameters. + Return a new :class:`Control` object. An entry in the ``Control`` table is + made with the specified parameters. - This is a generic method; for specific types, specialized methods are provided. + This is a generic method; for specific types, specialized methods are + provided. -.. method:: Dialog.text(name, x, y, width, height, attributes, text) + .. method:: text(name, x, y, width, height, attributes, text) - Add and return a ``Text`` control. + Add and return a ``Text`` control. -.. method:: Dialog.bitmap(name, x, y, width, height, text) + .. method:: bitmap(name, x, y, width, height, text) - Add and return a ``Bitmap`` control. + Add and return a ``Bitmap`` control. -.. method:: Dialog.line(name, x, y, width, height) + .. method:: line(name, x, y, width, height) - Add and return a ``Line`` control. + Add and return a ``Line`` control. -.. method:: Dialog.pushbutton(name, x, y, width, height, attributes, text, next_control) + .. method:: pushbutton(name, x, y, width, height, attributes, text, next_control) - Add and return a ``PushButton`` control. + Add and return a ``PushButton`` control. -.. method:: Dialog.radiogroup(name, x, y, width, height, attributes, property, text, next_control) + .. method:: radiogroup(name, x, y, width, height, attributes, property, text, next_control) - Add and return a ``RadioButtonGroup`` control. + Add and return a ``RadioButtonGroup`` control. -.. method:: Dialog.checkbox(name, x, y, width, height, attributes, property, text, next_control) + .. method:: checkbox(name, x, y, width, height, attributes, property, text, next_control) - Add and return a ``CheckBox`` control. + Add and return a ``CheckBox`` control. .. seealso:: Modified: python/branches/py3k-ctypes-pep3118/Doc/library/numbers.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/numbers.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/numbers.rst Wed Apr 30 15:57:13 2008 @@ -6,9 +6,8 @@ The :mod:`numbers` module (:pep:`3141`) defines a hierarchy of numeric abstract -base classes which progressively define more operations. These concepts also -provide a way to distinguish exact from inexact types. None of the types defined -in this module can be instantiated. +base classes which progressively define more operations. None of the types +defined in this module can be instantiated. .. class:: Number @@ -17,27 +16,6 @@ *x* is a number, without caring what kind, use ``isinstance(x, Number)``. -Exact and inexact operations ----------------------------- - -.. class:: Exact - - Subclasses of this type have exact operations. - - As long as the result of a homogenous operation is of the same type, you can - assume that it was computed exactly, and there are no round-off errors. Laws - like commutativity and associativity hold. - - -.. class:: Inexact - - Subclasses of this type have inexact operations. - - Given X, an instance of :class:`Inexact`, it is possible that ``(X + -X) + 3 - == 3``, but ``X + (-X + 3) == 0``. The exact form this error takes will vary - by type, but it's generally unsafe to compare this type for equality. - - The numeric tower ----------------- @@ -49,18 +27,18 @@ ``-``, ``*``, ``/``, :func:`abs`, :meth:`conjugate`, ``==``, and ``!=``. All except ``-`` and ``!=`` are abstract. -.. attribute:: Complex.real + .. attribute:: real - Abstract. Retrieves the :class:`Real` component of this number. + Abstract. Retrieves the :class:`Real` component of this number. -.. attribute:: Complex.imag + .. attribute:: imag - Abstract. Retrieves the :class:`Real` component of this number. + Abstract. Retrieves the :class:`Real` component of this number. -.. method:: Complex.conjugate() + .. method:: conjugate() - Abstract. Returns the complex conjugate. For example, ``(1+3j).conjugate() == - (1-3j)``. + Abstract. Returns the complex conjugate. For example, ``(1+3j).conjugate() + == (1-3j)``. .. class:: Real @@ -77,18 +55,18 @@ .. class:: Rational - Subtypes both :class:`Real` and :class:`Exact`, and adds + Subtypes :class:`Real` and adds :attr:`Rational.numerator` and :attr:`Rational.denominator` properties, which should be in lowest terms. With these, it provides a default for :func:`float`. -.. attribute:: Rational.numerator + .. attribute:: numerator - Abstract. + Abstract. -.. attribute:: Rational.denominator + .. attribute:: denominator - Abstract. + Abstract. .. class:: Integral @@ -97,3 +75,144 @@ 3-argument form of :func:`pow`, and the bit-string operations: ``<<``, ``>>``, ``&``, ``^``, ``|``, ``~``. Provides defaults for :func:`float`, :attr:`Rational.numerator`, and :attr:`Rational.denominator`. + + +Notes for type implementors +--------------------------- + +Implementors should be careful to make equal numbers equal and hash +them to the same values. This may be subtle if there are two different +extensions of the real numbers. For example, :class:`fractions.Fraction` +implements :func:`hash` as follows:: + + def __hash__(self): + if self.denominator == 1: + # Get integers right. + return hash(self.numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self.numerator, self.denominator)) + + +Adding More Numeric ABCs +~~~~~~~~~~~~~~~~~~~~~~~~ + +There are, of course, more possible ABCs for numbers, and this would +be a poor hierarchy if it precluded the possibility of adding +those. You can add ``MyFoo`` between :class:`Complex` and +:class:`Real` with:: + + class MyFoo(Complex): ... + MyFoo.register(Real) + + +Implementing the arithmetic operations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +We want to implement the arithmetic operations so that mixed-mode +operations either call an implementation whose author knew about the +types of both arguments, or convert both to the nearest built in type +and do the operation there. For subtypes of :class:`Integral`, this +means that :meth:`__add__` and :meth:`__radd__` should be defined as:: + + class MyIntegral(Integral): + + def __add__(self, other): + if isinstance(other, MyIntegral): + return do_my_adding_stuff(self, other) + elif isinstance(other, OtherTypeIKnowAbout): + return do_my_other_adding_stuff(self, other) + else: + return NotImplemented + + def __radd__(self, other): + if isinstance(other, MyIntegral): + return do_my_adding_stuff(other, self) + elif isinstance(other, OtherTypeIKnowAbout): + return do_my_other_adding_stuff(other, self) + elif isinstance(other, Integral): + return int(other) + int(self) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + else: + return NotImplemented + + +There are 5 different cases for a mixed-type operation on subclasses +of :class:`Complex`. I'll refer to all of the above code that doesn't +refer to ``MyIntegral`` and ``OtherTypeIKnowAbout`` as +"boilerplate". ``a`` will be an instance of ``A``, which is a subtype +of :class:`Complex` (``a : A <: Complex``), and ``b : B <: +Complex``. I'll consider ``a + b``: + + 1. If ``A`` defines an :meth:`__add__` which accepts ``b``, all is + well. + 2. If ``A`` falls back to the boilerplate code, and it were to + return a value from :meth:`__add__`, we'd miss the possibility + that ``B`` defines a more intelligent :meth:`__radd__`, so the + boilerplate should return :const:`NotImplemented` from + :meth:`__add__`. (Or ``A`` may not implement :meth:`__add__` at + all.) + 3. Then ``B``'s :meth:`__radd__` gets a chance. If it accepts + ``a``, all is well. + 4. If it falls back to the boilerplate, there are no more possible + methods to try, so this is where the default implementation + should live. + 5. If ``B <: A``, Python tries ``B.__radd__`` before + ``A.__add__``. This is ok, because it was implemented with + knowledge of ``A``, so it can handle those instances before + delegating to :class:`Complex`. + +If ``A<:Complex`` and ``B<:Real`` without sharing any other knowledge, +then the appropriate shared operation is the one involving the built +in :class:`complex`, and both :meth:`__radd__` s land there, so ``a+b +== b+a``. + +Because most of the operations on any given type will be very similar, +it can be useful to define a helper function which generates the +forward and reverse instances of any given operator. For example, +:class:`fractions.Fraction` uses:: + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """a + b""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + # ... Modified: python/branches/py3k-ctypes-pep3118/Doc/library/numeric.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/numeric.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/numeric.rst Wed Apr 30 15:57:13 2008 @@ -21,7 +21,7 @@ math.rst cmath.rst decimal.rst - rational.rst + fractions.rst random.rst itertools.rst functools.rst Modified: python/branches/py3k-ctypes-pep3118/Doc/library/operator.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/operator.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/operator.rst Wed Apr 30 15:57:13 2008 @@ -6,6 +6,11 @@ .. sectionauthor:: Skip Montanaro +.. testsetup:: + + import operator + from operator import itemgetter + The :mod:`operator` module exports a set of functions implemented in C corresponding to the intrinsic operators of Python. For example, @@ -93,13 +98,6 @@ Return the bitwise and of *a* and *b*. -.. function:: div(a, b) - __div__(a, b) - - Return ``a / b`` when ``__future__.division`` is not in effect. This is - also known as "classic" division. - - .. function:: floordiv(a, b) __floordiv__(a, b) @@ -171,8 +169,8 @@ .. function:: truediv(a, b) __truediv__(a, b) - Return ``a / b`` when ``__future__.division`` is in effect. This is also - known as "true" division. + Return ``a / b`` where 2/3 is .66 rather than 0. This is also known as + "true" division. .. function:: xor(a, b) @@ -211,7 +209,7 @@ Remove the value of *a* at index *b*. - + .. function:: delslice(a, b, c) __delslice__(a, b, c) @@ -241,14 +239,6 @@ Return ``a * b`` where *a* is a sequence and *b* is an integer. -.. function:: sequenceIncludes(...) - - .. deprecated:: 2.0 - Use :func:`contains` instead. - - Alias for :func:`contains`. - - .. function:: setitem(a, b, c) __setitem__(a, b, c) @@ -260,6 +250,7 @@ Set the slice of *a* from index *b* to index *c-1* to the sequence *v*. + Many operations have an "in-place" version. The following functions provide a more primitive access to in-place operators than the usual syntax does; for example, the :term:`statement` ``x += y`` is equivalent to @@ -285,13 +276,6 @@ ``a = iconcat(a, b)`` is equivalent to ``a += b`` for *a* and *b* sequences. -.. function:: idiv(a, b) - __idiv__(a, b) - - ``a = idiv(a, b)`` is equivalent to ``a /= b`` when ``__future__.division`` is - not in effect. - - .. function:: ifloordiv(a, b) __ifloordiv__(a, b) @@ -350,8 +334,7 @@ .. function:: itruediv(a, b) __itruediv__(a, b) - ``a = itruediv(a, b)`` is equivalent to ``a /= b`` when ``__future__.division`` - is in effect. + ``a = itruediv(a, b)`` is equivalent to ``a /= b``. .. function:: ixor(a, b) @@ -363,11 +346,12 @@ The :mod:`operator` module also defines a few predicates to test the type of objects. +.. XXX just remove them? .. note:: - Be careful not to misinterpret the results of these functions; only - :func:`isCallable` has any measure of reliability with instance objects. - For example:: + Be careful not to misinterpret the results of these functions; none have any + measure of reliability with instance objects. + For example: >>> class C: ... pass @@ -379,21 +363,10 @@ .. note:: - Python 3 is expected to introduce abstract base classes for - collection types, so it should be possible to write, for example, - ``isinstance(obj, collections.Mapping)`` and ``isinstance(obj, + Since there are now abstract classes for collection types, you should write, + for example, ``isinstance(obj, collections.Mapping)`` and ``isinstance(obj, collections.Sequence)``. -.. function:: isCallable(obj) - - .. deprecated:: 2.0 - Use the :func:`callable` built-in function instead. - - Returns true if the object *obj* can be called like a function, otherwise it - returns false. True is returned for functions, instance methods, class - objects, and instance objects which support the :meth:`__call__` method. - - .. function:: isMappingType(obj) Returns true if the object *obj* supports the mapping interface. This is true for @@ -431,13 +404,12 @@ useful than it otherwise might be. Example: Build a dictionary that maps the ordinals from ``0`` to ``255`` to -their character equivalents. :: +their character equivalents. - >>> import operator >>> d = {} >>> keys = range(256) >>> vals = map(chr, keys) - >>> map(operator.setitem, [d]*len(keys), keys, vals) + >>> map(operator.setitem, [d]*len(keys), keys, vals) # doctest: +SKIP .. XXX: find a better, readable, example @@ -451,28 +423,59 @@ Return a callable object that fetches *attr* from its operand. If more than one attribute is requested, returns a tuple of attributes. After, - ``f=attrgetter('name')``, the call ``f(b)`` returns ``b.name``. After, - ``f=attrgetter('name', 'date')``, the call ``f(b)`` returns ``(b.name, + ``f = attrgetter('name')``, the call ``f(b)`` returns ``b.name``. After, + ``f = attrgetter('name', 'date')``, the call ``f(b)`` returns ``(b.name, b.date)``. + The attribute names can also contain dots; after ``f = attrgetter('date.month')``, + the call ``f(b)`` returns ``b.date.month``. .. function:: itemgetter(item[, args...]) - Return a callable object that fetches *item* from its operand. If more than one - item is requested, returns a tuple of items. After, ``f=itemgetter(2)``, the - call ``f(b)`` returns ``b[2]``. After, ``f=itemgetter(2,5,3)``, the call - ``f(b)`` returns ``(b[2], b[5], b[3])``. - - -Examples:: - - >>> from operator import itemgetter - >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)] - >>> getcount = itemgetter(1) - >>> map(getcount, inventory) - [3, 2, 5, 1] - >>> sorted(inventory, key=getcount) - [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)] + Return a callable object that fetches *item* from its operand using the + operand's :meth:`__getitem__` method. If multiple items are specified, + returns a tuple of lookup values. Equivalent to:: + + def itemgetter(*items): + if len(items) == 1: + item = items[0] + def g(obj): + return obj[item] + else: + def g(obj): + return tuple(obj[item] for item in items) + return g + + The items can be any type accepted by the operand's :meth:`__getitem__` + method. Dictionaries accept any hashable value. Lists, tuples, and + strings accept an index or a slice: + + >>> itemgetter(1)('ABCDEFG') + 'B' + >>> itemgetter(1,3,5)('ABCDEFG') + ('B', 'D', 'F') + >>> itemgetter(slice(2,None))('ABCDEFG') + 'CDEFG' + + + Example of using :func:`itemgetter` to retrieve specific fields from a + tuple record: + + >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)] + >>> getcount = itemgetter(1) + >>> map(getcount, inventory) + [3, 2, 5, 1] + >>> sorted(inventory, key=getcount) + [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)] + + +.. function:: methodcaller(name[, args...]) + + Return a callable object that calls the method *name* on its operand. If + additional arguments and/or keyword arguments are given, they will be given + to the method as well. After ``f = methodcaller('name')``, the call ``f(b)`` + returns ``b.name()``. After ``f = methodcaller('name', 'foo', bar=1)``, the + call ``f(b)`` returns ``b.name('foo', bar=1)``. .. _operator-map: @@ -492,11 +495,7 @@ +-----------------------+-------------------------+---------------------------------+ | Containment Test | ``obj in seq`` | ``contains(seq, obj)`` | +-----------------------+-------------------------+---------------------------------+ -| Division | ``a / b`` | ``div(a, b)`` (without | -| | | ``__future__.division``) | -+-----------------------+-------------------------+---------------------------------+ -| Division | ``a / b`` | ``truediv(a, b)`` (with | -| | | ``__future__.division``) | +| Division | ``a / b`` | ``truediv(a, b)`` | +-----------------------+-------------------------+---------------------------------+ | Division | ``a // b`` | ``floordiv(a, b)`` | +-----------------------+-------------------------+---------------------------------+ Modified: python/branches/py3k-ctypes-pep3118/Doc/library/optparse.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/optparse.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/optparse.rst Wed Apr 30 15:57:13 2008 @@ -1629,7 +1629,7 @@ value.append(arg) del rargs[0] - setattr(parser.values, option.dest, value) + setattr(parser.values, option.dest, value) [...] parser.add_option("-c", "--callback", Modified: python/branches/py3k-ctypes-pep3118/Doc/library/os.path.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/os.path.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/os.path.rst Wed Apr 30 15:57:13 2008 @@ -130,7 +130,9 @@ .. function:: isabs(path) - Return ``True`` if *path* is an absolute pathname (begins with a slash). + Return ``True`` if *path* is an absolute pathname. On Unix, that means it + begins with a slash, on Windows that it begins with a (back)slash after chopping + off a potential drive letter. .. function:: isfile(path) @@ -286,5 +288,5 @@ .. data:: supports_unicode_filenames True if arbitrary Unicode strings can be used as file names (within limitations - imposed by the file system), and if :func:`os.listdir` returns Unicode strings - for a Unicode argument. + imposed by the file system), and if :func:`os.listdir` returns strings that + contain characters that cannot be represented by ASCII. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/os.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/os.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/os.rst Wed Apr 30 15:57:13 2008 @@ -701,13 +701,13 @@ .. function:: getcwd() - Return a string representing the current working directory. Availability: - Macintosh, Unix, Windows. + Return a bytestring representing the current working directory. + Availability: Macintosh, Unix, Windows. .. function:: getcwdu() - Return a Unicode object representing the current working directory. + Return a string representing the current working directory. Availability: Macintosh, Unix, Windows. @@ -1254,7 +1254,8 @@ For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note that these all end in "e"), the *env* parameter must be a mapping which is - used to define the environment variables for the new process; the :func:`execl`, + used to define the environment variables for the new process (these are used + instead of the current process' environment); the functions :func:`execl`, :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to inherit the environment of the current process. Availability: Macintosh, Unix, Windows. @@ -1387,7 +1388,8 @@ .. function:: fork() Fork a child process. Return ``0`` in the child and the child's process id in the - parent. Availability: Macintosh, Unix. + parent. If an error occurs :exc:`OSError` is raised. + Availability: Macintosh, Unix. .. function:: forkpty() @@ -1396,7 +1398,8 @@ terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the new child's process id in the parent, and *fd* is the file descriptor of the master end of the pseudo-terminal. For a more portable approach, use the - :mod:`pty` module. Availability: Macintosh, some flavors of Unix. + :mod:`pty` module. If an error occurs :exc:`OSError` is raised. + Availability: Macintosh, some flavors of Unix. .. function:: kill(pid, sig) @@ -1482,7 +1485,8 @@ For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe` (note that these all end in "e"), the *env* parameter must be a mapping - which is used to define the environment variables for the new process; the + which is used to define the environment variables for the new process (they are + used instead of the current process' environment); the functions :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause the new process to inherit the environment of the current process. @@ -1584,7 +1588,7 @@ user time, children's system time, and elapsed real time since a fixed point in the past, in that order. See the Unix manual page :manpage:`times(2)` or the corresponding Windows Platform API documentation. Availability: Macintosh, Unix, - Windows. + Windows. On Windows, only the first two items are filled, the others are zero. .. function:: wait() Modified: python/branches/py3k-ctypes-pep3118/Doc/library/othergui.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/othergui.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/othergui.rst Wed Apr 30 15:57:13 2008 @@ -36,14 +36,12 @@ `PyGTK `_ is a set of bindings for the `GTK `_ widget set. It - provides an object oriented interface that is slightly higher level than the C - one. It comes with many more widgets than Tkinter provides, and - has good Python-specific reference documentation. There are also `bindings - `_ to `GNOME `_. - One well known PyGTK application is - `PythonCAD `_. An - online `tutorial `_ is - available. + provides an object oriented interface that is slightly higher level than + the C one. It comes with many more widgets than Tkinter provides, and has + good Python-specific reference documentation. There are also bindings to + `GNOME `_. One well known PyGTK application is + `PythonCAD `_. An online `tutorial + `_ is available. `PyQt `_ PyQt is a :program:`sip`\ -wrapped binding to the Qt toolkit. Qt is an Modified: python/branches/py3k-ctypes-pep3118/Doc/library/pdb.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/pdb.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/pdb.rst Wed Apr 30 15:57:13 2008 @@ -103,9 +103,12 @@ being debugged (e.g. when an assertion fails). -.. function:: post_mortem(traceback) +.. function:: post_mortem([traceback]) - Enter post-mortem debugging of the given *traceback* object. + Enter post-mortem debugging of the given *traceback* object. If no + *traceback* is given, it uses the one of the exception that is currently + being handled (an exception must be being handled if the default is to be + used). .. function:: pm() Modified: python/branches/py3k-ctypes-pep3118/Doc/library/pickle.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/pickle.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/pickle.rst Wed Apr 30 15:57:13 2008 @@ -110,7 +110,7 @@ :mod:`pickle`'s representation) is that for debugging or recovery purposes it is possible for a human to read the pickled file with a standard text editor. -There are currently 3 different protocols which can be used for pickling. +There are currently 4 different protocols which can be used for pickling. * Protocol version 0 is the original ASCII protocol and is backwards compatible with earlier versions of Python. @@ -121,11 +121,14 @@ * Protocol version 2 was introduced in Python 2.3. It provides much more efficient pickling of :term:`new-style class`\es. +* Protocol version 3 was added in Python 3.0. It has explicit support for + bytes and cannot be unpickled by Python 2.x pickle modules. + Refer to :pep:`307` for more information. -If a *protocol* is not specified, protocol 0 is used. If *protocol* is specified -as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol version -available will be used. +If a *protocol* is not specified, protocol 3 is used. If *protocol* is +specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest +protocol version available will be used. A binary format, which is slightly more efficient, can be chosen by specifying a *protocol* version >= 1. @@ -164,9 +167,9 @@ Write a pickled representation of *obj* to the open file object *file*. This is equivalent to ``Pickler(file, protocol).dump(obj)``. - If the *protocol* parameter is omitted, protocol 0 is used. If *protocol* is - specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol - version will be used. + If the *protocol* parameter is omitted, protocol 3 is used. If *protocol* is + specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest + protocol version will be used. *file* must have a :meth:`write` method that accepts a single string argument. It can thus be a file object opened for writing, a :mod:`StringIO` object, or @@ -191,18 +194,18 @@ .. function:: dumps(obj[, protocol]) - Return the pickled representation of the object as a string, instead of writing - it to a file. + Return the pickled representation of the object as a :class:`bytes` + object, instead of writing it to a file. - If the *protocol* parameter is omitted, protocol 0 is used. If *protocol* is - specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol - version will be used. + If the *protocol* parameter is omitted, protocol 3 is used. If *protocol* + is specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest + protocol version will be used. -.. function:: loads(string) +.. function:: loads(bytes_object) - Read a pickled object hierarchy from a string. Characters in the string past - the pickled object's representation are ignored. + Read a pickled object hierarchy from a :class:`bytes` object. + Bytes past the pickled object's representation are ignored. The :mod:`pickle` module also defines three exceptions: @@ -234,7 +237,7 @@ This takes a file-like object to which it will write a pickle data stream. - If the *protocol* parameter is omitted, protocol 0 is used. If *protocol* is + If the *protocol* parameter is omitted, protocol 3 is used. If *protocol* is specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol version will be used. @@ -242,34 +245,34 @@ It can thus be an open file object, a :mod:`StringIO` object, or any other custom object that meets this interface. -:class:`Pickler` objects define one (or two) public methods: + :class:`Pickler` objects define one (or two) public methods: -.. method:: Pickler.dump(obj) + .. method:: dump(obj) - Write a pickled representation of *obj* to the open file object given in the - constructor. Either the binary or ASCII format will be used, depending on the - value of the *protocol* argument passed to the constructor. + Write a pickled representation of *obj* to the open file object given in the + constructor. Either the binary or ASCII format will be used, depending on the + value of the *protocol* argument passed to the constructor. -.. method:: Pickler.clear_memo() + .. method:: clear_memo() - Clears the pickler's "memo". The memo is the data structure that remembers - which objects the pickler has already seen, so that shared or recursive objects - pickled by reference and not by value. This method is useful when re-using - picklers. + Clears the pickler's "memo". The memo is the data structure that remembers + which objects the pickler has already seen, so that shared or recursive objects + pickled by reference and not by value. This method is useful when re-using + picklers. - .. note:: + .. note:: - Prior to Python 2.3, :meth:`clear_memo` was only available on the picklers - created by :mod:`cPickle`. In the :mod:`pickle` module, picklers have an - instance variable called :attr:`memo` which is a Python dictionary. So to clear - the memo for a :mod:`pickle` module pickler, you could do the following:: + Prior to Python 2.3, :meth:`clear_memo` was only available on the picklers + created by :mod:`cPickle`. In the :mod:`pickle` module, picklers have an + instance variable called :attr:`memo` which is a Python dictionary. So to clear + the memo for a :mod:`pickle` module pickler, you could do the following:: - mypickler.memo.clear() + mypickler.memo.clear() - Code that does not need to support older versions of Python should simply use - :meth:`clear_memo`. + Code that does not need to support older versions of Python should simply use + :meth:`clear_memo`. It is possible to make multiple calls to the :meth:`dump` method of the same :class:`Pickler` instance. These must then be matched to the same number of @@ -293,29 +296,30 @@ reading, a :mod:`StringIO` object, or any other custom object that meets this interface. -:class:`Unpickler` objects have one (or two) public methods: + :class:`Unpickler` objects have one (or two) public methods: -.. method:: Unpickler.load() + .. method:: load() - Read a pickled object representation from the open file object given in the - constructor, and return the reconstituted object hierarchy specified therein. + Read a pickled object representation from the open file object given in + the constructor, and return the reconstituted object hierarchy specified + therein. + + This method automatically determines whether the data stream was written + in binary mode or not. - This method automatically determines whether the data stream was written in - binary mode or not. + .. method:: noload() -.. method:: Unpickler.noload() + This is just like :meth:`load` except that it doesn't actually create any + objects. This is useful primarily for finding what's called "persistent + ids" that may be referenced in a pickle data stream. See section + :ref:`pickle-protocol` below for more details. - This is just like :meth:`load` except that it doesn't actually create any - objects. This is useful primarily for finding what's called "persistent ids" - that may be referenced in a pickle data stream. See section - :ref:`pickle-protocol` below for more details. - - **Note:** the :meth:`noload` method is currently only available on - :class:`Unpickler` objects created with the :mod:`cPickle` module. - :mod:`pickle` module :class:`Unpickler`\ s do not have the :meth:`noload` - method. + **Note:** the :meth:`noload` method is currently only available on + :class:`Unpickler` objects created with the :mod:`cPickle` module. + :mod:`pickle` module :class:`Unpickler`\ s do not have the :meth:`noload` + method. What can be pickled and unpickled? @@ -327,7 +331,7 @@ * integers, floating point numbers, complex numbers -* normal and Unicode strings +* strings, bytes, bytearrays * tuples, lists, sets, and dictionaries containing only picklable objects @@ -400,6 +404,7 @@ single: __init__() (instance constructor) .. XXX is __getinitargs__ only used with old-style classes? +.. XXX update w.r.t Py3k's classes When a pickled class instance is unpickled, its :meth:`__init__` method is normally *not* invoked. If it is desirable that the :meth:`__init__` method be @@ -444,13 +449,18 @@ .. warning:: - For :term:`new-style class`\es, if :meth:`__getstate__` returns a false - value, the :meth:`__setstate__` method will not be called. + If :meth:`__getstate__` returns a false value, the :meth:`__setstate__` + method will not be called. Pickling and unpickling extension types ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +.. index:: + single: __reduce__() (pickle protocol) + single: __reduce_ex__() (pickle protocol) + single: __safe_for_unpickling__ (pickle protocol) + When the :class:`Pickler` encounters an object of a type it knows nothing about --- such as an extension type --- it looks in two places for a hint of how to pickle it. One alternative is for the object to implement a :meth:`__reduce__` @@ -463,8 +473,9 @@ namespace to determine the object's module. When a tuple is returned, it must be between two and five elements long. -Optional elements can either be omitted, or ``None`` can be provided as their -value. The semantics of each element are: +Optional elements can either be omitted, or ``None`` can be provided as their +value. The contents of this tuple are pickled as normal and used to +reconstruct the object at unpickling time. The semantics of each element are: * A callable object that will be called to create the initial version of the object. The next element of the tuple will provide arguments for this callable, @@ -526,6 +537,10 @@ Pickling and unpickling external objects ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +.. index:: + single: persistent_id (pickle protocol) + single: persistent_load (pickle protocol) + For the benefit of object persistence, the :mod:`pickle` module supports the notion of a reference to an object outside the pickled data stream. Such objects are referenced by a "persistent id", which is just an arbitrary string @@ -615,6 +630,10 @@ Subclassing Unpicklers ---------------------- +.. index:: + single: load_global() (pickle protocol) + single: find_global() (pickle protocol) + By default, unpickling will import any class that it finds in the pickle data. You can control exactly what gets unpickled and what gets called by customizing your unpickler. Unfortunately, exactly how you do this is different depending @@ -659,7 +678,7 @@ import pickle data1 = {'a': [1, 2.0, 3, 4+6j], - 'b': ('string', u'Unicode string'), + 'b': ("string", "string using Unicode features \u0394"), 'c': None} selfref_list = [1, 2, 3] @@ -667,8 +686,8 @@ output = open('data.pkl', 'wb') - # Pickle dictionary using protocol 0. - pickle.dump(data1, output) + # Pickle dictionary using protocol 2. + pickle.dump(data1, output, 2) # Pickle the list using the highest protocol available. pickle.dump(selfref_list, output, -1) Modified: python/branches/py3k-ctypes-pep3118/Doc/library/pickletools.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/pickletools.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/pickletools.rst Wed Apr 30 15:57:13 2008 @@ -33,3 +33,9 @@ the opcode's argument; *pos* is the position at which this opcode is located. *pickle* can be a string or a file-like object. +.. function:: optimize(picklestring) + + Returns a new equivalent pickle string after eliminating unused ``PUT`` + opcodes. The optimized pickle is shorter, takes less transmission time, + requires less storage space, and unpickles more efficiently. + Modified: python/branches/py3k-ctypes-pep3118/Doc/library/pkgutil.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/pkgutil.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/pkgutil.rst Wed Apr 30 15:57:13 2008 @@ -6,7 +6,7 @@ :synopsis: Utilities to support extension of packages. -This module provides a single function: +This module provides functions to manipulate packages: .. function:: extend_path(path, name) @@ -34,8 +34,28 @@ returned. Items are only appended to the copy at the end. It is assumed that ``sys.path`` is a sequence. Items of ``sys.path`` that are - not (Unicode or 8-bit) strings referring to existing directories are ignored. - Unicode items on ``sys.path`` that cause errors when used as filenames may cause - this function to raise an exception (in line with :func:`os.path.isdir` - behavior). + not strings referring to existing directories are ignored. Unicode items on + ``sys.path`` that cause errors when used as filenames may cause this function + to raise an exception (in line with :func:`os.path.isdir` behavior). +.. function:: get_data(package, resource) + + Get a resource from a package. + + This is a wrapper round the PEP 302 loader :func:`get_data` API. The package + argument should be the name of a package, in standard module format + (foo.bar). The resource argument should be in the form of a relative + filename, using ``/`` as the path separator. The parent directory name + ``..`` is not allowed, and nor is a rooted name (starting with a ``/``). + + The function returns a binary string, which is the contents of the + specified resource. + + For packages located in the filesystem, which have already been imported, + this is the rough equivalent of:: + + d = os.path.dirname(sys.modules[package].__file__) + data = open(os.path.join(d, resource), 'rb').read() + + If the package cannot be located or loaded, or it uses a PEP 302 loader + which does not support :func:`get_data`, then None is returned. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/platform.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/platform.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/platform.rst Wed Apr 30 15:57:13 2008 @@ -187,8 +187,10 @@ .. note:: - This function only works if Mark Hammond's :mod:`win32all` package is installed - and (obviously) only runs on Win32 compatible platforms. + Note: this function works best with Mark Hammond's + :mod:`win32all` package installed, but also on Python 2.3 and + later (support for this was added in Python 2.6). It obviously + only runs on Win32 compatible platforms. Win95/98 specific @@ -222,13 +224,31 @@ -------------- -.. function:: dist(distname='', version='', id='', supported_dists=('SuSE','debian','redhat','mandrake')) +.. function:: dist(distname='', version='', id='', supported_dists=('SuSE','debian','redhat','mandrake',...)) Tries to determine the name of the OS distribution name Returns a tuple ``(distname, version, id)`` which defaults to the args given as parameters. -.. XXX Document linux_distribution()? + ``supported_dists`` may be given to define the set of Linux + distributions to look for. It defaults to a list of currently + supported Linux distributions identified by their release file + name. + +.. function:: linux_distribution(distname='', version='', id='', supported_dists=('SuSE','debian','redhat','mandrake',...), full_distribution_name=1) + + Tries to determine the name of the Linux OS distribution name. + + ``supported_dists`` may be given to define the set of Linux + distributions to look for. It defaults to a list of currently + supported Linux distributions identified by their release file + name. + + If ``full_distribution_name`` is true (default), the full + distribution read from the OS is returned. Otherwise the short name + taken from ``supported_dists`` is used. + Returns a tuple ``(distname,version,id)`` which defaults to the + args given as parameters. .. function:: libc_ver(executable=sys.executable, lib='', version='', chunksize=2048) @@ -237,7 +257,7 @@ version)`` which default to the given parameters in case the lookup fails. Note that this function has intimate knowledge of how different libc versions - add symbols to the executable is probably only useable for executables compiled + add symbols to the executable is probably only usable for executables compiled using :program:`gcc`. The file is read and scanned in chunks of *chunksize* bytes. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/plistlib.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/plistlib.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/plistlib.rst Wed Apr 30 15:57:13 2008 @@ -7,10 +7,6 @@ .. sectionauthor:: Georg Brandl .. (harvested from docstrings in the original file) -.. versionchanged:: 2.6 - This module was previously only available in the Mac-specific library, it is - now available for all platforms. - .. index:: pair: plist; file single: property list Modified: python/branches/py3k-ctypes-pep3118/Doc/library/pprint.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/pprint.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/pprint.rst Wed Apr 30 15:57:13 2008 @@ -22,9 +22,6 @@ Dictionaries are sorted by key before the display is computed. -.. versionchanged:: 2.6 - Added support for :class:`set` and :class:`frozenset`. - The :mod:`pprint` module defines one class: .. First the implementation class: @@ -46,14 +43,14 @@ the depth of the objects being formatted. The desired output width is constrained using the *width* parameter; the default is 80 characters. If a structure cannot be formatted within the constrained width, a best effort will - be made. :: + be made. >>> import pprint >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni'] >>> stuff.insert(0, stuff[:]) >>> pp = pprint.PrettyPrinter(indent=4) >>> pp.pprint(stuff) - [ ['spam', 'eggs', 'lumberjack', 'knights', 'ni'], + [ [ 'spam', 'eggs', 'lumberjack', 'knights', 'ni'], 'spam', 'eggs', 'lumberjack', @@ -84,19 +81,18 @@ in the interactive interpreter instead of the :func:`print` function for inspecting values (you can even reassign ``print = pprint.pprint`` for use within a scope). *indent*, *width* and *depth* will be passed to the - :class:`PrettyPrinter` constructor as formatting parameters. :: + :class:`PrettyPrinter` constructor as formatting parameters. >>> import pprint >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni'] >>> stuff.insert(0, stuff) >>> pprint.pprint(stuff) - [, - '', - '/usr/local/lib/python1.5', - '/usr/local/lib/python1.5/test', - '/usr/local/lib/python1.5/sunos5', - '/usr/local/lib/python1.5/sharedmodules', - '/usr/local/lib/python1.5/tkinter'] + [, + 'spam', + 'eggs', + 'lumberjack', + 'knights', + 'ni'] .. function:: isreadable(object) @@ -105,7 +101,7 @@ Determine if the formatted representation of *object* is "readable," or can be used to reconstruct the value using :func:`eval`. This always returns ``False`` - for recursive objects. :: + for recursive objects. >>> pprint.isreadable(stuff) False @@ -115,8 +111,8 @@ Determine if *object* requires a recursive representation. -One more support function is also defined: +One more support function is also defined: .. function:: saferepr(object) @@ -125,12 +121,8 @@ recursive reference will be represented as ````. The representation is not otherwise formatted. -:: - >>> pprint.saferepr(stuff) - "[, '', '/usr/local/lib/python1.5', '/usr/loca - l/lib/python1.5/test', '/usr/local/lib/python1.5/sunos5', '/usr/local/lib/python - 1.5/sharedmodules', '/usr/local/lib/python1.5/tkinter']" + "[, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']" .. _prettyprinter-objects: Modified: python/branches/py3k-ctypes-pep3118/Doc/library/profile.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/profile.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/profile.rst Wed Apr 30 15:57:13 2008 @@ -32,15 +32,6 @@ WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -The profiler was written after only programming in Python for 3 weeks. As a -result, it is probably clumsy code, but I don't know for sure yet 'cause I'm a -beginner :-). I did work hard to make the code run fast, so that profiling -would be a reasonable thing to do. I tried not to repeat code fragments, but -I'm sure I did some stuff in really awkward ways at times. Please send -suggestions for improvements to: jar at netscape.com. I won't promise *any* -support. ...but I'd appreciate the feedback. - - .. _profiler-introduction: Introduction to the profilers @@ -50,69 +41,38 @@ single: deterministic profiling single: profiling, deterministic -A :dfn:`profiler` is a program that describes the run time performance of a -program, providing a variety of statistics. This documentation describes the -profiler functionality provided in the modules :mod:`profile` and :mod:`pstats`. -This profiler provides :dfn:`deterministic profiling` of any Python programs. -It also provides a series of report generation tools to allow users to rapidly +A :dfn:`profiler` is a program that describes the run time performance +of a program, providing a variety of statistics. This documentation +describes the profiler functionality provided in the modules +:mod:`cProfile`, :mod:`profile` and :mod:`pstats`. This profiler +provides :dfn:`deterministic profiling` of Python programs. It also +provides a series of report generation tools to allow users to rapidly examine the results of a profile operation. The Python standard library provides two different profilers: -#. :mod:`profile`, a pure Python module, described in the sequel. Copyright ?? - 1994, by InfoSeek Corporation. - -#. :mod:`cProfile`, a module written in C, with a reasonable overhead that makes - it suitable for profiling long-running programs. Based on :mod:`lsprof`, - contributed by Brett Rosen and Ted Czotter. +#. :mod:`cProfile` is recommended for most users; it's a C extension + with reasonable overhead + that makes it suitable for profiling long-running programs. + Based on :mod:`lsprof`, + contributed by Brett Rosen and Ted Czotter. + +#. :mod:`profile`, a pure Python module whose interface is imitated by + :mod:`cProfile`. Adds significant overhead to profiled programs. + If you're trying to extend + the profiler in some way, the task might be easier with this module. + Copyright ?? 1994, by InfoSeek Corporation. The :mod:`profile` and :mod:`cProfile` modules export the same interface, so -they are mostly interchangeables; :mod:`cProfile` has a much lower overhead but -is not so far as well-tested and might not be available on all systems. +they are mostly interchangeable; :mod:`cProfile` has a much lower overhead but +is newer and might not be available on all systems. :mod:`cProfile` is really a compatibility layer on top of the internal +<<<<<<< .working :mod:`_lsprof` module. - -.. \section{How Is This Profiler Different From The Old Profiler?} - \nodename{Profiler Changes} - - (This section is of historical importance only; the old profiler - discussed here was last seen in Python 1.1.) - - The big changes from old profiling module are that you get more - information, and you pay less CPU time. It's not a trade-off, it's a - trade-up. - - To be specific: - - \begin{description} - - \item[Bugs removed:] - Local stack frame is no longer molested, execution time is now charged - to correct functions. - - \item[Accuracy increased:] - Profiler execution time is no longer charged to user's code, - calibration for platform is supported, file reads are not done \emph{by} - profiler \emph{during} profiling (and charged to user's code!). - - \item[Speed increased:] - Overhead CPU cost was reduced by more than a factor of two (perhaps a - factor of five), lightweight profiler module is all that must be - loaded, and the report generating module (\module{pstats}) is not needed - during profiling. - - \item[Recursive functions support:] - Cumulative times in recursive functions are correctly calculated; - recursive entries are counted. - - \item[Large growth in report generating UI:] - Distinct profiles runs can be added together forming a comprehensive - report; functions that import statistics take arbitrary lists of - files; sorting criteria is now based on keywords (instead of 4 integer - options); reports shows what functions were profiled as well as what - profile file was referenced; output format has been improved. - - \end{description} +======= +:mod:`_lsprof` module. The :mod:`hotshot` module is reserved for specialized +usage. +>>>>>>> .merge-right.r62379 .. _profile-instant: @@ -513,7 +473,7 @@ non-parenthesized number repeats the cumulative time spent in the function at the right. - * With :mod:`cProfile`, each caller is preceeded by three numbers: the number of + * With :mod:`cProfile`, each caller is preceded by three numbers: the number of times this specific call was made, and the total and cumulative times spent in the current function while it was invoked by this specific caller. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/py_compile.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/py_compile.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/py_compile.rst Wed Apr 30 15:57:13 2008 @@ -42,7 +42,8 @@ structure to locate source files; it only compiles files named explicitly. When this module is run as a script, the :func:`main` is used to compile all the -files named on the command line. +files named on the command line. The exit status is nonzero if one of the files +could not be compiled. .. seealso:: Modified: python/branches/py3k-ctypes-pep3118/Doc/library/pyexpat.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/pyexpat.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/pyexpat.rst Wed Apr 30 15:57:13 2008 @@ -62,7 +62,7 @@ must be a string naming the encoding used by the XML data. Expat doesn't support as many encodings as Python does, and its repertoire of encodings can't be extended; it supports UTF-8, UTF-16, ISO-8859-1 (Latin1), and ASCII. If - *encoding* is given it will override the implicit or explicit encoding of the + *encoding* [1]_ is given it will override the implicit or explicit encoding of the document. Expat can optionally do XML namespace processing for you, enabled by providing a @@ -182,9 +182,6 @@ to this attribute. When the size is changed, the buffer will be flushed. - .. versionchanged:: 2.6 - The buffer size can now be changed. - .. attribute:: xmlparser.buffer_text @@ -848,3 +845,11 @@ .. data:: XML_ERROR_SUSPEND_PE :noindex: + +.. rubric:: Footnotes + +.. [#] The encoding string included in XML output should conform to the + appropriate standards. For example, "UTF-8" is valid, but "UTF8" is + not. See http://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl + and http://www.iana.org/assignments/character-sets . + Modified: python/branches/py3k-ctypes-pep3118/Doc/library/queue.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/queue.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/queue.rst Wed Apr 30 15:57:13 2008 @@ -37,8 +37,6 @@ block once this size has been reached, until queue items are consumed. If *maxsize* is less than or equal to zero, the queue size is infinite. - .. versionadded:: 2.6 - .. class:: PriorityQueue(maxsize) @@ -51,8 +49,6 @@ one returned by ``sorted(list(entries))[0]``). A typical pattern for entries is a tuple in the form: ``(priority_number, data)``. - .. versionadded:: 2.6 - .. exception:: Empty @@ -71,7 +67,7 @@ Queue Objects ------------- -Queue objects (:class:``Queue``, :class:``LifoQueue``, or :class:``PriorityQueue`` +Queue objects (:class:`Queue`, :class:`LifoQueue`, or :class:`PriorityQueue`) provide the public methods described below. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/random.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/random.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/random.rst Wed Apr 30 15:57:13 2008 @@ -68,6 +68,17 @@ the time :func:`setstate` was called. +.. function:: jumpahead(n) + + Change the internal state to one different from and likely far away from the + current state. *n* is a non-negative integer which is used to scramble the + current state vector. This is most useful in multi-threaded programs, in + conjunction with multiple instances of the :class:`Random` class: + :meth:`setstate` or :meth:`seed` can be used to force all instances into the + same internal state, and then :meth:`jumpahead` can be used to force the + instances' states far apart. + + .. function:: getrandbits(k) Returns a python integer with *k* random bits. This method is supplied with @@ -143,6 +154,14 @@ Return a random floating point number *N* such that ``a <= N < b``. +.. function:: triangular(low, high, mode) + + Return a random floating point number *N* such that ``low <= N < high`` and + with the specified *mode* between those bounds. The *low* and *high* bounds + default to zero and one. The *mode* argument defaults to the midpoint + between the bounds, giving a symmetric distribution. + + .. function:: betavariate(alpha, beta) Beta distribution. Conditions on the parameters are ``alpha > 0`` and ``beta > Deleted: python/branches/py3k-ctypes-pep3118/Doc/library/rational.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/rational.rst Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,75 +0,0 @@ - -:mod:`rational` --- Rational numbers -==================================== - -.. module:: rational - :synopsis: Rational numbers. -.. moduleauthor:: Jeffrey Yasskin -.. sectionauthor:: Jeffrey Yasskin -.. versionadded:: 2.6 - - -The :mod:`rational` module defines an immutable, infinite-precision -Rational number class. - - -.. class:: Rational(numerator=0, denominator=1) - Rational(other_rational) - Rational(string) - - The first version requires that *numerator* and *denominator* are - instances of :class:`numbers.Integral` and returns a new - ``Rational`` representing ``numerator/denominator``. If - *denominator* is :const:`0`, raises a :exc:`ZeroDivisionError`. The - second version requires that *other_rational* is an instance of - :class:`numbers.Rational` and returns an instance of - :class:`Rational` with the same value. The third version expects a - string of the form ``[-+]?[0-9]+(/[0-9]+)?``, optionally surrounded - by spaces. - - Implements all of the methods and operations from - :class:`numbers.Rational` and is immutable and hashable. - - -.. method:: Rational.from_float(flt) - - This classmethod constructs a :class:`Rational` representing the - exact value of *flt*, which must be a :class:`float`. Beware that - ``Rational.from_float(0.3)`` is not the same value as ``Rational(3, - 10)`` - - -.. method:: Rational.from_decimal(dec) - - This classmethod constructs a :class:`Rational` representing the - exact value of *dec*, which must be a - :class:`decimal.Decimal`. - - -.. method:: Rational.__floor__() - - Returns the greatest :class:`int` ``<= self``. Will be accessible - through :func:`math.floor` in Py3k. - - -.. method:: Rational.__ceil__() - - Returns the least :class:`int` ``>= self``. Will be accessible - through :func:`math.ceil` in Py3k. - - -.. method:: Rational.__round__() - Rational.__round__(ndigits) - - The first version returns the nearest :class:`int` to ``self``, - rounding half to even. The second version rounds ``self`` to the - nearest multiple of ``Rational(1, 10**ndigits)`` (logically, if - ``ndigits`` is negative), again rounding half toward even. Will be - accessible through :func:`round` in Py3k. - - -.. seealso:: - - Module :mod:`numbers` - The abstract base classes making up the numeric tower. - Modified: python/branches/py3k-ctypes-pep3118/Doc/library/re.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/re.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/re.rst Wed Apr 30 15:57:13 2008 @@ -65,8 +65,7 @@ above, or almost any textbook about compiler construction. A brief explanation of the format of regular expressions follows. For further -information and a gentler presentation, consult the Regular Expression HOWTO, -accessible from http://www.python.org/doc/howto/. +information and a gentler presentation, consult the :ref:`regex-howto`. Regular expressions can contain both special and ordinary characters. Most ordinary characters, like ``'A'``, ``'a'``, or ``'0'``, are the simplest regular @@ -265,14 +264,14 @@ ``abc`` or ``a|b`` are allowed, but ``a*`` and ``a{3,4}`` are not. Note that patterns which start with positive lookbehind assertions will never match at the beginning of the string being searched; you will most likely want to use the - :func:`search` function rather than the :func:`match` function:: + :func:`search` function rather than the :func:`match` function: >>> import re >>> m = re.search('(?<=abc)def', 'abcdef') >>> m.group(0) 'def' - This example looks for a word following a hyphen:: + This example looks for a word following a hyphen: >>> m = re.search('(?<=-)\w+', 'spam-egg') >>> m.group(0) @@ -401,11 +400,11 @@ :const:`MULTILINE` mode also immediately following a newline. The "match" operation succeeds only if the pattern matches at the start of the string regardless of mode, or at the starting position given by the optional *pos* -argument regardless of whether a newline precedes it. :: +argument regardless of whether a newline precedes it. - >>> re.match("c", "abcdef") # No match - >>> re.search("c", "abcdef") - <_sre.SRE_Match object at 0x827e9c0> # Match + >>> re.match("c", "abcdef") # No match + >>> re.search("c", "abcdef") # Match + <_sre.SRE_Match object at ...> .. _contents-of-module-re: @@ -531,8 +530,7 @@ used in *pattern*, then the text of all groups in the pattern are also returned as part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit* splits occur, and the remainder of the string is returned as the final element - of the list. (Incompatibility note: in the original Python 1.5 release, - *maxsplit* was ignored. This has been fixed in later releases.) :: + of the list. :: >>> re.split('\W+', 'Words, words, words.') ['Words', 'words', 'words', ''] @@ -541,14 +539,26 @@ >>> re.split('\W+', 'Words, words, words.', 1) ['Words', 'words, words.'] + If there are capturing groups in the separator and it matches at the start of + the string, the result will start with an empty string. The same holds for + the end of the string: + + >>> re.split('(\W+)', '...words, words...') + ['', '...', 'words', ', ', 'words', '...', ''] + + That way, separator components are always found at the same relative + indices within the result list (e.g., if there's one capturing group + in the separator, the 0th, the 2nd and so forth). + Note that *split* will never split a string on an empty pattern match. - For example :: + For example: >>> re.split('x*', 'foo') ['foo'] >>> re.split("(?m)^$", "foo\n\nbar\n") ['foo\n\nbar\n'] + .. function:: findall(pattern, string[, flags]) Return all non-overlapping matches of *pattern* in *string*, as a list of @@ -574,7 +584,7 @@ converted to a single newline character, ``\r`` is converted to a linefeed, and so forth. Unknown escapes such as ``\j`` are left alone. Backreferences, such as ``\6``, are replaced with the substring matched by group 6 in the pattern. - For example:: + For example: >>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):', ... r'static PyObject*\npy_\1(void)\n{', @@ -583,7 +593,7 @@ If *repl* is a function, it is called for every non-overlapping occurrence of *pattern*. The function takes a single match object argument, and returns the - replacement string. For example:: + replacement string. For example: >>> def dashrepl(matchobj): ... if matchobj.group(0) == '-': return ' ' @@ -664,12 +674,12 @@ from *pos* to ``endpos - 1`` will be searched for a match. If *endpos* is less than *pos*, no match will be found, otherwise, if *rx* is a compiled regular expression object, ``rx.match(string, 0, 50)`` is equivalent to - ``rx.match(string[:50], 0)``. :: + ``rx.match(string[:50], 0)``. >>> pattern = re.compile("o") >>> pattern.match("dog") # No match as "o" is not at the start of "dog." >>> pattern.match("dog", 1) # Match as "o" is the 2nd character of "dog". - <_sre.SRE_Match object at 0x827eb10> + <_sre.SRE_Match object at ...> .. method:: RegexObject.search(string[, pos[, endpos]]) @@ -757,24 +767,24 @@ pattern, an :exc:`IndexError` exception is raised. If a group is contained in a part of the pattern that did not match, the corresponding result is ``None``. If a group is contained in a part of the pattern that matched multiple times, - the last match is returned. :: + the last match is returned. >>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist") - >>> m.group(0) - 'Isaac Newton' # The entire match - >>> m.group(1) - 'Isaac' # The first parenthesized subgroup. - >>> m.group(2) - 'Newton' # The second parenthesized subgroup. - >>> m.group(1, 2) - ('Isaac', 'Newton') # Multiple arguments give us a tuple. + >>> m.group(0) # The entire match + 'Isaac Newton' + >>> m.group(1) # The first parenthesized subgroup. + 'Isaac' + >>> m.group(2) # The second parenthesized subgroup. + 'Newton' + >>> m.group(1, 2) # Multiple arguments give us a tuple. + ('Isaac', 'Newton') If the regular expression uses the ``(?P...)`` syntax, the *groupN* arguments may also be strings identifying groups by their group name. If a string argument is not used as a group name in the pattern, an :exc:`IndexError` exception is raised. - A moderately complicated example:: + A moderately complicated example: >>> m = re.match(r"(?P\w+) (?P\w+)", "Malcom Reynolds") >>> m.group('first_name') @@ -782,14 +792,15 @@ >>> m.group('last_name') 'Reynolds' - Named groups can also be referred to by their index:: + Named groups can also be referred to by their index: >>> m.group(1) 'Malcom' >>> m.group(2) 'Reynolds' - If a group matches multiple times, only the last match is accessible:: + If a group matches multiple times, only the last match is accessible: + >>> m = re.match(r"(..)+", "a1b2c3") # Matches 3 times. >>> m.group(1) # Returns only the last match. 'c3' @@ -799,12 +810,9 @@ Return a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The *default* argument is used for groups that - did not participate in the match; it defaults to ``None``. (Incompatibility - note: in the original Python 1.5 release, if the tuple was one element long, a - string would be returned instead. In later versions (from 1.5.1 on), a - singleton tuple is returned in such cases.) + did not participate in the match; it defaults to ``None``. - For example:: + For example: >>> m = re.match(r"(\d+)\.(\d+)", "24.1632") >>> m.groups() @@ -812,20 +820,20 @@ If we make the decimal place and everything after it optional, not all groups might participate in the match. These groups will default to ``None`` unless - the *default* argument is given:: + the *default* argument is given: >>> m = re.match(r"(\d+)\.?(\d+)?", "24") - >>> m.groups() - ('24', None) # Second group defaults to None. - >>> m.groups('0') - ('24', '0') # Now, the second group defaults to '0'. + >>> m.groups() # Second group defaults to None. + ('24', None) + >>> m.groups('0') # Now, the second group defaults to '0'. + ('24', '0') .. method:: MatchObject.groupdict([default]) Return a dictionary containing all the *named* subgroups of the match, keyed by the subgroup name. The *default* argument is used for groups that did not - participate in the match; it defaults to ``None``. For example:: + participate in the match; it defaults to ``None``. For example: >>> m = re.match(r"(?P\w+) (?P\w+)", "Malcom Reynolds") >>> m.groupdict() @@ -848,7 +856,7 @@ ``m.start(0)`` is 1, ``m.end(0)`` is 2, ``m.start(1)`` and ``m.end(1)`` are both 2, and ``m.start(2)`` raises an :exc:`IndexError` exception. - An example that will remove *remove_this* from email addresses:: + An example that will remove *remove_this* from email addresses: >>> email = "tony at tiremove_thisger.net" >>> m = re.search("remove_this", email) @@ -911,7 +919,9 @@ ^^^^^^^^^^^^^^^^^^^ In this example, we'll use the following helper function to display match -objects a little more gracefully:: +objects a little more gracefully: + +.. testcode:: def displaymatch(match): if match is None: @@ -923,28 +933,30 @@ for king, "q" for queen, j for jack, "0" for 10, and "1" through "9" representing the card with that value. -To see if a given string is a valid hand, one could do the following:: +To see if a given string is a valid hand, one could do the following: - >>> valid = re.compile(r"[0-9akqj]{5}$" + >>> valid = re.compile(r"[0-9akqj]{5}$") >>> displaymatch(valid.match("ak05q")) # Valid. - + "" >>> displaymatch(valid.match("ak05e")) # Invalid. >>> displaymatch(valid.match("ak0")) # Invalid. >>> displaymatch(valid.match("727ak")) # Valid. - + "" That last hand, ``"727ak"``, contained a pair, or two of the same valued cards. -To match this with a regular expression, one could use backreferences as such:: +To match this with a regular expression, one could use backreferences as such: >>> pair = re.compile(r".*(.).*\1") >>> displaymatch(pair.match("717ak")) # Pair of 7s. - + "" >>> displaymatch(pair.match("718ak")) # No pairs. >>> displaymatch(pair.match("354aa")) # Pair of aces. - + "" To find out what card the pair consists of, one could use the :func:`group` -method of :class:`MatchObject` in the following manner:: +method of :class:`MatchObject` in the following manner: + +.. doctest:: >>> pair.match("717ak").group(1) '7' @@ -1013,7 +1025,6 @@ recursion, you may encounter a :exc:`RuntimeError` exception with the message ``maximum recursion limit`` exceeded. For example, :: - >>> import re >>> s = 'Begin ' + 1000*'a very long string ' + 'end' >>> re.match('Begin (\w| )*? end', s).end() Traceback (most recent call last): @@ -1035,28 +1046,30 @@ In a nutshell, :func:`match` only attempts to match a pattern at the beginning of a string where :func:`search` will match a pattern anywhere in a string. -For example:: +For example: >>> re.match("o", "dog") # No match as "o" is not the first letter of "dog". >>> re.search("o", "dog") # Match as search() looks everywhere in the string. - <_sre.SRE_Match object at 0x827e9f8> + <_sre.SRE_Match object at ...> .. note:: - The following applies only to regular expression objects like those created - with ``re.compile("pattern")``, not the primitives - ``re.match(pattern, string)`` or ``re.search(pattern, string)``. + The following applies only to regular expression objects like those created + with ``re.compile("pattern")``, not the primitives ``re.match(pattern, + string)`` or ``re.search(pattern, string)``. :func:`match` has an optional second parameter that gives an index in the string -where the search is to start:: +where the search is to start: >>> pattern = re.compile("o") >>> pattern.match("dog") # No match as "o" is not at the start of "dog." + # Equivalent to the above expression as 0 is the default starting index: >>> pattern.match("dog", 0) + # Match as "o" is the 2nd character of "dog" (index 0 is the first): >>> pattern.match("dog", 1) - <_sre.SRE_Match object at 0x827eb10> + <_sre.SRE_Match object at ...> >>> pattern.match("dog", 2) # No match as "o" is not the 3rd character of "dog." @@ -1069,29 +1082,35 @@ creates a phonebook. First, here is the input. Normally it may come from a file, here we are using -triple-quoted string syntax:: +triple-quoted string syntax: >>> input = """Ross McFluff: 834.345.1254 155 Elm Street - - Ronald Heathmore: 892.345.3428 436 Finley Avenue - Frank Burger: 925.541.7625 662 South Dogwood Way - - - Heather Albrecht: 548.326.4584 919 Park Place""" + ... + ... Ronald Heathmore: 892.345.3428 436 Finley Avenue + ... Frank Burger: 925.541.7625 662 South Dogwood Way + ... + ... + ... Heather Albrecht: 548.326.4584 919 Park Place""" The entries are separated by one or more newlines. Now we convert the string -into a list with each nonempty line having its own entry:: +into a list with each nonempty line having its own entry: + +.. doctest:: + :options: +NORMALIZE_WHITESPACE >>> entries = re.split("\n+", input) >>> entries - ['Ross McFluff 834.345.1254 155 Elm Street', - 'Ronald Heathmore 892.345.3428 436 Finley Avenue', - 'Frank Burger 925.541.7625 662 South Dogwood Way', - 'Heather Albrecht 548.326.4584 919 Park Place'] + ['Ross McFluff: 834.345.1254 155 Elm Street', + 'Ronald Heathmore: 892.345.3428 436 Finley Avenue', + 'Frank Burger: 925.541.7625 662 South Dogwood Way', + 'Heather Albrecht: 548.326.4584 919 Park Place'] Finally, split each entry into a list with first name, last name, telephone -number, and address. We use the ``maxsplit`` paramater of :func:`split` -because the address has spaces, our splitting pattern, in it:: +number, and address. We use the ``maxsplit`` parameter of :func:`split` +because the address has spaces, our splitting pattern, in it: + +.. doctest:: + :options: +NORMALIZE_WHITESPACE >>> [re.split(":? ", entry, 3) for entry in entries] [['Ross', 'McFluff', '834.345.1254', '155 Elm Street'], @@ -1100,8 +1119,11 @@ ['Heather', 'Albrecht', '548.326.4584', '919 Park Place']] The ``:?`` pattern matches the colon after the last name, so that it does not -occur in the result list. With a ``maxsplit`` of ``4``, we could seperate the -house number from the street name:: +occur in the result list. With a ``maxsplit`` of ``4``, we could separate the +house number from the street name: + +.. doctest:: + :options: +NORMALIZE_WHITESPACE >>> [re.split(":? ", entry, 4) for entry in entries] [['Ross', 'McFluff', '834.345.1254', '155', 'Elm Street'], @@ -1132,10 +1154,10 @@ Finding all Adverbs ^^^^^^^^^^^^^^^^^^^ -:func:`findall` matches *all* occurences of a pattern, not just the first +:func:`findall` matches *all* occurrences of a pattern, not just the first one as :func:`search` does. For example, if one was a writer and wanted to find all of the adverbs in some text, he or she might use :func:`findall` in -the following manner:: +the following manner: >>> text = "He was carefully disguised but captured quickly by police." >>> re.findall(r"\w+ly", text) @@ -1149,11 +1171,11 @@ text, :func:`finditer` is useful as it provides instances of :class:`MatchObject` instead of strings. Continuing with the previous example, if one was a writer who wanted to find all of the adverbs *and their positions* -in some text, he or she would use :func:`finditer` in the following manner:: +in some text, he or she would use :func:`finditer` in the following manner: >>> text = "He was carefully disguised but captured quickly by police." >>> for m in re.finditer(r"\w+ly", text): - print '%02d-%02d: %s' % (m.start(), m.end(), m.group(0)) + ... print('%02d-%02d: %s' % (m.start(), m.end(), m.group(0))) 07-16: carefully 40-47: quickly @@ -1164,19 +1186,19 @@ Raw string notation (``r"text"``) keeps regular expressions sane. Without it, every backslash (``'\'``) in a regular expression would have to be prefixed with another one to escape it. For example, the two following lines of code are -functionally identical:: +functionally identical: >>> re.match(r"\W(.)\1\W", " ff ") - <_sre.SRE_Match object at 0x8262760> + <_sre.SRE_Match object at ...> >>> re.match("\\W(.)\\1\\W", " ff ") - <_sre.SRE_Match object at 0x82627a0> + <_sre.SRE_Match object at ...> When one wants to match a literal backslash, it must be escaped in the regular expression. With raw string notation, this means ``r"\\"``. Without raw string notation, one must use ``"\\\\"``, making the following lines of code -functionally identical:: +functionally identical: >>> re.match(r"\\", r"\\") - <_sre.SRE_Match object at 0x827eb48> + <_sre.SRE_Match object at ...> >>> re.match("\\\\", r"\\") - <_sre.SRE_Match object at 0x827ec60> + <_sre.SRE_Match object at ...> Modified: python/branches/py3k-ctypes-pep3118/Doc/library/robotparser.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/robotparser.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/robotparser.rst Wed Apr 30 15:57:13 2008 @@ -15,9 +15,8 @@ This module provides a single class, :class:`RobotFileParser`, which answers questions about whether or not a particular user agent can fetch a URL on the -Web site that published the :file:`robots.txt` file. For more details on the -structure of :file:`robots.txt` files, see -http://www.robotstxt.org/wc/norobots.html. +Web site that published the :file:`robots.txt` file. For more details on the +structure of :file:`robots.txt` files, see http://www.robotstxt.org/orig.html. .. class:: RobotFileParser() @@ -26,35 +25,35 @@ single :file:`robots.txt` file. - .. method:: RobotFileParser.set_url(url) + .. method:: set_url(url) Sets the URL referring to a :file:`robots.txt` file. - .. method:: RobotFileParser.read() + .. method:: read() Reads the :file:`robots.txt` URL and feeds it to the parser. - .. method:: RobotFileParser.parse(lines) + .. method:: parse(lines) Parses the lines argument. - .. method:: RobotFileParser.can_fetch(useragent, url) + .. method:: can_fetch(useragent, url) Returns ``True`` if the *useragent* is allowed to fetch the *url* according to the rules contained in the parsed :file:`robots.txt` file. - .. method:: RobotFileParser.mtime() + .. method:: mtime() Returns the time the ``robots.txt`` file was last fetched. This is useful for long-running web spiders that need to check for new ``robots.txt`` files periodically. - .. method:: RobotFileParser.modified() + .. method:: modified() Sets the time the ``robots.txt`` file was last fetched to the current time. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/sched.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/sched.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/sched.rst Wed Apr 30 15:57:13 2008 @@ -25,7 +25,7 @@ Example:: >>> import sched, time - >>> s=sched.scheduler(time.time, time.sleep) + >>> s = sched.scheduler(time.time, time.sleep) >>> def print_time(): print("From print_time", time.time()) ... >>> def print_some_times(): @@ -129,5 +129,3 @@ Read-only attribute returning a list of upcoming events in the order they will be run. Each event is shown as a :term:`named tuple` with the following fields: time, priority, action, argument. - - .. versionadded:: 2.6 Modified: python/branches/py3k-ctypes-pep3118/Doc/library/select.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/select.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/select.rst Wed Apr 30 15:57:13 2008 @@ -7,10 +7,12 @@ This module provides access to the :cfunc:`select` and :cfunc:`poll` functions -available in most operating systems. Note that on Windows, it only works for -sockets; on other operating systems, it also works for other file types (in -particular, on Unix, it works on pipes). It cannot be used on regular files to -determine whether a file has grown since it was last read. +available in most operating systems, :cfunc:`epoll` available on Linux 2.5+ and +:cfunc:`kqueue` available on most BSD. +Note that on Windows, it only works for sockets; on other operating systems, +it also works for other file types (in particular, on Unix, it works on pipes). +It cannot be used on regular files to determine whether a file has grown since +it was last read. The module defines the following: @@ -22,6 +24,14 @@ string, as would be printed by the C function :cfunc:`perror`. +.. function:: epoll([sizehint=-1]) + + (Only supported on Linux 2.5.44 and newer.) Returns an edge polling object, + which can be used as Edge or Level Triggered interface for I/O events; see + section :ref:`epoll-objects` below for the methods supported by epolling + objects. + + .. function:: poll() (Not supported by all operating systems.) Returns a polling object, which @@ -30,6 +40,18 @@ by polling objects. +.. function:: kqueue() + + (Only supported on BSD.) Returns a kernel queue object object; see section + :ref:`kqueue-objects` below for the methods supported by kqueue objects. + + +.. function:: kqueue(ident, filter=KQ_FILTER_READ, flags=KQ_ADD, fflags=0, data=0, udata=0) + + (Only supported on BSD.) Returns a kernel event object object; see section + :ref:`kevent-objects` below for the methods supported by kqueue objects. + + .. function:: select(iwtd, owtd, ewtd[, timeout]) This is a straightforward interface to the Unix :cfunc:`select` system call. @@ -67,6 +89,81 @@ not handle file descriptors that don't originate from WinSock. +.. _epoll-objects: + +Edge and Level Trigger Polling (epoll) Objects +---------------------------------------------- + + http://linux.die.net/man/4/epoll + + *eventmask* + + +-----------------------+-----------------------------------------------+ + | Constant | Meaning | + +=======================+===============================================+ + | :const:`EPOLLIN` | Available for read | + +-----------------------+-----------------------------------------------+ + | :const:`EPOLLOUT` | Available for write | + +-----------------------+-----------------------------------------------+ + | :const:`EPOLLPRI` | Urgent data for read | + +-----------------------+-----------------------------------------------+ + | :const:`EPOLLERR` | Error condition happened on the assoc. fd | + +-----------------------+-----------------------------------------------+ + | :const:`EPOLLHUP` | Hang up happened on the assoc. fd | + +-----------------------+-----------------------------------------------+ + | :const:`EPOLLET` | Set Edge Trigger behavior, the default is | + | | Level Trigger behavior | + +-----------------------+-----------------------------------------------+ + | :const:`EPOLLONESHOT` | Set one-shot behavior. After one event is | + | | pulled out, the fd is internally disabled | + +-----------------------+-----------------------------------------------+ + | :const:`EPOLLRDNORM` | ??? | + +-----------------------+-----------------------------------------------+ + | :const:`EPOLLRDBAND` | ??? | + +-----------------------+-----------------------------------------------+ + | :const:`EPOLLWRNORM` | ??? | + +-----------------------+-----------------------------------------------+ + | :const:`EPOLLWRBAND` | ??? | + +-----------------------+-----------------------------------------------+ + | :const:`EPOLLMSG` | ??? | + +-----------------------+-----------------------------------------------+ + + +.. method:: epoll.close() + + Close the control file descriptor of the epoll object. + + +.. method:: epoll.fileno() + + Return the file descriptor number of the control fd. + + +.. method:: epoll.fromfd(fd) + + Create an epoll object from a given file descriptor. + + +.. method:: epoll.register(fd[, eventmask]) + + Register a fd descriptor with the epoll object. + + +.. method:: epoll.modify(fd, eventmask) + + Modify a register file descriptor. + + +.. method:: epoll.unregister(fd) + + Remove a registered file descriptor from the epoll object. + + +.. method:: epoll.poll([timeout=-1[, maxevents=-1]]) + + Wait for events. timeout in seconds (float) + + .. _poll-objects: Polling Objects @@ -114,6 +211,14 @@ the same effect as registering the descriptor exactly once. +.. method:: poll.modify(fd, eventmask) + + Modifies an already registered fd. This has the same effect as + :meth:`register(fd, eventmask)`. Attempting to modify a file descriptor + that was never registered causes an :exc:`IOError` exception with errno + :const:`ENOENT` to be raised. + + .. method:: poll.unregister(fd) Remove a file descriptor being tracked by a polling object. Just like the @@ -137,3 +242,184 @@ returning. If *timeout* is omitted, negative, or :const:`None`, the call will block until there is an event for this poll object. + +.. _kqueue-objects: + +Kqueue Objects +-------------- + +.. method:: kqueue.close() + + Close the control file descriptor of the kqueue object. + + +.. method:: kqueue.fileno() + + Return the file descriptor number of the control fd. + + +.. method:: epoll.fromfd(fd) + + Create a kqueue object from a given file descriptor. + + +.. method:: control(changelist, max_events=0[, timeout=None]) -> eventlist + + Low level interface to kevent + + - changelist must be an iterable of kevent object or None + - max_events must be 0 or a positive integer + - timeout in seconds (floats possible) + + +.. _kevent-objects: + +Kevent Objects +-------------- + +http://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2 + +.. attribute:: kevent.ident + + Value used to identify the event. The interpretation depends on the filter + but it's usually the file descriptor. In the constructor ident can either + be an int or an object with a fileno() function. kevent stores the integer + internally. + +.. attribute:: kevent.filter + + Name of the kernel filter + + +---------------------------+---------------------------------------------+ + | Constant | Meaning | + +===========================+=============================================+ + | :const:`KQ_FILTER_READ` | Takes a descriptor and returns whenever | + | | there is data available to read | + +---------------------------+---------------------------------------------+ + | :const:`KQ_FILTER_WRITE` | Takes a descriptor and returns whenever | + | | there is data available to read | + +---------------------------+---------------------------------------------+ + | :const:`KQ_FILTER_AIO` | AIO requests | + +---------------------------+---------------------------------------------+ + | :const:`KQ_FILTER_VNODE` | Returns when one or more of the requested | + | | events watched in *fflag* occurs | + +---------------------------+---------------------------------------------+ + | :const:`KQ_FILTER_PROC` | Watch for events on a process id | + +---------------------------+---------------------------------------------+ + | :const:`KQ_FILTER_NETDEV` | Watch for events on a network device | + | | [not available on Mac OS X] | + +---------------------------+---------------------------------------------+ + | :const:`KQ_FILTER_SIGNAL` | Returns whenever the watched signal is | + | | delivered to the process | + +---------------------------+---------------------------------------------+ + | :const:`KQ_FILTER_TIMER` | Establishes an arbitrary timer | + +---------------------------+---------------------------------------------+ + +.. attribute:: kevent.flags + + Filter action + + +---------------------------+---------------------------------------------+ + | Constant | Meaning | + +===========================+=============================================+ + | :const:`KQ_EV_ADD` | Adds or modifies an event | + +---------------------------+---------------------------------------------+ + | :const:`KQ_EV_DELETE` | Removes an event from the queue | + +---------------------------+---------------------------------------------+ + | :const:`KQ_EV_ENABLE` | Permitscontrol() to returns the event | + +---------------------------+---------------------------------------------+ + | :const:`KQ_EV_DISABLE` | Disablesevent | + +---------------------------+---------------------------------------------+ + | :const:`KQ_EV_ONESHOT` | Removes event after first occurence | + +---------------------------+---------------------------------------------+ + | :const:`KQ_EV_CLEAR` | Reset the state after an event is retrieved | + +---------------------------+---------------------------------------------+ + | :const:`KQ_EV_SYSFLAGS` | internal event | + +---------------------------+---------------------------------------------+ + | :const:`KQ_EV_FLAG1` | internal event | + +---------------------------+---------------------------------------------+ + | :const:`KQ_EV_EOF` | Filter specific EOF condition | + +---------------------------+---------------------------------------------+ + | :const:`KQ_EV_ERROR` | See return values | + +---------------------------+---------------------------------------------+ + + +.. attribute:: kevent.fflags + + Filter specific flags + + + *:const:`KQ_FILTER_READ` and :const:`KQ_FILTER_WRITE` filter flags* + + +----------------------------+--------------------------------------------+ + | Constant | Meaning | + +============================+============================================+ + | :const:`KQ_NOTE_LOWAT` | low water mark of a socket buffer | + +----------------------------+--------------------------------------------+ + + + *:const:`KQ_FILTER_VNODE` filter flags* + + +----------------------------+--------------------------------------------+ + | Constant | Meaning | + +============================+============================================+ + | :const:`KQ_NOTE_DELETE` | *unlink()* was called | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_WRITE` | a write occured | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_EXTEND` | the file was extended | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_ATTRIB` | an attribute was changed | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_LINK` | the link count has changed | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_RENAME` | the file was renamed | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_REVOKE` | access to the file was revoked | + +----------------------------+--------------------------------------------+ + + + *:const:`KQ_FILTER_PROC` filter flags* + + +----------------------------+--------------------------------------------+ + | Constant | Meaning | + +============================+============================================+ + | :const:`KQ_NOTE_EXIT` | the process has exited | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_FORK` | the process has called *fork()* | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_EXEC` | the process has executed a new process | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_PCTRLMASK` | internal filter flag | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_PDATAMASK` | internal filter flag | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_TRACK` | follow a process across *fork()* | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_CHILD` | returned on the child process for | + | | *NOTE_TRACK* | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_TRACKERR` | unable to attach to a child | + +----------------------------+--------------------------------------------+ + + *:const:`KQ_FILTER_NETDEV` filter flags* [not available on Mac OS X] + + +----------------------------+--------------------------------------------+ + | Constant | Meaning | + +============================+============================================+ + | :const:`KQ_NOTE_LINKUP` | link is up | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_LINKDOWN` | link is down | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_LINKINV` | link state is invalid | + +----------------------------+--------------------------------------------+ + + +.. attribute:: kevent.data + + Filter specific data + + +.. attribute:: kevent.udata + + User defined value Modified: python/branches/py3k-ctypes-pep3118/Doc/library/shutil.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/shutil.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/shutil.rst Wed Apr 30 15:57:13 2008 @@ -28,15 +28,6 @@ are not copied. -.. function:: copyfile(src, dst) - - Copy the contents (no metadata) of the file named *src* to a file named *dst*. - The destination location must be writable; otherwise, an :exc:`IOError` exception - will be raised. If *dst* already exists, it will be replaced. Special files - such as character or block devices and pipes cannot be copied with this - function. *src* and *dst* are path names given as strings. - - .. function:: copyfileobj(fsrc, fdst[, length]) Copy the contents of the file-like object *fsrc* to the file-like object *fdst*. @@ -48,6 +39,17 @@ be copied. +.. function:: copyfile(src, dst) + + Copy the contents (no metadata) of the file named *src* to a file named *dst*. + *dst* must be the complete target file name; look at :func:`copy` for a copy that + accepts a target directory path. + The destination location must be writable; otherwise, an :exc:`IOError` exception + will be raised. If *dst* already exists, it will be replaced. Special files + such as character or block devices and pipes cannot be copied with this + function. *src* and *dst* are path names given as strings. + + .. function:: copymode(src, dst) Copy the permission bits from *src* to *dst*. The file contents, owner, and @@ -108,10 +110,6 @@ information return by :func:`sys.exc_info`. Exceptions raised by *onerror* will not be caught. - .. versionchanged:: 2.6 - Explicitly check for *path* being a symbolic link and raise :exc:`OSError` - in that case. - .. function:: move(src, dst) Modified: python/branches/py3k-ctypes-pep3118/Doc/library/signal.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/signal.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/signal.rst Wed Apr 30 15:57:13 2008 @@ -39,12 +39,13 @@ * Some care must be taken if both signals and threads are used in the same program. The fundamental thing to remember in using signals and threads simultaneously is: always perform :func:`signal` operations in the main thread - of execution. Any thread can perform an :func:`alarm`, :func:`getsignal`, or - :func:`pause`; only the main thread can set a new signal handler, and the main - thread will be the only one to receive signals (this is enforced by the Python - :mod:`signal` module, even if the underlying thread implementation supports - sending signals to individual threads). This means that signals can't be used - as a means of inter-thread communication. Use locks instead. + of execution. Any thread can perform an :func:`alarm`, :func:`getsignal`, + :func:`pause`, :func:`setitimer` or :func:`getitimer`; only the main thread + can set a new signal handler, and the main thread will be the only one to + receive signals (this is enforced by the Python :mod:`signal` module, even + if the underlying thread implementation supports sending signals to + individual threads). This means that signals can't be used as a means of + inter-thread communication. Use locks instead. The variables defined in the :mod:`signal` module are: @@ -78,6 +79,36 @@ One more than the number of the highest signal number. + +.. data:: ITIMER_REAL + + Decrements interval timer in real time, and delivers :const:`SIGALRM` upon expiration. + + +.. data:: ITIMER_VIRTUAL + + Decrements interval timer only when the process is executing, and delivers + SIGVTALRM upon expiration. + + +.. data:: ITIMER_PROF + + Decrements interval timer both when the process executes and when the + system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL, + this timer is usually used to profile the time spent by the application + in user and kernel space. SIGPROF is delivered upon expiration. + + +The :mod:`signal` module defines one exception: + +.. exception:: ItimerError + + Raised to signal an error from the underlying :func:`setitimer` or + :func:`getitimer` implementation. Expect this error if an invalid + interval timer or a negative time is passed to :func:`setitimer`. + This error is a subtype of :exc:`IOError`. + + The :mod:`signal` module defines the following functions: @@ -110,6 +141,31 @@ :manpage:`signal(2)`.) +.. function:: setitimer(which, seconds[, interval]) + + Sets given interval timer (one of :const:`signal.ITIMER_REAL`, + :const:`signal.ITIMER_VIRTUAL` or :const:`signal.ITIMER_PROF`) specified + by *which* to fire after *seconds* (float is accepted, different from + :func:`alarm`) and after that every *interval* seconds. The interval + timer specified by *which* can be cleared by setting seconds to zero. + + When an interval timer fires, a signal is sent to the process. + The signal sent is dependent on the timer being used; + :const:`signal.ITIMER_REAL` will deliver :const:`SIGALRM`, + :const:`signal.ITIMER_VIRTUAL` sends :const:`SIGVTALRM`, + and :const:`signal.ITIMER_PROF` will deliver :const:`SIGPROF`. + + The old values are returned as a tuple: (delay, interval). + + Attempting to pass an invalid interval timer will cause a + :exc:`ItimerError`. + + +.. function:: getitimer(which) + + Returns current value of a given interval timer specified by *which*. + + .. function:: set_wakeup_fd(fd) Set the wakeup fd to *fd*. When a signal is received, a ``'\0'`` byte is @@ -124,6 +180,18 @@ exception to be raised. +.. function:: siginterrupt(signalnum, flag) + + Change system call restart behaviour: if *flag* is :const:`False`, system calls + will be restarted when interrupted by signal *signalnum*, otherwise system calls will + be interrupted. Returns nothing. Availability: Unix, Mac (see the man page + :manpage:`siginterrupt(3)` for further information). + + Note that installing a signal handler with :func:`signal` will reset the restart + behaviour to interruptible by implicitly calling :cfunc:`siginterrupt` with a true *flag* + value for the given signal. + + .. function:: signal(signalnum, handler) Set the handler for signal *signalnum* to the function *handler*. *handler* can Modified: python/branches/py3k-ctypes-pep3118/Doc/library/simplehttpserver.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/simplehttpserver.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/simplehttpserver.rst Wed Apr 30 15:57:13 2008 @@ -23,57 +23,59 @@ :class:`BaseHTTPServer.BaseHTTPRequestHandler`. This class implements the :func:`do_GET` and :func:`do_HEAD` functions. -The :class:`SimpleHTTPRequestHandler` defines the following member variables: + The :class:`SimpleHTTPRequestHandler` defines the following member variables: -.. attribute:: SimpleHTTPRequestHandler.server_version + .. attribute:: server_version - This will be ``"SimpleHTTP/" + __version__``, where ``__version__`` is defined - in the module. + This will be ``"SimpleHTTP/" + __version__``, where ``__version__`` is + defined in the module. -.. attribute:: SimpleHTTPRequestHandler.extensions_map + .. attribute:: extensions_map - A dictionary mapping suffixes into MIME types. The default is signified by an - empty string, and is considered to be ``application/octet-stream``. The mapping - is used case-insensitively, and so should contain only lower-cased keys. + A dictionary mapping suffixes into MIME types. The default is signified by + an empty string, and is considered to be ``application/octet-stream``. The + mapping is used case-insensitively, and so should contain only lower-cased + keys. -The :class:`SimpleHTTPRequestHandler` defines the following methods: + The :class:`SimpleHTTPRequestHandler` defines the following methods: -.. method:: SimpleHTTPRequestHandler.do_HEAD() + .. method:: do_HEAD() - This method serves the ``'HEAD'`` request type: it sends the headers it would - send for the equivalent ``GET`` request. See the :meth:`do_GET` method for a - more complete explanation of the possible headers. + This method serves the ``'HEAD'`` request type: it sends the headers it + would send for the equivalent ``GET`` request. See the :meth:`do_GET` + method for a more complete explanation of the possible headers. -.. method:: SimpleHTTPRequestHandler.do_GET() + .. method:: do_GET() - The request is mapped to a local file by interpreting the request as a path - relative to the current working directory. + The request is mapped to a local file by interpreting the request as a + path relative to the current working directory. - If the request was mapped to a directory, the directory is checked for a file - named ``index.html`` or ``index.htm`` (in that order). If found, the file's - contents are returned; otherwise a directory listing is generated by calling the - :meth:`list_directory` method. This method uses :func:`os.listdir` to scan the - directory, and returns a ``404`` error response if the :func:`listdir` fails. + If the request was mapped to a directory, the directory is checked for a + file named ``index.html`` or ``index.htm`` (in that order). If found, the + file's contents are returned; otherwise a directory listing is generated + by calling the :meth:`list_directory` method. This method uses + :func:`os.listdir` to scan the directory, and returns a ``404`` error + response if the :func:`listdir` fails. - If the request was mapped to a file, it is opened and the contents are returned. - Any :exc:`IOError` exception in opening the requested file is mapped to a - ``404``, ``'File not found'`` error. Otherwise, the content type is guessed by - calling the :meth:`guess_type` method, which in turn uses the *extensions_map* - variable. + If the request was mapped to a file, it is opened and the contents are + returned. Any :exc:`IOError` exception in opening the requested file is + mapped to a ``404``, ``'File not found'`` error. Otherwise, the content + type is guessed by calling the :meth:`guess_type` method, which in turn + uses the *extensions_map* variable. - A ``'Content-type:'`` header with the guessed content type is output, followed - by a ``'Content-Length:'`` header with the file's size and a - ``'Last-Modified:'`` header with the file's modification time. + A ``'Content-type:'`` header with the guessed content type is output, + followed by a ``'Content-Length:'`` header with the file's size and a + ``'Last-Modified:'`` header with the file's modification time. - Then follows a blank line signifying the end of the headers, and then the - contents of the file are output. If the file's MIME type starts with ``text/`` - the file is opened in text mode; otherwise binary mode is used. + Then follows a blank line signifying the end of the headers, and then the + contents of the file are output. If the file's MIME type starts with + ``text/`` the file is opened in text mode; otherwise binary mode is used. - For example usage, see the implementation of the :func:`test` function. + For example usage, see the implementation of the :func:`test` function. .. seealso:: Modified: python/branches/py3k-ctypes-pep3118/Doc/library/simplexmlrpcserver.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/simplexmlrpcserver.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/simplexmlrpcserver.rst Wed Apr 30 15:57:13 2008 @@ -101,7 +101,7 @@ Registers the XML-RPC multicall function system.multicall. -.. attribute:: SimpleXMLRPCServer.rpc_paths +.. attribute:: SimpleXMLRPCRequestHandler.rpc_paths An attribute value that must be a tuple listing valid path portions of the URL for receiving XML-RPC requests. Requests posted to other paths will result in a @@ -116,9 +116,15 @@ Server code:: from SimpleXMLRPCServer import SimpleXMLRPCServer + from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler + + # Restrict to a particular path. + class RequestHandler(SimpleXMLRPCRequestHandler): + rpc_paths = ('/RPC2',) # Create server - server = SimpleXMLRPCServer(("localhost", 8000)) + server = SimpleXMLRPCServer(("localhost", 8000), + requestHandler=RequestHandler) server.register_introspection_functions() # Register pow() function; this will use the value of @@ -149,7 +155,7 @@ s = xmlrpclib.ServerProxy('http://localhost:8000') print(s.pow(2,3)) # Returns 2**3 = 8 print(s.add(2,3)) # Returns 5 - print(s.div(5,2)) # Returns 5//2 = 2 + print(s.mul(5,2)) # Returns 5*2 = 10 # Print list of available methods print(s.system.listMethods()) Modified: python/branches/py3k-ctypes-pep3118/Doc/library/smtpd.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/smtpd.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/smtpd.rst Wed Apr 30 15:57:13 2008 @@ -27,14 +27,15 @@ :mod:`asyncore`'s event loop on instantiation. -.. method:: SMTPServer.process_message(peer, mailfrom, rcpttos, data) + .. method:: process_message(peer, mailfrom, rcpttos, data) - Raise :exc:`NotImplementedError` exception. Override this in subclasses to do - something useful with this message. Whatever was passed in the constructor as - *remoteaddr* will be available as the :attr:`_remoteaddr` attribute. *peer* is - the remote host's address, *mailfrom* is the envelope originator, *rcpttos* are - the envelope recipients and *data* is a string containing the contents of the - e-mail (which should be in :rfc:`2822` format). + Raise :exc:`NotImplementedError` exception. Override this in subclasses to + do something useful with this message. Whatever was passed in the + constructor as *remoteaddr* will be available as the :attr:`_remoteaddr` + attribute. *peer* is the remote host's address, *mailfrom* is the envelope + originator, *rcpttos* are the envelope recipients and *data* is a string + containing the contents of the e-mail (which should be in :rfc:`2822` + format). DebuggingServer Objects Modified: python/branches/py3k-ctypes-pep3118/Doc/library/smtplib.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/smtplib.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/smtplib.rst Wed Apr 30 15:57:13 2008 @@ -193,8 +193,6 @@ :exc:SMTPHeloError The server didn't reply properly to the ``HELO`` greeting. - .. versionadded:: 2.6 - .. method:: SMTP.has_extn(name) Return :const:`True` if *name* is in the set of SMTP service extensions returned @@ -243,16 +241,12 @@ If there has been no previous ``EHLO`` or ``HELO`` command this session, this method tries ESMTP ``EHLO`` first. - .. versionchanged:: 2.6 - :exc:`SMTPHeloError` The server didn't reply properly to the ``HELO`` greeting. :exc:`SMTPException` The server does not support the STARTTLS extension. - .. versionchanged:: 2.6 - :exc:`RuntimeError` SSL/TLS support is not available to your python interpreter. @@ -311,7 +305,9 @@ .. method:: SMTP.quit() - Terminate the SMTP session and close the connection. + Terminate the SMTP session and close the connection. Return the result of + the SMTP ``QUIT`` command. + Low-level methods corresponding to the standard SMTP/ESMTP commands ``HELP``, ``RSET``, ``NOOP``, ``MAIL``, ``RCPT``, and ``DATA`` are also supported. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/socket.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/socket.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/socket.rst Wed Apr 30 15:57:13 2008 @@ -23,7 +23,7 @@ socket-related system calls are also a valuable source of information on the details of socket semantics. For Unix, refer to the manual pages; for Windows, see the WinSock (or Winsock 2) specification. For IPv6-ready APIs, readers may -want to refer to :rfc:`2553` titled Basic Socket Interface Extensions for IPv6. +want to refer to :rfc:`3493` titled Basic Socket Interface Extensions for IPv6. .. index:: object: socket @@ -886,5 +886,5 @@ # receive a package print s.recvfrom(65565) - # disabled promiscous mode + # disabled promiscuous mode s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF) Modified: python/branches/py3k-ctypes-pep3118/Doc/library/socketserver.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/socketserver.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/socketserver.rst Wed Apr 30 15:57:13 2008 @@ -113,7 +113,8 @@ finished requests and to use :func:`select` to decide which request to work on next (or whether to handle a new incoming request). This is particularly important for stream services where each client can potentially be connected for -a long time (if threads or subprocesses cannot be used). +a long time (if threads or subprocesses cannot be used). See :mod:`asyncore` for +another way to manage this. .. XXX should data and methods be intermingled, or separate? how should the distinction between class and instance variables be drawn? @@ -132,16 +133,24 @@ .. function:: handle_request() - Process a single request. This function calls the following methods in order: - :meth:`get_request`, :meth:`verify_request`, and :meth:`process_request`. If - the user-provided :meth:`handle` method of the handler class raises an - exception, the server's :meth:`handle_error` method will be called. + Process a single request. This function calls the following methods in + order: :meth:`get_request`, :meth:`verify_request`, and + :meth:`process_request`. If the user-provided :meth:`handle` method of the + handler class raises an exception, the server's :meth:`handle_error` method + will be called. If no request is received within :attr:`self.timeout` + seconds, :meth:`handle_timeout` will be called and :meth:`handle_request` + will return. -.. function:: serve_forever() +.. function:: serve_forever(poll_interval=0.5) - Handle an infinite number of requests. This simply calls :meth:`handle_request` - inside an infinite loop. + Handle requests until an explicit :meth:`shutdown` request. Polls for + shutdown every *poll_interval* seconds. + + +.. function:: shutdown() + + Tells the :meth:`serve_forever` loop to stop and waits until it does. .. data:: address_family @@ -195,10 +204,9 @@ .. data:: timeout - Timeout duration, measured in seconds, or :const:`None` if no timeout is desired. - If no incoming requests are received within the timeout period, - the :meth:`handle_timeout` method is called and then the server resumes waiting for - requests. + Timeout duration, measured in seconds, or :const:`None` if no timeout is + desired. If :meth:`handle_request` receives no incoming requests within the + timeout period, the :meth:`handle_timeout` method is called. There are various server methods that can be overridden by subclasses of base server classes like :class:`TCPServer`; these methods aren't useful to external Modified: python/branches/py3k-ctypes-pep3118/Doc/library/sqlite3.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/sqlite3.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/sqlite3.rst Wed Apr 30 15:57:13 2008 @@ -184,7 +184,7 @@ Registers a callable to convert the custom Python type *type* into one of SQLite's supported types. The callable *callable* accepts as single parameter the Python value, and must return a value of the following types: int, - float, str (UTF-8 encoded), unicode or buffer. + float, str, bytes (UTF-8 encoded) or buffer. .. function:: complete_statement(sql) @@ -230,6 +230,24 @@ :class:`sqlite3.Cursor`. +.. method:: Connection.commit() + + This method commits the current transaction. If you don't call this method, + anything you did since the last call to commit() is not visible from from + other database connections. If you wonder why you don't see the data you've + written to the database, please check you didn't forget to call this method. + +.. method:: Connection.rollback() + + This method rolls back any changes to the database since the last call to + :meth:`commit`. + +.. method:: Connection.close() + + This closes the database connection. Note that this does not automatically + call :meth:`commit`. If you just close your database connection without + calling :meth:`commit` first, your changes will be lost! + .. method:: Connection.execute(sql, [parameters]) This is a nonstandard shortcut that creates an intermediate cursor object by @@ -258,7 +276,7 @@ parameters the function accepts, and *func* is a Python callable that is called as the SQL function. - The function can return any of the types supported by SQLite: unicode, str, int, + The function can return any of the types supported by SQLite: bytes, str, int, float, buffer and None. Example: @@ -275,7 +293,7 @@ final result of the aggregate. The ``finalize`` method can return any of the types supported by SQLite: - unicode, str, int, float, buffer and None. + bytes, str, int, float, buffer and None. Example: @@ -330,6 +348,17 @@ one. All necessary constants are available in the :mod:`sqlite3` module. +.. method:: Connection.set_progress_handler(handler, n) + + This routine registers a callback. The callback is invoked for every *n* + instructions of the SQLite virtual machine. This is useful if you want to + get called from SQLite during long-running operations, for example to update + a GUI. + + If you want to clear any previously installed progress handler, call the + method with :const:`None` for *handler*. + + .. attribute:: Connection.row_factory You can change this attribute to a callable that accepts the cursor and the @@ -354,13 +383,13 @@ .. attribute:: Connection.text_factory Using this attribute you can control what objects are returned for the TEXT data - type. By default, this attribute is set to :class:`unicode` and the - :mod:`sqlite3` module will return Unicode objects for TEXT. If you want to - return bytestrings instead, you can set it to :class:`str`. - - For efficiency reasons, there's also a way to return Unicode objects only for - non-ASCII data, and bytestrings otherwise. To activate it, set this attribute to - :const:`sqlite3.OptimizedUnicode`. + type. By default, this attribute is set to :class:`str` and the + :mod:`sqlite3` module will return strings for TEXT. If you want to + return bytestrings instead, you can set it to :class:`bytes`. + + For efficiency reasons, there's also a way to return :class:`str` objects + only for non-ASCII data, and :class:`bytes` otherwise. To activate it, set + this attribute to :const:`sqlite3.OptimizedUnicode`. You can also set it to any other callable that accepts a single bytestring parameter and returns the resulting object. @@ -376,6 +405,25 @@ deleted since the database connection was opened. +.. attribute:: Connection.iterdump + + Returns an iterator to dump the database in an SQL text format. Useful when + saving an in-memory database for later restoration. This function provides + the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3` + shell. + + Example:: + + # Convert file existing_db.db to SQL dump file dump.sql + import sqlite3, os + + con = sqlite3.connect('existing_db.db') + full_dump = os.linesep.join([line for line in con.iterdump()]) + f = open('dump.sql', 'w') + f.writelines(full_dump) + f.close() + + .. _sqlite3-cursor-objects: Cursor Objects @@ -424,36 +472,36 @@ at once. It issues a COMMIT statement first, then executes the SQL script it gets as a parameter. - *sql_script* can be a bytestring or a Unicode string. + *sql_script* can be an instance of :class:`str` or :class:`bytes`. Example: .. literalinclude:: ../includes/sqlite3/executescript.py -.. method:: Cursor.fetchone() - +.. method:: Cursor.fetchone() + Fetches the next row of a query result set, returning a single sequence, or ``None`` when no more data is available. .. method:: Cursor.fetchmany([size=cursor.arraysize]) - + Fetches the next set of rows of a query result, returning a list. An empty list is returned when no more rows are available. - + The number of rows to fetch per call is specified by the *size* parameter. If it is not given, the cursor's arraysize determines the number of rows to be fetched. The method should try to fetch as many rows as indicated by the size parameter. If this is not possible due to the specified number of rows not being available, fewer rows may be returned. - + Note there are performance considerations involved with the *size* parameter. For optimal performance, it is usually best to use the arraysize attribute. If the *size* parameter is used, then it is best for it to retain the same value from one :meth:`fetchmany` call to the next. - -.. method:: Cursor.fetchall() + +.. method:: Cursor.fetchall() Fetches all (remaining) rows of a query result, returning a list. Note that the cursor's arraysize attribute can affect the performance of this operation. @@ -479,6 +527,12 @@ This includes ``SELECT`` statements because we cannot determine the number of rows a query produced until all rows were fetched. +.. attribute:: Cursor.lastrowid + + This read-only attribute provides the rowid of the last modified row. It is + only set if you issued a ``INSERT`` statement using the :meth:`execute` + method. For operations other than ``INSERT`` or when :meth:`executemany` is + called, :attr:`lastrowid` is set to :const:`None`. .. _sqlite3-types: @@ -493,21 +547,21 @@ The following Python types can thus be sent to SQLite without any problem: -+------------------------+-------------+ -| Python type | SQLite type | -+========================+=============+ -| ``None`` | NULL | -+------------------------+-------------+ -| ``int`` | INTEGER | -+------------------------+-------------+ -| ``float`` | REAL | -+------------------------+-------------+ -| ``str (UTF8-encoded)`` | TEXT | -+------------------------+-------------+ -| ``unicode`` | TEXT | -+------------------------+-------------+ -| ``buffer`` | BLOB | -+------------------------+-------------+ ++-------------------------------+-------------+ +| Python type | SQLite type | ++===============================+=============+ +| ``None`` | NULL | ++-------------------------------+-------------+ +| :class:`int` | INTEGER | ++-------------------------------+-------------+ +| :class:`float` | REAL | ++-------------------------------+-------------+ +| :class:`bytes` (UTF8-encoded) | TEXT | ++-------------------------------+-------------+ +| :class:`str` | TEXT | ++-------------------------------+-------------+ +| :class:`buffer` | BLOB | ++-------------------------------+-------------+ This is how SQLite types are converted to Python types by default: @@ -520,7 +574,7 @@ +-------------+---------------------------------------------+ | ``REAL`` | float | +-------------+---------------------------------------------+ -| ``TEXT`` | depends on text_factory, unicode by default | +| ``TEXT`` | depends on text_factory, str by default | +-------------+---------------------------------------------+ | ``BLOB`` | buffer | +-------------+---------------------------------------------+ @@ -537,7 +591,7 @@ As described before, SQLite supports only a limited set of types natively. To use other Python types with SQLite, you must **adapt** them to one of the sqlite3 module's supported types for SQLite: one of NoneType, int, float, -str, unicode, buffer. +str, bytes, buffer. The :mod:`sqlite3` module uses Python object adaptation, as described in :pep:`246` for this. The protocol to use is :class:`PrepareProtocol`. @@ -671,10 +725,6 @@ statement, or set it to one of SQLite's supported isolation levels: DEFERRED, IMMEDIATE or EXCLUSIVE. -As the :mod:`sqlite3` module needs to keep track of the transaction state, you -should not use ``OR ROLLBACK`` or ``ON CONFLICT ROLLBACK`` in your SQL. Instead, -catch the :exc:`IntegrityError` and call the :meth:`rollback` method of the -connection yourself. Using pysqlite efficiently @@ -706,3 +756,13 @@ .. literalinclude:: ../includes/sqlite3/rowclass.py + +Using the connection as a context manager +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Connection objects can be used as context managers +that automatically commit or rollback transactions. In the event of an +exception, the transaction is rolled back; otherwise, the transaction is +committed: + +.. literalinclude:: ../includes/sqlite3/ctx_manager.py Modified: python/branches/py3k-ctypes-pep3118/Doc/library/ssl.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/ssl.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/ssl.rst Wed Apr 30 15:57:13 2008 @@ -543,7 +543,7 @@ server_side=True, certfile="mycertfile", keyfile="mykeyfile", - ssl_protocol=ssl.PROTOCOL_TLSv1) + ssl_version=ssl.PROTOCOL_TLSv1) deal_with_client(connstream) Then you'd read data from the ``connstream`` and do something with it till you are finished with the client (or the client is finished with you):: Modified: python/branches/py3k-ctypes-pep3118/Doc/library/stdtypes.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/stdtypes.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/stdtypes.rst Wed Apr 30 15:57:13 2008 @@ -601,7 +601,7 @@ Values of *n* less than ``0`` are treated as ``0`` (which yields an empty sequence of the same type as *s*). Note also that the copies are shallow; nested structures are not copied. This often haunts new Python programmers; - consider:: + consider: >>> lists = [[]] * 3 >>> lists @@ -611,9 +611,9 @@ [[3], [3], [3]] What has happened is that ``[[]]`` is a one-element list containing an empty - list, so all three elements of ``[[]] * 3`` are (pointers to) this single - empty list. Modifying any of the elements of ``lists`` modifies this single - list. You can create a list of different lists this way:: + list, so all three elements of ``[[]] * 3`` are (pointers to) this single empty + list. Modifying any of the elements of ``lists`` modifies this single list. + You can create a list of different lists this way: >>> lists = [[] for i in range(3)] >>> lists[0].append(3) @@ -819,7 +819,7 @@ Return a copy of the string with leading characters removed. The *chars* argument is a string specifying the set of characters to be removed. If omitted or ``None``, the *chars* argument defaults to removing whitespace. The *chars* - argument is not a prefix; rather, all combinations of its values are stripped:: + argument is not a prefix; rather, all combinations of its values are stripped: >>> ' spacious '.lstrip() 'spacious ' @@ -899,7 +899,7 @@ Return a copy of the string with trailing characters removed. The *chars* argument is a string specifying the set of characters to be removed. If omitted or ``None``, the *chars* argument defaults to removing whitespace. The *chars* - argument is not a suffix; rather, all combinations of its values are stripped:: + argument is not a suffix; rather, all combinations of its values are stripped: >>> ' spacious '.rstrip() ' spacious' @@ -953,7 +953,7 @@ The *chars* argument is a string specifying the set of characters to be removed. If omitted or ``None``, the *chars* argument defaults to removing whitespace. The *chars* argument is not a prefix or suffix; rather, all combinations of its - values are stripped:: + values are stripped: >>> ' spacious '.strip() 'spacious' @@ -983,6 +983,10 @@ A *map* for :meth:`translate` is usually best created by :meth:`str.maketrans`. + You can use the :func:`maketrans` helper function in the :mod:`string` module to + create a translation table. For string objects, set the *table* argument to + ``None`` for translations that only delete characters: + .. note:: An even more flexible approach is to create a custom character mapping @@ -1000,6 +1004,22 @@ Return the numeric string left filled with zeros in a string of length *width*. A sign prefix is handled correctly. The original string is returned if *width* is less than ``len(s)``. + + +.. method:: str.isnumeric() + + Return ``True`` if there are only numeric characters in S, ``False`` + otherwise. Numeric characters include digit characters, and all characters + that have the Unicode numeric value property, e.g. U+2155, + VULGAR FRACTION ONE FIFTH. + + +.. method:: str.isdecimal() + + Return ``True`` if there are only decimal characters in S, ``False`` + otherwise. Decimal characters include digit characters, and all characters + that that can be used to form decimal-radix numbers, e.g. U+0660, + ARABIC-INDIC DIGIT ZERO. @@ -1063,10 +1083,11 @@ When the right argument is a dictionary (or other mapping type), then the formats in the string *must* include a parenthesised mapping key into that dictionary inserted immediately after the ``'%'`` character. The mapping key -selects the value to be formatted from the mapping. For example:: +selects the value to be formatted from the mapping. For example: + - >>> print('%(language)s has %(#)03d quote types.' % - {'language': "Python", "#": 2}) + >>> print('%(language)s has %(#)03d quote types.' % \ + ... {'language': "Python", "#": 2}) Python has 002 quote types. In this case no ``*`` specifiers may occur in a format (since they require a @@ -1266,8 +1287,7 @@ | ``s.reverse()`` | reverses the items of *s* in | \(6) | | | place | | +------------------------------+--------------------------------+---------------------+ -| ``s.sort([cmp[, key[, | sort the items of *s* in place | (6), (7) | -| reverse]]])`` | | | +| ``s.sort([key[, reverse]])`` | sort the items of *s* in place | (6), (7), (8) | +------------------------------+--------------------------------+---------------------+ .. index:: @@ -1316,16 +1336,8 @@ sequence. (7) - :meth:`sort` is not supported by :class:`bytearray` objects. - The :meth:`sort` method takes optional arguments for controlling the - comparisons. - - *cmp* specifies a custom comparison function of two arguments (list items) which - should return a negative, zero or positive number depending on whether the first - argument is considered smaller than, equal to, or larger than the second - argument: ``cmp=lambda x,y: cmp(x.lower(), y.lower())``. The default value - is ``None``. + comparisons. Each must be specified as a keyword argument. *key* specifies a function of one argument that is used to extract a comparison key from each list element: ``key=str.lower``. The default value is ``None``. @@ -1333,21 +1345,18 @@ *reverse* is a boolean value. If set to ``True``, then the list elements are sorted as if each comparison were reversed. - In general, the *key* and *reverse* conversion processes are much faster than - specifying an equivalent *cmp* function. This is because *cmp* is called - multiple times for each list element while *key* and *reverse* touch each - element only once. - - Starting with Python 2.3, the :meth:`sort` method is guaranteed to be stable. A + The :meth:`sort` method is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal --- this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade). While a list is being sorted, the effect of attempting to mutate, or even - inspect, the list is undefined. The C implementation of Python 2.3 and newer + inspect, the list is undefined. The C implementation makes the list appear empty for the duration, and raises :exc:`ValueError` if it can detect that the list has been mutated during a sort. +(8) + :meth:`sort` is not supported by :class:`bytearray` objects. .. _bytes-methods: @@ -2051,9 +2060,13 @@ .. method:: file.write(str) - Write a string to the file. There is no return value. Due to buffering, the - string may not actually show up in the file until the :meth:`flush` or - :meth:`close` method is called. + Write a string to the file. Due to buffering, the string may not actually + show up in the file until the :meth:`flush` or :meth:`close` method is + called. + + The meaning of the return value is not defined for every file-like object. + Some (mostly low-level) file-like objects may return the number of bytes + actually written, others return ``None``. .. method:: file.writelines(sequence) @@ -2082,13 +2095,13 @@ .. XXX does this still apply? .. attribute:: file.encoding - The encoding that this file uses. When Unicode strings are written to a file, + The encoding that this file uses. When strings are written to a file, they will be converted to byte strings using this encoding. In addition, when the file is connected to a terminal, the attribute gives the encoding that the terminal is likely to use (that information might be incorrect if the user has misconfigured the terminal). The attribute is read-only and may not be present on all file-like objects. It may also be ``None``, in which case the file uses - the system default encoding for converting Unicode strings. + the system default encoding for converting strings. .. attribute:: file.mode @@ -2332,7 +2345,7 @@ types. The standard module :mod:`types` defines names for all standard built-in types. -Types are written like this: ````. +Types are written like this: ````. .. _bltin-null-object: Modified: python/branches/py3k-ctypes-pep3118/Doc/library/string.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/string.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/string.rst Wed Apr 30 15:57:13 2008 @@ -452,29 +452,29 @@ The constructor takes a single argument which is the template string. -.. method:: Template.substitute(mapping[, **kws]) + .. method:: substitute(mapping[, **kws]) - Performs the template substitution, returning a new string. *mapping* is any - dictionary-like object with keys that match the placeholders in the template. - Alternatively, you can provide keyword arguments, where the keywords are the - placeholders. When both *mapping* and *kws* are given and there are duplicates, - the placeholders from *kws* take precedence. - - -.. method:: Template.safe_substitute(mapping[, **kws]) - - Like :meth:`substitute`, except that if placeholders are missing from *mapping* - and *kws*, instead of raising a :exc:`KeyError` exception, the original - placeholder will appear in the resulting string intact. Also, unlike with - :meth:`substitute`, any other appearances of the ``$`` will simply return ``$`` - instead of raising :exc:`ValueError`. - - While other exceptions may still occur, this method is called "safe" because - substitutions always tries to return a usable string instead of raising an - exception. In another sense, :meth:`safe_substitute` may be anything other than - safe, since it will silently ignore malformed templates containing dangling - delimiters, unmatched braces, or placeholders that are not valid Python - identifiers. + Performs the template substitution, returning a new string. *mapping* is + any dictionary-like object with keys that match the placeholders in the + template. Alternatively, you can provide keyword arguments, where the + keywords are the placeholders. When both *mapping* and *kws* are given + and there are duplicates, the placeholders from *kws* take precedence. + + + .. method:: safe_substitute(mapping[, **kws]) + + Like :meth:`substitute`, except that if placeholders are missing from + *mapping* and *kws*, instead of raising a :exc:`KeyError` exception, the + original placeholder will appear in the resulting string intact. Also, + unlike with :meth:`substitute`, any other appearances of the ``$`` will + simply return ``$`` instead of raising :exc:`ValueError`. + + While other exceptions may still occur, this method is called "safe" + because substitutions always tries to return a usable string instead of + raising an exception. In another sense, :meth:`safe_substitute` may be + anything other than safe, since it will silently ignore malformed + templates containing dangling delimiters, unmatched braces, or + placeholders that are not valid Python identifiers. :class:`Template` instances also provide one public data attribute: @@ -484,7 +484,7 @@ This is the object passed to the constructor's *template* argument. In general, you shouldn't change it, but read-only access is not enforced. -Here is an example of how to use a Template:: +Here is an example of how to use a Template: >>> from string import Template >>> s = Template('$who likes $what') @@ -538,7 +538,7 @@ String functions ---------------- -The following functions are available to operate on string and Unicode objects. +The following functions are available to operate on string objects. They are not available as string methods. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/stringio.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/stringio.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/stringio.rst Wed Apr 30 15:57:13 2008 @@ -1,3 +1,4 @@ +.. XXX this whole file is outdated :mod:`StringIO` --- Read and write strings as files =================================================== @@ -9,7 +10,7 @@ This module implements a file-like class, :class:`StringIO`, that reads and writes a string buffer (also known as *memory files*). See the description of file objects for operations (section :ref:`bltin-file-objects`). (For -standard strings, see :class:`str` and :class:`unicode`.) +standard strings, see :class:`str`.) .. class:: StringIO([buffer]) @@ -19,20 +20,13 @@ :class:`StringIO` will start empty. In both cases, the initial file position starts at zero. - The :class:`StringIO` object can accept either Unicode or 8-bit strings, but - mixing the two may take some care. If both are used, 8-bit strings that cannot - be interpreted as 7-bit ASCII (that use the 8th bit) will cause a - :exc:`UnicodeError` to be raised when :meth:`getvalue` is called. - The following methods of :class:`StringIO` objects require special mention: .. method:: StringIO.getvalue() Retrieve the entire contents of the "file" at any time before the - :class:`StringIO` object's :meth:`close` method is called. See the note above - for information about mixing Unicode and 8-bit strings; such mixing can cause - this method to raise :exc:`UnicodeError`. + :class:`StringIO` object's :meth:`close` method is called. .. method:: StringIO.close() @@ -75,11 +69,11 @@ original :mod:`StringIO` module in that case. Unlike the memory files implemented by the :mod:`StringIO` module, those -provided by this module are not able to accept Unicode strings that cannot be -encoded as plain ASCII strings. +provided by this module are not able to accept strings that cannot be +encoded in plain ASCII. -Calling :func:`StringIO` with a Unicode string parameter populates -the object with the buffer representation of the Unicode string, instead of +Calling :func:`StringIO` with a string parameter populates +the object with the buffer representation of the string, instead of encoding the string. Another difference from the :mod:`StringIO` module is that calling Modified: python/branches/py3k-ctypes-pep3118/Doc/library/struct.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/struct.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/struct.rst Wed Apr 30 15:57:13 2008 @@ -73,7 +73,7 @@ +--------+-------------------------+--------------------+-------+ | ``B`` | :ctype:`unsigned char` | integer | | +--------+-------------------------+--------------------+-------+ -| ``t`` | :ctype:`_Bool` | bool | \(1) | +| ``?`` | :ctype:`_Bool` | bool | \(1) | +--------+-------------------------+--------------------+-------+ | ``h`` | :ctype:`short` | integer | | +--------+-------------------------+--------------------+-------+ @@ -106,7 +106,7 @@ Notes: (1) - The ``'t'`` conversion code corresponds to the :ctype:`_Bool` type defined by + The ``'?'`` conversion code corresponds to the :ctype:`_Bool` type defined by C99. If this type is not available, it is simulated using a :ctype:`char`. In standard mode, it is always represented by one byte. @@ -141,7 +141,7 @@ -For the ``'t'`` format character, the return value is either :const:`True` or +For the ``'?'`` format character, the return value is either :const:`True` or :const:`False`. When packing, the truth value of the argument object is used. Either 0 or 1 in the native or standard bool representation will be packed, and any non-zero value will be True when unpacking. @@ -242,37 +242,37 @@ since the format string only needs to be compiled once. -Compiled Struct objects support the following methods and attributes: + Compiled Struct objects support the following methods and attributes: -.. method:: Struct.pack(v1, v2, ...) + .. method:: pack(v1, v2, ...) - Identical to the :func:`pack` function, using the compiled format. - (``len(result)`` will equal :attr:`self.size`.) + Identical to the :func:`pack` function, using the compiled format. + (``len(result)`` will equal :attr:`self.size`.) -.. method:: Struct.pack_into(buffer, offset, v1, v2, ...) + .. method:: pack_into(buffer, offset, v1, v2, ...) - Identical to the :func:`pack_into` function, using the compiled format. + Identical to the :func:`pack_into` function, using the compiled format. -.. method:: Struct.unpack(string) + .. method:: unpack(string) - Identical to the :func:`unpack` function, using the compiled format. - (``len(string)`` must equal :attr:`self.size`). + Identical to the :func:`unpack` function, using the compiled format. + (``len(string)`` must equal :attr:`self.size`). -.. method:: Struct.unpack_from(buffer[, offset=0]) + .. method:: unpack_from(buffer[, offset=0]) - Identical to the :func:`unpack_from` function, using the compiled format. - (``len(buffer[offset:])`` must be at least :attr:`self.size`). + Identical to the :func:`unpack_from` function, using the compiled format. + (``len(buffer[offset:])`` must be at least :attr:`self.size`). -.. attribute:: Struct.format + .. attribute:: format - The format string used to construct this Struct object. + The format string used to construct this Struct object. -.. attribute:: Struct.size + .. attribute:: size - The calculated size of the struct (and hence of the string) corresponding - to :attr:`format`. + The calculated size of the struct (and hence of the string) corresponding + to :attr:`format`. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/subprocess.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/subprocess.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/subprocess.rst Wed Apr 30 15:57:13 2008 @@ -89,8 +89,9 @@ searching the executable, so you can't specify the program's path relative to *cwd*. - If *env* is not ``None``, it defines the environment variables for the new - process. + If *env* is not ``None``, it must be a mapping that defines the environment + variables for the new process; these are used instead of inheriting the current + process' environment, which is the default behavior. If *universal_newlines* is :const:`True`, the file objects stdout and stderr are opened as text files, but lines may be terminated by any of ``'\n'``, the Unix @@ -202,6 +203,29 @@ size is large or unlimited. +.. method:: Popen.send_signal(signal) + + Sends the signal *signal* to the child. + + .. note:: + + On Windows only SIGTERM is supported so far. It's an alias for + :meth:`terminate`. + + +.. method:: Popen.terminate() + + Stop the child. On Posix OSs the method sends SIGTERM to the + child. On Windows the Win32 API function TerminateProcess is called + to stop the child. + + +.. method:: Popen.kill() + + Kills the child. On Posix OSs the function sends SIGKILL to the child. + On Windows :meth:`kill` is an alias for :meth:`terminate`. + + The following attributes are also available: .. attribute:: Popen.stdin Modified: python/branches/py3k-ctypes-pep3118/Doc/library/sys.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/sys.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/sys.rst Wed Apr 30 15:57:13 2008 @@ -54,6 +54,28 @@ A string containing the copyright pertaining to the Python interpreter. +.. function:: _compact_freelists() + + Compact the free list of floats by deallocating unused blocks. + It can reduce the memory usage of the Python process several tenth of + thousands of integers or floats have been allocated at once. + + The return value is a tuple of tuples each containing three elements, + amount of used objects, total block count before the blocks are deallocated + and amount of freed blocks. + + This function should be used for specialized purposes only. + + +.. function:: _clear_type_cache() + + Clear the internal type cache. The type cache is used to speed up attribute + and method lookups. Use the function *only* to drop unnecessary references + during reference leak debugging. + + This function should be used for internal and specialized purposes only. + + .. function:: _current_frames() Return a dictionary mapping each thread's identifier to the topmost stack frame @@ -219,8 +241,6 @@ | :const:`unicode` | -U | +------------------------------+------------------------------------------+ - .. versionadded:: 2.6 - .. data:: float_info @@ -278,7 +298,7 @@ .. function:: getdlopenflags() Return the current value of the flags that are used for :cfunc:`dlopen` calls. - The flag constants are defined in the :mod:`dl` and :mod:`DLFCN` modules. + The flag constants are defined in the :mod:`ctypes` and :mod:`DLFCN` modules. Availability: Unix. @@ -334,8 +354,6 @@ Get the profiler function as set by :func:`setprofile`. - .. versionadded:: 2.6 - .. function:: gettrace() @@ -352,8 +370,6 @@ implementation platform, rather than part of the language definition, and thus may not be available in all Python implementations. - .. versionadded:: 2.6 - .. function:: getwindowsversion() @@ -530,8 +546,6 @@ environment variable, but you can set it yourself to control bytecode file generation. - .. versionadded:: 2.6 - .. function:: setcheckinterval(interval) @@ -561,8 +575,8 @@ the interpreter loads extension modules. Among other things, this will enable a lazy resolving of symbols when importing a module, if called as ``sys.setdlopenflags(0)``. To share symbols across extension modules, call as - ``sys.setdlopenflags(dl.RTLD_NOW | dl.RTLD_GLOBAL)``. Symbolic names for the - flag modules can be either found in the :mod:`dl` module, or in the :mod:`DLFCN` + ``sys.setdlopenflags(ctypes.RTLD_GLOBAL)``. Symbolic names for the + flag modules can be either found in the :mod:`ctypes` module, or in the :mod:`DLFCN` module. If :mod:`DLFCN` is not available, it can be generated from :file:`/usr/include/dlfcn.h` using the :program:`h2py` script. Availability: Unix. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/tempfile.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/tempfile.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/tempfile.rst Wed Apr 30 15:57:13 2008 @@ -51,7 +51,8 @@ The returned object is a true file object on POSIX platforms. On other platforms, it is a file-like object whose :attr:`file` attribute is the - underlying true file object. + underlying true file object. This file-like object can be used in a :keyword:`with` + statement, just like a normal file. .. function:: NamedTemporaryFile([mode='w+b'[, bufsize=-1[, suffix[, prefix[, dir[, delete]]]]]]) @@ -64,7 +65,8 @@ across platforms (it can be so used on Unix; it cannot on Windows NT or later). If *delete* is true (the default), the file is deleted as soon as it is closed. The returned object is always a file-like object whose :attr:`file` attribute - is the underlying true file object. + is the underlying true file object. This file-like object can be used in a :keyword:`with` + statement, just like a normal file. .. function:: SpooledTemporaryFile([max_size=0, [mode='w+b'[, bufsize=-1[, suffix[, prefix[, dir]]]]]]) @@ -79,7 +81,8 @@ The returned object is a file-like object whose :attr:`_file` attribute is either a :class:`StringIO` object or a true file object, depending on - whether :func:`rollover` has been called. + whether :func:`rollover` has been called. This file-like object can be used in a + :keyword:`with` statement, just like a normal file. .. function:: mkstemp([suffix[, prefix[, dir[, text]]]]) Modified: python/branches/py3k-ctypes-pep3118/Doc/library/textwrap.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/textwrap.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/textwrap.rst Wed Apr 30 15:57:13 2008 @@ -85,103 +85,104 @@ change any of its options through direct assignment to instance attributes between uses. -The :class:`TextWrapper` instance attributes (and keyword arguments to the -constructor) are as follows: + The :class:`TextWrapper` instance attributes (and keyword arguments to the + constructor) are as follows: -.. attribute:: TextWrapper.width + .. attribute:: width - (default: ``70``) The maximum length of wrapped lines. As long as there are no - individual words in the input text longer than :attr:`width`, - :class:`TextWrapper` guarantees that no output line will be longer than - :attr:`width` characters. + (default: ``70``) The maximum length of wrapped lines. As long as there + are no individual words in the input text longer than :attr:`width`, + :class:`TextWrapper` guarantees that no output line will be longer than + :attr:`width` characters. -.. attribute:: TextWrapper.expand_tabs + .. attribute:: expand_tabs - (default: ``True``) If true, then all tab characters in *text* will be expanded - to spaces using the :meth:`expandtabs` method of *text*. + (default: ``True``) If true, then all tab characters in *text* will be + expanded to spaces using the :meth:`expandtabs` method of *text*. -.. attribute:: TextWrapper.replace_whitespace + .. attribute:: replace_whitespace - (default: ``True``) If true, each whitespace character (as defined by - ``string.whitespace``) remaining after tab expansion will be replaced by a - single space. + (default: ``True``) If true, each whitespace character (as defined by + ``string.whitespace``) remaining after tab expansion will be replaced by a + single space. - .. note:: + .. note:: - If :attr:`expand_tabs` is false and :attr:`replace_whitespace` is true, each tab - character will be replaced by a single space, which is *not* the same as tab - expansion. + If :attr:`expand_tabs` is false and :attr:`replace_whitespace` is true, + each tab character will be replaced by a single space, which is *not* + the same as tab expansion. -.. attribute:: TextWrapper.drop_whitespace + .. attribute:: drop_whitespace - (default: ``True``) If true, whitespace that, after wrapping, happens to end up - at the beginning or end of a line is dropped (leading whitespace in the first - line is always preserved, though). + (default: ``True``) If true, whitespace that, after wrapping, happens to + end up at the beginning or end of a line is dropped (leading whitespace in + the first line is always preserved, though). -.. attribute:: TextWrapper.initial_indent + .. attribute:: initial_indent - (default: ``''``) String that will be prepended to the first line of wrapped - output. Counts towards the length of the first line. + (default: ``''``) String that will be prepended to the first line of + wrapped output. Counts towards the length of the first line. -.. attribute:: TextWrapper.subsequent_indent + .. attribute:: subsequent_indent - (default: ``''``) String that will be prepended to all lines of wrapped output - except the first. Counts towards the length of each line except the first. + (default: ``''``) String that will be prepended to all lines of wrapped + output except the first. Counts towards the length of each line except + the first. -.. attribute:: TextWrapper.fix_sentence_endings + .. attribute:: fix_sentence_endings - (default: ``False``) If true, :class:`TextWrapper` attempts to detect sentence - endings and ensure that sentences are always separated by exactly two spaces. - This is generally desired for text in a monospaced font. However, the sentence - detection algorithm is imperfect: it assumes that a sentence ending consists of - a lowercase letter followed by one of ``'.'``, ``'!'``, or ``'?'``, possibly - followed by one of ``'"'`` or ``"'"``, followed by a space. One problem with - this is algorithm is that it is unable to detect the difference between "Dr." in - :: + (default: ``False``) If true, :class:`TextWrapper` attempts to detect + sentence endings and ensure that sentences are always separated by exactly + two spaces. This is generally desired for text in a monospaced font. + However, the sentence detection algorithm is imperfect: it assumes that a + sentence ending consists of a lowercase letter followed by one of ``'.'``, + ``'!'``, or ``'?'``, possibly followed by one of ``'"'`` or ``"'"``, + followed by a space. One problem with this is algorithm is that it is + unable to detect the difference between "Dr." in :: - [...] Dr. Frankenstein's monster [...] + [...] Dr. Frankenstein's monster [...] - and "Spot." in :: + and "Spot." in :: - [...] See Spot. See Spot run [...] + [...] See Spot. See Spot run [...] - :attr:`fix_sentence_endings` is false by default. + :attr:`fix_sentence_endings` is false by default. - Since the sentence detection algorithm relies on ``string.lowercase`` for the - definition of "lowercase letter," and a convention of using two spaces after - a period to separate sentences on the same line, it is specific to - English-language texts. + Since the sentence detection algorithm relies on ``string.lowercase`` for + the definition of "lowercase letter," and a convention of using two spaces + after a period to separate sentences on the same line, it is specific to + English-language texts. -.. attribute:: TextWrapper.break_long_words + .. attribute:: break_long_words - (default: ``True``) If true, then words longer than :attr:`width` will be broken - in order to ensure that no lines are longer than :attr:`width`. If it is false, - long words will not be broken, and some lines may be longer than :attr:`width`. - (Long words will be put on a line by themselves, in order to minimize the amount - by which :attr:`width` is exceeded.) + (default: ``True``) If true, then words longer than :attr:`width` will be + broken in order to ensure that no lines are longer than :attr:`width`. If + it is false, long words will not be broken, and some lines may be longer + than :attr:`width`. (Long words will be put on a line by themselves, in + order to minimize the amount by which :attr:`width` is exceeded.) -:class:`TextWrapper` also provides two public methods, analogous to the -module-level convenience functions: + :class:`TextWrapper` also provides two public methods, analogous to the + module-level convenience functions: -.. method:: TextWrapper.wrap(text) + .. method:: wrap(text) - Wraps the single paragraph in *text* (a string) so every line is at most - :attr:`width` characters long. All wrapping options are taken from instance - attributes of the :class:`TextWrapper` instance. Returns a list of output lines, - without final newlines. + Wraps the single paragraph in *text* (a string) so every line is at most + :attr:`width` characters long. All wrapping options are taken from + instance attributes of the :class:`TextWrapper` instance. Returns a list + of output lines, without final newlines. -.. method:: TextWrapper.fill(text) + .. method:: fill(text) - Wraps the single paragraph in *text*, and returns a single string containing the - wrapped paragraph. + Wraps the single paragraph in *text*, and returns a single string + containing the wrapped paragraph. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/threading.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/threading.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/threading.rst Wed Apr 30 15:57:13 2008 @@ -724,3 +724,26 @@ with some_rlock: print("some_rlock is locked while this executes") + +.. _threaded-imports: + +Importing in threaded code +-------------------------- + +While the import machinery is thread safe, there are two key +restrictions on threaded imports due to inherent limitations in the way +that thread safety is provided: + +* Firstly, other than in the main module, an import should not have the + side effect of spawning a new thread and then waiting for that thread in + any way. Failing to abide by this restriction can lead to a deadlock if + the spawned thread directly or indirectly attempts to import a module. +* Secondly, all import attempts must be completed before the interpreter + starts shutting itself down. This can be most easily achieved by only + performing imports from non-daemon threads created through the threading + module. Daemon threads and threads created directly with the thread + module will require some other form of synchronization to ensure they do + not attempt imports after system shutdown has commenced. Failure to + abide by this restriction will lead to intermittent exceptions and + crashes during interpreter shutdown (as the late imports attempt to + access machinery which is no longer in a valid state). Modified: python/branches/py3k-ctypes-pep3118/Doc/library/time.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/time.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/time.rst Wed Apr 30 15:57:13 2008 @@ -350,11 +350,12 @@ The default values used to fill in any missing data when more accurate values cannot be inferred are ``(1900, 1, 1, 0, 0, 0, 0, 1, -1)``. - For example:: + For example: >>> import time - >>> time.strptime("30 Nov 00", "%d %b %y") - (2000, 11, 30, 0, 0, 0, 3, 335, -1) + >>> time.strptime("30 Nov 00", "%d %b %y") # doctest: +NORMALIZE_WHITESPACE + time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0, + tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1) Support for the ``%Z`` directive is based on the values contained in ``tzname`` and whether ``daylight`` is true. Because of this, it is platform-specific Modified: python/branches/py3k-ctypes-pep3118/Doc/library/tix.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/tix.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/tix.rst Wed Apr 30 15:57:13 2008 @@ -35,7 +35,7 @@ `Tix Programming Guide `_ On-line version of the programmer's reference material. - `Tix Development Applications `_ + `Tix Development Applications `_ Tix applications for development of Tix and Tkinter programs. Tide applications work under Tk or Tkinter, and include :program:`TixInspect`, an inspector to remotely modify and debug Tix/Tk/Tkinter applications. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/tkinter.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/tkinter.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/tkinter.rst Wed Apr 30 15:57:13 2008 @@ -21,7 +21,7 @@ `An Introduction to Tkinter `_ Fredrik Lundh's on-line reference material. - `Tkinter reference: a GUI for Python `_ + `Tkinter reference: a GUI for Python `_ On-line reference material. `Tkinter for JPython `_ Modified: python/branches/py3k-ctypes-pep3118/Doc/library/tokenize.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/tokenize.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/tokenize.rst Wed Apr 30 15:57:13 2008 @@ -9,50 +9,34 @@ The :mod:`tokenize` module provides a lexical scanner for Python source code, -implemented in Python. The scanner in this module returns comments as tokens as -well, making it useful for implementing "pretty-printers," including colorizers -for on-screen displays. +implemented in Python. The scanner in this module returns comments as tokens +as well, making it useful for implementing "pretty-printers," including +colorizers for on-screen displays. The primary entry point is a :term:`generator`: -.. function:: generate_tokens(readline) +.. function:: tokenize(readline) - The :func:`generate_tokens` generator requires one argment, *readline*, which + The :func:`tokenize` generator requires one argument, *readline*, which must be a callable object which provides the same interface as the :meth:`readline` method of built-in file objects (see section - :ref:`bltin-file-objects`). Each call to the function should return one line of - input as a string. + :ref:`bltin-file-objects`). Each call to the function should return one + line of input as bytes. - The generator produces 5-tuples with these members: the token type; the token - string; a 2-tuple ``(srow, scol)`` of ints specifying the row and column where - the token begins in the source; a 2-tuple ``(erow, ecol)`` of ints specifying - the row and column where the token ends in the source; and the line on which the - token was found. The line passed is the *logical* line; continuation lines are - included. - - -An older entry point is retained for backward compatibility: - -.. function:: tokenize(readline[, tokeneater]) - - The :func:`tokenize` function accepts two parameters: one representing the input - stream, and one providing an output mechanism for :func:`tokenize`. - - The first parameter, *readline*, must be a callable object which provides the - same interface as the :meth:`readline` method of built-in file objects (see - section :ref:`bltin-file-objects`). Each call to the function should return one - line of input as a string. Alternately, *readline* may be a callable object that - signals completion by raising :exc:`StopIteration`. - - The second parameter, *tokeneater*, must also be a callable object. It is - called once for each token, with five arguments, corresponding to the tuples - generated by :func:`generate_tokens`. + The generator produces 5-tuples with these members: the token type; the + token string; a 2-tuple ``(srow, scol)`` of ints specifying the row and + column where the token begins in the source; a 2-tuple ``(erow, ecol)`` of + ints specifying the row and column where the token ends in the source; and + the line on which the token was found. The line passed is the *logical* + line; continuation lines are included. + + tokenize determines the source encoding of the file by looking for a utf-8 + bom or encoding cookie, according to :pep:`263`. All constants from the :mod:`token` module are also exported from -:mod:`tokenize`, as are two additional token type values that might be passed to -the *tokeneater* function by :func:`tokenize`: +:mod:`tokenize`, as are three additional token type values: .. data:: COMMENT @@ -62,55 +46,95 @@ .. data:: NL Token value used to indicate a non-terminating newline. The NEWLINE token - indicates the end of a logical line of Python code; NL tokens are generated when - a logical line of code is continued over multiple physical lines. + indicates the end of a logical line of Python code; NL tokens are generated + when a logical line of code is continued over multiple physical lines. -Another function is provided to reverse the tokenization process. This is useful -for creating tools that tokenize a script, modify the token stream, and write -back the modified script. +.. data:: ENCODING -.. function:: untokenize(iterable) + Token value that indicates the encoding used to decode the source bytes + into text. The first token returned by :func:`tokenize` will always be an + ENCODING token. + + +Another function is provided to reverse the tokenization process. This is +useful for creating tools that tokenize a script, modify the token stream, and +write back the modified script. - Converts tokens back into Python source code. The *iterable* must return - sequences with at least two elements, the token type and the token string. Any - additional sequence elements are ignored. - - The reconstructed script is returned as a single string. The result is - guaranteed to tokenize back to match the input so that the conversion is - lossless and round-trips are assured. The guarantee applies only to the token - type and token string as the spacing between tokens (column positions) may - change. +.. function:: untokenize(iterable) + + Converts tokens back into Python source code. The *iterable* must return + sequences with at least two elements, the token type and the token string. + Any additional sequence elements are ignored. + + The reconstructed script is returned as a single string. The result is + guaranteed to tokenize back to match the input so that the conversion is + lossless and round-trips are assured. The guarantee applies only to the + token type and token string as the spacing between tokens (column + positions) may change. + + It returns bytes, encoded using the ENCODING token, which is the first + token sequence output by :func:`tokenize`. + + +:func:`tokenize` needs to detect the encoding of source files it tokenizes. The +function it uses to do this is available: + +.. function:: detect_encoding(readline) + + The :func:`detect_encoding` function is used to detect the encoding that + should be used to decode a Python source file. It requires one argment, + readline, in the same way as the :func:`tokenize` generator. + + It will call readline a maximum of twice, and return the encoding used + (as a string) and a list of any lines (not decoded from bytes) it has read + in. + + It detects the encoding from the presence of a utf-8 bom or an encoding + cookie as specified in pep-0263. If both a bom and a cookie are present, + but disagree, a SyntaxError will be raised. + + If no encoding is specified, then the default of 'utf-8' will be returned. + Example of a script re-writer that transforms float literals into Decimal objects:: - def decistmt(s): - """Substitute Decimals for floats in a string of statements. + def decistmt(s): + """Substitute Decimals for floats in a string of statements. + + >>> from decimal import Decimal + >>> s = 'print(+21.3e-5*-.1234/81.7)' + >>> decistmt(s) + "print (+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))" + + The format of the exponent is inherited from the platform C library. + Known cases are "e-007" (Windows) and "e-07" (not Windows). Since + we're only showing 12 digits, and the 13th isn't close to 5, the + rest of the output should be platform-independent. + + >>> exec(s) #doctest: +ELLIPSIS + -3.21716034272e-0...7 + + Output from calculations with Decimal should be identical across all + platforms. + + >>> exec(decistmt(s)) + -3.217160342717258261933904529E-7 + """ + result = [] + g = tokenize(BytesIO(s.encode('utf-8')).readline) # tokenize the string + for toknum, tokval, _, _, _ in g: + if toknum == NUMBER and '.' in tokval: # replace NUMBER tokens + result.extend([ + (NAME, 'Decimal'), + (OP, '('), + (STRING, repr(tokval)), + (OP, ')') + ]) + else: + result.append((toknum, tokval)) + return untokenize(result).decode('utf-8') - >>> from decimal import Decimal - >>> s = 'print(+21.3e-5*-.1234/81.7)' - >>> decistmt(s) - "print(+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))" - - >>> exec(s) - -3.21716034272e-007 - >>> exec(decistmt(s)) - -3.217160342717258261933904529E-7 - - """ - result = [] - g = generate_tokens(StringIO(s).readline) # tokenize the string - for toknum, tokval, _, _, _ in g: - if toknum == NUMBER and '.' in tokval: # replace NUMBER tokens - result.extend([ - (NAME, 'Decimal'), - (OP, '('), - (STRING, repr(tokval)), - (OP, ')') - ]) - else: - result.append((toknum, tokval)) - return untokenize(result) Modified: python/branches/py3k-ctypes-pep3118/Doc/library/trace.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/trace.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/trace.rst Wed Apr 30 15:57:13 2008 @@ -80,7 +80,7 @@ --------------------- -.. class:: Trace([count=1[, trace=1[, countfuncs=0[, countcallers=0[, ignoremods=()[, ignoredirs=()[, infile=None[, outfile=None]]]]]]]]) +.. class:: Trace([count=1[, trace=1[, countfuncs=0[, countcallers=0[, ignoremods=()[, ignoredirs=()[, infile=None[, outfile=None[, timing=False]]]]]]]]]) Create an object to trace execution of a single statement or expression. All parameters are optional. *count* enables counting of line numbers. *trace* @@ -89,7 +89,8 @@ *ignoremods* is a list of modules or packages to ignore. *ignoredirs* is a list of directories whose modules or packages should be ignored. *infile* is the file from which to read stored count information. *outfile* is a file in which - to write updated count information. + to write updated count information. *timing* enables a timestamp relative + to when tracing was started to be displayed. .. method:: Trace.run(cmd) Modified: python/branches/py3k-ctypes-pep3118/Doc/library/traceback.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/traceback.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/traceback.rst Wed Apr 30 15:57:13 2008 @@ -42,7 +42,7 @@ .. function:: print_exc([limit[, file]]) - This is a shorthand for ``print_exception(*sys.exc_info()``. + This is a shorthand for ``print_exception(*sys.exc_info())``. .. function:: format_exc([limit]) @@ -172,26 +172,26 @@ lumberjack() except: exceptionType, exceptionValue, exceptionTraceback = sys.exc_info() - print "*** print_tb:" + print("*** print_tb:") traceback.print_tb(exceptionTraceback, limit=1, file=sys.stdout) - print "*** print_exception:" + print("*** print_exception:") traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback, limit=2, file=sys.stdout) - print "*** print_exc:" + print("*** print_exc:") traceback.print_exc() - print "*** format_exc, first and last line:" + print("*** format_exc, first and last line:") formatted_lines = traceback.format_exc().splitlines() - print formatted_lines[0] - print formatted_lines[-1] - print "*** format_exception:" - print repr(traceback.format_exception(exceptionType, exceptionValue, - exceptionTraceback)) - print "*** extract_tb:" - print repr(traceback.extract_tb(exceptionTraceback)) - print "*** format_tb:" - print repr(traceback.format_tb(exceptionTraceback)) - print "*** tb_lineno:", traceback.tb_lineno(exceptionTraceback) - print "*** print_last:" + print(formatted_lines[0]) + print(formatted_lines[-1]) + print("*** format_exception:") + print(repr(traceback.format_exception(exceptionType, exceptionValue, + exceptionTraceback))) + print("*** extract_tb:") + print(repr(traceback.extract_tb(exceptionTraceback))) + print("*** format_tb:") + print(repr(traceback.format_tb(exceptionTraceback))) + print("*** tb_lineno:", traceback.tb_lineno(exceptionTraceback)) + print("*** print_last:") traceback.print_last() @@ -249,8 +249,8 @@ ... >>> def lumberstack(): ... traceback.print_stack() - ... print repr(traceback.extract_stack()) - ... print repr(traceback.format_stack()) + ... print(repr(traceback.extract_stack())) + ... print(repr(traceback.format_stack())) ... >>> another_function() File "", line 10, in @@ -261,10 +261,10 @@ traceback.print_stack() [('', 10, '', 'another_function()'), ('', 3, 'another_function', 'lumberstack()'), - ('', 7, 'lumberstack', 'print repr(traceback.extract_stack())')] + ('', 7, 'lumberstack', 'print(repr(traceback.extract_stack()))')] [' File "", line 10, in \n another_function()\n', ' File "", line 3, in another_function\n lumberstack()\n', - ' File "", line 8, in lumberstack\n print repr(traceback.format_stack())\n'] + ' File "", line 8, in lumberstack\n print(repr(traceback.format_stack()))\n'] This last example demonstrates the final few formatting functions:: Modified: python/branches/py3k-ctypes-pep3118/Doc/library/types.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/types.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/types.rst Wed Apr 30 15:57:13 2008 @@ -86,15 +86,17 @@ .. data:: GetSetDescriptorType - The type of objects defined in extension modules with ``PyGetSetDef``, such as - ``FrameType.f_locals`` or ``array.array.typecode``. This constant is not - defined in implementations of Python that do not have such extension types, so - for portable code use ``hasattr(types, 'GetSetDescriptorType')``. + The type of objects defined in extension modules with ``PyGetSetDef``, such + as ``FrameType.f_locals`` or ``array.array.typecode``. This type is used as + descriptor for object attributes; it has the same purpose as the + :class:`property` type, but for classes defined in extension modules. .. data:: MemberDescriptorType - The type of objects defined in extension modules with ``PyMemberDef``, such as - ``datetime.timedelta.days``. This constant is not defined in implementations of - Python that do not have such extension types, so for portable code use - ``hasattr(types, 'MemberDescriptorType')``. + The type of objects defined in extension modules with ``PyMemberDef``, such + as ``datetime.timedelta.days``. This type is used as descriptor for simple C + data members which use standard conversion functions; it has the same purpose + as the :class:`property` type, but for classes defined in extension modules. + In other implementations of Python, this type may be identical to + ``GetSetDescriptorType``. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/undoc.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/undoc.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/undoc.rst Wed Apr 30 15:57:13 2008 @@ -61,18 +61,6 @@ :synopsis: Rudimentary decoder for AppleSingle format files. - -:mod:`buildtools` --- Helper module for BuildApplet and Friends ---------------------------------------------------------------- - -.. module:: buildtools - :platform: Mac - :synopsis: Helper module for BuildApplet, BuildApplication and macfreeze. - - -.. deprecated:: 2.4 - - :mod:`icopen` --- Internet Config replacement for :meth:`open` -------------------------------------------------------------- Modified: python/branches/py3k-ctypes-pep3118/Doc/library/unicodedata.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/unicodedata.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/unicodedata.rst Wed Apr 30 15:57:13 2008 @@ -27,72 +27,72 @@ .. function:: lookup(name) Look up character by name. If a character with the given name is found, return - the corresponding Unicode character. If not found, :exc:`KeyError` is raised. + the corresponding character. If not found, :exc:`KeyError` is raised. -.. function:: name(unichr[, default]) +.. function:: name(chr[, default]) - Returns the name assigned to the Unicode character *unichr* as a string. If no + Returns the name assigned to the character *chr* as a string. If no name is defined, *default* is returned, or, if not given, :exc:`ValueError` is raised. -.. function:: decimal(unichr[, default]) +.. function:: decimal(chr[, default]) - Returns the decimal value assigned to the Unicode character *unichr* as integer. + Returns the decimal value assigned to the character *chr* as integer. If no such value is defined, *default* is returned, or, if not given, :exc:`ValueError` is raised. -.. function:: digit(unichr[, default]) +.. function:: digit(chr[, default]) - Returns the digit value assigned to the Unicode character *unichr* as integer. + Returns the digit value assigned to the character *chr* as integer. If no such value is defined, *default* is returned, or, if not given, :exc:`ValueError` is raised. -.. function:: numeric(unichr[, default]) +.. function:: numeric(chr[, default]) - Returns the numeric value assigned to the Unicode character *unichr* as float. + Returns the numeric value assigned to the character *chr* as float. If no such value is defined, *default* is returned, or, if not given, :exc:`ValueError` is raised. -.. function:: category(unichr) +.. function:: category(chr) - Returns the general category assigned to the Unicode character *unichr* as + Returns the general category assigned to the character *chr* as string. -.. function:: bidirectional(unichr) +.. function:: bidirectional(chr) - Returns the bidirectional category assigned to the Unicode character *unichr* as + Returns the bidirectional category assigned to the character *chr* as string. If no such value is defined, an empty string is returned. -.. function:: combining(unichr) +.. function:: combining(chr) - Returns the canonical combining class assigned to the Unicode character *unichr* + Returns the canonical combining class assigned to the character *chr* as integer. Returns ``0`` if no combining class is defined. -.. function:: east_asian_width(unichr) +.. function:: east_asian_width(chr) - Returns the east asian width assigned to the Unicode character *unichr* as + Returns the east asian width assigned to the character *chr* as string. -.. function:: mirrored(unichr) +.. function:: mirrored(chr) - Returns the mirrored property assigned to the Unicode character *unichr* as + Returns the mirrored property assigned to the character *chr* as integer. Returns ``1`` if the character has been identified as a "mirrored" character in bidirectional text, ``0`` otherwise. -.. function:: decomposition(unichr) +.. function:: decomposition(chr) - Returns the character decomposition mapping assigned to the Unicode character - *unichr* as string. An empty string is returned in case no such mapping is + Returns the character decomposition mapping assigned to the character + *chr* as string. An empty string is returned in case no such mapping is defined. @@ -142,20 +142,21 @@ Unicode database version 3.2 instead, for applications that require this specific version of the Unicode database (such as IDNA). -Examples:: +Examples: + >>> import unicodedata >>> unicodedata.lookup('LEFT CURLY BRACKET') u'{' - >>> unicodedata.name(u'/') + >>> unicodedata.name('/') 'SOLIDUS' - >>> unicodedata.decimal(u'9') + >>> unicodedata.decimal('9') 9 - >>> unicodedata.decimal(u'a') + >>> unicodedata.decimal('a') Traceback (most recent call last): File "", line 1, in ? ValueError: not a decimal - >>> unicodedata.category(u'A') # 'L'etter, 'u'ppercase + >>> unicodedata.category('A') # 'L'etter, 'u'ppercase 'Lu' - >>> unicodedata.bidirectional(u'\u0660') # 'A'rabic, 'N'umber + >>> unicodedata.bidirectional('\u0660') # 'A'rabic, 'N'umber 'AN' Modified: python/branches/py3k-ctypes-pep3118/Doc/library/unittest.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/unittest.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/unittest.rst Wed Apr 30 15:57:13 2008 @@ -562,6 +562,7 @@ .. method:: TestCase.assert_(expr[, msg]) TestCase.failUnless(expr[, msg]) + TestCase.assertTrue(expr[, msg]) Signal a test failure if *expr* is false; the explanation for the error will be *msg* if given, otherwise it will be :const:`None`. @@ -618,6 +619,7 @@ .. method:: TestCase.failIf(expr[, msg]) + TestCase.assertFalse(expr[, msg]) The inverse of the :meth:`failUnless` method is the :meth:`failIf` method. This signals a test failure if *expr* is true, with *msg* or :const:`None` for the Modified: python/branches/py3k-ctypes-pep3118/Doc/library/unix.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/unix.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/unix.rst Wed Apr 30 15:57:13 2008 @@ -17,7 +17,6 @@ spwd.rst grp.rst crypt.rst - dl.rst termios.rst tty.rst pty.rst Modified: python/branches/py3k-ctypes-pep3118/Doc/library/urllib.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/urllib.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/urllib.rst Wed Apr 30 15:57:13 2008 @@ -107,10 +107,6 @@ filehandle = urllib.urlopen(some_url, proxies=None) filehandle = urllib.urlopen(some_url) - The :func:`urlopen` function does not support explicit proxy specification. If - you need to override environmental proxy settings, use :class:`URLopener`, or a - subclass such as :class:`FancyURLopener`. - Proxies which require authentication for use are not currently supported; this is considered an implementation limitation. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/urllib2.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/urllib2.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/urllib2.rst Wed Apr 30 15:57:13 2008 @@ -33,10 +33,12 @@ This function returns a file-like object with two additional methods: - * :meth:`geturl` --- return the URL of the resource retrieved + * :meth:`geturl` --- return the URL of the resource retrieved, commonly used to + determine if a redirect was followed - * :meth:`info` --- return the meta-information of the page, as a dictionary-like - object + * :meth:`info` --- return the meta-information of the page, such as headers, in + the form of an ``httplib.HTTPMessage`` instance + (see `Quick Reference to HTTP Headers `_) Raises :exc:`URLError` on errors. @@ -81,18 +83,32 @@ The handlers raise this exception (or derived exceptions) when they run into a problem. It is a subclass of :exc:`IOError`. + .. attribute:: reason + + The reason for this error. It can be a message string or another exception + instance (:exc:`socket.error` for remote URLs, :exc:`OSError` for local + URLs). + .. exception:: HTTPError - A subclass of :exc:`URLError`, it can also function as a non-exceptional - file-like return value (the same thing that :func:`urlopen` returns). This - is useful when handling exotic HTTP errors, such as requests for - authentication. + Though being an exception (a subclass of :exc:`URLError`), an :exc:`HTTPError` + can also function as a non-exceptional file-like return value (the same thing + that :func:`urlopen` returns). This is useful when handling exotic HTTP + errors, such as requests for authentication. + + .. attribute:: code + + An HTTP status code as defined in `RFC 2616 `_. + This numeric value corresponds to a value found in the dictionary of + codes as found in :attr:`BaseHTTPServer.BaseHTTPRequestHandler.responses`. + + The following classes are provided: -.. class:: Request(url[, data][, headers] [, origin_req_host][, unverifiable]) +.. class:: Request(url[, data][, headers][, origin_req_host][, unverifiable]) This class is an abstraction of a URL request. @@ -107,7 +123,12 @@ returns a string in this format. *headers* should be a dictionary, and will be treated as if :meth:`add_header` - was called with each key and value as arguments. + was called with each key and value as arguments. This is often used to "spoof" + the ``User-Agent`` header, which is used by a browser to identify itself -- + some HTTP servers only allow requests coming from common browsers as opposed + to scripts. For example, Mozilla Firefox may identify itself as ``"Mozilla/5.0 + (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"``, while :mod:`urllib2`'s + default user agent string is ``"Python-urllib/2.6"`` (on Python 2.6). The final two arguments are only of interest for correct handling of third-party HTTP cookies: @@ -158,6 +179,7 @@ Cause requests to go through a proxy. If *proxies* is given, it must be a dictionary mapping protocol names to URLs of proxies. The default is to read the list of proxies from the environment variables :envvar:`_proxy`. + To disable autodetected proxy pass an empty dictionary. .. class:: HTTPPasswordMgr() Modified: python/branches/py3k-ctypes-pep3118/Doc/library/urlparse.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/urlparse.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/urlparse.rst Wed Apr 30 15:57:13 2008 @@ -35,12 +35,13 @@ smaller parts (for example, the network location is a single string), and % escapes are not expanded. The delimiters as shown above are not part of the result, except for a leading slash in the *path* component, which is retained if - present. For example:: + present. For example: >>> from urlparse import urlparse >>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html') - >>> o - ('http', 'www.cwi.nl:80', '/%7Eguido/Python.html', '', '', '') + >>> o # doctest: +NORMALIZE_WHITESPACE + ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html', + params='', query='', fragment='') >>> o.scheme 'http' >>> o.port @@ -151,7 +152,7 @@ Construct a full ("absolute") URL by combining a "base URL" (*base*) with another URL (*url*). Informally, this uses components of the base URL, in particular the addressing scheme, the network location and (part of) the path, - to provide missing components in the relative URL. For example:: + to provide missing components in the relative URL. For example: >>> from urlparse import urljoin >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html') @@ -165,7 +166,7 @@ If *url* is an absolute URL (that is, starting with ``//`` or ``scheme://``), the *url*'s host name and/or scheme will be present in the result. For example: - :: + .. doctest:: >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', ... '//www.python.org/%7Eguido') @@ -216,7 +217,7 @@ and fragment identifiers will be removed. The result of this method is a fixpoint if passed back through the original - parsing function:: + parsing function: >>> import urlparse >>> url = 'HTTP://www.Python.org/doc/#' Deleted: python/branches/py3k-ctypes-pep3118/Doc/library/userdict.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/userdict.rst Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,185 +0,0 @@ - -:mod:`UserDict` --- Class wrapper for dictionary objects -======================================================== - -.. module:: UserDict - :synopsis: Class wrapper for dictionary objects. - - -The module defines a mixin, :class:`DictMixin`, defining all dictionary methods -for classes that already have a minimum mapping interface. This greatly -simplifies writing classes that need to be substitutable for dictionaries (such -as the shelve module). - -This also module defines a class, :class:`UserDict`, that acts as a wrapper -around dictionary objects. The need for this class has been largely supplanted -by the ability to subclass directly from :class:`dict` (a feature that became -available starting with Python version 2.2). Prior to the introduction of -:class:`dict`, the :class:`UserDict` class was used to create dictionary-like -sub-classes that obtained new behaviors by overriding existing methods or adding -new ones. - -The :mod:`UserDict` module defines the :class:`UserDict` class and -:class:`DictMixin`: - - -.. class:: UserDict([initialdata]) - - Class that simulates a dictionary. The instance's contents are kept in a - regular dictionary, which is accessible via the :attr:`data` attribute of - :class:`UserDict` instances. If *initialdata* is provided, :attr:`data` is - initialized with its contents; note that a reference to *initialdata* will not - be kept, allowing it be used for other purposes. - - .. note:: - - For backward compatibility, instances of :class:`UserDict` are not - iterable. - - -.. class:: IterableUserDict([initialdata]) - - Subclass of :class:`UserDict` that supports direct iteration (e.g. ``for key in - myDict``). - -In addition to supporting the methods and operations of mappings (see section -:ref:`typesmapping`), :class:`UserDict` and :class:`IterableUserDict` instances -provide the following attribute: - - -.. attribute:: IterableUserDict.data - - A real dictionary used to store the contents of the :class:`UserDict` class. - - -.. class:: DictMixin() - - Mixin defining all dictionary methods for classes that already have a minimum - dictionary interface including :meth:`__getitem__`, :meth:`__setitem__`, - :meth:`__delitem__`, and :meth:`keys`. - - This mixin should be used as a superclass. Adding each of the above methods - adds progressively more functionality. For instance, defining all but - :meth:`__delitem__` will preclude only :meth:`pop` and :meth:`popitem` from the - full interface. - - In addition to the four base methods, progressively more efficiency comes - with defining :meth:`__contains__` and :meth:`__iter__`. - - Since the mixin has no knowledge of the subclass constructor, it does not define - :meth:`__init__` or :meth:`copy`. - - -:mod:`UserList` --- Class wrapper for list objects -================================================== - -.. module:: UserList - :synopsis: Class wrapper for list objects. - - -.. note:: - - This module is available for backward compatibility only. If you are writing - code that does not need to work with versions of Python earlier than Python 2.2, - please consider subclassing directly from the built-in :class:`list` type. - -This module defines a class that acts as a wrapper around list objects. It is a -useful base class for your own list-like classes, which can inherit from them -and override existing methods or add new ones. In this way one can add new -behaviors to lists. - -The :mod:`UserList` module defines the :class:`UserList` class: - - -.. class:: UserList([list]) - - Class that simulates a list. The instance's contents are kept in a regular - list, which is accessible via the :attr:`data` attribute of - :class:`UserList` - instances. The instance's contents are initially set to a copy of *list*, - defaulting to the empty list ``[]``. *list* can be any iterable, for - example a real Python list or a :class:`UserList` object. - -In addition to supporting the methods and operations of mutable sequences (see -section :ref:`typesseq`), :class:`UserList` instances provide the following -attribute: - - -.. attribute:: UserList.data - - A real Python list object used to store the contents of the :class:`UserList` - class. - -**Subclassing requirements:** Subclasses of :class:`UserList` are expect to -offer a constructor which can be called with either no arguments or one -argument. List operations which return a new sequence attempt to create an -instance of the actual implementation class. To do so, it assumes that the -constructor can be called with a single parameter, which is a sequence object -used as a data source. - -If a derived class does not wish to comply with this requirement, all of the -special methods supported by this class will need to be overridden; please -consult the sources for information about the methods which need to be provided -in that case. - - -:mod:`UserString` --- Class wrapper for string objects -====================================================== - -.. module:: UserString - :synopsis: Class wrapper for string objects. -.. moduleauthor:: Peter Funk -.. sectionauthor:: Peter Funk - - -.. note:: - - This :class:`UserString` class from this module is available for backward - compatibility only. If you are writing code that does not need to work with - versions of Python earlier than Python 2.2, please consider subclassing directly - from the built-in :class:`str` type instead of using :class:`UserString` (there - is no built-in equivalent to :class:`MutableString`). - -This module defines a class that acts as a wrapper around string objects. It is -a useful base class for your own string-like classes, which can inherit from -them and override existing methods or add new ones. In this way one can add new -behaviors to strings. - -It should be noted that these classes are highly inefficient compared to real -string or Unicode objects; this is especially the case for -:class:`MutableString`. - -The :mod:`UserString` module defines the following classes: - - -.. class:: UserString([sequence]) - - Class that simulates a string or a Unicode string object. The instance's - content is kept in a regular string or Unicode string object, which is - accessible via the :attr:`data` attribute of :class:`UserString` instances. The - instance's contents are initially set to a copy of *sequence*. *sequence* can - be either a regular Python string or Unicode string, an instance of - :class:`UserString` (or a subclass) or an arbitrary sequence which can be - converted into a string using the built-in :func:`str` function. - - -.. class:: MutableString([sequence]) - - This class is derived from the :class:`UserString` above and redefines strings - to be *mutable*. Mutable strings can't be used as dictionary keys, because - dictionaries require *immutable* objects as keys. The main intention of this - class is to serve as an educational example for inheritance and necessity to - remove (override) the :meth:`__hash__` method in order to trap attempts to use a - mutable object as dictionary key, which would be otherwise very error prone and - hard to track down. - -In addition to supporting the methods and operations of string and Unicode -objects (see section :ref:`string-methods`), :class:`UserString` instances -provide the following attribute: - - -.. attribute:: MutableString.data - - A real Python string or Unicode object used to store the content of the - :class:`UserString` class. - Modified: python/branches/py3k-ctypes-pep3118/Doc/library/warnings.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/warnings.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/warnings.rst Wed Apr 30 15:57:13 2008 @@ -202,16 +202,16 @@ sources). -.. function:: showwarning(message, category, filename, lineno[, file]) +.. function:: showwarning(message, category, filename, lineno[, file[, line]]) Write a warning to a file. The default implementation calls - ``formatwarning(message, category, filename, lineno)`` and writes the resulting - string to *file*, which defaults to ``sys.stderr``. You may replace this - function with an alternative implementation by assigning to + ``formatwarning(message, category, filename, lineno, line)`` and writes the + resulting string to *file*, which defaults to ``sys.stderr``. You may replace + this function with an alternative implementation by assigning to ``warnings.showwarning``. -.. function:: formatwarning(message, category, filename, lineno) +.. function:: formatwarning(message, category, filename, lineno[, line]) Format a warning the standard way. This returns a string which may contain embedded newlines and ends in a newline. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/weakref.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/weakref.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/weakref.rst Wed Apr 30 15:57:13 2008 @@ -24,18 +24,20 @@ :term:`garbage collection` is free to destroy the referent and reuse its memory for something else. A primary use for weak references is to implement caches or mappings holding large objects, where it's desired that a large object not be -kept alive solely because it appears in a cache or mapping. For example, if you -have a number of large binary image objects, you may wish to associate a name -with each. If you used a Python dictionary to map names to images, or images to -names, the image objects would remain alive just because they appeared as values -or keys in the dictionaries. The :class:`WeakKeyDictionary` and -:class:`WeakValueDictionary` classes supplied by the :mod:`weakref` module are -an alternative, using weak references to construct mappings that don't keep -objects alive solely because they appear in the mapping objects. If, for -example, an image object is a value in a :class:`WeakValueDictionary`, then when -the last remaining references to that image object are the weak references held -by weak mappings, garbage collection can reclaim the object, and its -corresponding entries in weak mappings are simply deleted. +kept alive solely because it appears in a cache or mapping. + +For example, if you have a number of large binary image objects, you may wish to +associate a name with each. If you used a Python dictionary to map names to +images, or images to names, the image objects would remain alive just because +they appeared as values or keys in the dictionaries. The +:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` classes supplied by +the :mod:`weakref` module are an alternative, using weak references to construct +mappings that don't keep objects alive solely because they appear in the mapping +objects. If, for example, an image object is a value in a +:class:`WeakValueDictionary`, then when the last remaining references to that +image object are the weak references held by weak mappings, garbage collection +can reclaim the object, and its corresponding entries in weak mappings are +simply deleted. :class:`WeakKeyDictionary` and :class:`WeakValueDictionary` use weak references in their implementation, setting up callback functions on the weak references @@ -49,6 +51,12 @@ directly. The low-level machinery used by the weak dictionary implementations is exposed by the :mod:`weakref` module for the benefit of advanced uses. +.. note:: + + Weak references to an object are cleared before the object's :meth:`__del__` + is called, to ensure that the weak reference callback (if any) finds the + object still alive. + Not all objects can be weakly referenced; those objects which can include class instances, functions written in Python (but not in C), instance methods, sets, frozensets, file objects, :term:`generator`\s, type objects, :class:`DBcursor` @@ -61,7 +69,7 @@ class Dict(dict): pass - obj = Dict(red=1, green=2, blue=3) # this object is weak referencable + obj = Dict(red=1, green=2, blue=3) # this object is weak referenceable Extension types can easily be made to support weak references; see :ref:`weakref-support`. @@ -130,11 +138,11 @@ .. note:: - Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python + Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python dictionary, it must not change size when iterating over it. This can be - difficult to ensure for a :class:`WeakKeyDictionary` because actions performed - by the program during iteration may cause items in the dictionary to vanish "by - magic" (as a side effect of garbage collection). + difficult to ensure for a :class:`WeakKeyDictionary` because actions + performed by the program during iteration may cause items in the + dictionary to vanish "by magic" (as a side effect of garbage collection). :class:`WeakKeyDictionary` objects have the following additional methods. These expose the internal references directly. The references are not guaranteed to @@ -229,7 +237,7 @@ ---------------------- Weak reference objects have no attributes or methods, but do allow the referent -to be obtained, if it still exists, by calling it:: +to be obtained, if it still exists, by calling it: >>> import weakref >>> class Object: @@ -242,7 +250,7 @@ True If the referent no longer exists, calling the reference object returns -:const:`None`:: +:const:`None`: >>> del o, o2 >>> print(r()) Modified: python/branches/py3k-ctypes-pep3118/Doc/library/wsgiref.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/wsgiref.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/wsgiref.rst Wed Apr 30 15:57:13 2008 @@ -169,7 +169,7 @@ wrapper = FileWrapper(filelike, blksize=5) for chunk in wrapper: - print chunk + print(chunk) @@ -428,7 +428,7 @@ validator_app = validator(simple_app) httpd = make_server('', 8000, validator_app) - print "Listening on port 8000...." + print("Listening on port 8000....") httpd.serve_forever() @@ -720,7 +720,7 @@ return ["Hello World"] httpd = make_server('', 8000, hello_world_app) - print "Serving on port 8000..." + print("Serving on port 8000...") # Serve until process is killed httpd.serve_forever() Modified: python/branches/py3k-ctypes-pep3118/Doc/library/xml.dom.minidom.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/xml.dom.minidom.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/xml.dom.minidom.rst Wed Apr 30 15:57:13 2008 @@ -126,7 +126,7 @@ to discard children of that node. -.. method:: Node.writexml(writer[,indent=""[,addindent=""[,newl=""]]]) +.. method:: Node.writexml(writer[, indent=""[, addindent=""[, newl=""[, encoding=""]]]]) Write XML to the writer object. The writer should have a :meth:`write` method which matches that of the file object interface. The *indent* parameter is the @@ -147,13 +147,13 @@ document. Encoding this string in an encoding other than UTF-8 is likely incorrect, since UTF-8 is the default encoding of XML. - With an explicit *encoding* argument, the result is a byte string in the + With an explicit *encoding* [1]_ argument, the result is a byte string in the specified encoding. It is recommended that this argument is always specified. To avoid :exc:`UnicodeError` exceptions in case of unrepresentable text data, the encoding argument should be specified as "utf-8". -.. method:: Node.toprettyxml([indent[, newl[, encoding]]]) +.. method:: Node.toprettyxml([indent=""[, newl=""[, encoding=""]]]) Return a pretty-printed version of the document. *indent* specifies the indentation string and defaults to a tabulator; *newl* specifies the string @@ -212,7 +212,7 @@ ``boolean`` all map to Python integer objects. * The type ``DOMString`` maps to Python strings. :mod:`xml.dom.minidom` supports - either byte or Unicode strings, but will normally produce Unicode strings. + either bytes or strings, but will normally produce strings. Values of type ``DOMString`` may also be ``None`` where allowed to have the IDL ``null`` value by the DOM specification from the W3C. @@ -252,3 +252,9 @@ Most of these reflect information in the XML document that is not of general utility to most DOM users. +.. rubric:: Footnotes + +.. [#] The encoding string included in XML output should conform to the + appropriate standards. For example, "UTF-8" is valid, but "UTF8" is + not. See http://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl + and http://www.iana.org/assignments/character-sets . Modified: python/branches/py3k-ctypes-pep3118/Doc/library/xml.dom.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/xml.dom.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/xml.dom.rst Wed Apr 30 15:57:13 2008 @@ -506,7 +506,7 @@ ^^^^^^^^^^^^^^^^ A :class:`Document` represents an entire XML document, including its constituent -elements, attributes, processing instructions, comments etc. Remeber that it +elements, attributes, processing instructions, comments etc. Remember that it inherits properties from :class:`Node`. @@ -641,8 +641,8 @@ .. method:: Element.removeAttribute(name) - Remove an attribute by name. No exception is raised if there is no matching - attribute. + Remove an attribute by name. If there is no matching attribute, a + :exc:`NotFoundErr` is raised. .. method:: Element.removeAttributeNode(oldAttr) @@ -985,7 +985,7 @@ +------------------+-------------------------------------------+ Additionally, the :class:`DOMString` defined in the recommendation is mapped to -a Python string or Unicode string. Applications should be able to handle +a bytes or string object. Applications should be able to handle Unicode whenever a string is returned from the DOM. The IDL ``null`` value is mapped to ``None``, which may be accepted or Modified: python/branches/py3k-ctypes-pep3118/Doc/library/xml.etree.elementtree.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/xml.etree.elementtree.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/xml.etree.elementtree.rst Wed Apr 30 15:57:13 2008 @@ -43,10 +43,11 @@ .. function:: Comment([text]) - Comment element factory. This factory function creates a special element that - will be serialized as an XML comment. The comment string can be either an 8-bit - ASCII string or a Unicode string. *text* is a string containing the comment - string. Returns an element instance representing a comment. + Comment element factory. This factory function creates a special element + that will be serialized as an XML comment. The comment string can be either + an ASCII-only :class:`bytes` object or a :class:`str` object. *text* is a + string containing the comment string. Returns an element instance + representing a comment. .. function:: dump(elem) @@ -67,10 +68,11 @@ dependent, but it will always be compatible with the _ElementInterface class in this module. - The element name, attribute names, and attribute values can be either 8-bit - ASCII strings or Unicode strings. *tag* is the element name. *attrib* is an - optional dictionary, containing element attributes. *extra* contains additional - attributes, given as keyword arguments. Returns an element instance. + The element name, attribute names, and attribute values can be either an + ASCII-only :class:`bytes` object or a :class:`str` object. *tag* is the + element name. *attrib* is an optional dictionary, containing element + attributes. *extra* contains additional attributes, given as keyword + arguments. Returns an element instance. .. function:: fromstring(text) @@ -114,11 +116,11 @@ Subelement factory. This function creates an element instance, and appends it to an existing element. - The element name, attribute names, and attribute values can be either 8-bit - ASCII strings or Unicode strings. *parent* is the parent element. *tag* is the - subelement name. *attrib* is an optional dictionary, containing element - attributes. *extra* contains additional attributes, given as keyword arguments. - Returns an element instance. + The element name, attribute names, and attribute values can be an ASCII-only + :class:`bytes` object or a :class:`str` object. *parent* is the parent + element. *tag* is the subelement name. *attrib* is an optional dictionary, + containing element attributes. *extra* contains additional attributes, given + as keyword arguments. Returns an element instance. .. function:: tostring(element[, encoding]) @@ -275,7 +277,7 @@ with subelements: :meth:`__delitem__`, :meth:`__getitem__`, :meth:`__setitem__`, :meth:`__len__`. -Caution: Because Element objects do not define a :meth:`__nonzero__` method, +Caution: Because Element objects do not define a :meth:`__bool__` method, elements with no subelements will test as ``False``. :: element = root.find('foo') @@ -302,61 +304,63 @@ XML *file* if given. -.. method:: ElementTree._setroot(element) + .. method:: _setroot(element) - Replaces the root element for this tree. This discards the current contents of - the tree, and replaces it with the given element. Use with care. *element* is - an element instance. + Replaces the root element for this tree. This discards the current + contents of the tree, and replaces it with the given element. Use with + care. *element* is an element instance. -.. method:: ElementTree.find(path) + .. method:: find(path) - Finds the first toplevel element with given tag. Same as getroot().find(path). - *path* is the element to look for. Returns the first matching element, or - ``None`` if no element was found. + Finds the first toplevel element with given tag. Same as + getroot().find(path). *path* is the element to look for. Returns the + first matching element, or ``None`` if no element was found. -.. method:: ElementTree.findall(path) + .. method:: findall(path) - Finds all toplevel elements with the given tag. Same as getroot().findall(path). - *path* is the element to look for. Returns a list or :term:`iterator` containing all - matching elements, in document order. + Finds all toplevel elements with the given tag. Same as + getroot().findall(path). *path* is the element to look for. Returns a + list or :term:`iterator` containing all matching elements, in document + order. -.. method:: ElementTree.findtext(path[, default]) + .. method:: findtext(path[, default]) - Finds the element text for the first toplevel element with given tag. Same as - getroot().findtext(path). *path* is the toplevel element to look for. *default* - is the value to return if the element was not found. Returns the text content of - the first matching element, or the default value no element was found. Note - that if the element has is found, but has no text content, this method returns - an empty string. + Finds the element text for the first toplevel element with given tag. + Same as getroot().findtext(path). *path* is the toplevel element to look + for. *default* is the value to return if the element was not + found. Returns the text content of the first matching element, or the + default value no element was found. Note that if the element has is + found, but has no text content, this method returns an empty string. -.. method:: ElementTree.getiterator([tag]) + .. method:: getiterator([tag]) - Creates and returns a tree iterator for the root element. The iterator loops - over all elements in this tree, in section order. *tag* is the tag to look for - (default is to return all elements) + Creates and returns a tree iterator for the root element. The iterator + loops over all elements in this tree, in section order. *tag* is the tag + to look for (default is to return all elements) -.. method:: ElementTree.getroot() + .. method:: getroot() - Returns the root element for this tree. + Returns the root element for this tree. -.. method:: ElementTree.parse(source[, parser]) + .. method:: parse(source[, parser]) - Loads an external XML section into this element tree. *source* is a file name or - file object. *parser* is an optional parser instance. If not given, the - standard XMLTreeBuilder parser is used. Returns the section root element. + Loads an external XML section into this element tree. *source* is a file + name or file object. *parser* is an optional parser instance. If not + given, the standard XMLTreeBuilder parser is used. Returns the section + root element. -.. method:: ElementTree.write(file[, encoding]) + .. method:: write(file[, encoding]) - Writes the element tree to a file, as XML. *file* is a file name, or a file - object opened for writing. *encoding* is the output encoding (default is - US-ASCII). + Writes the element tree to a file, as XML. *file* is a file name, or a + file object opened for writing. *encoding* [1]_ is the output encoding + (default is US-ASCII). This is the XML file that is going to be manipulated:: @@ -417,28 +421,28 @@ Element instances when given. -.. method:: TreeBuilder.close() + .. method:: close() - Flushes the parser buffers, and returns the toplevel documen element. Returns an - Element instance. + Flushes the parser buffers, and returns the toplevel document + element. Returns an Element instance. -.. method:: TreeBuilder.data(data) + .. method:: data(data) - Adds text to the current element. *data* is a string. This should be either an - 8-bit string containing ASCII text, or a Unicode string. + Adds text to the current element. *data* is a string. This should be + either an ASCII-only :class:`bytes` object or a :class:`str` object. -.. method:: TreeBuilder.end(tag) + .. method:: end(tag) - Closes the current element. *tag* is the element name. Returns the closed - element. + Closes the current element. *tag* is the element name. Returns the closed + element. -.. method:: TreeBuilder.start(tag, attrs) + .. method:: start(tag, attrs) - Opens a new element. *tag* is the element name. *attrs* is a dictionary - containing element attributes. Returns the opened element. + Opens a new element. *tag* is the element name. *attrs* is a dictionary + containing element attributes. Returns the opened element. .. _elementtree-xmltreebuilder-objects: @@ -455,20 +459,20 @@ instance of the standard TreeBuilder class. -.. method:: XMLTreeBuilder.close() + .. method:: close() - Finishes feeding data to the parser. Returns an element structure. + Finishes feeding data to the parser. Returns an element structure. -.. method:: XMLTreeBuilder.doctype(name, pubid, system) + .. method:: doctype(name, pubid, system) - Handles a doctype declaration. *name* is the doctype name. *pubid* is the public - identifier. *system* is the system identifier. + Handles a doctype declaration. *name* is the doctype name. *pubid* is the + public identifier. *system* is the system identifier. -.. method:: XMLTreeBuilder.feed(data) + .. method:: feed(data) - Feeds data to the parser. *data* is encoded data. + Feeds data to the parser. *data* is encoded data. :meth:`XMLTreeBuilder.feed` calls *target*\'s :meth:`start` method for each opening tag, its :meth:`end` method for each closing tag, @@ -508,3 +512,12 @@ >>> parser.feed(exampleXml) >>> parser.close() 4 + + +.. rubric:: Footnotes + +.. [#] The encoding string included in XML output should conform to the + appropriate standards. For example, "UTF-8" is valid, but "UTF8" is + not. See http://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl + and http://www.iana.org/assignments/character-sets . + Modified: python/branches/py3k-ctypes-pep3118/Doc/library/xml.sax.handler.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/xml.sax.handler.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/xml.sax.handler.rst Wed Apr 30 15:57:13 2008 @@ -281,8 +281,8 @@ must come from the same external entity so that the Locator provides useful information. - *content* may be a Unicode string or a byte string; the ``expat`` reader module - produces always Unicode strings. + *content* may be a string or bytes instance; the ``expat`` reader module + always produces strings. .. note:: Modified: python/branches/py3k-ctypes-pep3118/Doc/library/xml.sax.reader.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/xml.sax.reader.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/xml.sax.reader.rst Wed Apr 30 15:57:13 2008 @@ -307,7 +307,7 @@ .. method:: InputSource.setCharacterStream(charfile) Set the character stream for this input source. (The stream must be a Python 1.6 - Unicode-wrapped file-like that performs conversion to Unicode strings.) + Unicode-wrapped file-like that performs conversion to strings.) If there is a character stream specified, the SAX parser will ignore any byte stream and will not attempt to open a URI connection to the system identifier. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/xmlrpclib.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/xmlrpclib.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/xmlrpclib.rst Wed Apr 30 15:57:13 2008 @@ -32,10 +32,7 @@ all clients and servers; see http://ontosys.com/xml-rpc/extensions.php for a description. The *use_datetime* flag can be used to cause date/time values to be presented as :class:`datetime.datetime` objects; this is false by default. - :class:`datetime.datetime`, :class:`datetime.date` and :class:`datetime.time` - objects may be passed to calls. :class:`datetime.date` objects are converted - with a time of "00:00:00". :class:`datetime.time` objects are converted using - today's date. + :class:`datetime.datetime` objects may be passed to calls. Both the HTTP and HTTPS transports support the URL syntax extension for HTTP Basic Authentication: ``http://user:pass at host:port/path``. The ``user:pass`` @@ -79,9 +76,7 @@ +---------------------------------+---------------------------------------------+ | :const:`dates` | in seconds since the epoch (pass in an | | | instance of the :class:`DateTime` class) or | - | | a :class:`datetime.datetime`, | - | | :class:`datetime.date` or | - | | :class:`datetime.time` instance | + | | a :class:`datetime.datetime` instance. | +---------------------------------+---------------------------------------------+ | :const:`binary data` | pass in an instance of the :class:`Binary` | | | wrapper class | @@ -194,7 +189,7 @@ return n%2 == 0 server = SimpleXMLRPCServer(("localhost", 8000)) - print "Listening on port 8000..." + print("Listening on port 8000...") server.register_function(is_even, "is_even") server.serve_forever() @@ -203,18 +198,18 @@ import xmlrpclib proxy = xmlrpclib.ServerProxy("http://localhost:8000/") - print "3 is even: %s" % str(proxy.is_even(3)) - print "100 is even: %s" % str(proxy.is_even(100)) + print("3 is even: %s" % str(proxy.is_even(3))) + print("100 is even: %s" % str(proxy.is_even(100))) .. _datetime-objects: DateTime Objects ---------------- -This class may be initialized with seconds since the epoch, a time tuple, an ISO -8601 time/date string, or a :class:`datetime.datetime`, :class:`datetime.date` -or :class:`datetime.time` instance. It has the following methods, supported -mainly for internal use by the marshalling/unmarshalling code: +This class may be initialized with seconds since the epoch, a time +tuple, an ISO 8601 time/date string, or a :class:`datetime.datetime` +instance. It has the following methods, supported mainly for internal +use by the marshalling/unmarshalling code: .. method:: DateTime.decode(string) @@ -241,7 +236,7 @@ return xmlrpclib.DateTime(today) server = SimpleXMLRPCServer(("localhost", 8000)) - print "Listening on port 8000..." + print("Listening on port 8000...") server.register_function(today, "today") server.serve_forever() @@ -255,7 +250,7 @@ today = proxy.today() # convert the ISO8601 string to a datetime object converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S") - print "Today: %s" % converted.strftime("%d.%m.%Y, %H:%M") + print("Today: %s" % converted.strftime("%d.%m.%Y, %H:%M")) .. _binary-objects: @@ -300,7 +295,7 @@ handle.close() server = SimpleXMLRPCServer(("localhost", 8000)) - print "Listening on port 8000..." + print("Listening on port 8000...") server.register_function(python_logo, 'python_logo') server.serve_forever() @@ -343,7 +338,7 @@ return x+y+0j server = SimpleXMLRPCServer(("localhost", 8000)) - print "Listening on port 8000..." + print("Listening on port 8000...") server.register_function(add, 'add') server.serve_forever() @@ -356,9 +351,9 @@ try: proxy.add(2, 5) except xmlrpclib.Fault, err: - print "A fault occured" - print "Fault code: %d" % err.faultCode - print "Fault string: %s" % err.faultString + print("A fault occured") + print("Fault code: %d" % err.faultCode) + print("Fault string: %s" % err.faultString) @@ -403,11 +398,11 @@ try: proxy.some_method() except xmlrpclib.ProtocolError, err: - print "A protocol error occured" - print "URL: %s" % err.url - print "HTTP/HTTPS headers: %s" % err.headers - print "Error code: %d" % err.errcode - print "Error message: %s" % err.errmsg + print("A protocol error occured") + print("URL: %s" % err.url) + print("HTTP/HTTPS headers: %s" % err.headers) + print("Error code: %d" % err.errcode) + print("Error message: %s" % err.errmsg) MultiCall Objects ----------------- @@ -444,7 +439,7 @@ # A simple server with simple arithmetic functions server = SimpleXMLRPCServer(("localhost", 8000)) - print "Listening on port 8000..." + print("Listening on port 8000...") server.register_multicall_functions() server.register_function(add, 'add') server.register_function(subtract, 'subtract') @@ -464,7 +459,7 @@ multicall.divide(7,3) result = multicall() - print "7+3=%d, 7-3=%d, 7*3=%d, 7/3=%d" % tuple(result) + print("7+3=%d, 7-3=%d, 7*3=%d, 7/3=%d" % tuple(result)) Convenience Functions @@ -495,10 +490,7 @@ ``None`` if no method name is present in the packet. If the XML-RPC packet represents a fault condition, this function will raise a :exc:`Fault` exception. The *use_datetime* flag can be used to cause date/time values to be presented as - :class:`datetime.datetime` objects; this is false by default. Note that even if - you call an XML-RPC method with :class:`datetime.date` or :class:`datetime.time` - objects, they are converted to :class:`DateTime` objects internally, so only - :class:`datetime.datetime` objects will be returned. + :class:`datetime.datetime` objects; this is false by default. .. _xmlrpc-client-example: Modified: python/branches/py3k-ctypes-pep3118/Doc/library/zipfile.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/zipfile.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/zipfile.rst Wed Apr 30 15:57:13 2008 @@ -11,7 +11,7 @@ provides tools to create, read, write, append, and list a ZIP file. Any advanced use of this module will require an understanding of the format, as defined in `PKZIP Application Note -`_. +`_. This module does not currently handle multi-disk ZIP files, or ZIP files which have appended comments (although it correctly handles comments @@ -81,7 +81,7 @@ .. seealso:: - `PKZIP Application Note `_ + `PKZIP Application Note `_ Documentation on the ZIP file format by Phil Katz, the creator of the format and algorithms used. @@ -182,8 +182,6 @@ filename or a :class:`ZipInfo` object. *pwd* is the password used for encrypted files. - .. versionadded:: 2.6 - .. method:: ZipFile.extractall([path[, members[, pwd]]]) @@ -192,8 +190,6 @@ be a subset of the list returned by :meth:`namelist`. *pwd* is the password used for encrypted files. - .. versionadded:: 2.6 - .. method:: ZipFile.printdir() @@ -361,7 +357,7 @@ .. attribute:: ZipInfo.extra Expansion field data. The `PKZIP Application Note - `_ contains + `_ contains some comments on the internal structure of the data contained in this string. Modified: python/branches/py3k-ctypes-pep3118/Doc/library/zipimport.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/zipimport.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/zipimport.rst Wed Apr 30 15:57:13 2008 @@ -29,7 +29,7 @@ .. seealso:: - `PKZIP Application Note `_ + `PKZIP Application Note `_ Documentation on the ZIP file format by Phil Katz, the creator of the format and algorithms used. @@ -70,55 +70,57 @@ (provided that it exists). -.. method:: zipimporter.find_module(fullname[, path]) + .. method:: find_module(fullname[, path]) - Search for a module specified by *fullname*. *fullname* must be the fully - qualified (dotted) module name. It returns the zipimporter instance itself if - the module was found, or :const:`None` if it wasn't. The optional *path* - argument is ignored---it's there for compatibility with the importer protocol. + Search for a module specified by *fullname*. *fullname* must be the fully + qualified (dotted) module name. It returns the zipimporter instance itself + if the module was found, or :const:`None` if it wasn't. The optional + *path* argument is ignored---it's there for compatibility with the + importer protocol. -.. method:: zipimporter.get_code(fullname) + .. method:: get_code(fullname) - Return the code object for the specified module. Raise :exc:`ZipImportError` if - the module couldn't be found. + Return the code object for the specified module. Raise + :exc:`ZipImportError` if the module couldn't be found. -.. method:: zipimporter.get_data(pathname) + .. method:: get_data(pathname) - Return the data associated with *pathname*. Raise :exc:`IOError` if the file - wasn't found. + Return the data associated with *pathname*. Raise :exc:`IOError` if the + file wasn't found. -.. method:: zipimporter.get_source(fullname) + .. method:: get_source(fullname) - Return the source code for the specified module. Raise :exc:`ZipImportError` if - the module couldn't be found, return :const:`None` if the archive does contain - the module, but has no source for it. + Return the source code for the specified module. Raise + :exc:`ZipImportError` if the module couldn't be found, return + :const:`None` if the archive does contain the module, but has no source + for it. -.. method:: zipimporter.is_package(fullname) + .. method:: is_package(fullname) - Return True if the module specified by *fullname* is a package. Raise - :exc:`ZipImportError` if the module couldn't be found. + Return True if the module specified by *fullname* is a package. Raise + :exc:`ZipImportError` if the module couldn't be found. -.. method:: zipimporter.load_module(fullname) + .. method:: load_module(fullname) - Load the module specified by *fullname*. *fullname* must be the fully qualified - (dotted) module name. It returns the imported module, or raises - :exc:`ZipImportError` if it wasn't found. + Load the module specified by *fullname*. *fullname* must be the fully + qualified (dotted) module name. It returns the imported module, or raises + :exc:`ZipImportError` if it wasn't found. -.. attribute:: zipimporter.archive + .. attribute:: archive - The file name of the importer's associated ZIP file. + The file name of the importer's associated ZIP file. -.. attribute:: zipimporter.prefix + .. attribute:: prefix - The path within the ZIP file where modules are searched; see - :class:`zipimporter` for details. + The path within the ZIP file where modules are searched; see + :class:`zipimporter` for details. .. _zipimport-examples: Modified: python/branches/py3k-ctypes-pep3118/Doc/library/zlib.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/library/zlib.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/library/zlib.rst Wed Apr 30 15:57:13 2008 @@ -42,6 +42,8 @@ the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm. + Always returns an unsigned 32-bit integer. + .. function:: compress(string[, level]) @@ -74,6 +76,8 @@ the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm. + Always returns an unsigned 32-bit integer. + .. function:: decompress(string[, wbits[, bufsize]]) Modified: python/branches/py3k-ctypes-pep3118/Doc/license.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/license.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/license.rst Wed Apr 30 15:57:13 2008 @@ -120,7 +120,7 @@ analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python |release| alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of - copyright, i.e., "Copyright ?? 2001-2007 Python Software Foundation; All Rights + copyright, i.e., "Copyright ?? 2001-2008 Python Software Foundation; All Rights Reserved" are retained in Python |release| alone or in any derivative version prepared by Licensee. @@ -347,7 +347,7 @@ The :mod:`socket` module uses the functions, :func:`getaddrinfo`, and :func:`getnameinfo`, which are coded in separate source files from the WIDE -Project, http://www.wide.ad.jp/about/index.html. :: +Project, http://www.wide.ad.jp/. :: Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. All rights reserved. @@ -599,3 +599,58 @@ ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +test_epoll +---------- + +The :mod:`test_epoll` contains the following notice:: + + Copyright (c) 2001-2006 Twisted Matrix Laboratories. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Select kqueue +------------- + +The :mod:`select` and contains the following notice for the kqueue interface:: + + Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. Modified: python/branches/py3k-ctypes-pep3118/Doc/reference/compound_stmts.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/reference/compound_stmts.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/reference/compound_stmts.rst Wed Apr 30 15:57:13 2008 @@ -52,6 +52,7 @@ : | `with_stmt` : | `funcdef` : | `classdef` + : | `decorated` suite: `stmt_list` NEWLINE | NEWLINE INDENT `statement`+ DEDENT statement: `stmt_list` NEWLINE | `compound_stmt` stmt_list: `simple_stmt` (";" `simple_stmt`)* [";"] @@ -424,6 +425,7 @@ funcdef: [`decorators`] "def" `funcname` "(" [`parameter_list`] ")" ["->" `expression`]? ":" `suite` decorators: `decorator`+ decorator: "@" `dotted_name` ["(" [`argument_list` [","]] ")"] NEWLINE + funcdef: "def" `funcname` "(" [`parameter_list`] ")" ":" `suite` dotted_name: `identifier` ("." `identifier`)* parameter_list: (`defparameter` ",")* : ( "*" [`parameter`] ("," `defparameter`)* @@ -444,6 +446,9 @@ The function definition does not execute the function body; this gets executed only when the function is called. +.. index:: + statement: @ + A function definition may be wrapped by one or more :term:`decorator` expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is @@ -484,7 +489,11 @@ penguin.append("property of the zoo") return penguin -Function call semantics are described in more detail in section :ref:`calls`. A +.. index:: + statement: * + statement: ** + +Function call semantics are described in more detail in section :ref:`calls`. A function call always assigns values to all parameters mentioned in the parameter list, either from position arguments, from keyword arguments, or from default values. If the form "``*identifier``" is present, it is initialized to a tuple @@ -575,9 +584,8 @@ variables are accessible through the notation "``self.name``", and an instance variable hides a class variable with the same name when accessed in this way. Class variables can be used as defaults for instance variables, but using -mutable values there can lead to unexpected results. For :term:`new-style -class`\es, descriptors can be used to create instance variables with different -implementation details. +mutable values there can lead to unexpected results. Descriptors can be used +to create instance variables with different implementation details. .. XXX add link to descriptor docs above @@ -585,11 +593,15 @@ :pep:`3129` - Class Decorators +Class definitions, like function definitions, may be wrapped by one or +more :term:`decorator` expressions. The evaluation rules for the +decorator expressions are the same as for functions. The result must +be a class object, which is then bound to the class name. .. rubric:: Footnotes -.. [#] The exception is propogated to the invocation stack only if there is no +.. [#] The exception is propagated to the invocation stack only if there is no :keyword:`finally` clause that negates the exception. .. [#] Currently, control "flows off the end" except in the case of an exception or the Modified: python/branches/py3k-ctypes-pep3118/Doc/reference/datamodel.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/reference/datamodel.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/reference/datamodel.rst Wed Apr 30 15:57:13 2008 @@ -510,6 +510,10 @@ An instance method object combines a class, a class instance and any callable object (normally a user-defined function). + .. versionchanged:: 2.6 + For 3.0 forward-compatibility, :attr:`im_func` is also available as + :attr:`__func__`, and :attr:`im_self` as :attr:`__self__`. + .. index:: single: __func__ (method attribute) single: __self__ (method attribute) @@ -901,7 +905,6 @@ pair: exception; handler pair: execution; stack single: exc_info (in module sys) - single: exc_traceback (in module sys) single: last_traceback (in module sys) single: sys.exc_info single: sys.last_traceback @@ -977,45 +980,6 @@ by the built-in :func:`classmethod` constructor. -.. _newstyle: - -New-style and classic classes -============================= - -Classes and instances come in two flavors: old-style or classic, and new-style. - -Up to Python 2.1, old-style classes were the only flavour available to the user. -The concept of (old-style) class is unrelated to the concept of type: if *x* is -an instance of an old-style class, then ``x.__class__`` designates the class of -*x*, but ``type(x)`` is always ````. This reflects the fact -that all old-style instances, independently of their class, are implemented with -a single built-in type, called ``instance``. - -New-style classes were introduced in Python 2.2 to unify classes and types. A -new-style class neither more nor less than a user-defined type. If *x* is an -instance of a new-style class, then ``type(x)`` is the same as ``x.__class__``. - -The major motivation for introducing new-style classes is to provide a unified -object model with a full meta-model. It also has a number of immediate -benefits, like the ability to subclass most built-in types, or the introduction -of "descriptors", which enable computed properties. - -For compatibility reasons, classes are still old-style by default. New-style -classes are created by specifying another new-style class (i.e. a type) as a -parent class, or the "top-level type" :class:`object` if no other parent is -needed. The behaviour of new-style classes differs from that of old-style -classes in a number of important details in addition to what :func:`type` -returns. Some of these changes are fundamental to the new object model, like -the way special methods are invoked. Others are "fixes" that could not be -implemented before for compatibility concerns, like the method resolution order -in case of multiple inheritance. - -This manual is not up-to-date with respect to new-style classes. For now, -please see http://www.python.org/doc/newstyle/ for more information. - -.. XXX remove old style classes from docs - - .. _specialnames: Special method names @@ -1415,9 +1379,7 @@ However, if the looked-up value is an object defining one of the descriptor methods, then Python may override the default behavior and invoke the descriptor method instead. Where this occurs in the precedence chain depends on which -descriptor methods were defined and how they were called. Note that descriptors -are only invoked for new style objects or classes (ones that subclass -:class:`object()` or :class:`type()`). +descriptor methods were defined and how they were called. The starting point for descriptor invocation is a binding, ``a.x``. How the arguments are assembled depends on ``a``: @@ -1474,7 +1436,7 @@ .. data:: object.__slots__ This class variable can be assigned a string, iterable, or sequence of - strings with variable names used by instances. If defined in a new-style + strings with variable names used by instances. If defined in a class, *__slots__* reserves space for the declared variables and prevents the automatic creation of *__dict__* and *__weakref__* for each instance. @@ -1798,7 +1760,7 @@ ``-``, ``*``, ``/``, ``%``, :func:`divmod`, :func:`pow`, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``) with reflected (swapped) operands. These functions are only called if the left operand does not support the corresponding operation and - the operands are of different types. [#]_ For instance, to evaluate the + the operands are of different types. [#]_ For instance, to evaluate the expression *x*``-``*y*, where *y* is an instance of a class that has an :meth:`__rsub__` method, ``y.__rsub__(x)`` is called if ``x.__sub__(y)`` returns *NotImplemented*. @@ -1924,18 +1886,6 @@ .. rubric:: Footnotes -.. [#] Since Python 2.2, a gradual merging of types and classes has been started that - makes this and a few other assertions made in this manual not 100% accurate and - complete: for example, it *is* now possible in some cases to change an object's - type, under certain controlled conditions. Until this manual undergoes - extensive revision, it must now be taken as authoritative only regarding - "classic classes", that are still the default, for compatibility purposes, in - Python 2.2 and 2.3. For more information, see - http://www.python.org/doc/newstyle/. - -.. [#] This, and other statements, are only roughly true for instances of new-style - classes. - .. [#] A descriptor can define any combination of :meth:`__get__`, :meth:`__set__` and :meth:`__delete__`. If it does not define :meth:`__get__`, then accessing the attribute even on an instance will return the descriptor @@ -1946,4 +1896,3 @@ .. [#] For operands of the same type, it is assumed that if the non-reflected method (such as :meth:`__add__`) fails the operation is not supported, which is why the reflected method is not called. - Modified: python/branches/py3k-ctypes-pep3118/Doc/reference/expressions.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/reference/expressions.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/reference/expressions.rst Wed Apr 30 15:57:13 2008 @@ -232,6 +232,20 @@ constructed from the elements resulting from the comprehension. +Variables used in the generator expression are evaluated lazily in a separate +scope when the :meth:`next` method is called for the generator object (in the +same fashion as for normal generators). However, the :keyword:`in` expression +of the leftmost :keyword:`for` clause is immediately evaluated in the current +scope so that an error produced by it can be seen before any other possible +error in the code that handles the generator expression. Subsequent +:keyword:`for` and :keyword:`if` clauses cannot be evaluated immediately since +they may depend on the previous :keyword:`for` loop. For example: +``(x*y for x in range(10) for y in bar(x))``. + +The parentheses can be omitted on calls with only one argument. See section +:ref:`calls` for the detail. + + .. _dict: Dictionary displays @@ -380,7 +394,7 @@ generator, or raises :exc:`StopIteration` if the generator exits without yielding another value. When :meth:`send` is called to start the generator, it must be called with :const:`None` as the argument, because there is no - :keyword:`yield` expression that could receieve the value. + :keyword:`yield` expression that could receive the value. .. method:: generator.throw(type[, value[, traceback]]) @@ -652,7 +666,7 @@ If the syntax ``*expression`` appears in the function call, ``expression`` must evaluate to a sequence. Elements from this sequence are treated as if they were -additional positional arguments; if there are postional arguments *x1*,...,*xN* +additional positional arguments; if there are positional arguments *x1*,...,*xN* , and ``expression`` evaluates to a sequence *y1*,...,*yM*, this is equivalent to a call with M+N positional arguments *x1*,...,*xN*,*y1*,...,*yM*. Modified: python/branches/py3k-ctypes-pep3118/Doc/reference/index.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/reference/index.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/reference/index.rst Wed Apr 30 15:57:13 2008 @@ -17,7 +17,7 @@ interfaces available to C/C++ programmers in detail. .. toctree:: - :maxdepth: 3 + :maxdepth: 2 introduction.rst lexical_analysis.rst Modified: python/branches/py3k-ctypes-pep3118/Doc/reference/lexical_analysis.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/reference/lexical_analysis.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/reference/lexical_analysis.rst Wed Apr 30 15:57:13 2008 @@ -423,8 +423,9 @@ itself, or the quote character. String literals may optionally be prefixed with a letter ``'r'`` or ``'R'``; -such strings are called :dfn:`raw strings` and use different rules for -interpreting backslash escape sequences. +such strings are called :dfn:`raw strings` and treat backslashes as literal +characters. As a result, ``'\U'`` and ``'\u'`` escapes in raw strings are not +treated specially. Bytes literals are always prefixed with ``'b'`` or ``'B'``; they produce an instance of the :class:`bytes` type instead of the :class:`str` type. They @@ -520,15 +521,6 @@ escape sequences only recognized in string literals fall into the category of unrecognized escapes for bytes literals. -When an ``'r'`` or ``'R'`` prefix is used in a string literal, then the -``\uXXXX`` and ``\UXXXXXXXX`` escape sequences are processed while *all other -backslashes are left in the string*. For example, the string literal -``r"\u0062\n"`` consists of three Unicode characters: 'LATIN SMALL LETTER B', -'REVERSE SOLIDUS', and 'LATIN SMALL LETTER N'. Backslashes can be escaped with a -preceding backslash; however, both remain in the string. As a result, -``\uXXXX`` escape sequences are only recognized when there is an odd number of -backslashes. - Even in a raw string, string quotes can be escaped with a backslash, but the backslash remains in the string; for example, ``r"\""`` is a valid string literal consisting of two characters: a backslash and a double quote; ``r"\"`` @@ -587,7 +579,7 @@ Integer literals are described by the following lexical definitions: .. productionlist:: - integer: `decimalinteger` | `octinteger` | `hexinteger` + integer: `decimalinteger` | `octinteger` | `hexinteger` | `bininteger` decimalinteger: `nonzerodigit` `digit`* | "0"+ nonzerodigit: "1"..."9" digit: "0"..."9" Modified: python/branches/py3k-ctypes-pep3118/Doc/reference/simple_stmts.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/reference/simple_stmts.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/reference/simple_stmts.rst Wed Apr 30 15:57:13 2008 @@ -438,7 +438,36 @@ and is only used in the body of the generator function. Using a :keyword:`yield` statement in a function definition is sufficient to cause that definition to create a generator function instead of a normal function. ->>>>>>> .merge-right.r59773 +When a generator function is called, it returns an iterator known as a generator +iterator, or more commonly, a generator. The body of the generator function is +executed by calling the generator's :meth:`next` method repeatedly until it +raises an exception. + +When a :keyword:`yield` statement is executed, the state of the generator is +frozen and the value of :token:`expression_list` is returned to :meth:`next`'s +caller. By "frozen" we mean that all local state is retained, including the +current bindings of local variables, the instruction pointer, and the internal +evaluation stack: enough information is saved so that the next time :meth:`next` +is invoked, the function can proceed exactly as if the :keyword:`yield` +statement were just another external call. + +As of Python version 2.5, the :keyword:`yield` statement is now allowed in the +:keyword:`try` clause of a :keyword:`try` ... :keyword:`finally` construct. If +the generator is not resumed before it is finalized (by reaching a zero +reference count or by being garbage collected), the generator-iterator's +:meth:`close` method will be called, allowing any pending :keyword:`finally` +clauses to execute. + + +.. seealso:: + + :pep:`0255` - Simple Generators + The proposal for adding generators and the :keyword:`yield` statement to Python. + + :pep:`0342` - Coroutines via Enhanced Generators + The proposal that, among other generator enhancements, proposed allowing + :keyword:`yield` to appear inside a :keyword:`try` ... :keyword:`finally` block. + .. _raise: @@ -539,9 +568,13 @@ :keyword:`continue` may only occur syntactically nested in a :keyword:`for` or :keyword:`while` loop, but not nested in a function or class definition or -:keyword:`finally` statement within that loop. [#]_ It continues with the next +:keyword:`finally` clause within that loop. It continues with the next cycle of the nearest enclosing loop. +When :keyword:`continue` passes control out of a :keyword:`try` statement with a +:keyword:`finally` clause, that :keyword:`finally` clause is executed before +really starting the next loop cycle. + .. _import: .. _from: @@ -832,4 +865,3 @@ .. [#] It may occur within an :keyword:`except` or :keyword:`else` clause. The restriction on occurring in the :keyword:`try` clause is implementor's laziness and will eventually be lifted. - Modified: python/branches/py3k-ctypes-pep3118/Doc/tools/sphinxext/download.html ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/tools/sphinxext/download.html (original) +++ python/branches/py3k-ctypes-pep3118/Doc/tools/sphinxext/download.html Wed Apr 30 15:57:13 2008 @@ -5,6 +5,9 @@

Download Python {{ release }} Documentation {%- if last_updated %} (last updated on {{ last_updated }}){% endif %}

+

Currently, the development documentation isn't packaged for download.

+ + + {% endblock %} Modified: python/branches/py3k-ctypes-pep3118/Doc/tools/sphinxext/indexcontent.html ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/tools/sphinxext/indexcontent.html (original) +++ python/branches/py3k-ctypes-pep3118/Doc/tools/sphinxext/indexcontent.html Wed Apr 30 15:57:13 2008 @@ -1,3 +1,5 @@ +{% extends "defindex.html" %} +{% block tables %}

Parts of the documentation:

@@ -54,3 +56,4 @@
+{% endblock %} Modified: python/branches/py3k-ctypes-pep3118/Doc/tools/sphinxext/patchlevel.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/tools/sphinxext/patchlevel.py (original) +++ python/branches/py3k-ctypes-pep3118/Doc/tools/sphinxext/patchlevel.py Wed Apr 30 15:57:13 2008 @@ -66,3 +66,6 @@ print >>sys.stderr, 'Can\'t get version info from Include/patchlevel.h, ' \ 'using version of this interpreter (%s).' % release return version, release + +if __name__ == '__main__': + print get_header_version_info('.')[1] Modified: python/branches/py3k-ctypes-pep3118/Doc/tutorial/appetite.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/tutorial/appetite.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/tutorial/appetite.rst Wed Apr 30 15:57:13 2008 @@ -68,7 +68,7 @@ application. By the way, the language is named after the BBC show "Monty Python's Flying -Circus" and has nothing to do with nasty reptiles. Making references to Monty +Circus" and has nothing to do with reptiles. Making references to Monty Python skits in documentation is not only allowed, it is encouraged! Now that you are all excited about Python, you'll want to examine it in some Modified: python/branches/py3k-ctypes-pep3118/Doc/tutorial/classes.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/tutorial/classes.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/tutorial/classes.rst Wed Apr 30 15:57:13 2008 @@ -124,6 +124,8 @@ a variable will simply create a *new* local variable in the innermost scope, leaving the identically named outer variable unchanged). +.. XXX mention nonlocal + Usually, the local scope references the local names of the (textually) current function. Outside functions, the local scope references the same namespace as the global scope: the module's namespace. Class definitions place yet another @@ -137,12 +139,15 @@ time, so don't rely on dynamic name resolution! (In fact, local variables are already determined statically.) -A special quirk of Python is that assignments normally go into the innermost -scope. Assignments do not copy data --- they just bind names to objects. The -same is true for deletions: the statement ``del x`` removes the binding of ``x`` -from the namespace referenced by the local scope. In fact, all operations that -introduce new names use the local scope: in particular, import statements and -function definitions bind the module or function name in the local scope. +A special quirk of Python is that -- if no :keyword:`global` or +:keyword:`nonlocal` statement is in effect -- assignments to names always go +into the innermost scope. Assignments do not copy data --- they just bind names +to objects. The same is true for deletions: the statement ``del x`` removes the +binding of ``x`` from the namespace referenced by the local scope. In fact, all +operations that introduce new names use the local scope: in particular, import +statements and function definitions bind the module or function name in the +local scope. (The :keyword:`global` statement can be used to indicate that +particular variables live in the global scope.) The :keyword:`global` statement can be used to indicate that particular variables live in the global scope and should be rebound there; the @@ -466,6 +471,9 @@ defined in this global scope, and in the next section we'll find some good reasons why a method would want to reference its own class! +Each value is an object, and therefore has a *class* (also called its *type*). +It is stored as ``object.__class__``. + .. _tut-inheritance: @@ -515,6 +523,19 @@ only works if the base class is defined or imported directly in the global scope.) +Python has two builtin functions that work with inheritance: + +* Use :func:`isinstance` to check an object's type: ``isinstance(obj, int)`` + will be ``True`` only if ``obj.__class__`` is :class:`int` or some class + derived from :class:`int`. + +* Use :func:`issubclass` to check class inheritance: ``issubclass(bool, int)`` + is ``True`` since :class:`bool` is a subclass of :class:`int`. However, + ``issubclass(unicode, str)`` is ``False`` since :class:`unicode` is not a + subclass of :class:`str` (they only share a common ancestor, + :class:`basestring`). + + .. _tut-multiple: @@ -811,7 +832,7 @@ 260 >>> from math import pi, sin - >>> sine_table = dict((x, sin(x*pi/180)) for x in range(0, 91)) + >>> sine_table = {x: sin(x*pi/180) for x in range(0, 91)} >>> unique_words = set(word for line in page for word in line.split()) Modified: python/branches/py3k-ctypes-pep3118/Doc/tutorial/controlflow.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/tutorial/controlflow.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/tutorial/controlflow.rst Wed Apr 30 15:57:13 2008 @@ -467,6 +467,9 @@ Arbitrary Argument Lists ------------------------ +.. index:: + statement: * + Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple. Before the variable number of arguments, zero or more normal @@ -508,6 +511,9 @@ >>> list(range(*args)) # call with arguments unpacked from a list [3, 4, 5] +.. index:: + statement: ** + In the same fashion, dictionaries can deliver keyword arguments with the ``**``\ -operator:: @@ -610,7 +616,7 @@ Making it easy for others to read your code is always a good idea, and adopting a nice coding style helps tremendously for that. -For Python, :pep:`8` has emerged as the style guide that most projects adher to; +For Python, :pep:`8` has emerged as the style guide that most projects adhere to; it promotes a very readable and eye-pleasing coding style. Every Python developer should read it at some point; here are the most important points extracted for you: Modified: python/branches/py3k-ctypes-pep3118/Doc/tutorial/datastructures.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/tutorial/datastructures.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/tutorial/datastructures.rst Wed Apr 30 15:57:13 2008 @@ -83,17 +83,20 @@ .. method:: list.append(x) + :noindex: Add an item to the end of the list; equivalent to ``a[len(a):] = [x]``. .. method:: list.extend(L) + :noindex: Extend the list by appending all the items in the given list; equivalent to ``a[len(a):] = L``. .. method:: list.insert(i, x) + :noindex: Insert an item at a given position. The first argument is the index of the element before which to insert, so ``a.insert(0, x)`` inserts at the front of @@ -101,12 +104,14 @@ .. method:: list.remove(x) + :noindex: Remove the first item from the list whose value is *x*. It is an error if there is no such item. .. method:: list.pop([i]) + :noindex: Remove the item at the given position in the list, and return it. If no index is specified, ``a.pop()`` removes and returns the last item in the list. (The @@ -116,22 +121,26 @@ .. method:: list.index(x) + :noindex: Return the index in the list of the first item whose value is *x*. It is an error if there is no such item. .. method:: list.count(x) + :noindex: Return the number of times *x* appears in the list. .. method:: list.sort() + :noindex: Sort the items of the list, in place. .. method:: list.reverse() + :noindex: Reverse the elements of the list, in place. @@ -273,7 +282,7 @@ List comprehensions can be applied to complex expressions and nested functions:: - >>> [str(round(355/113.0, i)) for i in range(1, 6)] + >>> [str(round(355/113, i)) for i in range(1, 6)] ['3.1', '3.14', '3.142', '3.1416', '3.14159'] @@ -437,6 +446,9 @@ >>> fruit = set(basket) # create a set without duplicates >>> fruit {'orange', 'pear', 'apple', 'banana'} + >>> fruit = {'orange', 'apple'} # {} syntax is equivalent to [] for lists + >>> fruit + {'orange', 'apple'} >>> 'orange' in fruit # fast membership testing True >>> 'crabgrass' in fruit @@ -457,6 +469,11 @@ >>> a ^ b # letters in a or b but not both {'r', 'd', 'b', 'm', 'z', 'l'} +Like for lists, there is a set comprehension syntax:: + + >>> a = {x for x in 'abracadabra' if x not in 'abc'} + >>> a + {'r', 'd'} @@ -518,12 +535,12 @@ >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) {'sape': 4139, 'jack': 4098, 'guido': 4127} - >>> dict([(x, x**2) for x in (2, 4, 6)]) # use a list comprehension - {2: 4, 4: 16, 6: 36} -Later in the tutorial, we will learn about Generator Expressions which are even -better suited for the task of supplying key-values pairs to the :func:`dict` -constructor. +In addition, dict comprehensions can be used to create dictionaries from +arbitrary key and value expressions:: + + >>> {x: x**2 for x in (2, 4, 6)} + {2: 4, 4: 16, 6: 36} When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:: @@ -532,9 +549,8 @@ {'sape': 4139, 'jack': 4098, 'guido': 4127} +.. XXX Find out the right way to do these DUBOIS .. _tut-loopidioms: -.. % - Find out the right way to do these DUBOIS Looping Techniques ================== Modified: python/branches/py3k-ctypes-pep3118/Doc/tutorial/errors.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/tutorial/errors.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/tutorial/errors.rst Wed Apr 30 15:57:13 2008 @@ -131,8 +131,8 @@ f = open('myfile.txt') s = f.readline() i = int(s.strip()) - except IOError as e: - print("I/O error(%s): %s" % (e.errno, e.strerror)) + except IOError as (errno, strerror): + print "I/O error(%s): %s" % (errno, strerror) except ValueError: print("Could not convert data to an integer.") except: @@ -184,7 +184,7 @@ ... print('x =', x) ... print('y =', y) ... - + ('spam', 'eggs') ('spam', 'eggs') x = spam Modified: python/branches/py3k-ctypes-pep3118/Doc/tutorial/inputoutput.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/tutorial/inputoutput.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/tutorial/inputoutput.rst Wed Apr 30 15:57:13 2008 @@ -195,16 +195,15 @@ writing. The *mode* argument is optional; ``'r'`` will be assumed if it's omitted. -``'b'`` appended to the mode opens the file in binary mode, so there are -also modes like ``'rb'``, ``'wb'``, and ``'r+b'``. Python distinguishes -between text and binary files. Binary files are read and written without -any data transformation. In text mode, platform-specific newline -representations are automatically converted to newlines when read and -newline characters are automatically converted to the proper -platform-specific representation when written. This makes writing portable -code which reads or writes text files easier. In addition, when reading -from or writing to text files, the data are automatically decoded or -encoding, respectively, using the encoding associated with the file. +On Windows and the Macintosh, ``'b'`` appended to the mode opens the file in +binary mode, so there are also modes like ``'rb'``, ``'wb'``, and ``'r+b'``. +Windows makes a distinction between text and binary files; the end-of-line +characters in text files are automatically altered slightly when data is read or +written. This behind-the-scenes modification to file data is fine for ASCII +text files, but it'll corrupt binary data like that in :file:`JPEG` or +:file:`EXE` files. Be very careful to use binary mode when reading and writing +such files. On Unix, it doesn't hurt to append a ``'b'`` to the mode, so +you can use it platform-independently for all binary files. This behind-the-scenes modification to file data is fine for text files, but will corrupt binary data like that in :file:`JPEG` or :file:`EXE` files. Be Modified: python/branches/py3k-ctypes-pep3118/Doc/tutorial/stdlib.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/tutorial/stdlib.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/tutorial/stdlib.rst Wed Apr 30 15:57:13 2008 @@ -121,7 +121,7 @@ floating point math:: >>> import math - >>> math.cos(math.pi / 4.0) + >>> math.cos(math.pi / 4) 0.70710678118654757 >>> math.log(1024, 2) 10.0 @@ -264,7 +264,7 @@ >>> print(average([20, 30, 70])) 40.0 """ - return sum(values, 0.0) / len(values) + return sum(values) / len(values) import doctest doctest.testmod() # automatically validate the embedded tests Modified: python/branches/py3k-ctypes-pep3118/Doc/tutorial/stdlib2.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/tutorial/stdlib2.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/tutorial/stdlib2.rst Wed Apr 30 15:57:13 2008 @@ -269,7 +269,7 @@ 0 >>> d['primary'] # entry was automatically removed Traceback (most recent call last): - File "", line 1, in -toplevel- + File "", line 1, in d['primary'] # entry was automatically removed File "C:/python30/lib/weakref.py", line 46, in __getitem__ o = self.data[key]() Modified: python/branches/py3k-ctypes-pep3118/Doc/tutorial/whatnow.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/tutorial/whatnow.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/tutorial/whatnow.rst Wed Apr 30 15:57:13 2008 @@ -38,9 +38,9 @@ * http://docs.python.org: Fast access to Python's documentation. -* http://cheeseshop.python.org: The Python Package Index, nicknamed the Cheese - Shop, is an index of user-created Python modules that are available for - download. Once you begin releasing code, you can register it here so that +* http://pypi.python.org: The Python Package Index, previously also nicknamed + the Cheese Shop, is an index of user-created Python modules that are available + for download. Once you begin releasing code, you can register it here so that others can find it. * http://aspn.activestate.com/ASPN/Python/Cookbook/: The Python Cookbook is a Modified: python/branches/py3k-ctypes-pep3118/Doc/using/cmdline.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/using/cmdline.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/using/cmdline.rst Wed Apr 30 15:57:13 2008 @@ -311,7 +311,8 @@ Augment the default search path for module files. The format is the same as the shell's :envvar:`PATH`: one or more directory pathnames separated by - colons. Non-existent directories are silently ignored. + :data:`os.pathsep` (e.g. colons on Unix or semicolons on Windows). + Non-existent directories are silently ignored. The default search path is installation dependent, but generally begins with :file:`{prefix}/lib/python{version}`` (see :envvar:`PYTHONHOME` above). It Modified: python/branches/py3k-ctypes-pep3118/Doc/using/unix.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/using/unix.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/using/unix.rst Wed Apr 30 15:57:13 2008 @@ -20,7 +20,7 @@ that are not available on your distro's package. You can easily compile the latest version of Python from source. -In the event Python doesn't come preinstalled and isn't in the repositories as +In the event that Python doesn't come preinstalled and isn't in the repositories as well, you can easily make packages for your own distro. Have a look at the following links: Modified: python/branches/py3k-ctypes-pep3118/Doc/using/windows.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/using/windows.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/using/windows.rst Wed Apr 30 15:57:13 2008 @@ -21,7 +21,7 @@ `_ for many years. With ongoing development of Python, some platforms that used to be supported -earlier are not longer supported (due to the lack of users or developers). +earlier are no longer supported (due to the lack of users or developers). Check :pep:`11` for details on all unsupported platforms. * DOS and Windows 3.x are deprecated since Python 2.0 and code specific to these Modified: python/branches/py3k-ctypes-pep3118/Doc/whatsnew/2.6.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/whatsnew/2.6.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/whatsnew/2.6.rst Wed Apr 30 15:57:13 2008 @@ -2,7 +2,7 @@ What's New in Python 2.6 **************************** -.. XXX mention switch to Roundup for bug tracking +.. XXX add trademark info for Apple, Microsoft, SourceForge. :Author: A.M. Kuchling :Release: |release| @@ -40,24 +40,25 @@ * Credit the author of a patch or bugfix. Just the name is sufficient; the e-mail address isn't necessary. - * It's helpful to add the bug/patch number as a comment: + * It's helpful to add the bug/patch number in an parenthetical - % Patch 12345 XXX Describe the transmogrify() function added to the socket module. - (Contributed by P.Y. Developer.) + (Contributed by P.Y. Developer; :issue:`12345`.) - This saves the maintainer the effort of going through the SVN log + This saves the maintainer the effort of going through the SVN logs when researching a change. This article explains the new features in Python 2.6. No release date for Python 2.6 has been set; it will probably be released in mid 2008. -This article doesn't attempt to provide a complete specification of the new -features, but instead provides a convenient overview. For full details, you -should refer to the documentation for Python 2.6. If you want to understand the -complete implementation and design rationale, refer to the PEP for a particular -new feature. +This article doesn't attempt to provide a complete specification of +the new features, but instead provides a convenient overview. For +full details, you should refer to the documentation for Python 2.6. If +you want to understand the complete implementation and design +rationale, refer to the PEP for a particular new feature. For smaller +changes, this edition of "What's New in Python" links to the bug/patch +item for each change whenever possible. .. Compare with previous release in 2 - 3 sentences here. add hyperlink when the documentation becomes available online. @@ -96,6 +97,14 @@ to Python code as the boolean variable ``sys.py3kwarning``, and to C extension code as :cdata:`Py_Py3kWarningFlag`. +Python 3.0 adds several new built-in functions and change the +semantics of some existing built-ins. Entirely new functions such as +:func:`bin` have simply been added to Python 2.6, but existing +built-ins haven't been changed; instead, the :mod:`future_builtins` +module has versions with the new 3.0 semantics. Code written to be +compatible with 3.0 can do ``from future_builtins import hex, map`` +as necessary. + .. seealso:: The 3xxx series of PEPs, which describes the development process for @@ -116,23 +125,66 @@ New Issue Tracker: Roundup -------------------------------------------------- -XXX write this. +For a long time, the Python developers have been growing increasingly +annoyed by SourceForge's bug tracker. SourceForge's hosted solution +doesn't permit much customization; for example, it wasn't possible to +customize the life cycle of issues. + +The infrastructure committee of the Python Software Foundation +therefore posted a call for issue trackers, asking volunteers to set +up different products and import some of the bugs and patches from +SourceForge. Four different trackers were examined: Atlassian's `Jira +`__, +`Launchpad `__, +`Roundup `__, and +Trac `__. +The committee eventually settled on Jira +and Roundup as the two candidates. Jira is a commercial product that +offers a no-cost hosted instance to free-software projects; Roundup +is an open-source project that requires volunteers +to administer it and a server to host it. + +After posting a call for volunteers, a new Roundup installation was +set up at http://bugs.python.org. One installation of Roundup can +host multiple trackers, and this server now also hosts issue trackers +for Jython and for the Python web site. It will surely find +other uses in the future. Where possible, +this edition of "What's New in Python" links to the bug/patch +item for each change. + +Hosting is kindly provided by +`Upfront Systems `__ +of Stellenbosch, South Africa. Martin von Loewis put a +lot of effort into importing existing bugs and patches from +SourceForge; his scripts for this import operation are at +http://svn.python.org/view/tracker/importer/. +.. seealso:: + + http://bugs.python.org + The Python bug tracker. + + http://bugs.jython.org: + The Jython bug tracker. + + http://roundup.sourceforge.net/ + Roundup downloads and documentation. -New Documentation Format: ReStructured Text --------------------------------------------------- -Python's documentation had been written using LaTeX since the -project's inception around 1989. At that time, most documentation was +New Documentation Format: ReStructured Text Using Sphinx +----------------------------------------------------------- + +Since the Python project's inception around 1989, the documentation +had been written using LaTeX. At that time, most documentation was printed out for later study, not viewed online. LaTeX was widely used -because it provided attractive printed output while -remaining straightforward to write, once the basic rules -of the markup have been learned. +because it provided attractive printed output while remaining +straightforward to write, once the basic rules of the markup have been +learned. LaTeX is still used today for writing technical publications destined for printing, but the landscape for programming tools has shifted. We no longer print out reams of documentation; instead, we browse through -it online and HTML is the most important format to support. +it online and HTML has become the most important format to support. Unfortunately, converting LaTeX to HTML is fairly complicated, and Fred L. Drake Jr., the Python documentation editor for many years, spent a lot of time wrestling the conversion process into shape. @@ -140,23 +192,26 @@ SGML or, later, XML, but performing a good conversion is a major task and no one pursued the task to completion. -During the 2.6 development cycle, Georg Brandl put a substantial -effort into building a new toolchain called Sphinx -for processing the documentation. -The input format is reStructured Text, -a markup commonly used in the Python community that supports -custom extensions and directives. Sphinx concentrates -on HTML output, producing attractively styled -and modern HTML, but printed output is still supported through -conversion to LaTeX as an output format. +During the 2.6 development cycle, Georg Brandl put a substantial +effort into building a new toolchain for processing the documentation. +The resulting package is called Sphinx, and is available from +http://sphinx.pocoo.org/. The input format is reStructured Text, a +markup commonly used in the Python community that supports custom +extensions and directives. Sphinx concentrates on HTML output, +producing attractively styled and modern HTML, though printed output +is still supported through conversion to LaTeX. Sphinx is a +standalone package that can be used in documenting other projects. .. seealso:: - `Docutils `__: The fundamental - reStructured Text parser and toolset. + :ref:`documenting-index` + Describes how to write for Python's documentation. + + `Sphinx `__ + Documentation and code for the Sphinx toolchain. - :ref:`documenting-index`: Describes how to write for - Python's documentation. + `Docutils `__ + The underlying reStructured Text parser and toolset. PEP 343: The 'with' statement @@ -443,12 +498,179 @@ .. seealso:: :pep:`370` - XXX - - PEP written by XXX; implemented by Christian Heimes. + PEP written by XXX; implemented by Christian Heimes. .. ====================================================================== +.. _pep-3101: + +PEP 3101: Advanced String Formatting +===================================================== + +In Python 3.0, the `%` operator is supplemented by a more powerful +string formatting method, :meth:`format`. Support for the +:meth:`format` method has been backported to Python 2.6. + +In 2.6, both 8-bit and Unicode strings have a `.format()` method that +treats the string as a template and takes the arguments to be formatted. +The formatting template uses curly brackets (`{`, `}`) as special characters:: + + # Substitute positional argument 0 into the string. + "User ID: {0}".format("root") -> "User ID: root" + + # Use the named keyword arguments + uid = 'root' + + 'User ID: {uid} Last seen: {last_login}'.format(uid='root', + last_login = '5 Mar 2008 07:20') -> + 'User ID: root Last seen: 5 Mar 2008 07:20' + +Curly brackets can be escaped by doubling them:: + + format("Empty dict: {{}}") -> "Empty dict: {}" + +Field names can be integers indicating positional arguments, such as +``{0}``, ``{1}``, etc. or names of keyword arguments. You can also +supply compound field names that read attributes or access dictionary keys:: + + import sys + 'Platform: {0.platform}\nPython version: {0.version}'.format(sys) -> + 'Platform: darwin\n + Python version: 2.6a1+ (trunk:61261M, Mar 5 2008, 20:29:41) \n + [GCC 4.0.1 (Apple Computer, Inc. build 5367)]' + + import mimetypes + 'Content-type: {0[.mp4]}'.format(mimetypes.types_map) -> + 'Content-type: video/mp4' + +Note that when using dictionary-style notation such as ``[.mp4]``, you +don't need to put any quotation marks around the string; it will look +up the value using ``.mp4`` as the key. Strings beginning with a +number will be converted to an integer. You can't write more +complicated expressions inside a format string. + +So far we've shown how to specify which field to substitute into the +resulting string. The precise formatting used is also controllable by +adding a colon followed by a format specifier. For example:: + + # Field 0: left justify, pad to 15 characters + # Field 1: right justify, pad to 6 characters + fmt = '{0:15} ${1:>6}' + fmt.format('Registration', 35) -> + 'Registration $ 35' + fmt.format('Tutorial', 50) -> + 'Tutorial $ 50' + fmt.format('Banquet', 125) -> + 'Banquet $ 125' + +Format specifiers can reference other fields through nesting:: + + fmt = '{0:{1}}' + fmt.format('Invoice #1234', 15) -> + 'Invoice #1234 ' + width = 35 + fmt.format('Invoice #1234', width) -> + 'Invoice #1234 ' + +The alignment of a field within the desired width can be specified: + +================ ============================================ +Character Effect +================ ============================================ +< (default) Left-align +> Right-align +^ Center += (For numeric types only) Pad after the sign. +================ ============================================ + +Format specifiers can also include a presentation type, which +controls how the value is formatted. For example, floating-point numbers +can be formatted as a general number or in exponential notation: + + >>> '{0:g}'.format(3.75) + '3.75' + >>> '{0:e}'.format(3.75) + '3.750000e+00' + +A variety of presentation types are available. Consult the 2.6 +documentation for a complete list (XXX add link, once it's in the 2.6 +docs), but here's a sample:: + + 'b' - Binary. Outputs the number in base 2. + 'c' - Character. Converts the integer to the corresponding + Unicode character before printing. + 'd' - Decimal Integer. Outputs the number in base 10. + 'o' - Octal format. Outputs the number in base 8. + 'x' - Hex format. Outputs the number in base 16, using lower- + case letters for the digits above 9. + 'e' - Exponent notation. Prints the number in scientific + notation using the letter 'e' to indicate the exponent. + 'g' - General format. This prints the number as a fixed-point + number, unless the number is too large, in which case + it switches to 'e' exponent notation. + 'n' - Number. This is the same as 'g', except that it uses the + current locale setting to insert the appropriate + number separator characters. + '%' - Percentage. Multiplies the number by 100 and displays + in fixed ('f') format, followed by a percent sign. + +Classes and types can define a __format__ method to control how they're +formatted. It receives a single argument, the format specifier:: + + def __format__(self, format_spec): + if isinstance(format_spec, unicode): + return unicode(str(self)) + else: + return str(self) + +There's also a format() built-in that will format a single value. It calls +the type's :meth:`__format__` method with the provided specifier:: + + >>> format(75.6564, '.2f') + '75.66' + +.. seealso:: + + :pep:`3101` - Advanced String Formatting + PEP written by Talin. + +.. ====================================================================== + +.. _pep-3105: + +PEP 3105: ``print`` As a Function +===================================================== + +The ``print`` statement becomes the :func:`print` function in Python 3.0. +Making :func:`print` a function makes it easier to change +by doing 'def print(...)' or importing a new function from somewhere else. + +Python 2.6 has a ``__future__`` import that removes ``print`` as language +syntax, letting you use the functional form instead. For example:: + + from __future__ import print_function + print('# of entries', len(dictionary), file=sys.stderr) + +The signature of the new function is:: + + def print(*args, sep=' ', end='\n', file=None) + +The parameters are: + + * **args**: positional arguments whose values will be printed out. + * **sep**: the separator, which will be printed between arguments. + * **end**: the ending text, which will be printed after all of the + arguments have been output. + * **file**: the file object to which the output will be sent. + +.. seealso:: + + :pep:`3105` - Make print a function + PEP written by Georg Brandl. + +.. ====================================================================== + .. _pep-3110: PEP 3110: Exception-Handling Changes @@ -499,50 +721,389 @@ .. ====================================================================== +.. _pep-3112: + +PEP 3112: Byte Literals +===================================================== + +Python 3.0 adopts Unicode as the language's fundamental string type, and +denotes 8-bit literals differently, either as ``b'string'`` +or using a :class:`bytes` constructor. For future compatibility, +Python 2.6 adds :class:`bytes` as a synonym for the :class:`str` type, +and it also supports the ``b''`` notation. + +There's also a ``__future__`` import that causes all string literals +to become Unicode strings. This means that ``\u`` escape sequences +can be used to include Unicode characters. + + from __future__ import unicode_literals + + s = ('\u751f\u3080\u304e\u3000\u751f\u3054' + '\u3081\u3000\u751f\u305f\u307e\u3054') + + print len(s) # 12 Unicode characters + + +.. seealso:: + + :pep:`3112` - Bytes literals in Python 3000 + PEP written by Jason Orendorff; backported to 2.6 by Christian Heimes. + +.. ====================================================================== + +.. _pep-3116: + +PEP 3116: New I/O Library +===================================================== + +Python's built-in file objects support a number of methods, but +file-like objects don't necessarily support all of them. Objects that +imitate files usually support :meth:`read` and :meth:`write`, but they +may not support :meth:`readline`. Python 3.0 introduces a layered I/O +library in the :mod:`io` module that separates buffering and +text-handling features from the fundamental read and write operations. + +There are three levels of abstract base classes provided by +the :mod:`io` module: + +* :class:`RawIOBase`: defines raw I/O operations: :meth:`read`, + :meth:`readinto`, + :meth:`write`, :meth:`seek`, :meth:`tell`, :meth:`truncate`, + and :meth:`close`. + Most of the methods of this class will often map to a single system call. + There are also :meth:`readable`, :meth:`writable`, and :meth:`seekable` + methods for determining what operations a given object will allow. + + Python 3.0 has concrete implementations of this class for files and + sockets, but Python 2.6 hasn't restructured its file and socket objects + in this way. + + .. XXX should 2.6 register them in io.py? + +* :class:`BufferedIOBase`: is an abstract base class that + buffers data in memory to reduce the number of + system calls used, making I/O processing more efficient. + It supports all of the methods of :class:`RawIOBase`, + and adds a :attr:`raw` attribute holding the underlying raw object. + + There are four concrete classes implementing this ABC: + :class:`BufferedWriter` and + :class:`BufferedReader` for objects that only support + writing or reading and don't support random access, + :class:`BufferedRandom` for objects that support the :meth:`seek` method + for random access, + and :class:`BufferedRWPair` for objects such as TTYs that have + both read and write operations that act upon unconnected streams of data. + +* :class:`TextIOBase`: Provides functions for reading and writing + strings (remember, strings will be Unicode in Python 3.0), + and supporting universal newlines. :class:`TextIOBase` defines + the :meth:`readline` method and supports iteration upon + objects. + + There are two concrete implementations. :class:`TextIOWrapper` + wraps a buffered I/O object, supporting all of the methods for + text I/O and adding a :attr:`buffer` attribute for access + to the underlying object. :class:`StringIO` simply buffers + everything in memory without ever writing anything to disk. + + (In current 2.6 alpha releases, :class:`io.StringIO` is implemented in + pure Python, so it's pretty slow. You should therefore stick with the + existing :mod:`StringIO` module or :mod:`cStringIO` for now. At some + point Python 3.0's :mod:`io` module will be rewritten into C for speed, + and perhaps the C implementation will be backported to the 2.x releases.) + + .. XXX check before final release: is io.py still written in Python? + +In Python 2.6, the underlying implementations haven't been +restructured to build on top of the :mod:`io` module's classes. The +module is being provided to make it easier to write code that's +forward-compatible with 3.0, and to save developers the effort of writing +their own implementations of buffering and text I/O. + +.. seealso:: + + :pep:`3116` - New I/O + PEP written by Daniel Stutzbach, Mike Verdone, and Guido van Rossum. + Code by Guido van Rossum, Georg Brandl, Walter Doerwald, + Jeremy Hylton, Martin von Loewis, Tony Lownds, and others. + +.. ====================================================================== + +.. _pep-3118: + +PEP 3118: Revised Buffer Protocol +===================================================== + +The buffer protocol is a C-level API that lets Python types +exchange pointers into their internal representations. A +memory-mapped file can be viewed as a buffer of characters, for +example, and this lets another module such as :mod:`re` +treat memory-mapped files as a string of characters to be searched. + +The primary users of the buffer protocol are numeric-processing +packages such as NumPy, which can expose the internal representation +of arrays so that callers can write data directly into an array instead +of going through a slower API. This PEP updates the buffer protocol in light of experience +from NumPy development, adding a number of new features +such as indicating the shape of an array, +locking memory . + +The most important new C API function is +``PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)``, which +takes an object and a set of flags, and fills in the +``Py_buffer`` structure with information +about the object's memory representation. Objects +can use this operation to lock memory in place +while an external caller could be modifying the contents, +so there's a corresponding +``PyObject_ReleaseBuffer(PyObject *obj, Py_buffer *view)`` to +indicate that the external caller is done. + +The **flags** argument to :cfunc:`PyObject_GetBuffer` specifies +constraints upon the memory returned. Some examples are: + + * :const:`PyBUF_WRITABLE` indicates that the memory must be writable. + + * :const:`PyBUF_LOCK` requests a read-only or exclusive lock on the memory. + + * :const:`PyBUF_C_CONTIGUOUS` and :const:`PyBUF_F_CONTIGUOUS` + requests a C-contiguous (last dimension varies the fastest) or + Fortran-contiguous (first dimension varies the fastest) layout. + +.. XXX this feature is not in 2.6 docs yet + +.. seealso:: + + :pep:`3118` - Revising the buffer protocol + PEP written by Travis Oliphant and Carl Banks; implemented by + Travis Oliphant. + + +.. ====================================================================== + .. _pep-3119: PEP 3119: Abstract Base Classes ===================================================== -XXX +Some object-oriented languages such as Java support interfaces: declarations +that a class has a given set of methods or supports a given access protocol. +Abstract Base Classes (or ABCs) are an equivalent feature for Python. The ABC +support consists of an :mod:`abc` module containing a metaclass called +:class:`ABCMeta`, special handling +of this metaclass by the :func:`isinstance` and :func:`issubclass` built-ins, +and a collection of basic ABCs that the Python developers think will be widely +useful. + +Let's say you have a particular class and wish to know whether it supports +dictionary-style access. The phrase "dictionary-style" is vague, however. +It probably means that accessing items with ``obj[1]`` works. +Does it imply that setting items with ``obj[2] = value`` works? +Or that the object will have :meth:`keys`, :meth:`values`, and :meth:`items` +methods? What about the iterative variants such as :meth:`iterkeys`? :meth:`copy` +and :meth:`update`? Iterating over the object with :func:`iter`? + +Python 2.6 includes a number of different ABCs in the :mod:`collections` +module. :class:`Iterable` indicates that a class defines :meth:`__iter__`, +and :class:`Container` means the class supports ``x in y`` expressions +by defining a :meth:`__contains__` method. The basic dictionary interface of +getting items, setting items, and +:meth:`keys`, :meth:`values`, and :meth:`items`, is defined by the +:class:`MutableMapping` ABC. -How to identify a file object? +You can derive your own classes from a particular ABC +to indicate they support that ABC's interface:: -ABCs are a collection of classes describing various interfaces. -Classes can derive from an ABC to indicate they support that ABC's -interface. Concrete classes should obey the semantics specified by -an ABC, but Python can't check this; it's up to the implementor. + import collections + + class Storage(collections.MutableMapping): + ... + + +Alternatively, you could write the class without deriving from +the desired ABC and instead register the class by +calling the ABC's :meth:`register` method:: + + import collections + + class Storage: + ... + + collections.MutableMapping.register(Storage) + +For classes that you write, deriving from the ABC is probably clearer. +The :meth:`register` method is useful when you've written a new +ABC that can describe an existing type or class, or if you want +to declare that some third-party class implements an ABC. +For example, if you defined a :class:`PrintableType` ABC, +it's legal to do: + + # Register Python's types + PrintableType.register(int) + PrintableType.register(float) + PrintableType.register(str) + +Classes should obey the semantics specified by an ABC, but +Python can't check this; it's up to the class author to +understand the ABC's requirements and to implement the code accordingly. + +To check whether an object supports a particular interface, you can +now write:: + + def func(d): + if not isinstance(d, collections.MutableMapping): + raise ValueError("Mapping object expected, not %r" % d) + +(Don't feel that you must now begin writing lots of checks as in the +above example. Python has a strong tradition of duck-typing, where +explicit type-checking isn't done and code simply calls methods on +an object, trusting that those methods will be there and raising an +exception if they aren't. Be judicious in checking for ABCs +and only do it where it helps.) + +You can write your own ABCs by using ``abc.ABCMeta`` as the +metaclass in a class definition:: -A metaclass lets you declare that an existing class or type -derives from a particular ABC. You can even + from abc import ABCMeta -class AppendableSequence: - __metaclass__ = ABCMeta + class Drawable(): + __metaclass__ = ABCMeta + + def draw(self, x, y, scale=1.0): + pass + + def draw_doubled(self, x, y): + self.draw(x, y, scale=2.0) -AppendableSequence.register(list) -assert issubclass(list, AppendableSequence) -assert isinstance([], AppendableSequence) + + class Square(Drawable): + def draw(self, x, y, scale): + ... - at abstractmethod decorator -- you can't instantiate classes w/ -an abstract method. + +In the :class:`Drawable` ABC above, the :meth:`draw_doubled` method +renders the object at twice its size and can be implemented in terms +of other methods described in :class:`Drawable`. Classes implementing +this ABC therefore don't need to provide their own implementation +of :meth:`draw_doubled`, though they can do so. An implementation +of :meth:`draw` is necessary, though; the ABC can't provide +a useful generic implementation. You +can apply the ``@abstractmethod`` decorator to methods such as +:meth:`draw` that must be implemented; Python will +then raise an exception for classes that +don't define the method:: + + class Drawable(): + __metaclass__ = ABCMeta + + @abstractmethod + def draw(self, x, y, scale): + pass + +Note that the exception is only raised when you actually +try to create an instance of a subclass without the method:: + + >>> s=Square() + Traceback (most recent call last): + File "", line 1, in + TypeError: Can't instantiate abstract class Square with abstract methods draw + >>> -:: +Abstract data attributes can be declared using the ``@abstractproperty`` decorator:: - @abstractproperty decorator @abstractproperty def readonly(self): return self._x +Subclasses must then define a :meth:`readonly` property .. seealso:: :pep:`3119` - Introducing Abstract Base Classes PEP written by Guido van Rossum and Talin. - Implemented by XXX. + Implemented by Guido van Rossum. Backported to 2.6 by Benjamin Aranguren, with Alex Martelli. .. ====================================================================== +.. _pep-3127: + +PEP 3127: Integer Literal Support and Syntax +===================================================== + +Python 3.0 changes the syntax for octal (base-8) integer literals, +which are now prefixed by "0o" or "0O" instead of a leading zero, and +adds support for binary (base-2) integer literals, signalled by a "0b" +or "0B" prefix. + +Python 2.6 doesn't drop support for a leading 0 signalling +an octal number, but it does add support for "0o" and "0b":: + + >>> 0o21, 2*8 + 1 + (17, 17) + >>> 0b101111 + 47 + +The :func:`oct` built-in still returns numbers +prefixed with a leading zero, and a new :func:`bin` +built-in returns the binary representation for a number:: + + >>> oct(42) + '052' + >>> bin(173) + '0b10101101' + +The :func:`int` and :func:`long` built-ins will now accept the "0o" +and "0b" prefixes when base-8 or base-2 are requested, or when the +**base** argument is zero (meaning the base used is determined from +the string): + + >>> int ('0o52', 0) + 42 + >>> int('1101', 2) + 13 + >>> int('0b1101', 2) + 13 + >>> int('0b1101', 0) + 13 + + +.. seealso:: + + :pep:`3127` - Integer Literal Support and Syntax + PEP written by Patrick Maupin; backported to 2.6 by + Eric Smith. + +.. ====================================================================== + +.. _pep-3129: + +PEP 3129: Class Decorators +===================================================== + +Decorators have been extended from functions to classes. It's now legal to +write:: + + @foo + @bar + class A: + pass + +This is equivalent to:: + + class A: + pass + + A = foo(bar(A)) + +.. seealso:: + + :pep:`3129` - Class Decorators + PEP written by Collin Winter. + +.. ====================================================================== + .. _pep-3141: PEP 3141: A Type Hierarchy for Numbers @@ -559,7 +1120,7 @@ Numbers are further divided into :class:`Exact` and :class:`Inexact`. Exact numbers can represent values precisely and operations never round off the results or introduce tiny errors that may break the -communtativity and associativity properties; inexact numbers may +commutativity and associativity properties; inexact numbers may perform such rounding or introduce small errors. Integers, long integers, and rational numbers are exact, while floating-point and complex numbers are inexact. @@ -577,8 +1138,10 @@ :class:`Rational` numbers derive from :class:`Real`, have :attr:`numerator` and :attr:`denominator` properties, and can be -converted to floats. Python 2.6 adds a simple rational-number class -in the :mod:`rational` module. +converted to floats. Python 2.6 adds a simple rational-number class, +:class:`Fraction`, in the :mod:`fractions` module. (It's called +:class:`Fraction` instead of :class:`Rational` to avoid +a name clash with :class:`numbers.Rational`.) :class:`Integral` numbers derive from :class:`Rational`, and can be shifted left and right with ``<<`` and ``>>``, @@ -586,44 +1149,64 @@ and can be used as array indexes and slice boundaries. In Python 3.0, the PEP slightly redefines the existing built-ins -:func:`math.floor`, :func:`math.ceil`, :func:`round`, and adds a new -one, :func:`trunc`, that's been backported to Python 2.6. -:func:`trunc` rounds toward zero, returning the closest +:func:`round`, :func:`math.floor`, :func:`math.ceil`, and adds a new +one, :func:`math.trunc`, that's been backported to Python 2.6. +:func:`math.trunc` rounds toward zero, returning the closest :class:`Integral` that's between the function's argument and zero. .. seealso:: - XXX link: Discusses Scheme's numeric tower. + :pep:`3141` - A Type Hierarchy for Numbers + PEP written by Jeffrey Yasskin. + + `Scheme's numerical tower `__, from the Guile manual. + `Scheme's number datatypes `__ from the R5RS Scheme specification. -The Rational Module +The :mod:`fractions` Module -------------------------------------------------- To fill out the hierarchy of numeric types, a rational-number class -has been added as the :mod:`rational` module. Rational numbers are -represented as a fraction; rational numbers can exactly represent +has been added as the :mod:`fractions` module. Rational numbers are +represented as a fraction, and can exactly represent numbers such as two-thirds that floating-point numbers can only approximate. -The :class:`Rational` constructor takes two :class:`Integral` values +The :class:`Fraction` constructor takes two :class:`Integral` values that will be the numerator and denominator of the resulting fraction. :: - >>> from rational import Rational - >>> a = Rational(2, 3) - >>> b = Rational(2, 5) + >>> from fractions import Fraction + >>> a = Fraction(2, 3) + >>> b = Fraction(2, 5) >>> float(a), float(b) (0.66666666666666663, 0.40000000000000002) >>> a+b - rational.Rational(16,15) + Fraction(16, 15) >>> a/b - rational.Rational(5,3) + Fraction(5, 3) + +To help in converting floating-point numbers to rationals, +the float type now has a :meth:`as_integer_ratio()` method that returns +the numerator and denominator for a fraction that evaluates to the same +floating-point value:: + + >>> (2.5) .as_integer_ratio() + (5, 2) + >>> (3.1415) .as_integer_ratio() + (7074029114692207L, 2251799813685248L) + >>> (1./3) .as_integer_ratio() + (6004799503160661L, 18014398509481984L) + +Note that values that can only be approximated by floating-point +numbers, such as 1./3, are not simplified to the number being +approximated; the fraction attempts to match the floating-point value +**exactly**. -The :mod:`rational` module is based upon an implementation by Sjoerd +The :mod:`fractions` module is based upon an implementation by Sjoerd Mullender that was in Python's :file:`Demo/classes/` directory for a long time. This implementation was significantly updated by Jeffrey -Yaskin. - +Yasskin. Other Language Changes ====================== @@ -643,7 +1226,14 @@ >>> f(**ud) ['a', 'b'] - .. Patch 1686487 + (Contributed by Alexander Belopolsky; :issue:`1686487`.) + +* Tuples now have an :meth:`index` method matching the list type's + :meth:`index` method:: + + >>> t = (0,1,2,3,4) + >>> t.index(3) + 3 * The built-in types now have improved support for extended slicing syntax, where various combinations of ``(start, stop, step)`` are supplied. @@ -685,34 +1275,59 @@ have a :meth:`__complex__` method. In particular, the functions in the :mod:`cmath` module will now accept objects with this method. This is a backport of a Python 3.0 change. - (Contributed by Mark Dickinson.) - - .. Patch #1675423 + (Contributed by Mark Dickinson; :issue:`1675423`.) A numerical nicety: when creating a complex number from two floats on systems that support signed zeros (-0 and +0), the - :func:`complex()` constructor will now preserve the sign - of the zero. - - .. Patch 1507 + :func:`complex` constructor will now preserve the sign + of the zero. (:issue:`1507`) * More floating-point features were also added. The :func:`float` function will now turn the strings ``+nan`` and ``-nan`` into the corresponding IEEE 754 Not A Number values, and ``+inf`` and ``-inf`` into positive or negative infinity. This works on any platform with - IEEE 754 semantics. (Contributed by Christian Heimes.) - - .. Patch 1635. + IEEE 754 semantics. (Contributed by Christian Heimes; :issue:`1635`.) Other functions in the :mod:`math` module, :func:`isinf` and :func:`isnan`, return true if their floating-point argument is - infinite or Not A Number. - .. Patch 1640 - The ``math.copysign(x, y)`` function - copies the sign bit of an IEEE 754 number, returning the absolute - value of *x* combined with the sign bit of *y*. For example, - ``math.copysign(1, -0.0)`` returns -1.0. (Contributed by Christian - Heimes.) + infinite or Not A Number. (:issue:`1640`) + +* The :mod:`math` module has seven new functions, and the existing + functions have been improved to give more consistent behaviour + across platforms, especially with respect to handling of + floating-point exceptions and IEEE 754 special values. + The new functions are: + + * :func:`isinf` and :func:`isnan` determine whether a given float is + a (positive or negative) infinity or a NaN (Not a Number), + respectively. + + * ``copysign(x, y)`` copies the sign bit of an IEEE 754 number, + returning the absolute value of *x* combined with the sign bit of + *y*. For example, ``math.copysign(1, -0.0)`` returns -1.0. + (Contributed by Christian Heimes.) + + * The inverse hyperbolic functions :func:`acosh`, :func:`asinh` and + :func:`atanh`. + + * The function :func:`log1p`, returning the natural logarithm of + *1+x* (base *e*). + + There's also a new :func:`trunc` function as a result of the + backport of `PEP 3141's type hierarchy for numbers <#pep-3141>`__. + + The existing math functions have been modified to follow the + recommendations of the C99 standard with respect to special values + whenever possible. For example, ``sqrt(-1.)`` should now give a + :exc:`ValueError` across (nearly) all platforms, while + ``sqrt(float('NaN'))`` should return a NaN on all IEEE 754 + platforms. Where Annex 'F' of the C99 standard recommends signaling + 'divide-by-zero' or 'invalid', Python will raise :exc:`ValueError`. + Where Annex 'F' of the C99 standard recommends signaling 'overflow', + Python will raise :exc:`OverflowError`. (See :issue:`711019`, + :issue:`1640`.) + + (Contributed by Christian Heimes and Mark Dickinson.) * Changes to the :class:`Exception` interface as dictated by :pep:`352` continue to be made. For 2.6, @@ -723,28 +1338,26 @@ :exc:`BaseException` instead of :exc:`Exception`. This means that an exception handler that does ``except Exception:`` will not inadvertently catch :exc:`GeneratorExit`. - (Contributed by Chad Austin.) + (Contributed by Chad Austin; :issue:`1537`.) - .. Patch #1537 +* Generator objects now have a :attr:`gi_code` attribute that refers to + the original code object backing the generator. + (Contributed by Collin Winter; :issue:`1473257`.) * The :func:`compile` built-in function now accepts keyword arguments - as well as positional parameters. (Contributed by Thomas Wouters.) - - .. Patch 1444529 + as well as positional parameters. (Contributed by Thomas Wouters; + :issue:`1444529`.) * The :func:`complex` constructor now accepts strings containing parenthesized complex numbers, letting ``complex(repr(cmplx))`` will now round-trip values. For example, ``complex('(3+4j)')`` - now returns the value (3+4j). - - .. Patch 1491866 + now returns the value (3+4j). (:issue:`1491866`) * The string :meth:`translate` method now accepts ``None`` as the translation table parameter, which is treated as the identity transformation. This makes it easier to carry out operations - that only delete characters. (Contributed by Bengt Richter.) - - .. Patch 1193128 + that only delete characters. (Contributed by Bengt Richter; + :issue:`1193128`.) * The built-in :func:`dir` function now checks for a :meth:`__dir__` method on the objects it receives. This method must return a list @@ -752,8 +1365,12 @@ and lets the object control the value that :func:`dir` produces. Objects that have :meth:`__getattr__` or :meth:`__getattribute__` methods can use this to advertise pseudo-attributes they will honor. + (:issue:`1591665`) - .. Patch 1591665 +* Instance method objects have new attributes for the object and function + comprising the method; the new synonym for :attr:`im_self` is + :attr:`__self__`, and :attr:`im_func` is also available as :attr:`__func__`. + The old names are still supported in Python 2.6; they're gone in 3.0. * An obscure change: when you use the the :func:`locals` function inside a :keyword:`class` statement, the resulting dictionary no longer returns free @@ -774,9 +1391,7 @@ so the cache should remain correct even in the face of Python's dynamic nature. (Original optimization implemented by Armin Rigo, updated for - Python 2.6 by Kevin Jacobs.) - - .. % Patch 1700288 + Python 2.6 by Kevin Jacobs; :issue:`1700288`.) * All of the functions in the :mod:`struct` module have been rewritten in C, thanks to work at the Need For Speed sprint. @@ -786,11 +1401,38 @@ built-in types. This speeds up checking if an object is a subclass of one of these types. (Contributed by Neal Norwitz.) +* Unicode strings now uses faster code for detecting + whitespace and line breaks; this speeds up the :meth:`split` method + by about 25% and :meth:`splitlines` by 35%. + (Contributed by Antoine Pitrou.) Memory usage is reduced + by using pymalloc for the Unicode string's data. + +* The ``with`` statement now stores the :meth:`__exit__` method on the stack, + producing a small speedup. (Implemented by Jeffrey Yasskin.) + +* To reduce memory usage, the garbage collector will now clear internal + free lists when garbage-collecting the highest generation of objects. + This may return memory to the OS sooner. + The net result of the 2.6 optimizations is that Python 2.6 runs the pystone benchmark around XX% faster than Python 2.5. .. ====================================================================== +.. _new-26-interactive: + +Interactive Interpreter Changes +------------------------------- + +Two command-line options have been reserved for use by other Python +implementations. The :option:`-J` switch has been reserved for use by +Jython for Jython-specific options, such as ones that are passed to +the underlying JVM. :option:`-X` has been reserved for options +specific to a particular implementation of Python such as CPython, +Jython, or IronPython. If either option is used with Python 2.6, the +interpreter will report that the option isn't currently used. + +.. ====================================================================== New, Improved, and Deprecated Modules ===================================== @@ -802,9 +1444,41 @@ * The :mod:`bsddb.dbshelve` module now uses the highest pickling protocol available, instead of restricting itself to protocol 1. - (Contributed by W. Barnes.) + (Contributed by W. Barnes; :issue:`1551443`.) + +* The :mod:`cmath` module underwent an extensive set of revisions, + thanks to Mark Dickinson and Christian Heimes, that added some new + features and greatly improved the accuracy of the computations. + + Five new functions were added: + + * :func:`polar` converts a complex number to polar form, returning + the modulus and argument of that complex number. + + * :func:`rect` does the opposite, turning a (modulus, argument) pair + back into the corresponding complex number. + + * :func:`phase` returns the phase or argument of a complex number. + + * :func:`isnan` returns True if either + the real or imaginary part of its argument is a NaN. + + * :func:`isinf` returns True if either the real or imaginary part of + its argument is infinite. - .. Patch 1551443 + The revisions also improved the numerical soundness of the + :mod:`cmath` module. For all functions, the real and imaginary + parts of the results are accurate to within a few units of least + precision (ulps) whenever possible. See :issue:`1381` for the + details. The branch cuts for :func:`asinh`, :func:`atanh`: and + :func:`atan` have also been corrected. + + The tests for the module have been greatly expanded; nearly 2000 new + test cases exercise the algebraic functions. + + On IEEE 754 platforms, the :mod:`cmath` module now handles IEEE 754 + special values and floating-point exceptions in a manner consistent + with Annex 'G' of the C99 standard. * A new data type in the :mod:`collections` module: :class:`namedtuple(typename, fieldnames)` is a factory function that creates subclasses of the standard tuple @@ -824,7 +1498,7 @@ int int >>> var._asdict() {'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'} - >>> v2 = var._replace('name', 'amplitude') + >>> v2 = var._replace(name='amplitude') >>> v2 variable(id=1, name='amplitude', type='int', size=4) @@ -857,9 +1531,8 @@ (Contributed by Raymond Hettinger.) * The :mod:`ctypes` module now supports a :class:`c_bool` datatype - that represents the C99 ``bool`` type. (Contributed by David Remahl.) - - .. Patch 1649190 + that represents the C99 ``bool`` type. (Contributed by David Remahl; + :issue:`1649190`.) The :mod:`ctypes` string, buffer and array types also have improved support for extended slicing syntax, @@ -882,6 +1555,11 @@ Insert mode is enabled by supplying a true value for the *insert_mode* parameter when creating the :class:`Textbox` instance. +* The :mod:`datetime` module's :meth:`strftime` methods now support a + ``%f`` format code that expands to the number of microseconds in the + object, zero-padded on + the left to six places. (Contributed by Skip Montanaro; :issue:`1158`.) + * The :mod:`decimal` module was updated to version 1.66 of `the General Decimal Specification `__. New features include some methods for some basic mathematical functions such as @@ -909,31 +1587,37 @@ * An optional ``timeout`` parameter was added to the :class:`ftplib.FTP` class constructor as well as the :meth:`connect` method, specifying a timeout measured in seconds. (Added by Facundo - Batista.) + Batista.) Also, the :class:`FTP` class's + :meth:`storbinary` and :meth:`storlines` + now take an optional *callback* parameter that will be called with + each block of data after the data has been sent. + (Contributed by Phil Schwartz; :issue:`1221598`.) * The :func:`reduce` built-in function is also available in the :mod:`functools` module. In Python 3.0, the built-in is dropped and it's only available from :mod:`functools`; currently there are no plans to drop the built-in in the 2.x series. (Patched by - Christian Heimes.) - - .. Patch 1739906 + Christian Heimes; :issue:`1739906`.) * The :func:`glob.glob` function can now return Unicode filenames if - a Unicode path was used and Unicode filenames are matched within the directory. - - .. Patch #1001604 + a Unicode path was used and Unicode filenames are matched within the + directory. (:issue:`1001604`) * The :mod:`gopherlib` module has been removed. -* A new function in the :mod:`heapq` module: ``merge(iter1, iter2, ...)`` - takes any number of iterables that return data *in sorted order*, and returns - a new iterator that returns the contents of all the iterators, also in sorted - order. For example:: +* A new function in the :mod:`heapq` module: ``merge(iter1, iter2, ...)`` + takes any number of iterables that return data *in sorted + order*, and returns a new iterator that returns the contents of all + the iterators, also in sorted order. For example:: heapq.merge([1, 3, 5, 9], [2, 8, 16]) -> [1, 2, 3, 5, 8, 9, 16] + Another new function, ``heappushpop(heap, item)``, + pushes *item* onto *heap*, then pops off and returns the smallest item. + This is more efficient than making a call to :func:`heappush` and then + :func:`heappop`. + (Contributed by Raymond Hettinger.) * An optional ``timeout`` parameter was added to the @@ -947,33 +1631,123 @@ can also be accessed as attributes. (Contributed by Raymond Hettinger.) -* A new function in the :mod:`itertools` module: ``izip_longest(iter1, iter2, - ...[, fillvalue])`` makes tuples from each of the elements; if some of the - iterables are shorter than others, the missing values are set to *fillvalue*. - For example:: + Some new functions in the module include + :func:`isgenerator`, :func:`isgeneratorfunction`, + and :func:`isabstract`. + +* The :mod:`itertools` module gained several new functions. + + ``izip_longest(iter1, iter2, ...[, fillvalue])`` makes tuples from + each of the elements; if some of the iterables are shorter than + others, the missing values are set to *fillvalue*. For example:: itertools.izip_longest([1,2,3], [1,2,3,4,5]) -> [(1, 1), (2, 2), (3, 3), (None, 4), (None, 5)] - (Contributed by Raymond Hettinger.) + ``product(iter1, iter2, ..., [repeat=N])`` returns the Cartesian product + of the supplied iterables, a set of tuples containing + every possible combination of the elements returned from each iterable. :: + + itertools.product([1,2,3], [4,5,6]) -> + [(1, 4), (1, 5), (1, 6), + (2, 4), (2, 5), (2, 6), + (3, 4), (3, 5), (3, 6)] + + The optional *repeat* keyword argument is used for taking the + product of an iterable or a set of iterables with themselves, + repeated *N* times. With a single iterable argument, *N*-tuples + are returned:: + + itertools.product([1,2], repeat=3)) -> + [(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2), + (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)] + + With two iterables, *2N*-tuples are returned. :: + + itertools(product([1,2], [3,4], repeat=2) -> + [(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4), + (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4), + (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4), + (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)] + + ``combinations(iterable, r)`` returns sub-sequences of length *r* from + the elements of *iterable*. :: + + itertools.combinations('123', 2) -> + [('1', '2'), ('1', '3'), ('2', '3')] + + itertools.combinations('123', 3) -> + [('1', '2', '3')] + + itertools.combinations('1234', 3) -> + [('1', '2', '3'), ('1', '2', '4'), ('1', '3', '4'), + ('2', '3', '4')] + + ``permutations(iter[, r])`` returns all the permutations of length *r* of + the iterable's elements. If *r* is not specified, it will default to the + number of elements produced by the iterable. + + itertools.permutations([1,2,3,4], 2) -> + [(1, 2), (1, 3), (1, 4), + (2, 1), (2, 3), (2, 4), + (3, 1), (3, 2), (3, 4), + (4, 1), (4, 2), (4, 3)] + + ``itertools.chain(*iterables)`` is an existing function in + :mod:`itertools` that gained a new constructor in Python 2.6. + ``itertools.chain.from_iterable(iterable)`` takes a single + iterable that should return other iterables. :func:`chain` will + then return all the elements of the first iterable, then + all the elements of the second, and so on. :: + + chain.from_iterable([[1,2,3], [4,5,6]]) -> + [1, 2, 3, 4, 5, 6] + + (All contributed by Raymond Hettinger.) + +* The :mod:`logging` module's :class:`FileHandler` class + and its subclasses :class:`WatchedFileHandler`, :class:`RotatingFileHandler`, + and :class:`TimedRotatingFileHandler` now + have an optional *delay* parameter to its constructor. If *delay* + is true, opening of the log file is deferred until the first + :meth:`emit` call is made. (Contributed by Vinay Sajip.) * The :mod:`macfs` module has been removed. This in turn required the :func:`macostools.touched` function to be removed because it depended on the - :mod:`macfs` module. - - .. Patch #1490190 + :mod:`macfs` module. (:issue:`1490190`) * :class:`mmap` objects now have a :meth:`rfind` method that finds a substring, beginning at the end of the string and searching backwards. The :meth:`find` method - also gained a *end* parameter containing the index at which to stop + also gained an *end* parameter containing the index at which to stop the forward search. (Contributed by John Lenton.) -* The :mod:`new` module has been removed from Python 3.0. - Importing it therefore - triggers a warning message when Python is running in 3.0-warning - mode. +* (3.0-warning mode) The :mod:`new` module has been removed from + Python 3.0. Importing it therefore triggers a warning message. + +* The :mod:`operator` module gained a + :func:`methodcaller` function that takes a name and an optional + set of arguments, returning a callable that will call + the named function on any arguments passed to it. For example:: + + >>> # Equivalent to lambda s: s.replace('old', 'new') + >>> replacer = operator.methodcaller('replace', 'old', 'new') + >>> replacer('old wine in old bottles') + 'new wine in new bottles' + + (Contributed by Georg Brandl, after a suggestion by Gregory Petrosyan.) + + The :func:`attrgetter` function now accepts dotted names and performs + the corresponding attribute lookups:: + + >>> inst_name = operator.attrgetter('__class__.__name__') + >>> inst_name('') + 'str' + >>> inst_name(help) + '_Helper' + + (Contributed by Georg Brandl, after a suggestion by Barry Warsaw.) * New functions in the :mod:`os` module include ``fchmod(fd, mode)``, ``fchown(fd, uid, gid)``, @@ -989,43 +1763,43 @@ visit the directory's contents. For backward compatibility, the parameter's default value is false. Note that the function can fall into an infinite recursion if there's a symlink that points to a - parent directory. + parent directory. (:issue:`1273829`) - .. Patch 1273829 - * The ``os.environ`` object's :meth:`clear` method will now unset the environment variables using :func:`os.unsetenv` in addition to clearing - the object's keys. (Contributed by Martin Horcicka.) - - .. Patch #1181 + the object's keys. (Contributed by Martin Horcicka; :issue:`1181`.) * In the :mod:`os.path` module, the :func:`splitext` function has been changed to not split on leading period characters. This produces better results when operating on Unix's dot-files. For example, ``os.path.splitext('.ipython')`` now returns ``('.ipython', '')`` instead of ``('', '.ipython')``. - - .. Bug #115886 + (:issue:`115886`) A new function, :func:`relpath(path, start)` returns a relative path from the ``start`` path, if it's supplied, or from the current working directory to the destination ``path``. (Contributed by - Richard Barran.) - - .. Patch 1339796 + Richard Barran; :issue:`1339796`.) On Windows, :func:`os.path.expandvars` will now expand environment variables in the form "%var%", and "~user" will be expanded into the - user's home directory path. (Contributed by Josiah Carlson.) - - .. Patch 957650 + user's home directory path. (Contributed by Josiah Carlson; + :issue:`957650`.) * The Python debugger provided by the :mod:`pdb` module gained a new command: "run" restarts the Python program being debugged, and can optionally take new command-line arguments for the program. - (Contributed by Rocky Bernstein.) + (Contributed by Rocky Bernstein; :issue:`1393667`.) - .. Patch #1393667 + The :func:`post_mortem` function, used to enter debugging of a + traceback, will now use the traceback returned by :func:`sys.exc_info` + if no traceback is supplied. (Contributed by Facundo Batista; + :issue:`1106316`.) + +* The :mod:`pickletools` module now has an :func:`optimize` function + that takes a string containing a pickle and removes some unused + opcodes, returning a shorter pickle that contains the same data structure. + (Contributed by Raymond Hettinger.) * New functions in the :mod:`posix` module: :func:`chflags` and :func:`lchflags` are wrappers for the corresponding system calls (where they're available). @@ -1034,37 +1808,64 @@ changed and :const:`UF_APPEND` to indicate that data can only be appended to the file. (Contributed by M. Levinson.) + ``os.closerange(*low*, *high*)`` efficiently closes all file descriptors + from *low* to *high*, ignoring any errors and not including *high* itself. + This function is now used by the :mod:`subprocess` module to make starting + processes faster. (Contributed by Georg Brandl; :issue:`1663329`.) + * The :mod:`pyexpat` module's :class:`Parser` objects now allow setting their :attr:`buffer_size` attribute to change the size of the buffer used to hold character data. - (Contributed by Achim Gaedke.) + (Contributed by Achim Gaedke; :issue:`1137`.) - .. Patch 1137 +* The :mod:`Queue` module now provides queue classes that retrieve entries + in different orders. The :class:`PriorityQueue` class stores + queued items in a heap and retrieves them in priority order, + and :class:`LifoQueue` retrieves the most recently added entries first, + meaning that it behaves like a stack. + (Contributed by Raymond Hettinger.) * The :mod:`random` module's :class:`Random` objects can now be pickled on a 32-bit system and unpickled on a 64-bit system, and vice versa. Unfortunately, this change also means that Python 2.6's :class:`Random` objects can't be unpickled correctly on earlier versions of Python. - (Contributed by Shawn Ligocki.) + (Contributed by Shawn Ligocki; :issue:`1727780`.) - .. Issue 1727780 + The new ``triangular(low, high, mode)`` function returns random + numbers following a triangular distribution. The returned values + are between *low* and *high*, not including *high* itself, and + with *mode* as the mode, the most frequently occurring value + in the distribution. (Contributed by Wladmir van der Laan and + Raymond Hettinger; :issue:`1681432`.) * Long regular expression searches carried out by the :mod:`re` module will now check for signals being delivered, so especially long searches can now be interrupted. - (Contributed by Josh Hoyt and Ralf Schmitt.) - - .. % Patch 846388 + (Contributed by Josh Hoyt and Ralf Schmitt; :issue:`846388`.) * The :mod:`rgbimg` module has been removed. +* The :mod:`sched` module's :class:`scheduler` instances now + have a read-only :attr:`queue` attribute that returns the + contents of the scheduler's queue, represented as a list of + named tuples with the fields ``(time, priority, action, argument)``. + (Contributed by Raymond Hettinger; :issue:`1861`.) + +* The :mod:`select` module now has wrapper functions + for the Linux :cfunc:`epoll` and BSD :cfunc:`kqueue` system calls. + Also, a :meth:`modify` method was added to the existing :class:`poll` + objects; ``pollobj.modify(fd, eventmask)`` takes a file descriptor + or file object and an event mask, + + (Contributed by Christian Heimes; :issue:`1657`.) + * The :mod:`sets` module has been deprecated; it's better to use the built-in :class:`set` and :class:`frozenset` types. * Integrating signal handling with GUI handling event loops like those used by Tkinter or GTk+ has long been a problem; most - software ends up polling, waking up every fraction of a second. Thi + software ends up polling, waking up every fraction of a second. The :mod:`signal` module can now make this more efficient. Calling ``signal.set_wakeup_fd(fd)`` sets a file descriptor to be used; when a signal is received, a byte is written to that @@ -1072,16 +1873,25 @@ :cfunc:`PySignal_SetWakeupFd`, for setting the descriptor. Event loops will use this by opening a pipe to create two descriptors, - one for reading and one for writing. The writeable descriptor + one for reading and one for writing. The writable descriptor will be passed to :func:`set_wakeup_fd`, and the readable descriptor will be added to the list of descriptors monitored by the event loop via :cfunc:`select` or :cfunc:`poll`. On receiving a signal, a byte will be written and the main event loop will be woken up, without the need to poll. - Contributed by Adam Olsen. + (Contributed by Adam Olsen; :issue:`1583`.) - .. % Patch 1583 + The :func:`siginterrupt` function is now available from Python code, + and allows changing whether signals can interrupt system calls or not. + (Contributed by Ralf Schmitt.) + + The :func:`setitimer` and :func:`getitimer` functions have also been + added on systems that support these system calls. :func:`setitimer` + allows setting interval timers that will cause a signal to be + delivered to the process after a specified time, measured in + wall-clock time, consumed process time, or combined process+system + time. (Contributed by Guilherme Polo; :issue:`2240`.) * The :mod:`smtplib` module now supports SMTP over SSL thanks to the addition of the :class:`SMTP_SSL` class. This class supports an @@ -1096,29 +1906,34 @@ (SMTP over SSL contributed by Monty Taylor; timeout parameter added by Facundo Batista; LMTP implemented by Leif - Hedstrom.) - - .. Patch #957003 + Hedstrom; :issue:`957003`.) * In the :mod:`smtplib` module, SMTP.starttls() now complies with :rfc:`3207` and forgets any knowledge obtained from the server not obtained from - the TLS negotiation itself. Patch contributed by Bill Fenner. - - .. Issue 829951 + the TLS negotiation itself. (Patch contributed by Bill Fenner; + :issue:`829951`.) * The :mod:`socket` module now supports TIPC (http://tipc.sf.net), a high-performance non-IP-based protocol designed for use in clustered environments. TIPC addresses are 4- or 5-tuples. - (Contributed by Alberto Bertogli.) + (Contributed by Alberto Bertogli; :issue:`1646`.) - .. Patch #1646 + A new function, :func:`create_connection`, takes an address + and connects to it using an optional timeout value, returning + the connected socket object. * The base classes in the :mod:`SocketServer` module now support calling a :meth:`handle_timeout` method after a span of inactivity specified by the server's :attr:`timeout` attribute. (Contributed - by Michael Pomraning.) - - .. Patch #742598 + by Michael Pomraning.) The :meth:`serve_forever` method + now takes an optional poll interval measured in seconds, + controlling how often the server will check for a shutdown request. + (Contributed by Pedro Werneck and Jeffrey Yasskin; + :issue:`742598`, :issue:`1193577`.) + +* The :mod:`struct` module now supports the C99 :ctype:`_Bool` type, + using the format character ``'?'``. + (Contributed by David Remahl.) * A new variable in the :mod:`sys` module, :attr:`float_info`, is an object @@ -1127,9 +1942,8 @@ include :attr:`mant_dig` (number of digits in the mantissa), :attr:`epsilon` (smallest difference between 1.0 and the next largest value - representable), and several others. (Contributed by Christian Heimes.) - - .. Patch 1534 + representable), and several others. (Contributed by Christian Heimes; + :issue:`1534`.) Another new variable, :attr:`dont_write_bytecode`, controls whether Python writes any :file:`.pyc` or :file:`.pyo` files on importing a module. @@ -1149,6 +1963,10 @@ These attributes are all read-only. (Contributed by Christian Heimes.) + It's now possible to determine the current profiler and tracer functions + by calling :func:`sys.getprofile` and :func:`sys.gettrace`. + (Contributed by Georg Brandl; :issue:`1648`.) + * The :mod:`tarfile` module now supports POSIX.1-2001 (pax) and POSIX.1-1988 (ustar) format tarfiles, in addition to the GNU tar format that was already supported. The default format @@ -1181,9 +1999,17 @@ * The :class:`tempfile.NamedTemporaryFile` class usually deletes the temporary file it created when the file is closed. This behaviour can now be changed by passing ``delete=False`` to the - constructor. (Contributed by Damien Miller.) + constructor. (Contributed by Damien Miller; :issue:`1537850`.) - .. Patch #1537850 + A new class, :class:`SpooledTemporaryFile`, behaves like + a temporary file but stores its data in memory until a maximum size is + exceeded. On reaching that limit, the contents will be written to + an on-disk temporary file. (Contributed by Dustin J. Mitchell.) + + The :class:`NamedTemporaryFile` and :class:`SpooledTemporaryFile` classes + both work as context managers, so you can write + ``with tempfile.NamedTemporaryFile() as tmp: ...``. + (Contributed by Alexander Belopolsky; :issue:`2021`.) * The :mod:`test.test_support` module now contains a :func:`EnvironmentVarGuard` @@ -1220,7 +2046,7 @@ whitespace. >>> - .. Patch #1581073 + (Contributed by Dwayne Bailey; :issue:`1581073`.) * The :mod:`timeit` module now accepts callables as well as strings for the statement being timed and for the setup code. @@ -1228,9 +2054,8 @@ :class:`Timer` instances: ``repeat(stmt, setup, time, repeat, number)`` and ``timeit(stmt, setup, time, number)`` create an instance and call - the corresponding method. (Contributed by Erik Demaine.) - - .. Patch #1533909 + the corresponding method. (Contributed by Erik Demaine; + :issue:`1533909`.) * An optional ``timeout`` parameter was added to the :func:`urllib.urlopen` function and the @@ -1253,9 +2078,7 @@ :attr:`allow_reuse_address` attribute before calling the :meth:`server_bind` and :meth:`server_activate` methods to open the socket and begin listening for connections. - (Contributed by Peter Parente.) - - .. Patch 1599845 + (Contributed by Peter Parente; :issue:`1599845`.) :class:`SimpleXMLRPCServer` also has a :attr:`_send_traceback_header` attribute; if true, the exception and formatted traceback are returned @@ -1278,8 +2101,7 @@ # Unpack all the files in the archive. z.extractall() - (Contributed by Alan McIntyre.) - .. % Patch 467924 + (Contributed by Alan McIntyre; :issue:`467924`.) .. ====================================================================== .. whole new modules get described in subsections here @@ -1288,15 +2110,21 @@ -------------------------------------------------- Bill Janssen made extensive improvements to Python 2.6's support for -SSL. - -XXX use ssl.sslsocket - subclass of socket.socket. +the Secure Sockets Layer by adding a new module, :mod:`ssl`, on top of +the `OpenSSL `__ library. This new module +provides more control over the protocol negotiated, the X.509 +certificates used, and has better support for writing SSL servers (as +opposed to clients) in Python. The existing SSL support in the +:mod:`socket` module hasn't been removed and continues to work, +though it will be removed in Python 3.0. + +To use the new module, first you must create a TCP connection in the +usual way and then pass it to the :func:`ssl.wrap_socket` function. +XXX describe parameters. XXX Can specify if certificate is required, and obtain certificate info by calling getpeercert method. -XXX sslwrap() behaves like socket.ssl - XXX Certain features require the OpenSSL package to be installed, notably the 'openssl' binary. @@ -1304,6 +2132,47 @@ SSL module documentation. + +.. ====================================================================== + +plistlib: A Property-List Parser +-------------------------------------------------- + +A commonly-used format on MacOS X is the ``.plist`` format, +which stores basic data types (numbers, strings, lists, +and dictionaries) and serializes them into an XML-based format. +(It's a lot like the XML-RPC serialization of data types.) + +Despite being primarily used on MacOS X, the format +has nothing Mac-specific about it and the Python implementation works +on any platform that Python supports, so the :mod:`plistlib` module +has been promoted to the standard library. + +Using the module is simple:: + + import sys + import plistlib + import datetime + + # Create data structure + data_struct = dict(lastAccessed=datetime.datetime.now(), + version=1, + categories=('Personal', 'Shared', 'Private')) + + # Create string containing XML. + plist_str = plistlib.writePlistToString(data_struct) + new_struct = plistlib.readPlistFromString(plist_str) + print data_struct + print new_struct + + # Write data structure to a file and read it back. + plistlib.writePlist(data_struct, '/tmp/customizations.plist') + new_struct = plistlib.readPlist('/tmp/customizations.plist') + + # read/writePlist accepts file-like objects as well as paths. + plistlib.writePlist(data_struct, sys.stdout) + + .. ====================================================================== @@ -1316,12 +2185,41 @@ See the :file:`PCbuild9` directory for the build files. (Implemented by Christian Heimes.) +* Python now can only be compiled with C89 compilers (after 19 + years!). This means that the Python source tree can now drop its + own implementations of :cfunc:`memmove` and :cfunc:`strerror`, which + are in the C89 standard library. + * The BerkeleyDB module now has a C API object, available as ``bsddb.db.api``. This object can be used by other C extensions that wish to use the :mod:`bsddb` module for their own purposes. - (Contributed by Duncan Grisby.) + (Contributed by Duncan Grisby; :issue:`1551895`.) - .. Patch 1551895 +* The new buffer interface, previously described in + `the PEP 3118 section <#pep-3118-revised-buffer-protocol>`__, + adds :cfunc:`PyObject_GetBuffer` and :cfunc:`PyObject_ReleaseBuffer`, + as well as a few other functions. + +* Python's use of the C stdio library is now thread-safe, or at least + as thread-safe as the underlying library is. A long-standing potential + bug occurred if one thread closed a file object while another thread + was reading from or writing to the object. In 2.6 file objects + have a reference count, manipulated by the + :cfunc:`PyFile_IncUseCount` and :cfunc:`PyFile_DecUseCount` + functions. File objects can't be closed unless the reference count + is zero. :cfunc:`PyFile_IncUseCount` should be called while the GIL + is still held, before carrying out an I/O operation using the + ``FILE *`` pointer, and :cfunc:`PyFile_DecUseCount` should be called + immediately after the GIL is re-acquired. + (Contributed by Antoine Pitrou and Gregory P. Smith.) + +* Importing modules simultaneously in two different threads no longer + deadlocks; it will now raise an :exc:`ImportError`. A new API + function, :cfunc:`PyImport_ImportModuleNoBlock`, will look for a + module in ``sys.modules`` first, then try to import it after + acquiring an import lock. If the import lock is held by another + thread, the :exc:`ImportError` is raised. + (Contributed by Christian Heimes.) * Several functions return information about the platform's floating-point support. :cfunc:`PyFloat_GetMax` returns @@ -1332,24 +2230,46 @@ ``"mant_dig"`` (number of digits in the mantissa), ``"epsilon"`` (smallest difference between 1.0 and the next largest value representable), and several others. - (Contributed by Christian Heimes.) - - .. Issue 1534 + (Contributed by Christian Heimes; :issue:`1534`.) * Python's C API now includes two functions for case-insensitive string - comparisions, ``PyOS_stricmp(char*, char*)`` + comparisons, ``PyOS_stricmp(char*, char*)`` and ``PyOS_strnicmp(char*, char*, Py_ssize_t)``. - (Contributed by Christian Heimes.) + (Contributed by Christian Heimes; :issue:`1635`.) - .. Issue 1635 +* Many C extensions define their own little macro for adding + integers and strings to the module's dictionary in the + ``init*`` function. Python 2.6 finally defines standard macros + for adding values to a module, :cmacro:`PyModule_AddStringMacro` + and :cmacro:`PyModule_AddIntMacro()`. (Contributed by + Christian Heimes.) -* Some macros were renamed to make it clearer that they are macros, +* Some macros were renamed in both 3.0 and 2.6 to make it clearer that + they are macros, not functions. :cmacro:`Py_Size()` became :cmacro:`Py_SIZE()`, :cmacro:`Py_Type()` became :cmacro:`Py_TYPE()`, and - :cmacro:`Py_Refcnt()` became :cmacro:`Py_REFCNT()`. Macros for backward - compatibility are still available for Python 2.6. - - .. Issue 1629 + :cmacro:`Py_Refcnt()` became :cmacro:`Py_REFCNT()`. + The mixed-case macros are still available + in Python 2.6 for backward compatibility. + (:issue:`1629`) + +* Distutils now places C extensions it builds in a + different directory when running on a debug version of Python. + (Contributed by Collin Winter; :issue:`1530959`.) + +* Several basic data types, such as integers and strings, maintain + internal free lists of objects that can be re-used. The data + structures for these free lists now follow a naming convention: the + variable is always named ``free_list``, the counter is always named + ``numfree``, and a macro :cmacro:`Py_MAXFREELIST` is + always defined. + +* A new Makefile target, "make check", prepares the Python source tree + for making a patch: it fixes trailing whitespace in all modified + ``.py`` files, checks whether the documentation has been changed, + and reports whether the :file:`Misc/ACKS` and :file:`Misc/NEWS` files + have been updated. + (Contributed by Brett Cannon.) .. ====================================================================== @@ -1379,6 +2299,12 @@ module now support the context protocol, so they can be used in :keyword:`with` statements. (Contributed by Christian Heimes.) + :mod:`_winreg` also has better support for x64 systems, + exposing the :func:`DisableReflectionKey`, :func:`EnableReflectionKey`, + and :func:`QueryReflectionKey` functions, which enable and disable + registry reflection for 32-bit processes running on 64-bit systems. + (:issue:`1753245`) + * The new default compiler on Windows is Visual Studio 2008 (VS 9.0). The build directories for Visual Studio 2003 (VS7.1) and 2005 (VS8.0) were moved into the PC/ directory. The new PCbuild directory supports @@ -1417,9 +2343,8 @@ Porting to Python 2.6 ===================== -This section lists previously described changes, and a few -esoteric bugfixes, that may require changes to your -code: +This section lists previously described changes and other bugfixes +that may require changes to your code: * The :meth:`__init__` method of :class:`collections.deque` now clears any existing contents of the deque @@ -1439,12 +2364,34 @@ the implementation now explicitly checks for this case and raises an :exc:`ImportError`. +* C API: the :cfunc:`PyImport_Import` and :cfunc:`PyImport_ImportModule` + functions now default to absolute imports, not relative imports. + This will affect C extensions that import other modules. + * The :mod:`socket` module exception :exc:`socket.error` now inherits from :exc:`IOError`. Previously it wasn't a subclass of :exc:`StandardError` but now it is, through :exc:`IOError`. - (Implemented by Gregory P. Smith.) + (Implemented by Gregory P. Smith; :issue:`1706815`.) - .. Issue 1706815 +* The :mod:`xmlrpclib` module no longer automatically converts + :class:`datetime.date` and :class:`datetime.time` to the + :class:`xmlrpclib.DateTime` type; the conversion semantics were + not necessarily correct for all applications. Code using + :mod:`xmlrpclib` should convert :class:`date` and :class:`time` + instances. (:issue:`1330538`) + +* (3.0-warning mode) The :class:`Exception` class now warns + when accessed using slicing or index access; having + :class:`Exception` behave like a tuple is being phased out. + +* (3.0-warning mode) inequality comparisons between two dictionaries + or two objects that don't implement comparison methods are reported + as warnings. ``dict1 == dict2`` still works, but ``dict1 < dict2`` + is being phased out. + + Comparisons between cells, which are an implementation detail of Python's + scoping rules, also cause warnings because such comparisons are forbidden + entirely in 3.0. .. ====================================================================== @@ -1455,5 +2402,6 @@ ================ The author would like to thank the following people for offering suggestions, -corrections and assistance with various drafts of this article: . +corrections and assistance with various drafts of this article: +Georg Brandl, Jim Jewett. Modified: python/branches/py3k-ctypes-pep3118/Doc/whatsnew/3.0.rst ============================================================================== --- python/branches/py3k-ctypes-pep3118/Doc/whatsnew/3.0.rst (original) +++ python/branches/py3k-ctypes-pep3118/Doc/whatsnew/3.0.rst Wed Apr 30 15:57:13 2008 @@ -79,7 +79,7 @@ remains syntactically valid that trips people up. I'm also omitting changes to rarely used features.) -* The ``print`` statement has been replaced with a ``print()`` function, +* The ``print`` statement has been replaced with a :func:`print` function, with keyword arguments to replace most of the special syntax of the old ``print`` statement (PEP 3105). Examples:: @@ -106,9 +106,9 @@ There are <4294967296> possibilities! - Notes about the ``print()`` function: + Notes about the :func:`print` function: - * The ``print()`` function doesn't support the "softspace" feature of + * The :func:`print` function doesn't support the "softspace" feature of the old ``print`` statement. For example, in Python 2.x, ``print "A\n", "B"`` would write ``"A\nB\n"``; but in Python 3.0, ``print("A\n", "B")`` writes ``"A\n B\n"``. @@ -118,7 +118,7 @@ ``print(x)`` instead! * When using the ``2to3`` source-to-source conversion tool, all - ``print`` statements are autmatically converted to ``print()`` + ``print`` statements are autmatically converted to :func:`print` function calls, so this is mostly a non-issue for larger projects. * Python 3.0 uses strings and bytes instead of the Unicode strings and @@ -131,19 +131,23 @@ that if a file is opened using an incorrect mode or encoding, I/O will likely fail. -* ``map()`` and ``filter()`` return iterators. A quick fix is e.g. +* :func:`map` and :func:`filter` return iterators. A quick fix is e.g. ``list(map(...))``, but a better fix is often to use a list - comprehension (especially when the original code uses ``lambda``). - Particularly tricky is ``map()`` invoked for the side effects of the + comprehension (especially when the original code uses :keyword:`lambda`). + Particularly tricky is :func:`map` invoked for the side effects of the function; the correct transformation is to use a for-loop. -* ``dict`` methods ``.keys()``, ``.items()`` and ``.values()`` return - views instead of lists. For example, this no longer works: - ``k = d.keys(); k.sort()``. Use ``k = sorted(d)`` instead. +* :class:`dict` methods :meth:`dict.keys`, :meth:`dict.items` and + :meth:`dict.values` return views instead of lists. For example, this no + longer works: ``k = d.keys(); k.sort()``. Use ``k = sorted(d)`` instead. + +* :meth:`builtin.sorted` and :meth:`list.sort` no longer accept the *cmp* + argument providing a comparison function. Use the *key* argument + instead. N.B. the *key* and *reverse* arguments are now "keyword-only". * ``1/2`` returns a float. Use ``1//2`` to get the truncating behavior. -* The ``repr()`` of a long integer doesn't include the trailing ``L`` +* The :func:`repr` of a long integer doesn't include the trailing ``L`` anymore, so code that unconditionally strips that character will chop off the last digit instead. @@ -151,70 +155,91 @@ Strings and Bytes ================= -* There is only one string type; its name is ``str`` but its behavior - and implementation are more like ``unicode`` in 2.x. +* There is only one string type; its name is :class:`str` but its behavior and + implementation are like :class:`unicode` in 2.x. -* The ``basestring`` superclass has been removed. The ``2to3`` tool - replaces every occurence of ``basestring`` with ``str``. +* The :class:`basestring` superclass has been removed. The ``2to3`` tool + replaces every occurence of :class:`basestring` with :class:`str`. -* PEP 3137: There is a new type, ``bytes``, to represent binary data - (and encoded text, which is treated as binary data until you decide - to decode it). The ``str`` and ``bytes`` types cannot be mixed; you - must always explicitly convert between them, using the ``.encode()`` - (str -> bytes) or ``.decode()`` (bytes -> str) methods. +* PEP 3137: There is a new type, :class:`bytes`, to represent binary data (and + encoded text, which is treated as binary data until you decide to decode it). + The :class:`str` and :class:`bytes` types cannot be mixed; you must always + explicitly convert between them, using the :meth:`str.encode` (str -> bytes) + or :meth:`bytes.decode` (bytes -> str) methods. -* PEP 3112: Bytes literals. E.g. b"abc". +* All backslashes in raw strings are interpreted literally. This means that + Unicode escapes are not treated specially. + +.. XXX add bytearray + +* PEP 3112: Bytes literals, e.g. ``b"abc"``, create :class:`bytes` instances. * PEP 3120: UTF-8 default source encoding. -* PEP 3131: Non-ASCII identifiers. (However, the standard library - remains ASCII-only with the exception of contributor names in - comments.) +* PEP 3131: Non-ASCII identifiers. (However, the standard library remains + ASCII-only with the exception of contributor names in comments.) * PEP 3116: New I/O Implementation. The API is nearly 100% backwards - compatible, but completely reimplemented (currently mostly in - Python). Also, binary files use bytes instead of strings. + compatible, but completely reimplemented (currently mostly in Python). Also, + binary files use bytes instead of strings. + +* The :mod:`StringIO` and :mod:`cStringIO` modules are gone. Instead, import + :class:`io.StringIO` or :class:`io.BytesIO`. -* The ``StringIO`` and ``cStringIO`` modules are gone. Instead, - import ``StringIO`` or ``BytesIO`` from the ``io`` module. +* ``'\U'`` and ``'\u'`` escapes in raw strings are not treated specially. PEP 3101: A New Approach to String Formatting ============================================= -XXX +.. XXX expand this + +* A new system for built-in string formatting operations replaces the ``%`` + string formatting operator. + + +PEP 3106: Revamping dict :meth:`dict.keys`, :meth:`dict.items` and :meth:`dict.values` +====================================================================================== +.. XXX expand this -PEP 3106: Revamping ``.keys()``, ``.items()`` and ``.values()`` -=============================================================== +* The :meth:`dict.iterkeys`, :meth:`dict.itervalues` and :meth:`dict.iteritems` + methods have been removed. -XXX +* :meth:`dict.keys`, :meth:`dict.values` and :meth:`dict.items` return objects + with set behavior that reference the underlying dict. PEP 3107: Function Annotations ============================== -XXX +.. XXX expand this + +* A standardized way of annotating a function's parameters and return values. Exception Stuff =============== -* PEP 352: Exceptions must derive from BaseException. This is the - root of the exception hierarchy. +* PEP 352: Exceptions must derive from :exc:`BaseException`. This is the root + of the exception hierarchy. -* StandardException was removed (already in 2.6). +* :exc:`StandardError` was removed (already in 2.6). -* Dropping sequence behavior (slicing!) and ``.message`` attribute of +* Dropping sequence behavior (slicing!) and :attr:`message` attribute of exception instances. -* PEP 3109: Raising exceptions. You must now use ``raise - Exception(args)`` instead of ``raise Exception, args``. +* PEP 3109: Raising exceptions. You must now use ``raise Exception(args)`` + instead of ``raise Exception, args``. * PEP 3110: Catching exceptions. -* PEP 3134: Exception chaining. (The ``__context__`` feature from the - PEP hasn't been implemented yet in 3.0a1.) +* PEP 3134: Exception chaining. (The :attr:`__context__` feature from the PEP + hasn't been implemented yet in 3.0a2.) + +* A few exception messages are improved when Windows fails to load an extension + module. For example, ``error code 193`` is now ``%1 is not a valid Win32 + application``. Strings now deal with non-English locales. New Class and Metaclass Stuff @@ -238,79 +263,98 @@ Here are most of the changes that Python 3.0 makes to the core Python language and built-in functions. -* Removed backticks (use ``repr()`` instead). +* Removed backticks (use :func:`repr` instead). * Removed ``<>`` (use ``!=`` instead). -* ``as`` and ``with`` are keywords. +* ``!=`` now returns the opposite of ``==``, unless ``==`` returns + ``NotImplemented``. + +* :keyword:`as` and :keyword:`with` are keywords. -* PEP 237: ``long`` renamed to ``int``. That is, there is only one - built-in integral type, named ``int``; but it behaves like the old - ``long`` type, with the exception that the literal suffix ``L`` is - neither supported by the parser nor produced by ``repr()`` anymore. - ``sys.maxint`` was also removed since the int type has no maximum - value anymore. +* ``True``, ``False``, and ``None`` are keywords. + +* PEP 237: :class:`long` renamed to :class:`int`. That is, there is only one + built-in integral type, named :class:`int`; but it behaves like the old + :class:`long` type, with the exception that the literal suffix ``L`` is + neither supported by the parser nor produced by :func:`repr` anymore. + :data:`sys.maxint` was also removed since the int type has no maximum value + anymore. * PEP 238: int division returns a float. -* The ordering operators behave differently: for example, ``x < y`` - where ``x`` and ``y`` have incompatible types raises ``TypeError`` - instead of returning a pseudo-random boolean. - -* ``__getslice__()`` and friends killed. The syntax ``a[i:j]`` now - translates to ``a.__getitem__(slice(i, j))`` (or ``__setitem__`` - or ``__delitem__``, depending on context). - -* PEP 3102: Keyword-only arguments. Named parameters occurring after - ``*args`` in the parameter list *must* be specified using keyword - syntax in the call. You can also use a bare ``*`` in the parameter - list to indicate that you don't accept a variable-length argument - list, but you do have keyword-only arguments. +* The ordering operators behave differently: for example, ``x < y`` where ``x`` + and ``y`` have incompatible types raises :exc:`TypeError` instead of returning + a pseudo-random boolean. + +* :meth:`__getslice__` and friends killed. The syntax ``a[i:j]`` now translates + to ``a.__getitem__(slice(i, j))`` (or :meth:`__setitem__` or + :meth:`__delitem__`, depending on context). + +* PEP 3102: Keyword-only arguments. Named parameters occurring after ``*args`` + in the parameter list *must* be specified using keyword syntax in the call. + You can also use a bare ``*`` in the parameter list to indicate that you don't + accept a variable-length argument list, but you do have keyword-only + arguments. -* PEP 3104: ``nonlocal`` statement. Using ``nonlocal x`` you can now +* PEP 3104: :keyword:`nonlocal` statement. Using ``nonlocal x`` you can now assign directly to a variable in an outer (but non-global) scope. -* PEP 3111: ``raw_input()`` renamed to ``input()``. That is, the new - ``input()`` function reads a line from ``sys.stdin`` and returns it - with the trailing newline stripped. It raises ``EOFError`` if the - input is terminated prematurely. To get the old behavior of - ``input()``, use ``eval(input())``. - -* ``xrange()`` renamed to ``range()``. - -* PEP 3113: Tuple parameter unpacking removed. You can no longer write - ``def foo(a, (b, c)): ...``. Use ``def foo(a, b_c): b, c = b_c`` - instead. - -* PEP 3114: ``.next()`` renamed to ``.__next__()``, new builtin - ``next()`` to call the ``__next__()`` method on an object. - -* PEP 3127: New octal literals; binary literals and ``bin()``. - Instead of ``0666``, you write ``0o666``. The oct() function is - modified accordingly. Also, ``0b1010`` equals 10, and ``bin(10)`` - returns ``"0b1010"``. ``0666`` is now a ``SyntaxError``. - -* PEP 3132: Extended Iterable Unpacking. You can now write things - like ``a, b, *rest = some_sequence``. And even ``*rest, a = - stuff``. The ``rest`` object is always a list; the right-hand - side may be any iterable. - -* PEP 3135: New ``super()``. You can now invoke ``super()`` without - arguments and the right class and instance will automatically be - chosen. With arguments, its behavior is unchanged. +* PEP 3111: :func:`raw_input` renamed to :func:`input`. That is, the new + :func:`input` function reads a line from :data:`sys.stdin` and returns it with + the trailing newline stripped. It raises :exc:`EOFError` if the input is + terminated prematurely. To get the old behavior of :func:`input`, use + ``eval(input())``. + +* :func:`xrange` renamed to :func:`range`, so :func:`range` will no longer + produce a list but an iterable yielding integers when iterated over. + +* PEP 3113: Tuple parameter unpacking removed. You can no longer write ``def + foo(a, (b, c)): ...``. Use ``def foo(a, b_c): b, c = b_c`` instead. + +* PEP 3114: ``.next()`` renamed to :meth:`__next__`, new builtin :func:`next` to + call the :meth:`__next__` method on an object. + +* PEP 3127: New octal literals; binary literals and :func:`bin`. Instead of + ``0666``, you write ``0o666``. The :func:`oct` function is modified + accordingly. Also, ``0b1010`` equals 10, and ``bin(10)`` returns + ``"0b1010"``. ``0666`` is now a :exc:`SyntaxError`. + +* PEP 3132: Extended Iterable Unpacking. You can now write things like ``a, b, + *rest = some_sequence``. And even ``*rest, a = stuff``. The ``rest`` object + is always a list; the right-hand side may be any iterable. + +* PEP 3135: New :func:`super`. You can now invoke :func:`super` without + arguments and the right class and instance will automatically be chosen. With + arguments, its behavior is unchanged. -* ``zip()``, ``map()`` and ``filter()`` return iterators. +* :func:`zip`, :func:`map` and :func:`filter` return iterators. -* ``string.letters`` and its friends (``.lowercase`` and - ``.uppercase``) are gone. Use ``string.ascii_letters`` +* :data:`string.letters` and its friends (:data:`string.lowercase` and + :data:`string.uppercase`) are gone. Use :data:`string.ascii_letters` etc. instead. -* Removed: ``apply()``, ``callable()``, ``coerce()``, ``execfile()``, - ``file()``, ``reduce()``, ``reload()``. +* Removed: :func:`apply`, :func:`callable`, :func:`coerce`, :func:`execfile`, + :func:`file`, :func:`reduce`, :func:`reload`. + +* Removed: :meth:`dict.has_key` -- use the ``in`` operator instead. + +* :func:`exec` is now a function. -* Removed: ``dict.has_key()``. +* There is a new free format floating point representation, which is based on + "Floating-Point Printer Sample Code", by Robert G. Burger. ``repr(11./5)`` + now returns ``2.2`` instead of ``2.2000000000000002``. -* ``exec`` is now a function. +* The :meth:`__oct__` and :meth:`__hex__` special methods are removed -- + :func:`oct` and :func:`hex` use :meth:`__index__` now to convert the argument + to an integer. + +* Support is removed for :attr:`__members__` and :attr:`__methods__`. + +* Renamed the boolean conversion C-level slot and method: ``nb_nonzero`` is now + ``nb_bool`` and :meth:`__nonzero__` is now :meth:`__bool__`. + +* Removed :data:`sys.maxint`. Use :data:`sys.maxsize`. .. ====================================================================== @@ -321,10 +365,10 @@ * Detailed changes are listed here. -The net result of the 3.0 generalizations is that Python 3.0 runs the -pystone benchmark around 33% slower than Python 2.5. There's room for -improvement; we expect to be optimizing string and integer operations -significantly before the final 3.0 release! +The net result of the 3.0 generalizations is that Python 3.0 runs the pystone +benchmark around 33% slower than Python 2.5. There's room for improvement; we +expect to be optimizing string and integer operations significantly before the +final 3.0 release! .. ====================================================================== @@ -332,15 +376,31 @@ New, Improved, and Deprecated Modules ===================================== -As usual, Python's standard library received a number of enhancements -and bug fixes. Here's a partial list of the most notable changes, -sorted alphabetically by module name. Consult the :file:`Misc/NEWS` -file in the source tree for a more complete list of changes, or look -through the Subversion logs for all the details. +As usual, Python's standard library received a number of enhancements and bug +fixes. Here's a partial list of the most notable changes, sorted alphabetically +by module name. Consult the :file:`Misc/NEWS` file in the source tree for a more +complete list of changes, or look through the Subversion logs for all the +details. -* The ``cPickle`` module is gone. Use ``pickle`` instead. Eventually +* The :mod:`cPickle` module is gone. Use :mod:`pickle` instead. Eventually we'll have a transparent accelerator module. +* The :mod:`imageop` module is gone. + +* The :mod:`audiodev`, :mod:`Bastion`, :mod:`bsddb185`, :mod:`exceptions`, + :mod:`linuxaudiodev`, :mod:`md5`, :mod:`MimeWriter`, :mod:`mimify`, + :mod:`popen2`, :mod:`rexec`, :mod:`sets`, :mod:`sha`, :mod:`stringold`, + :mod:`strop`, :mod:`sunaudiodev`, :mod:`timing`, and :mod:`xmllib` modules are + gone. + +* The :mod:`new` module is gone. + +* The functions :func:`os.tmpnam`, :func:`os.tempnam` and :func:`os.tmpfile` + have been removed in favor of the :mod:`tempfile` module. + +* The :mod:`tokenize` module has been changed to work with bytes. The main + entry point is now :func:`tokenize.tokenize`, instead of generate_tokens. + .. ====================================================================== .. whole new modules get described in subsections here @@ -356,7 +416,16 @@ * PEP 3121: Extension Module Initialization & Finalization. -* PEP 3123: Making ``PyObject_HEAD`` conform to standard C. +* PEP 3123: Making :cmacro:`PyObject_HEAD` conform to standard C. + +* No more C API support for restricted execution. + +* :cfunc:`PyNumber_Coerce`, :cfunc:`PyNumber_CoerceEx`, :cfunc:`PyMember_Get`, + and :cfunc:`PyMember_Set` C APIs are removed. + +* New C API :cfunc:`PyImport_ImportModuleNoBlock`, works like + :cfunc:`PyImport_ImportModule` but won't block on the import lock (returning + an error instead). .. ====================================================================== @@ -366,6 +435,7 @@ Platform-specific changes go here. + .. ====================================================================== Modified: python/branches/py3k-ctypes-pep3118/Include/Python-ast.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/Python-ast.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/Python-ast.h Wed Apr 30 15:57:13 2008 @@ -342,10 +342,17 @@ asdl_seq *ifs; }; +enum _excepthandler_kind {ExceptHandler_kind=1}; struct _excepthandler { - expr_ty type; - identifier name; - asdl_seq *body; + enum _excepthandler_kind kind; + union { + struct { + expr_ty type; + identifier name; + asdl_seq *body; + } ExceptHandler; + + } v; int lineno; int col_offset; }; @@ -525,8 +532,8 @@ #define comprehension(a0, a1, a2, a3) _Py_comprehension(a0, a1, a2, a3) comprehension_ty _Py_comprehension(expr_ty target, expr_ty iter, asdl_seq * ifs, PyArena *arena); -#define excepthandler(a0, a1, a2, a3, a4, a5) _Py_excepthandler(a0, a1, a2, a3, a4, a5) -excepthandler_ty _Py_excepthandler(expr_ty type, identifier name, asdl_seq * +#define ExceptHandler(a0, a1, a2, a3, a4, a5) _Py_ExceptHandler(a0, a1, a2, a3, a4, a5) +excepthandler_ty _Py_ExceptHandler(expr_ty type, identifier name, asdl_seq * body, int lineno, int col_offset, PyArena *arena); #define arguments(a0, a1, a2, a3, a4, a5, a6, a7, a8) _Py_arguments(a0, a1, a2, a3, a4, a5, a6, a7, a8) @@ -542,3 +549,5 @@ alias_ty _Py_alias(identifier name, identifier asname, PyArena *arena); PyObject* PyAST_mod2obj(mod_ty t); +mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode); +int PyAST_Check(PyObject* obj); Modified: python/branches/py3k-ctypes-pep3118/Include/Python.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/Python.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/Python.h Wed Apr 30 15:57:13 2008 @@ -57,6 +57,7 @@ #if defined(PYMALLOC_DEBUG) && !defined(WITH_PYMALLOC) #error "PYMALLOC_DEBUG requires WITH_PYMALLOC" #endif +#include "pymath.h" #include "pymem.h" #include "object.h" @@ -93,6 +94,7 @@ #include "iterobject.h" #include "genobject.h" #include "descrobject.h" +#include "warnings.h" #include "weakrefobject.h" #include "codecs.h" @@ -124,7 +126,7 @@ #ifdef __CHAR_UNSIGNED__ #define Py_CHARMASK(c) (c) #else -#define Py_CHARMASK(c) ((c) & 0xff) +#define Py_CHARMASK(c) ((unsigned char)((c) & 0xff)) #endif #include "pyfpe.h" Modified: python/branches/py3k-ctypes-pep3118/Include/abstract.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/abstract.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/abstract.h Wed Apr 30 15:57:13 2008 @@ -611,6 +611,13 @@ */ + PyAPI_FUNC(PyObject *) PyObject_Format(PyObject* obj, + PyObject *format_spec); + /* + Takes an arbitrary object and returns the result of + calling obj.__format__(format_spec). + */ + /* Iterators */ PyAPI_FUNC(PyObject *) PyObject_GetIter(PyObject *); @@ -793,6 +800,19 @@ PyAPI_FUNC(Py_ssize_t) PyNumber_AsSsize_t(PyObject *o, PyObject *exc); /* + Returns the Integral instance converted to an int. The + instance is expected to be int or long or have an __int__ + method. Steals integral's reference. error_format will be + used to create the TypeError if integral isn't actually an + Integral instance. error_format should be a format string + that can accept a char* naming integral's type. + */ + + PyAPI_FUNC(PyObject *) _PyNumber_ConvertIntegralToInt( + PyObject *integral, + const char* error_format); + + /* Returns the object converted to Py_ssize_t by going through PyNumber_Index first. If an overflow error occurs while converting the int-or-long to Py_ssize_t, then the second argument Modified: python/branches/py3k-ctypes-pep3118/Include/ceval.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/ceval.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/ceval.h Wed Apr 30 15:57:13 2008 @@ -51,7 +51,7 @@ _Py_CheckRecursiveCall(where)) #define Py_LeaveRecursiveCall() \ do{ if((--PyThreadState_GET()->recursion_depth) < \ - _Py_CheckRecursionLimit - 50); \ + _Py_CheckRecursionLimit - 50) \ PyThreadState_GET()->overflowed = 0; \ } while(0) PyAPI_FUNC(int) _Py_CheckRecursiveCall(char *where); Modified: python/branches/py3k-ctypes-pep3118/Include/classobject.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/classobject.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/classobject.h Wed Apr 30 15:57:13 2008 @@ -31,6 +31,7 @@ #define PyMethod_GET_SELF(meth) \ (((PyMethodObject *)meth) -> im_self) +PyAPI_FUNC(int) PyMethod_ClearFreeList(void); typedef struct { PyObject_HEAD Modified: python/branches/py3k-ctypes-pep3118/Include/code.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/code.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/code.h Wed Apr 30 15:57:13 2008 @@ -48,6 +48,8 @@ #define CO_FUTURE_DIVISION 0x2000 #define CO_FUTURE_ABSOLUTE_IMPORT 0x4000 /* do absolute imports by default */ #define CO_FUTURE_WITH_STATEMENT 0x8000 +#define CO_FUTURE_PRINT_FUNCTION 0x10000 +#define CO_FUTURE_UNICODE_LITERALS 0x20000 #endif /* This should be defined if a future statement modifies the syntax. Modified: python/branches/py3k-ctypes-pep3118/Include/compile.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/compile.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/compile.h Wed Apr 30 15:57:13 2008 @@ -24,6 +24,8 @@ #define FUTURE_DIVISION "division" #define FUTURE_ABSOLUTE_IMPORT "absolute_import" #define FUTURE_WITH_STATEMENT "with_statement" +#define FUTURE_PRINT_FUNCTION "print_function" +#define FUTURE_UNICODE_LITERALS "unicode_literals" struct _mod; /* Declare the existence of this type */ PyAPI_FUNC(PyCodeObject *) PyAST_Compile(struct _mod *, const char *, Modified: python/branches/py3k-ctypes-pep3118/Include/complexobject.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/complexobject.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/complexobject.h Wed Apr 30 15:57:13 2008 @@ -19,6 +19,7 @@ #define c_prod _Py_c_prod #define c_quot _Py_c_quot #define c_pow _Py_c_pow +#define c_abs _Py_c_abs PyAPI_FUNC(Py_complex) c_sum(Py_complex, Py_complex); PyAPI_FUNC(Py_complex) c_diff(Py_complex, Py_complex); @@ -26,6 +27,7 @@ PyAPI_FUNC(Py_complex) c_prod(Py_complex, Py_complex); PyAPI_FUNC(Py_complex) c_quot(Py_complex, Py_complex); PyAPI_FUNC(Py_complex) c_pow(Py_complex, Py_complex); +PyAPI_FUNC(double) c_abs(Py_complex); /* Complex object interface */ Modified: python/branches/py3k-ctypes-pep3118/Include/floatobject.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/floatobject.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/floatobject.h Wed Apr 30 15:57:13 2008 @@ -21,6 +21,17 @@ #define PyFloat_Check(op) PyObject_TypeCheck(op, &PyFloat_Type) #define PyFloat_CheckExact(op) (Py_TYPE(op) == &PyFloat_Type) +#ifdef Py_NAN +#define Py_RETURN_NAN return PyFloat_FromDouble(Py_NAN) +#endif + +#define Py_RETURN_INF(sign) do \ + if (copysign(1., sign) == 1.) { \ + return PyFloat_FromDouble(Py_HUGE_VAL); \ + } else { \ + return PyFloat_FromDouble(-Py_HUGE_VAL); \ + } while(0) + PyAPI_FUNC(double) PyFloat_GetMax(void); PyAPI_FUNC(double) PyFloat_GetMin(void); PyAPI_FUNC(PyObject *) PyFloat_GetInfo(void); @@ -91,6 +102,9 @@ PyAPI_FUNC(double) _PyFloat_Unpack4(const unsigned char *p, int le); PyAPI_FUNC(double) _PyFloat_Unpack8(const unsigned char *p, int le); +/* free list api */ +PyAPI_FUNC(void) PyFloat_CompactFreeList(size_t *, size_t *, size_t *); + #ifdef __cplusplus } #endif Modified: python/branches/py3k-ctypes-pep3118/Include/frameobject.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/frameobject.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/frameobject.h Wed Apr 30 15:57:13 2008 @@ -73,6 +73,8 @@ PyAPI_FUNC(void) PyFrame_LocalsToFast(PyFrameObject *, int); PyAPI_FUNC(void) PyFrame_FastToLocals(PyFrameObject *); +PyAPI_FUNC(int) PyFrame_ClearFreeList(void); + #ifdef __cplusplus } #endif Modified: python/branches/py3k-ctypes-pep3118/Include/genobject.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/genobject.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/genobject.h Wed Apr 30 15:57:13 2008 @@ -18,6 +18,9 @@ /* True if generator is being executed. */ int gi_running; + + /* The code object backing the generator */ + PyObject *gi_code; /* List of weak reference. */ PyObject *gi_weakreflist; Modified: python/branches/py3k-ctypes-pep3118/Include/graminit.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/graminit.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/graminit.h Wed Apr 30 15:57:13 2008 @@ -1,3 +1,5 @@ +/* Generated by Parser/pgen */ + #define single_input 256 #define file_input 257 #define eval_input 258 Modified: python/branches/py3k-ctypes-pep3118/Include/iterobject.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/iterobject.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/iterobject.h Wed Apr 30 15:57:13 2008 @@ -7,7 +7,6 @@ PyAPI_DATA(PyTypeObject) PySeqIter_Type; PyAPI_DATA(PyTypeObject) PyCallIter_Type; -PyAPI_DATA(PyTypeObject) PyZipIter_Type; PyAPI_DATA(PyTypeObject) PyCmpWrapper_Type; #define PySeqIter_Check(op) (Py_TYPE(op) == &PySeqIter_Type) @@ -19,8 +18,6 @@ PyAPI_FUNC(PyObject *) PyCallIter_New(PyObject *, PyObject *); -PyObject* _PyZip_CreateIter(PyObject* args); - #ifdef __cplusplus } #endif Modified: python/branches/py3k-ctypes-pep3118/Include/methodobject.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/methodobject.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/methodobject.h Wed Apr 30 15:57:13 2008 @@ -85,6 +85,8 @@ PyObject *m_module; /* The __module__ attribute, can be anything */ } PyCFunctionObject; +PyAPI_FUNC(int) PyCFunction_ClearFreeList(void); + #ifdef __cplusplus } #endif Modified: python/branches/py3k-ctypes-pep3118/Include/object.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/object.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/object.h Wed Apr 30 15:57:13 2008 @@ -277,7 +277,6 @@ typedef struct { getbufferproc bf_getbuffer; releasebufferproc bf_releasebuffer; - inquiry bf_multisegment; } PyBufferProcs; typedef void (*freefunc)(void *); @@ -428,6 +427,7 @@ PyAPI_FUNC(PyObject *) PyType_GenericNew(PyTypeObject *, PyObject *, PyObject *); PyAPI_FUNC(PyObject *) _PyType_Lookup(PyTypeObject *, PyObject *); +PyAPI_FUNC(unsigned int) PyType_ClearCache(void); /* Generic operations on objects */ PyAPI_FUNC(int) PyObject_Print(PyObject *, FILE *, int); @@ -532,6 +532,9 @@ #define Py_TPFLAGS_HAVE_VERSION_TAG (1L<<18) #define Py_TPFLAGS_VALID_VERSION_TAG (1L<<19) +/* Type is abstract and cannot be instantiated */ +#define Py_TPFLAGS_IS_ABSTRACT (1L<<20) + /* These flags are used to determine if a type is a subclass. */ #define Py_TPFLAGS_INT_SUBCLASS (1L<<23) #define Py_TPFLAGS_LONG_SUBCLASS (1L<<24) @@ -559,7 +562,7 @@ objects that don't contain references to other objects or heap memory this can be the standard function free(). Both macros can be used wherever a void expression is allowed. The argument must not be a -NIL pointer. If it may be NIL, use Py_XINCREF/Py_XDECREF instead. +NULL pointer. If it may be NULL, use Py_XINCREF/Py_XDECREF instead. The macro _Py_NewReference(op) initialize reference counts to 1, and in special builds (Py_REF_DEBUG, Py_TRACE_REFS) performs additional bookkeeping appropriate to the special build. Modified: python/branches/py3k-ctypes-pep3118/Include/osdefs.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/osdefs.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/osdefs.h Wed Apr 30 15:57:13 2008 @@ -12,20 +12,20 @@ #if defined(MS_WINDOWS) || defined(__BORLANDC__) || defined(__WATCOMC__) || defined(__DJGPP__) || defined(PYOS_OS2) #if defined(PYOS_OS2) && defined(PYCC_GCC) #define MAXPATHLEN 260 -#define SEP '/' -#define ALTSEP '\\' +#define SEP L'/' +#define ALTSEP L'\\' #else -#define SEP '\\' -#define ALTSEP '/' +#define SEP L'\\' +#define ALTSEP L'/' #define MAXPATHLEN 256 #endif -#define DELIM ';' +#define DELIM L';' #endif #endif /* Filename separator */ #ifndef SEP -#define SEP '/' +#define SEP L'/' #endif /* Max pathname length */ @@ -39,7 +39,7 @@ /* Search path entry delimiter */ #ifndef DELIM -#define DELIM ':' +#define DELIM L':' #endif #ifdef __cplusplus Modified: python/branches/py3k-ctypes-pep3118/Include/parsetok.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/parsetok.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/parsetok.h Wed Apr 30 15:57:13 2008 @@ -25,6 +25,8 @@ #if 0 #define PyPARSE_WITH_IS_KEYWORD 0x0003 +#define PyPARSE_PRINT_IS_FUNCTION 0x0004 +#define PyPARSE_UNICODE_LITERALS 0x0008 #endif PyAPI_FUNC(node *) PyParser_ParseString(const char *, grammar *, int, @@ -38,11 +40,19 @@ const char*, grammar *, int, char *, char *, perrdetail *, int); +PyAPI_FUNC(node *) PyParser_ParseFileFlagsEx(FILE *, const char *, + const char*, grammar *, + int, char *, char *, + perrdetail *, int *); PyAPI_FUNC(node *) PyParser_ParseStringFlagsFilename(const char *, const char *, grammar *, int, perrdetail *, int); +PyAPI_FUNC(node *) PyParser_ParseStringFlagsFilenameEx(const char *, + const char *, + grammar *, int, + perrdetail *, int *); /* Note that he following function is defined in pythonrun.c not parsetok.c. */ PyAPI_FUNC(void) PyParser_SetError(perrdetail *); Modified: python/branches/py3k-ctypes-pep3118/Include/patchlevel.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/patchlevel.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/patchlevel.h Wed Apr 30 15:57:13 2008 @@ -15,14 +15,16 @@ /* Higher for patch releases */ /* Version parsed out into numeric values */ +/*--start constants--*/ #define PY_MAJOR_VERSION 3 #define PY_MINOR_VERSION 0 #define PY_MICRO_VERSION 0 #define PY_RELEASE_LEVEL PY_RELEASE_LEVEL_ALPHA -#define PY_RELEASE_SERIAL 2 +#define PY_RELEASE_SERIAL 4 /* Version as a string */ -#define PY_VERSION "3.0a2+" +#define PY_VERSION "3.0a4+" +/*--end constants--*/ /* Subversion Revision number of this file (not of the repository) */ #define PY_PATCHLEVEL_REVISION "$Revision$" Modified: python/branches/py3k-ctypes-pep3118/Include/pyerrors.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/pyerrors.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/pyerrors.h Wed Apr 30 15:57:13 2008 @@ -152,6 +152,8 @@ PyAPI_DATA(PyObject *) PyExc_VMSError; #endif +PyAPI_DATA(PyObject *) PyExc_BufferError; + PyAPI_DATA(PyObject *) PyExc_MemoryErrorInst; PyAPI_DATA(PyObject *) PyExc_RecursionErrorInst; @@ -216,13 +218,6 @@ PyObject *dict); PyAPI_FUNC(void) PyErr_WriteUnraisable(PyObject *); -/* Issue a warning or exception */ -PyAPI_FUNC(int) PyErr_WarnEx(PyObject *category, const char *msg, - Py_ssize_t stack_level); -PyAPI_FUNC(int) PyErr_WarnExplicit(PyObject *, const char *, - const char *, int, - const char *, PyObject *); - /* In sigcheck.c or signalmodule.c */ PyAPI_FUNC(int) PyErr_CheckSignals(void); PyAPI_FUNC(void) PyErr_SetInterrupt(void); Modified: python/branches/py3k-ctypes-pep3118/Include/pygetopt.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/pygetopt.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/pygetopt.h Wed Apr 30 15:57:13 2008 @@ -7,9 +7,9 @@ PyAPI_DATA(int) _PyOS_opterr; PyAPI_DATA(int) _PyOS_optind; -PyAPI_DATA(char *) _PyOS_optarg; +PyAPI_DATA(wchar_t *) _PyOS_optarg; -PyAPI_FUNC(int) _PyOS_GetOpt(int argc, char **argv, char *optstring); +PyAPI_FUNC(int) _PyOS_GetOpt(int argc, wchar_t **argv, wchar_t *optstring); #ifdef __cplusplus } Modified: python/branches/py3k-ctypes-pep3118/Include/pyport.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/pyport.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/pyport.h Wed Apr 30 15:57:13 2008 @@ -111,6 +111,10 @@ /* Smallest negative value of type Py_ssize_t. */ #define PY_SSIZE_T_MIN (-PY_SSIZE_T_MAX-1) +#if SIZEOF_PID_T > SIZEOF_LONG +# error "Python doesn't support sizeof(pid_t) > sizeof(long)" +#endif + /* PY_FORMAT_SIZE_T is a platform-specific modifier for use in a printf * format to convert an argument with the width of a size_t or Py_ssize_t. * C99 introduced "z" for this purpose, but not all platforms support that; @@ -332,123 +336,6 @@ #define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) (NARROW)(VALUE) #endif -/* High precision defintion of pi and e (Euler) - * The values are taken from libc6's math.h. - */ -#ifndef Py_MATH_PIl -#define Py_MATH_PIl 3.1415926535897932384626433832795029L -#endif -#ifndef Py_MATH_PI -#define Py_MATH_PI 3.14159265358979323846 -#endif - -#ifndef Py_MATH_El -#define Py_MATH_El 2.7182818284590452353602874713526625L -#endif - -#ifndef Py_MATH_E -#define Py_MATH_E 2.7182818284590452354 -#endif - -/* Py_IS_NAN(X) - * Return 1 if float or double arg is a NaN, else 0. - * Caution: - * X is evaluated more than once. - * This may not work on all platforms. Each platform has *some* - * way to spell this, though -- override in pyconfig.h if you have - * a platform where it doesn't work. - */ -#ifndef Py_IS_NAN -#ifdef HAVE_ISNAN -#define Py_IS_NAN(X) isnan(X) -#else -#define Py_IS_NAN(X) ((X) != (X)) -#endif -#endif - -/* Py_IS_INFINITY(X) - * Return 1 if float or double arg is an infinity, else 0. - * Caution: - * X is evaluated more than once. - * This implementation may set the underflow flag if |X| is very small; - * it really can't be implemented correctly (& easily) before C99. - * Override in pyconfig.h if you have a better spelling on your platform. - */ -#ifndef Py_IS_INFINITY -#ifdef HAVE_ISINF -#define Py_IS_INFINITY(X) isinf(X) -#else -#define Py_IS_INFINITY(X) ((X) && (X)*0.5 == (X)) -#endif -#endif - -/* Py_IS_FINITE(X) - * Return 1 if float or double arg is neither infinite nor NAN, else 0. - * Some compilers (e.g. VisualStudio) have intrisics for this, so a special - * macro for this particular test is useful - */ -#ifndef Py_IS_FINITE -#ifdef HAVE_FINITE -#define Py_IS_FINITE(X) finite(X) -#else -#define Py_IS_FINITE(X) (!Py_IS_INFINITY(X) && !Py_IS_NAN(X)) -#endif -#endif - -/* HUGE_VAL is supposed to expand to a positive double infinity. Python - * uses Py_HUGE_VAL instead because some platforms are broken in this - * respect. We used to embed code in pyport.h to try to worm around that, - * but different platforms are broken in conflicting ways. If you're on - * a platform where HUGE_VAL is defined incorrectly, fiddle your Python - * config to #define Py_HUGE_VAL to something that works on your platform. - */ -#ifndef Py_HUGE_VAL -#define Py_HUGE_VAL HUGE_VAL -#endif - -/* Py_NAN - * A value that evaluates to a NaN. On IEEE 754 platforms INF*0 or - * INF/INF works. Define Py_NO_NAN in pyconfig.h if your platform - * doesn't support NaNs. - */ -#if !defined(Py_NAN) && !defined(Py_NO_NAN) -#define Py_NAN (Py_HUGE_VAL * 0.) -#endif - -/* Py_OVERFLOWED(X) - * Return 1 iff a libm function overflowed. Set errno to 0 before calling - * a libm function, and invoke this macro after, passing the function - * result. - * Caution: - * This isn't reliable. C99 no longer requires libm to set errno under - * any exceptional condition, but does require +- HUGE_VAL return - * values on overflow. A 754 box *probably* maps HUGE_VAL to a - * double infinity, and we're cool if that's so, unless the input - * was an infinity and an infinity is the expected result. A C89 - * system sets errno to ERANGE, so we check for that too. We're - * out of luck if a C99 754 box doesn't map HUGE_VAL to +Inf, or - * if the returned result is a NaN, or if a C89 box returns HUGE_VAL - * in non-overflow cases. - * X is evaluated more than once. - * Some platforms have better way to spell this, so expect some #ifdef'ery. - * - * OpenBSD uses 'isinf()' because a compiler bug on that platform causes - * the longer macro version to be mis-compiled. This isn't optimal, and - * should be removed once a newer compiler is available on that platform. - * The system that had the failure was running OpenBSD 3.2 on Intel, with - * gcc 2.95.3. - * - * According to Tim's checkin, the FreeBSD systems use isinf() to work - * around a FPE bug on that platform. - */ -#if defined(__FreeBSD__) || defined(__OpenBSD__) -#define Py_OVERFLOWED(X) isinf(X) -#else -#define Py_OVERFLOWED(X) ((X) != 0.0 && (errno == ERANGE || \ - (X) == Py_HUGE_VAL || \ - (X) == -Py_HUGE_VAL)) -#endif - /* Py_SET_ERRNO_ON_MATH_ERROR(x) * If a libm function did not set errno, but it looks like the result * overflowed or not-a-number, set errno to ERANGE or EDOM. Set errno @@ -550,20 +437,11 @@ functions, even though they are included in libutil. */ #include extern int openpty(int *, int *, char *, struct termios *, struct winsize *); -extern int forkpty(int *, char *, struct termios *, struct winsize *); +extern pid_t forkpty(int *, char *, struct termios *, struct winsize *); #endif /* !defined(HAVE_PTY_H) && !defined(HAVE_LIBUTIL_H) */ #endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) */ -/************************ - * WRAPPER FOR * - ************************/ - -#ifndef HAVE_HYPOT -extern double hypot(double, double); -#endif - - /* On 4.4BSD-descendants, ctype functions serves the whole range of * wchar_t character set rather than single byte code points only. * This characteristic can break some operations of string object Modified: python/branches/py3k-ctypes-pep3118/Include/pythonrun.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/pythonrun.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/pythonrun.h Wed Apr 30 15:57:13 2008 @@ -17,11 +17,11 @@ int cf_flags; /* bitmask of CO_xxx flags relevant to future */ } PyCompilerFlags; -PyAPI_FUNC(void) Py_SetProgramName(char *); -PyAPI_FUNC(char *) Py_GetProgramName(void); +PyAPI_FUNC(void) Py_SetProgramName(wchar_t *); +PyAPI_FUNC(wchar_t *) Py_GetProgramName(void); -PyAPI_FUNC(void) Py_SetPythonHome(char *); -PyAPI_FUNC(char *) Py_GetPythonHome(void); +PyAPI_FUNC(void) Py_SetPythonHome(wchar_t *); +PyAPI_FUNC(wchar_t *) Py_GetPythonHome(void); PyAPI_FUNC(void) Py_Initialize(void); PyAPI_FUNC(void) Py_InitializeEx(int); @@ -81,7 +81,7 @@ PyAPI_FUNC(int) Py_FdIsInteractive(FILE *, const char *); /* Bootstrap */ -PyAPI_FUNC(int) Py_Main(int argc, char **argv); +PyAPI_FUNC(int) Py_Main(int argc, wchar_t **argv); /* Use macros for a bunch of old variants */ #define PyRun_String(str, s, g, l) PyRun_StringFlags(str, s, g, l, NULL) @@ -103,10 +103,10 @@ PyRun_FileExFlags(fp, p, s, g, l, 0, flags) /* In getpath.c */ -PyAPI_FUNC(char *) Py_GetProgramFullPath(void); -PyAPI_FUNC(char *) Py_GetPrefix(void); -PyAPI_FUNC(char *) Py_GetExecPrefix(void); -PyAPI_FUNC(char *) Py_GetPath(void); +PyAPI_FUNC(wchar_t *) Py_GetProgramFullPath(void); +PyAPI_FUNC(wchar_t *) Py_GetPrefix(void); +PyAPI_FUNC(wchar_t *) Py_GetExecPrefix(void); +PyAPI_FUNC(wchar_t *) Py_GetPath(void); /* In their own files */ PyAPI_FUNC(const char *) Py_GetVersion(void); @@ -134,6 +134,7 @@ PyAPI_FUNC(void) PyMethod_Fini(void); PyAPI_FUNC(void) PyFrame_Fini(void); PyAPI_FUNC(void) PyCFunction_Fini(void); +PyAPI_FUNC(void) PyDict_Fini(void); PyAPI_FUNC(void) PyTuple_Fini(void); PyAPI_FUNC(void) PyList_Fini(void); PyAPI_FUNC(void) PySet_Fini(void); Modified: python/branches/py3k-ctypes-pep3118/Include/setobject.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/setobject.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/setobject.h Wed Apr 30 15:57:13 2008 @@ -74,6 +74,12 @@ (Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type || \ PyType_IsSubtype(Py_TYPE(ob), &PySet_Type) || \ PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type)) +#define PySet_Check(ob) \ + (Py_TYPE(ob) == &PySet_Type || \ + PyType_IsSubtype(Py_TYPE(ob), &PySet_Type)) +#define PyFrozenSet_Check(ob) \ + (Py_TYPE(ob) == &PyFrozenSet_Type || \ + PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type)) PyAPI_FUNC(PyObject *) PySet_New(PyObject *); PyAPI_FUNC(PyObject *) PyFrozenSet_New(PyObject *); @@ -83,7 +89,6 @@ PyAPI_FUNC(int) PySet_Contains(PyObject *anyset, PyObject *key); PyAPI_FUNC(int) PySet_Discard(PyObject *set, PyObject *key); PyAPI_FUNC(int) PySet_Add(PyObject *set, PyObject *key); -PyAPI_FUNC(int) _PySet_Next(PyObject *set, Py_ssize_t *pos, PyObject **key); PyAPI_FUNC(int) _PySet_NextEntry(PyObject *set, Py_ssize_t *pos, PyObject **key, long *hash); PyAPI_FUNC(PyObject *) PySet_Pop(PyObject *set); PyAPI_FUNC(int) _PySet_Update(PyObject *set, PyObject *iterable); Modified: python/branches/py3k-ctypes-pep3118/Include/sysmodule.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/sysmodule.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/sysmodule.h Wed Apr 30 15:57:13 2008 @@ -9,8 +9,8 @@ PyAPI_FUNC(PyObject *) PySys_GetObject(const char *); PyAPI_FUNC(int) PySys_SetObject(const char *, PyObject *); -PyAPI_FUNC(void) PySys_SetArgv(int, char **); -PyAPI_FUNC(void) PySys_SetPath(const char *); +PyAPI_FUNC(void) PySys_SetArgv(int, wchar_t **); +PyAPI_FUNC(void) PySys_SetPath(const wchar_t *); PyAPI_FUNC(void) PySys_WriteStdout(const char *format, ...) Py_GCC_ATTRIBUTE((format(printf, 1, 2))); @@ -21,7 +21,8 @@ PyAPI_DATA(int) _PySys_CheckInterval; PyAPI_FUNC(void) PySys_ResetWarnOptions(void); -PyAPI_FUNC(void) PySys_AddWarnOption(const char *); +PyAPI_FUNC(void) PySys_AddWarnOption(const wchar_t *); +PyAPI_FUNC(int) PySys_HasWarnOptions(void); #ifdef __cplusplus } Modified: python/branches/py3k-ctypes-pep3118/Include/traceback.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/traceback.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/traceback.h Wed Apr 30 15:57:13 2008 @@ -19,6 +19,7 @@ PyAPI_FUNC(int) PyTraceBack_Here(struct _frame *); PyAPI_FUNC(int) PyTraceBack_Print(PyObject *, PyObject *); +PyAPI_FUNC(int) Py_DisplaySourceLine(PyObject *, const char *, int); /* Reveal traceback type so we can typecheck traceback objects */ PyAPI_DATA(PyTypeObject) PyTraceBack_Type; Modified: python/branches/py3k-ctypes-pep3118/Include/tupleobject.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/tupleobject.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/tupleobject.h Wed Apr 30 15:57:13 2008 @@ -53,6 +53,8 @@ /* Macro, *only* to be used to fill in brand new tuples */ #define PyTuple_SET_ITEM(op, i, v) (((PyTupleObject *)(op))->ob_item[i] = v) +PyAPI_FUNC(int) PyTuple_ClearFreeList(void); + #ifdef __cplusplus } #endif Modified: python/branches/py3k-ctypes-pep3118/Include/unicodeobject.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Include/unicodeobject.h (original) +++ python/branches/py3k-ctypes-pep3118/Include/unicodeobject.h Wed Apr 30 15:57:13 2008 @@ -1,6 +1,8 @@ #ifndef Py_UNICODEOBJECT_H #define Py_UNICODEOBJECT_H +#include + /* Unicode implementation based on original code by Fredrik Lundh, @@ -208,6 +210,7 @@ # define _PyUnicode_AsDefaultEncodedString _PyUnicodeUCS2_AsDefaultEncodedString # define _PyUnicode_Fini _PyUnicodeUCS2_Fini # define _PyUnicode_Init _PyUnicodeUCS2_Init +# define PyUnicode_ClearFreeList PyUnicodeUCS2_ClearFreelist # define _PyUnicode_IsAlpha _PyUnicodeUCS2_IsAlpha # define _PyUnicode_IsDecimalDigit _PyUnicodeUCS2_IsDecimalDigit # define _PyUnicode_IsDigit _PyUnicodeUCS2_IsDigit @@ -301,6 +304,7 @@ # define _PyUnicode_AsDefaultEncodedString _PyUnicodeUCS4_AsDefaultEncodedString # define _PyUnicode_Fini _PyUnicodeUCS4_Fini # define _PyUnicode_Init _PyUnicodeUCS4_Init +# define PyUnicode_ClearFreeList PyUnicodeUCS2_ClearFreelist # define _PyUnicode_IsAlpha _PyUnicodeUCS4_IsAlpha # define _PyUnicode_IsDecimalDigit _PyUnicodeUCS4_IsDecimalDigit # define _PyUnicode_IsDigit _PyUnicodeUCS4_IsDigit @@ -356,7 +360,14 @@ #else -#define Py_UNICODE_ISSPACE(ch) _PyUnicode_IsWhitespace(ch) +/* Since splitting on whitespace is an important use case, and whitespace + in most situations is solely ASCII whitespace, we optimize for the common + case by using a quick look-up table with an inlined check. + */ +extern const unsigned char _Py_ascii_whitespace[]; + +#define Py_UNICODE_ISSPACE(ch) \ + ((ch) < 128U ? _Py_ascii_whitespace[(ch)] : _PyUnicode_IsWhitespace(ch)) #define Py_UNICODE_ISLOWER(ch) _PyUnicode_IsLowercase(ch) #define Py_UNICODE_ISUPPER(ch) _PyUnicode_IsUppercase(ch) @@ -404,6 +415,8 @@ extern "C" { #endif +PyAPI_FUNC(int) PyUnicode_ClearFreeList(void); + /* --- Unicode Type ------------------------------------------------------- */ typedef struct { @@ -647,7 +660,8 @@ */ PyAPI_FUNC(PyObject *) _PyUnicode_AsDefaultEncodedString( - PyObject *, const char *); + PyObject *unicode, + const char *errors); /* Decode a null-terminated string using Py_FileSystemDefaultEncoding. @@ -668,26 +682,36 @@ Py_ssize_t size /* size */ ); +/* Returns a pointer to the default encoding (normally, UTF-8) of the + Unicode object unicode and the size of the encoded representation + in bytes stored in *size. -/* Return a char* holding the UTF-8 encoded value of the - Unicode object. + In case of an error, no *size is set. - DEPRECATED: use PyUnicode_AsStringAndSize() instead. */ -PyAPI_FUNC(char *) PyUnicode_AsStringAndSize(PyObject*, Py_ssize_t *); +PyAPI_FUNC(char *) PyUnicode_AsStringAndSize( + PyObject *unicode, + Py_ssize_t *size); -/* Returns the UTF-8 encoding, and its size. +/* Returns a pointer to the default encoding (normally, UTf-8) of the + Unicode object unicode. - If the output argument is NULL, no size is stored. - */ + Use of this API is DEPRECATED since no size information can be + extracted from the returned data. Use PyUnicode_AsStringAndSize() + instead. -PyAPI_FUNC(char *) PyUnicode_AsString(PyObject*); +*/ -/* Returns the UTF-8 encoding. +PyAPI_FUNC(char *) PyUnicode_AsString(PyObject *unicode); - This is equivalent to PyUnicode_AsStringAndSize(x, NULL). +/* Returns the currently active default encoding. + The default encoding is currently implemented as run-time settable + process global. This may change in future versions of the + interpreter to become a parameter which is managed on a per-thread + basis. + */ PyAPI_FUNC(const char*) PyUnicode_GetDefaultEncoding(void); Modified: python/branches/py3k-ctypes-pep3118/LICENSE ============================================================================== --- python/branches/py3k-ctypes-pep3118/LICENSE (original) +++ python/branches/py3k-ctypes-pep3118/LICENSE Wed Apr 30 15:57:13 2008 @@ -55,7 +55,7 @@ 2.4.4 2.4.3 2006 PSF yes 2.5 2.4 2006 PSF yes 2.5.1 2.5 2007 PSF yes - 2.6 2.5 unreleased PSF yes + 2.6 2.5 2008 PSF yes 3.0 2.6 2007 PSF yes Footnotes: @@ -92,7 +92,7 @@ prepare derivative works, distribute, and otherwise use Python alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright (c) -2001, 2002, 2003, 2004, 2005, 2006, 2007 Python Software Foundation; +2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Python Software Foundation; All Rights Reserved" are retained in Python alone or in any derivative version prepared by Licensee. Modified: python/branches/py3k-ctypes-pep3118/Lib/BaseHTTPServer.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/BaseHTTPServer.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/BaseHTTPServer.py Wed Apr 30 15:57:13 2008 @@ -77,7 +77,7 @@ import mimetools import SocketServer -# Default error message +# Default error message template DEFAULT_ERROR_MESSAGE = """\ Error response @@ -90,6 +90,8 @@ """ +DEFAULT_ERROR_CONTENT_TYPE = "text/html;charset=utf-8" + def _quote_html(html): return html.replace("&", "&").replace("<", "<").replace(">", ">") @@ -217,6 +219,9 @@ # where each string is of the form name[/version]. server_version = "BaseHTTP/" + __version__ + error_message_format = DEFAULT_ERROR_MESSAGE + error_content_type = DEFAULT_ERROR_CONTENT_TYPE + def parse_request(self): """Parse a request (internal). @@ -356,14 +361,12 @@ content = (self.error_message_format % {'code': code, 'message': _quote_html(message), 'explain': explain}) self.send_response(code, message) - self.send_header("Content-Type", "text/html;charset=utf-8") + self.send_header("Content-Type", self.error_content_type) self.send_header('Connection', 'close') self.end_headers() if self.command != 'HEAD' and code >= 200 and code not in (204, 304): self.wfile.write(content.encode('UTF-8', 'replace')) - error_message_format = DEFAULT_ERROR_MESSAGE - def send_response(self, code, message=None): """Send the response header and log the response code. Modified: python/branches/py3k-ctypes-pep3118/Lib/ConfigParser.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/ConfigParser.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/ConfigParser.py Wed Apr 30 15:57:13 2008 @@ -235,8 +235,12 @@ """Create a new section in the configuration. Raise DuplicateSectionError if a section by the specified name - already exists. + already exists. Raise ValueError if name is DEFAULT or any of it's + case-insensitive variants. """ + if section.lower() == "default": + raise ValueError('Invalid section name: %s' % section) + if section in self._sections: raise DuplicateSectionError(section) self._sections[section] = self._dict() Modified: python/branches/py3k-ctypes-pep3118/Lib/DocXMLRPCServer.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/DocXMLRPCServer.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/DocXMLRPCServer.py Wed Apr 30 15:57:13 2008 @@ -30,7 +30,7 @@ results = [] here = 0 - # XXX Note that this regular expressions does not allow for the + # XXX Note that this regular expression does not allow for the # hyperlinking of arbitrary strings being used as method # names. Only methods with names consisting of word characters # and '.'s are hyperlinked. @@ -52,7 +52,7 @@ url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc) results.append('%s' % (url, escape(all))) elif pep: - url = 'http://www.python.org/peps/pep-%04d.html' % int(pep) + url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep) results.append('%s' % (url, escape(all))) elif text[end:end+1] == '(': results.append(self.namelink(name, methods, funcs, classes)) Modified: python/branches/py3k-ctypes-pep3118/Lib/SimpleHTTPServer.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/SimpleHTTPServer.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/SimpleHTTPServer.py Wed Apr 30 15:57:13 2008 @@ -14,7 +14,6 @@ import posixpath import BaseHTTPServer import urllib -import urlparse import cgi import shutil import mimetypes @@ -110,8 +109,9 @@ list.sort(key=lambda a: a.lower()) f = StringIO() displaypath = cgi.escape(urllib.unquote(self.path)) - f.write("Directory listing for %s\n" % displaypath) - f.write("

Directory listing for %s

\n" % displaypath) + f.write('') + f.write("\nDirectory listing for %s\n" % displaypath) + f.write("\n

Directory listing for %s

\n" % displaypath) f.write("
\n
    \n") for name in list: fullname = os.path.join(path, name) @@ -125,7 +125,7 @@ # Note: a link to a directory displays with @ and links with / f.write('
  • %s\n' % (urllib.quote(linkname), cgi.escape(displayname))) - f.write("
\n
\n") + f.write("\n
\n\n\n") length = f.tell() f.seek(0) self.send_response(200) @@ -143,7 +143,8 @@ """ # abandon query parameters - path = urlparse.urlparse(path)[2] + path = path.split('?',1)[0] + path = path.split('#',1)[0] path = posixpath.normpath(urllib.unquote(path)) words = path.split('/') words = filter(None, words) Modified: python/branches/py3k-ctypes-pep3118/Lib/SocketServer.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/SocketServer.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/SocketServer.py Wed Apr 30 15:57:13 2008 @@ -130,8 +130,13 @@ import socket +import select import sys import os +try: + import threading +except ImportError: + import dummy_threading as threading __all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer", "ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler", @@ -149,7 +154,8 @@ Methods for the caller: - __init__(server_address, RequestHandlerClass) - - serve_forever() + - serve_forever(poll_interval=0.5) + - shutdown() - handle_request() # if you do not use serve_forever() - fileno() -> int # for select() @@ -190,6 +196,8 @@ """Constructor. May be extended, do not override.""" self.server_address = server_address self.RequestHandlerClass = RequestHandlerClass + self.__is_shut_down = threading.Event() + self.__serving = False def server_activate(self): """Called by constructor to activate the server. @@ -199,27 +207,73 @@ """ pass - def serve_forever(self): - """Handle one request at a time until doomsday.""" - while 1: - self.handle_request() + def serve_forever(self, poll_interval=0.5): + """Handle one request at a time until shutdown. + + Polls for shutdown every poll_interval seconds. Ignores + self.timeout. If you need to do periodic tasks, do them in + another thread. + """ + self.__serving = True + self.__is_shut_down.clear() + while self.__serving: + # XXX: Consider using another file descriptor or + # connecting to the socket to wake this up instead of + # polling. Polling reduces our responsiveness to a + # shutdown request and wastes cpu at all other times. + r, w, e = select.select([self], [], [], poll_interval) + if r: + self._handle_request_noblock() + self.__is_shut_down.set() + + def shutdown(self): + """Stops the serve_forever loop. + + Blocks until the loop has finished. This must be called while + serve_forever() is running in another thread, or it will + deadlock. + """ + self.__serving = False + self.__is_shut_down.wait() # The distinction between handling, getting, processing and # finishing a request is fairly arbitrary. Remember: # # - handle_request() is the top-level call. It calls - # await_request(), verify_request() and process_request() - # - get_request(), called by await_request(), is different for - # stream or datagram sockets + # select, get_request(), verify_request() and process_request() + # - get_request() is different for stream or datagram sockets # - process_request() is the place that may fork a new process # or create a new thread to finish the request # - finish_request() instantiates the request handler class; # this constructor will handle the request all by itself def handle_request(self): - """Handle one request, possibly blocking.""" + """Handle one request, possibly blocking. + + Respects self.timeout. + """ + # Support people who used socket.settimeout() to escape + # handle_request before self.timeout was available. + timeout = self.socket.gettimeout() + if timeout is None: + timeout = self.timeout + elif self.timeout is not None: + timeout = min(timeout, self.timeout) + fd_sets = select.select([self], [], [], timeout) + if not fd_sets[0]: + self.handle_timeout() + return + self._handle_request_noblock() + + def _handle_request_noblock(self): + """Handle one request, without blocking. + + I assume that select.select has returned that the socket is + readable before this function was called, so there should be + no risk of blocking in get_request(). + """ try: - request, client_address = self.await_request() + request, client_address = self.get_request() except socket.error: return if self.verify_request(request, client_address): @@ -229,21 +283,6 @@ self.handle_error(request, client_address) self.close_request(request) - def await_request(self): - """Call get_request or handle_timeout, observing self.timeout. - - Returns value from get_request() or raises socket.timeout exception if - timeout was exceeded. - """ - if self.timeout is not None: - # If timeout == 0, you're responsible for your own fd magic. - import select - fd_sets = select.select([self], [], [], self.timeout) - if not fd_sets[0]: - self.handle_timeout() - raise socket.timeout("Listening timed out") - return self.get_request() - def handle_timeout(self): """Called if no new request arrives within self.timeout. @@ -307,7 +346,8 @@ Methods for the caller: - __init__(server_address, RequestHandlerClass, bind_and_activate=True) - - serve_forever() + - serve_forever(poll_interval=0.5) + - shutdown() - handle_request() # if you don't use serve_forever() - fileno() -> int # for select() @@ -440,20 +480,36 @@ def collect_children(self): """Internal routine to wait for children that have exited.""" - while self.active_children: - if len(self.active_children) < self.max_children: - options = os.WNOHANG - else: - # If the maximum number of children are already - # running, block while waiting for a child to exit - options = 0 + if self.active_children is None: return + while len(self.active_children) >= self.max_children: + # XXX: This will wait for any child process, not just ones + # spawned by this library. This could confuse other + # libraries that expect to be able to wait for their own + # children. try: - pid, status = os.waitpid(0, options) + pid, status = os.waitpid(0, options=0) except os.error: pid = None - if not pid: break + if pid not in self.active_children: continue self.active_children.remove(pid) + # XXX: This loop runs more system calls than it ought + # to. There should be a way to put the active_children into a + # process group and then use os.waitpid(-pgid) to wait for any + # of that set, but I couldn't find a way to allocate pgids + # that couldn't collide. + for child in self.active_children: + try: + pid, status = os.waitpid(child, os.WNOHANG) + except os.error: + pid = None + if not pid: continue + try: + self.active_children.remove(pid) + except ValueError as e: + raise ValueError('%s. x=%d and list=%r' % (e.message, pid, + self.active_children)) + def handle_timeout(self): """Wait for zombies after self.timeout seconds of inactivity. @@ -507,7 +563,6 @@ def process_request(self, request, client_address): """Start a new thread to process the request.""" - import threading t = threading.Thread(target = self.process_request_thread, args = (request, client_address)) if self.daemon_threads: Deleted: python/branches/py3k-ctypes-pep3118/Lib/UserDict.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/UserDict.py Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,181 +0,0 @@ -"""A more or less complete user-defined wrapper around dictionary objects.""" - -class UserDict: - def __init__(self, dict=None, **kwargs): - self.data = {} - if dict is not None: - self.update(dict) - if len(kwargs): - self.update(kwargs) - def __repr__(self): return repr(self.data) - def __eq__(self, dict): - if isinstance(dict, UserDict): - return self.data == dict.data - else: - return self.data == dict - def __ne__(self, dict): - if isinstance(dict, UserDict): - return self.data != dict.data - else: - return self.data != dict - def __len__(self): return len(self.data) - def __getitem__(self, key): - if key in self.data: - return self.data[key] - if hasattr(self.__class__, "__missing__"): - return self.__class__.__missing__(self, key) - raise KeyError(key) - def __setitem__(self, key, item): self.data[key] = item - def __delitem__(self, key): del self.data[key] - def clear(self): self.data.clear() - def copy(self): - if self.__class__ is UserDict: - return UserDict(self.data.copy()) - import copy - data = self.data - try: - self.data = {} - c = copy.copy(self) - finally: - self.data = data - c.update(self) - return c - def keys(self): return self.data.keys() - def items(self): return self.data.items() - def values(self): return self.data.values() - def update(self, dict=None, **kwargs): - if dict is None: - pass - elif isinstance(dict, UserDict): - self.data.update(dict.data) - elif isinstance(dict, type({})) or not hasattr(dict, 'items'): - self.data.update(dict) - else: - for k, v in dict.items(): - self[k] = v - if len(kwargs): - self.data.update(kwargs) - def get(self, key, failobj=None): - if key not in self: - return failobj - return self[key] - def setdefault(self, key, failobj=None): - if key not in self: - self[key] = failobj - return self[key] - def pop(self, key, *args): - return self.data.pop(key, *args) - def popitem(self): - return self.data.popitem() - def __contains__(self, key): - return key in self.data - @classmethod - def fromkeys(cls, iterable, value=None): - d = cls() - for key in iterable: - d[key] = value - return d - -class IterableUserDict(UserDict): - def __iter__(self): - return iter(self.data) - -class DictMixin: - # Mixin defining all dictionary methods for classes that already have - # a minimum dictionary interface including getitem, setitem, delitem, - # and keys. Without knowledge of the subclass constructor, the mixin - # does not define __init__() or copy(). In addition to the four base - # methods, progressively more efficiency comes with defining - # __contains__(), __iter__(), and iteritems(). - - # XXX It would make more sense to expect __iter__ to be primitive. - - # second level definitions support higher levels - def __iter__(self): - for k in self.keys(): - yield k - def __contains__(self, key): - try: - value = self[key] - except KeyError: - return False - return True - - # third level takes advantage of second level definitions - def iterkeys(self): - return self.__iter__() - def iteritems(self): - for k in self: - yield (k, self[k]) - - # fourth level uses definitions from lower levels - def itervalues(self): - for _, v in self.iteritems(): - yield v - def values(self): - return [v for _, v in self.iteritems()] - def items(self): - return list(self.iteritems()) - def clear(self): - for key in list(self.iterkeys()): - del self[key] - def setdefault(self, key, default=None): - try: - return self[key] - except KeyError: - self[key] = default - return default - def pop(self, key, *args): - if len(args) > 1: - raise TypeError("pop expected at most 2 arguments, got " - + repr(1 + len(args))) - try: - value = self[key] - except KeyError: - if args: - return args[0] - raise - del self[key] - return value - def popitem(self): - try: - k, v = next(self.iteritems()) - except StopIteration: - raise KeyError('container is empty') - del self[k] - return (k, v) - def update(self, other=None, **kwargs): - # Make progressively weaker assumptions about "other" - if other is None: - pass - elif hasattr(other, 'iteritems'): # iteritems saves memory and lookups - for k, v in other.iteritems(): - self[k] = v - elif hasattr(other, 'items'): # items may also save memory and lookups - for k, v in other.items(): - self[k] = v - elif hasattr(other, 'keys'): - for k in other.keys(): - self[k] = other[k] - else: - for k, v in other: - self[k] = v - if kwargs: - self.update(kwargs) - def get(self, key, default=None): - try: - return self[key] - except KeyError: - return default - def __repr__(self): - return repr(dict(self.iteritems())) - def __eq__(self, other): - if isinstance(other, DictMixin): - other = dict(other.iteritems()) - return dict(self.iteritems()) == other - def __ne__(self, other): - if isinstance(other, DictMixin): - other = dict(other.iteritems()) - return dict(self.iteritems()) != other - def __len__(self): - return len(self.keys()) Deleted: python/branches/py3k-ctypes-pep3118/Lib/UserList.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/UserList.py Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,71 +0,0 @@ -"""A more or less complete user-defined wrapper around list objects.""" - -class UserList: - def __init__(self, initlist=None): - self.data = [] - if initlist is not None: - # XXX should this accept an arbitrary sequence? - if type(initlist) == type(self.data): - self.data[:] = initlist - elif isinstance(initlist, UserList): - self.data[:] = initlist.data[:] - else: - self.data = list(initlist) - def __repr__(self): return repr(self.data) - def __lt__(self, other): return self.data < self.__cast(other) - def __le__(self, other): return self.data <= self.__cast(other) - def __eq__(self, other): return self.data == self.__cast(other) - def __ne__(self, other): return self.data != self.__cast(other) - def __gt__(self, other): return self.data > self.__cast(other) - def __ge__(self, other): return self.data >= self.__cast(other) - def __cast(self, other): - if isinstance(other, UserList): return other.data - else: return other - def __cmp__(self, other): - return cmp(self.data, self.__cast(other)) - def __contains__(self, item): return item in self.data - def __len__(self): return len(self.data) - def __getitem__(self, i): return self.data[i] - def __setitem__(self, i, item): self.data[i] = item - def __delitem__(self, i): del self.data[i] - def __add__(self, other): - if isinstance(other, UserList): - return self.__class__(self.data + other.data) - elif isinstance(other, type(self.data)): - return self.__class__(self.data + other) - else: - return self.__class__(self.data + list(other)) - def __radd__(self, other): - if isinstance(other, UserList): - return self.__class__(other.data + self.data) - elif isinstance(other, type(self.data)): - return self.__class__(other + self.data) - else: - return self.__class__(list(other) + self.data) - def __iadd__(self, other): - if isinstance(other, UserList): - self.data += other.data - elif isinstance(other, type(self.data)): - self.data += other - else: - self.data += list(other) - return self - def __mul__(self, n): - return self.__class__(self.data*n) - __rmul__ = __mul__ - def __imul__(self, n): - self.data *= n - return self - def append(self, item): self.data.append(item) - def insert(self, i, item): self.data.insert(i, item) - def pop(self, i=-1): return self.data.pop(i) - def remove(self, item): self.data.remove(item) - def count(self, item): return self.data.count(item) - def index(self, item, *args): return self.data.index(item, *args) - def reverse(self): self.data.reverse() - def sort(self, *args, **kwds): self.data.sort(*args, **kwds) - def extend(self, other): - if isinstance(other, UserList): - self.data.extend(other.data) - else: - self.data.extend(other) Deleted: python/branches/py3k-ctypes-pep3118/Lib/UserString.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/UserString.py Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,241 +0,0 @@ -#!/usr/bin/env python -## vim:ts=4:et:nowrap -"""A user-defined wrapper around string objects - -Note: string objects have grown methods in Python 1.6 -This module requires Python 1.6 or later. -""" -import sys - -__all__ = ["UserString","MutableString"] - -class UserString: - def __init__(self, seq): - if isinstance(seq, str): - self.data = seq - elif isinstance(seq, UserString): - self.data = seq.data[:] - else: - self.data = str(seq) - def __str__(self): return str(self.data) - def __repr__(self): return repr(self.data) - def __int__(self): return int(self.data) - def __long__(self): return int(self.data) - def __float__(self): return float(self.data) - def __complex__(self): return complex(self.data) - def __hash__(self): return hash(self.data) - - def __eq__(self, string): - if isinstance(string, UserString): - return self.data == string.data - else: - return self.data == string - def __ne__(self, string): - if isinstance(string, UserString): - return self.data != string.data - else: - return self.data != string - def __lt__(self, string): - if isinstance(string, UserString): - return self.data < string.data - else: - return self.data < string - def __le__(self, string): - if isinstance(string, UserString): - return self.data <= string.data - else: - return self.data <= string - def __gt__(self, string): - if isinstance(string, UserString): - return self.data > string.data - else: - return self.data > string - def __ge__(self, string): - if isinstance(string, UserString): - return self.data >= string.data - else: - return self.data >= string - - def __contains__(self, char): - if isinstance(char, UserString): - char = char.data - return char in self.data - - def __len__(self): return len(self.data) - def __getitem__(self, index): return self.__class__(self.data[index]) - def __add__(self, other): - if isinstance(other, UserString): - return self.__class__(self.data + other.data) - elif isinstance(other, str): - return self.__class__(self.data + other) - else: - return self.__class__(self.data + str(other)) - def __radd__(self, other): - if isinstance(other, str): - return self.__class__(other + self.data) - else: - return self.__class__(str(other) + self.data) - def __mul__(self, n): - return self.__class__(self.data*n) - __rmul__ = __mul__ - def __mod__(self, args): - return self.__class__(self.data % args) - - # the following methods are defined in alphabetical order: - def capitalize(self): return self.__class__(self.data.capitalize()) - def center(self, width, *args): - return self.__class__(self.data.center(width, *args)) - def count(self, sub, start=0, end=sys.maxsize): - if isinstance(sub, UserString): - sub = sub.data - return self.data.count(sub, start, end) - def decode(self, encoding=None, errors=None): # XXX improve this? - if encoding: - if errors: - return self.__class__(self.data.decode(encoding, errors)) - else: - return self.__class__(self.data.decode(encoding)) - else: - return self.__class__(self.data.decode()) - def encode(self, encoding=None, errors=None): # XXX improve this? - if encoding: - if errors: - return self.__class__(self.data.encode(encoding, errors)) - else: - return self.__class__(self.data.encode(encoding)) - else: - return self.__class__(self.data.encode()) - def endswith(self, suffix, start=0, end=sys.maxsize): - return self.data.endswith(suffix, start, end) - def expandtabs(self, tabsize=8): - return self.__class__(self.data.expandtabs(tabsize)) - def find(self, sub, start=0, end=sys.maxsize): - if isinstance(sub, UserString): - sub = sub.data - return self.data.find(sub, start, end) - def index(self, sub, start=0, end=sys.maxsize): - return self.data.index(sub, start, end) - def isalpha(self): return self.data.isalpha() - def isalnum(self): return self.data.isalnum() - def isdecimal(self): return self.data.isdecimal() - def isdigit(self): return self.data.isdigit() - def islower(self): return self.data.islower() - def isnumeric(self): return self.data.isnumeric() - def isspace(self): return self.data.isspace() - def istitle(self): return self.data.istitle() - def isupper(self): return self.data.isupper() - def join(self, seq): return self.data.join(seq) - def ljust(self, width, *args): - return self.__class__(self.data.ljust(width, *args)) - def lower(self): return self.__class__(self.data.lower()) - def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars)) - def partition(self, sep): - return self.data.partition(sep) - def replace(self, old, new, maxsplit=-1): - if isinstance(old, UserString): - old = old.data - if isinstance(new, UserString): - new = new.data - return self.__class__(self.data.replace(old, new, maxsplit)) - def rfind(self, sub, start=0, end=sys.maxsize): - return self.data.rfind(sub, start, end) - def rindex(self, sub, start=0, end=sys.maxsize): - return self.data.rindex(sub, start, end) - def rjust(self, width, *args): - return self.__class__(self.data.rjust(width, *args)) - def rpartition(self, sep): - return self.data.rpartition(sep) - def rstrip(self, chars=None): return self.__class__(self.data.rstrip(chars)) - def split(self, sep=None, maxsplit=-1): - return self.data.split(sep, maxsplit) - def rsplit(self, sep=None, maxsplit=-1): - return self.data.rsplit(sep, maxsplit) - def splitlines(self, keepends=0): return self.data.splitlines(keepends) - def startswith(self, prefix, start=0, end=sys.maxsize): - return self.data.startswith(prefix, start, end) - def strip(self, chars=None): return self.__class__(self.data.strip(chars)) - def swapcase(self): return self.__class__(self.data.swapcase()) - def title(self): return self.__class__(self.data.title()) - def translate(self, *args): - return self.__class__(self.data.translate(*args)) - def upper(self): return self.__class__(self.data.upper()) - def zfill(self, width): return self.__class__(self.data.zfill(width)) - -class MutableString(UserString): - """mutable string objects - - Python strings are immutable objects. This has the advantage, that - strings may be used as dictionary keys. If this property isn't needed - and you insist on changing string values in place instead, you may cheat - and use MutableString. - - But the purpose of this class is an educational one: to prevent - people from inventing their own mutable string class derived - from UserString and than forget thereby to remove (override) the - __hash__ method inherited from UserString. This would lead to - errors that would be very hard to track down. - - A faster and better solution is to rewrite your program using lists.""" - def __init__(self, string=""): - self.data = string - def __hash__(self): - raise TypeError("unhashable type (it is mutable)") - def __setitem__(self, index, sub): - if isinstance(index, slice): - if isinstance(sub, UserString): - sub = sub.data - elif not isinstance(sub, str): - sub = str(sub) - start, stop, step = index.indices(len(self.data)) - if step == -1: - start, stop = stop+1, start+1 - sub = sub[::-1] - elif step != 1: - # XXX(twouters): I guess we should be reimplementing - # the extended slice assignment/deletion algorithm here... - raise TypeError("invalid step in slicing assignment") - start = min(start, stop) - self.data = self.data[:start] + sub + self.data[stop:] - else: - if index < 0: - index += len(self.data) - if index < 0 or index >= len(self.data): raise IndexError - self.data = self.data[:index] + sub + self.data[index+1:] - def __delitem__(self, index): - if isinstance(index, slice): - start, stop, step = index.indices(len(self.data)) - if step == -1: - start, stop = stop+1, start+1 - elif step != 1: - # XXX(twouters): see same block in __setitem__ - raise TypeError("invalid step in slicing deletion") - start = min(start, stop) - self.data = self.data[:start] + self.data[stop:] - else: - if index < 0: - index += len(self.data) - if index < 0 or index >= len(self.data): raise IndexError - self.data = self.data[:index] + self.data[index+1:] - def immutable(self): - return UserString(self.data) - def __iadd__(self, other): - if isinstance(other, UserString): - self.data += other.data - elif isinstance(other, str): - self.data += other - else: - self.data += str(other) - return self - def __imul__(self, n): - self.data *= n - return self - -if __name__ == "__main__": - # execute the regression test to stdout, if called as a script: - import os - called_in_dir, called_as = os.path.split(sys.argv[0]) - called_as, py = os.path.splitext(called_as) - if '-q' in sys.argv: - from test import test_support - test_support.verbose = 0 - __import__('test.test_' + called_as.lower()) Modified: python/branches/py3k-ctypes-pep3118/Lib/__future__.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/__future__.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/__future__.py Wed Apr 30 15:57:13 2008 @@ -53,6 +53,8 @@ "division", "absolute_import", "with_statement", + "print_function", + "unicode_literals", ] __all__ = ["all_feature_names"] + all_feature_names @@ -66,6 +68,8 @@ CO_FUTURE_DIVISION = 0x2000 # division CO_FUTURE_ABSOLUTE_IMPORT = 0x4000 # perform absolute imports by default CO_FUTURE_WITH_STATEMENT = 0x8000 # with statement +CO_FUTURE_PRINT_FUNCTION = 0x10000 # print function +CO_FUTURE_UNICODE_LITERALS = 0x20000 # unicode string literals class _Feature: def __init__(self, optionalRelease, mandatoryRelease, compiler_flag): @@ -114,3 +118,11 @@ with_statement = _Feature((2, 5, 0, "alpha", 1), (2, 6, 0, "alpha", 0), CO_FUTURE_WITH_STATEMENT) + +print_function = _Feature((2, 6, 0, "alpha", 2), + (3, 0, 0, "alpha", 0), + CO_FUTURE_PRINT_FUNCTION) + +unicode_literals = _Feature((2, 6, 0, "alpha", 2), + (3, 0, 0, "alpha", 0), + CO_FUTURE_UNICODE_LITERALS) Modified: python/branches/py3k-ctypes-pep3118/Lib/_abcoll.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/_abcoll.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/_abcoll.py Wed Apr 30 15:57:13 2008 @@ -82,7 +82,7 @@ return NotImplemented -class Iterator(metaclass=ABCMeta): +class Iterator(Iterable): @abstractmethod def __next__(self): @@ -143,7 +143,7 @@ class Callable(metaclass=ABCMeta): @abstractmethod - def __contains__(self, x): + def __call__(self, *args, **kwds): return False @classmethod @@ -157,7 +157,7 @@ ### SETS ### -class Set(metaclass=ABCMeta): +class Set(Sized, Iterable, Container): """A set is a finite, iterable container. @@ -169,19 +169,6 @@ then the other operations will automatically follow suit. """ - @abstractmethod - def __contains__(self, value): - return False - - @abstractmethod - def __iter__(self): - while False: - yield None - - @abstractmethod - def __len__(self): - return 0 - def __le__(self, other): if not isinstance(other, Set): return NotImplemented @@ -197,24 +184,49 @@ return NotImplemented return len(self) < len(other) and self.__le__(other) + def __gt__(self, other): + if not isinstance(other, Set): + return NotImplemented + return other < self + + def __ge__(self, other): + if not isinstance(other, Set): + return NotImplemented + return other <= self + def __eq__(self, other): if not isinstance(other, Set): return NotImplemented return len(self) == len(other) and self.__le__(other) + def __ne__(self, other): + return not (self == other) + @classmethod def _from_iterable(cls, it): - return frozenset(it) + '''Construct an instance of the class from any iterable input. + + Must override this method if the class constructor signature + does not accept an iterable for an input. + ''' + return cls(it) def __and__(self, other): if not isinstance(other, Iterable): return NotImplemented return self._from_iterable(value for value in other if value in self) + def isdisjoint(self, other): + for value in other: + if value in self: + return False + return True + def __or__(self, other): if not isinstance(other, Iterable): return NotImplemented - return self._from_iterable(itertools.chain(self, other)) + chain = (e for s in (self, other) for e in s) + return self._from_iterable(chain) def __sub__(self, other): if not isinstance(other, Set): @@ -278,6 +290,12 @@ """Return True if it was deleted, False if not there.""" raise NotImplementedError + def remove(self, value): + """Remove an element. If not a member, raise a KeyError.""" + if value not in self: + raise KeyError(value) + self.discard(value) + def pop(self): """Return the popped value. Raise KeyError if empty.""" it = iter(self) @@ -288,16 +306,6 @@ self.discard(value) return value - def toggle(self, value): - """Return True if it was added, False if deleted.""" - # XXX This implementation is not thread-safe - if value in self: - self.discard(value) - return False - else: - self.add(value) - return True - def clear(self): """This is slow (creates N new iterators!) but effective.""" try: @@ -318,9 +326,13 @@ return self def __ixor__(self, it: Iterable): - # This calls toggle(), so if that is overridded, we call the override + if not isinstance(it, Set): + it = self._from_iterable(it) for value in it: - self.toggle(it) + if value in self: + self.discard(value) + else: + self.add(value) return self def __isub__(self, it: Iterable): @@ -334,7 +346,7 @@ ### MAPPINGS ### -class Mapping(metaclass=ABCMeta): +class Mapping(Sized, Iterable, Container): @abstractmethod def __getitem__(self, key): @@ -354,15 +366,6 @@ else: return True - @abstractmethod - def __len__(self): - return 0 - - @abstractmethod - def __iter__(self): - while False: - yield None - def keys(self): return KeysView(self) @@ -372,8 +375,15 @@ def values(self): return ValuesView(self) + def __eq__(self, other): + return isinstance(other, Mapping) and \ + dict(self.items()) == dict(other.items()) + + def __ne__(self, other): + return not (self == other) -class MappingView(metaclass=ABCMeta): + +class MappingView(Sized): def __init__(self, mapping): self._mapping = mapping @@ -479,13 +489,20 @@ for key, value in kwds.items(): self[key] = value + def setdefault(self, key, default=None): + try: + return self[key] + except KeyError: + self[key] = default + return default + MutableMapping.register(dict) ### SEQUENCES ### -class Sequence(metaclass=ABCMeta): +class Sequence(Sized, Iterable, Container): """All the operations on a read-only sequence. @@ -497,19 +514,15 @@ def __getitem__(self, index): raise IndexError - @abstractmethod - def __len__(self): - return 0 - def __iter__(self): i = 0 - while True: - try: + try: + while True: v = self[i] - except IndexError: - break - yield v - i += 1 + yield v + i += 1 + except IndexError: + return def __contains__(self, value): for v in self: Modified: python/branches/py3k-ctypes-pep3118/Lib/_strptime.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/_strptime.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/_strptime.py Wed Apr 30 15:57:13 2008 @@ -22,7 +22,7 @@ except: from dummy_thread import allocate_lock as _thread_allocate_lock -__all__ = ['strptime'] +__all__ = [] def _getlang(): # Figure out what the current language is set to. @@ -190,6 +190,7 @@ base.__init__({ # The " \d" part of the regex is to make %c from ANSI C work 'd': r"(?P3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])", + 'f': r"(?P[0-9]{1,6})", 'H': r"(?P2[0-3]|[0-1]\d|\d)", 'I': r"(?P1[0-2]|0[1-9]|[1-9])", 'j': r"(?P36[0-6]|3[0-5]\d|[1-2]\d\d|0[1-9]\d|00[1-9]|[1-9]\d|0[1-9]|[1-9])", @@ -291,7 +292,7 @@ return 1 + days_to_week + day_of_week -def strptime(data_string, format="%a %b %d %H:%M:%S %Y"): +def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"): """Return a time struct based on the input string and the format string.""" global _TimeRE_cache, _regex_cache with _cache_lock: @@ -327,7 +328,7 @@ data_string[found.end():]) year = 1900 month = day = 1 - hour = minute = second = 0 + hour = minute = second = fraction = 0 tz = -1 # Default to -1 to signify that values not known; not critical to have, # though @@ -384,6 +385,11 @@ minute = int(found_dict['M']) elif group_key == 'S': second = int(found_dict['S']) + elif group_key == 'f': + s = found_dict['f'] + # Pad to always return microseconds. + s += "0" * (6 - len(s)) + fraction = int(s) elif group_key == 'A': weekday = locale_time.f_weekday.index(found_dict['A'].lower()) elif group_key == 'a': @@ -440,6 +446,9 @@ day = datetime_result.day if weekday == -1: weekday = datetime_date(year, month, day).weekday() - return time.struct_time((year, month, day, - hour, minute, second, - weekday, julian, tz)) + return (time.struct_time((year, month, day, + hour, minute, second, + weekday, julian, tz)), fraction) + +def _strptime_time(data_string, format="%a %b %d %H:%M:%S %Y"): + return _strptime(data_string, format)[0] Modified: python/branches/py3k-ctypes-pep3118/Lib/abc.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/abc.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/abc.py Wed Apr 30 15:57:13 2008 @@ -3,7 +3,7 @@ """Abstract Base Classes (ABCs) according to PEP 3119.""" -from weakref import WeakSet +from _weakrefset import WeakSet def abstractmethod(funcobj): """A decorator indicating abstract methods. @@ -52,50 +52,6 @@ __isabstractmethod__ = True -class _Abstract(object): - - """Helper class inserted into the bases by ABCMeta (using _fix_bases()). - - You should never need to explicitly subclass this class. - """ - - def __new__(cls, *args, **kwds): - am = cls.__dict__.get("__abstractmethods__") - if am: - raise TypeError("Can't instantiate abstract class %s " - "with abstract methods %s" % - (cls.__name__, ", ".join(sorted(am)))) - if (args or kwds) and cls.__init__ is object.__init__: - raise TypeError("Can't pass arguments to __new__ " - "without overriding __init__") - return super().__new__(cls) - - @classmethod - def __subclasshook__(cls, subclass): - """Abstract classes can override this to customize issubclass(). - - This is invoked early on by __subclasscheck__() below. It - should return True, False or NotImplemented. If it returns - NotImplemented, the normal algorithm is used. Otherwise, it - overrides the normal algorithm (and the outcome is cached). - """ - return NotImplemented - - -def _fix_bases(bases): - """Helper method that inserts _Abstract in the bases if needed.""" - for base in bases: - if issubclass(base, _Abstract): - # _Abstract is already a base (maybe indirectly) - return bases - if object in bases: - # Replace object with _Abstract - return tuple([_Abstract if base is object else base - for base in bases]) - # Append _Abstract to the end - return bases + (_Abstract,) - - class ABCMeta(type): """Metaclass for defining Abstract Base Classes (ABCs). @@ -118,7 +74,6 @@ _abc_invalidation_counter = 0 def __new__(mcls, name, bases, namespace): - bases = _fix_bases(bases) cls = super().__new__(mcls, name, bases, namespace) # Compute set of abstract method names abstracts = {name @@ -129,7 +84,7 @@ value = getattr(cls, name, None) if getattr(value, "__isabstractmethod__", False): abstracts.add(name) - cls.__abstractmethods__ = abstracts + cls.__abstractmethods__ = frozenset(abstracts) # Set up inheritance registry cls._abc_registry = WeakSet() cls._abc_cache = WeakSet() @@ -162,8 +117,19 @@ def __instancecheck__(cls, instance): """Override for isinstance(instance, cls).""" - return any(cls.__subclasscheck__(c) - for c in {instance.__class__, type(instance)}) + # Inline the cache checking + subclass = instance.__class__ + if subclass in cls._abc_cache: + return True + subtype = type(instance) + if subtype is subclass: + if (cls._abc_negative_cache_version == + ABCMeta._abc_invalidation_counter and + subclass in cls._abc_negative_cache): + return False + # Fall back to the subclass check. + return cls.__subclasscheck__(subclass) + return any(cls.__subclasscheck__(c) for c in {subclass, subtype}) def __subclasscheck__(cls, subclass): """Override for issubclass(subclass, cls).""" Modified: python/branches/py3k-ctypes-pep3118/Lib/bdb.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/bdb.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/bdb.py Wed Apr 30 15:57:13 2008 @@ -361,10 +361,9 @@ if not isinstance(cmd, types.CodeType): cmd = cmd+'\n' try: - try: - exec(cmd, globals, locals) - except BdbQuit: - pass + exec(cmd, globals, locals) + except BdbQuit: + pass finally: self.quitting = 1 sys.settrace(None) @@ -380,10 +379,9 @@ if not isinstance(expr, types.CodeType): expr = expr+'\n' try: - try: - return eval(expr, globals, locals) - except BdbQuit: - pass + return eval(expr, globals, locals) + except BdbQuit: + pass finally: self.quitting = 1 sys.settrace(None) @@ -399,10 +397,9 @@ sys.settrace(self.trace_dispatch) res = None try: - try: - res = func(*args, **kwds) - except BdbQuit: - pass + res = func(*args, **kwds) + except BdbQuit: + pass finally: self.quitting = 1 sys.settrace(None) Modified: python/branches/py3k-ctypes-pep3118/Lib/bsddb/__init__.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/bsddb/__init__.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/bsddb/__init__.py Wed Apr 30 15:57:13 2008 @@ -64,10 +64,10 @@ #---------------------------------------------------------------------- -import sys, os, UserDict +import sys, os, collections from weakref import ref -class _iter_mixin(UserDict.DictMixin): +class _iter_mixin(collections.MutableMapping): def _make_iter_cursor(self): cur = _DeadlockWrap(self.db.cursor) key = id(cur) @@ -170,6 +170,9 @@ def __del__(self): self.close() + def __repr__(self): + return repr(dict(self.iteritems())) + def _checkCursor(self): if self.dbc is None: self.dbc = _DeadlockWrap(self.db.cursor) @@ -289,7 +292,7 @@ def _cursor_refs(self): return self.db._cursor_refs -class StringKeys(UserDict.DictMixin, _ExposedProperties): +class StringKeys(collections.MutableMapping, _ExposedProperties): """Wrapper around DB object that automatically encodes all keys as UTF-8; the keys must be strings.""" @@ -357,7 +360,7 @@ def sync(self): return self.db.sync() -class StringValues(UserDict.DictMixin, _ExposedProperties): +class StringValues(collections.MutableMapping, _ExposedProperties): """Wrapper around DB object that automatically encodes and decodes all values as UTF-8; input values must be strings.""" Modified: python/branches/py3k-ctypes-pep3118/Lib/bsddb/dbobj.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/bsddb/dbobj.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/bsddb/dbobj.py Wed Apr 30 15:57:13 2008 @@ -24,10 +24,9 @@ from . import db try: - from UserDict import DictMixin + from collections import MutableMapping except ImportError: - # DictMixin is new in Python 2.3 - class DictMixin: pass + class MutableMapping: pass class DBEnv: def __init__(self, *args, **kwargs): @@ -113,7 +112,7 @@ return self._cobj.lsn_reset(*args, **kwargs) -class DB(DictMixin): +class DB(MutableMapping): def __init__(self, dbenv, *args, **kwargs): # give it the proper DBEnv C object that its expecting self._cobj = db.DB(dbenv._cobj, *args, **kwargs) @@ -127,6 +126,8 @@ self._cobj[key] = value def __delitem__(self, arg): del self._cobj[arg] + def __iter__(self): + return iter(self.keys()) def append(self, *args, **kwargs): return self._cobj.append(*args, **kwargs) Modified: python/branches/py3k-ctypes-pep3118/Lib/bsddb/dbshelve.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/bsddb/dbshelve.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/bsddb/dbshelve.py Wed Apr 30 15:57:13 2008 @@ -32,18 +32,17 @@ import pickle import sys -#At version 2.3 cPickle switched to using protocol instead of bin and -#DictMixin was added +#At version 2.3 cPickle switched to using protocol instead of bin if sys.version_info[:3] >= (2, 3, 0): HIGHEST_PROTOCOL = pickle.HIGHEST_PROTOCOL def _dumps(object, protocol): return pickle.dumps(object, protocol=protocol) - from UserDict import DictMixin + from collections import MutableMapping else: HIGHEST_PROTOCOL = None def _dumps(object, protocol): return pickle.dumps(object, bin=protocol) - class DictMixin: pass + class MutableMapping: pass from . import db @@ -90,7 +89,7 @@ class DBShelveError(db.DBError): pass -class DBShelf(DictMixin): +class DBShelf(MutableMapping): """A shelf to hold pickled objects, built upon a bsddb DB object. It automatically pickles/unpickles data objects going to/from the DB. """ @@ -136,11 +135,13 @@ def keys(self, txn=None): - if txn != None: + if txn is not None: return self.db.keys(txn) else: return self.db.keys() + def __iter__(self): + return iter(self.keys()) def open(self, *args, **kwargs): self.db.open(*args, **kwargs) @@ -160,7 +161,7 @@ def items(self, txn=None): - if txn != None: + if txn is not None: items = self.db.items(txn) else: items = self.db.items() @@ -171,7 +172,7 @@ return newitems def values(self, txn=None): - if txn != None: + if txn is not None: values = self.db.values(txn) else: values = self.db.values() Modified: python/branches/py3k-ctypes-pep3118/Lib/bsddb/dbtables.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/bsddb/dbtables.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/bsddb/dbtables.py Wed Apr 30 15:57:13 2008 @@ -88,6 +88,15 @@ def __call__(self, s): return self.re.match(s.decode(self.encoding)) +def CmpToKey(mycmp): + 'Convert a cmp= function into a key= function' + class K(object): + def __init__(self, obj, *args): + self.obj = obj + def __lt__(self, other): + return mycmp(self.obj, other.obj) == -1 + return K + # # keys used to store database metadata # @@ -587,7 +596,7 @@ return 0 conditionlist = list(conditions.items()) - conditionlist.sort(cmp_conditions) + conditionlist.sort(key=CmpToKey(cmp_conditions)) # Apply conditions to column data to find what we want cur = self.db.cursor() Modified: python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_1413192.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_1413192.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_1413192.py Wed Apr 30 15:57:13 2008 @@ -5,7 +5,9 @@ import shutil import tempfile +from test.test_support import catch_warning import warnings + try: # For Pythons w/distutils and add-on pybsddb from bsddb3 import db @@ -33,12 +35,11 @@ del self.the_txn -warnings.filterwarnings('ignore', 'DBTxn aborted in destructor') -try: +with catch_warning(): + warnings.filterwarnings('ignore', 'DBTxn aborted in destructor') context = Context() del context -finally: - warnings.resetwarnings() + # try not to leave a turd try: Modified: python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_associate.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_associate.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_associate.py Wed Apr 30 15:57:13 2008 @@ -24,6 +24,11 @@ # For Python 2.3 from bsddb import db, dbshelve +try: + from bsddb3 import test_support +except ImportError: + from test import test_support + #---------------------------------------------------------------------- @@ -92,15 +97,22 @@ class AssociateErrorTestCase(unittest.TestCase): def setUp(self): self.filename = self.__class__.__name__ + '.db' - self.homeDir = tempfile.mkdtemp() + homeDir = os.path.join(tempfile.gettempdir(), 'db_home%d'%os.getpid()) + self.homeDir = homeDir + try: + os.mkdir(homeDir) + except os.error: + import glob + files = glob.glob(os.path.join(self.homeDir, '*')) + for file in files: + os.remove(file) self.env = db.DBEnv() self.env.open(self.homeDir, db.DB_CREATE | db.DB_INIT_MPOOL) def tearDown(self): self.env.close() self.env = None - shutil.rmtree(self.homeDir) - + test_support.rmtree(self.homeDir) def test00_associateDBError(self): if verbose: @@ -141,7 +153,15 @@ def setUp(self): self.filename = self.__class__.__name__ + '.db' - self.homeDir = tempfile.mkdtemp() + homeDir = os.path.join(tempfile.gettempdir(), 'db_home%d'%os.getpid()) + self.homeDir = homeDir + try: + os.mkdir(homeDir) + except os.error: + import glob + files = glob.glob(os.path.join(self.homeDir, '*')) + for file in files: + os.remove(file) self.env = db.DBEnv() self.env.open(self.homeDir, db.DB_CREATE | db.DB_INIT_MPOOL | db.DB_INIT_LOCK | db.DB_THREAD | self.envFlags) Modified: python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_basics.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_basics.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_basics.py Wed Apr 30 15:57:13 2008 @@ -6,7 +6,6 @@ import os import sys import errno -import shutil import string import tempfile from pprint import pprint @@ -21,6 +20,10 @@ from bsddb import db from bsddb.test.test_all import verbose +try: + from bsddb3 import test_support +except ImportError: + from test import test_support DASH = b'-' letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' @@ -54,7 +57,10 @@ def setUp(self): if self.useEnv: - self.homeDir = tempfile.mkdtemp() + homeDir = os.path.join(tempfile.gettempdir(), 'db_home%d'%os.getpid()) + self.homeDir = homeDir + test_support.rmtree(homeDir) + os.mkdir(homeDir) try: self.env = db.DBEnv() self.env.set_lg_max(1024*1024) @@ -68,7 +74,7 @@ tempfile.tempdir = old_tempfile_tempdir # Yes, a bare except is intended, since we're re-raising the exc. except: - shutil.rmtree(self.homeDir) + test_support.rmtree(homeDir) raise else: self.env = None @@ -93,7 +99,8 @@ self.d.close() if self.env is not None: self.env.close() - shutil.rmtree(self.homeDir) + test_support.rmtree(self.homeDir) + ## XXX(nnorwitz): is this comment stil valid? ## Make a new DBEnv to remove the env files from the home dir. ## (It can't be done while the env is open, nor after it has been ## closed, so we make a new one to do it.) @@ -359,7 +366,7 @@ else: if set_raises_error: self.fail("expected exception") - if n != None: + if n is not None: self.fail("expected None: %r" % (n,)) rec = c.get_both(b'0404', self.makeData(b'0404')) @@ -373,7 +380,7 @@ else: if get_raises_error: self.fail("expected exception") - if n != None: + if n is not None: self.fail("expected None: %r" % (n,)) if self.d.get_type() == db.DB_BTREE: Modified: python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_compare.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_compare.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_compare.py Wed Apr 30 15:57:13 2008 @@ -6,6 +6,7 @@ import sys, os, re from io import StringIO import tempfile +from . import test_all import unittest try: @@ -15,6 +16,11 @@ # For Python 2.3 from bsddb import db, dbshelve +try: + from bsddb3 import test_support +except ImportError: + from test import test_support + lexical_cmp = cmp def lowercase_cmp(left, right): @@ -31,10 +37,20 @@ _expected_lowercase_test_data = [s.encode('ascii') for s in ('', 'a', 'aaa', 'b', 'c', 'CC', 'cccce', 'ccccf', 'CCCP')] + +def CmpToKey(mycmp): + 'Convert a cmp= function into a key= function' + class K(object): + def __init__(self, obj, *args): + self.obj = obj + def __lt__(self, other): + return mycmp(self.obj, other.obj) == -1 + return K + class ComparatorTests (unittest.TestCase): def comparator_test_helper (self, comparator, expected_data): data = expected_data[:] - data.sort (comparator) + data.sort (key=CmpToKey(comparator)) self.failUnless (data == expected_data, "comparator `%s' is not right: %s vs. %s" % (comparator, expected_data, data)) @@ -55,7 +71,12 @@ def setUp (self): self.filename = self.__class__.__name__ + '.db' - self.homeDir = tempfile.mkdtemp() + homeDir = os.path.join (tempfile.gettempdir(), 'db_home%d'%os.getpid()) + self.homeDir = homeDir + try: + os.mkdir (homeDir) + except os.error: + pass env = db.DBEnv () env.open (self.homeDir, @@ -68,7 +89,7 @@ if self.env is not None: self.env.close () self.env = None - shutil.rmtree(self.homeDir) + test_support.rmtree(self.homeDir) def addDataToDB (self, data): i = 0 Modified: python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_cursor_pget_bug.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_cursor_pget_bug.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_cursor_pget_bug.py Wed Apr 30 15:57:13 2008 @@ -1,10 +1,16 @@ import unittest +import tempfile import sys, os, glob import shutil import tempfile from bsddb import db +try: + from bsddb3 import test_support +except ImportError: + from test import test_support + #---------------------------------------------------------------------- @@ -13,7 +19,11 @@ db_name = 'test-cursor_pget.db' def setUp(self): - self.homeDir = tempfile.mkdtemp() + self.homeDir = os.path.join(tempfile.gettempdir(), 'db_home%d'%os.getpid()) + try: + os.mkdir(self.homeDir) + except os.error: + pass self.env = db.DBEnv() self.env.open(self.homeDir, db.DB_CREATE | db.DB_INIT_MPOOL) self.primary_db = db.DB(self.env) @@ -34,7 +44,7 @@ del self.secondary_db del self.primary_db del self.env - shutil.rmtree(self.homeDir) + test_support.rmtree(self.homeDir) def test_pget(self): cursor = self.secondary_db.cursor() Modified: python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_dbobj.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_dbobj.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_dbobj.py Wed Apr 30 15:57:13 2008 @@ -2,7 +2,6 @@ import shutil import sys, os import unittest -import glob import tempfile try: @@ -12,6 +11,11 @@ # For Python 2.3 from bsddb import db, dbobj +try: + from bsddb3 import test_support +except ImportError: + from test import test_support + #---------------------------------------------------------------------- @@ -20,14 +24,17 @@ db_name = 'test-dbobj.db' def setUp(self): - self.homeDir = tempfile.mkdtemp() + homeDir = os.path.join(tempfile.gettempdir(), 'db_home%d'%os.getpid()) + self.homeDir = homeDir + try: os.mkdir(homeDir) + except os.error: pass def tearDown(self): if hasattr(self, 'db'): del self.db if hasattr(self, 'env'): del self.env - shutil.rmtree(self.homeDir) + test_support.rmtree(self.homeDir) def test01_both(self): class TestDBEnv(dbobj.DBEnv): pass Modified: python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_dbshelve.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_dbshelve.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_dbshelve.py Wed Apr 30 15:57:13 2008 @@ -9,6 +9,11 @@ from bsddb import db, dbshelve +try: + from bsddb3 import test_support +except ImportError: + from test import test_support + from bsddb.test.test_all import verbose @@ -45,10 +50,7 @@ def tearDown(self): self.do_close() - try: - os.remove(self.filename) - except os.error: - pass + test_support.unlink(self.filename) def mk(self, key): """Turn key into an appropriate key type for this db""" @@ -262,6 +264,10 @@ self.do_open() def do_open(self): + self.homeDir = homeDir = os.path.join( + tempfile.gettempdir(), 'db_home%d'%os.getpid()) + try: os.mkdir(homeDir) + except os.error: pass self.env = db.DBEnv() self.env.open(self.homeDir, self.envflags | db.DB_INIT_MPOOL | db.DB_CREATE) @@ -276,8 +282,7 @@ def tearDown(self): self.do_close() - shutil.rmtree(self.homeDir) - + test_support.rmtree(self.homeDir) class EnvBTreeShelveTestCase(BasicEnvShelveTestCase): Modified: python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_dbtables.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_dbtables.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_dbtables.py Wed Apr 30 15:57:13 2008 @@ -20,7 +20,6 @@ # # $Id$ -import shutil import sys, os, re import pickle import tempfile @@ -35,6 +34,10 @@ # For Python 2.3 from bsddb import db, dbtables +try: + from bsddb3 import test_support +except ImportError: + from test import test_support #---------------------------------------------------------------------- @@ -43,13 +46,17 @@ db_name = 'test-table.db' def setUp(self): - self.homeDir = tempfile.mkdtemp() + homeDir = tempfile.mkdtemp() + self.testHomeDir = homeDir + try: os.mkdir(homeDir) + except os.error: pass + self.tdb = dbtables.bsdTableDB( - filename='tabletest.db', dbhome=self.homeDir, create=1) + filename='tabletest.db', dbhome=homeDir, create=1) def tearDown(self): self.tdb.close() - shutil.rmtree(self.homeDir) + test_support.rmtree(self.testHomeDir) def test01(self): tabname = "test01" @@ -321,7 +328,7 @@ self.tdb.Insert(tabname, {'Type': b'Unknown', 'Access': b'0'}) def set_type(type): - if type == None: + if type is None: return b'MP3' return type Modified: python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_env_close.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_env_close.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_env_close.py Wed Apr 30 15:57:13 2008 @@ -6,7 +6,6 @@ import shutil import sys import tempfile -import glob import unittest try: @@ -16,6 +15,11 @@ # For Python 2.3 from bsddb import db +try: + from bsddb3 import test_support +except ImportError: + from test import test_support + from bsddb.test.test_all import verbose # We're going to get warnings in this module about trying to close the db when @@ -34,15 +38,15 @@ class DBEnvClosedEarlyCrash(unittest.TestCase): def setUp(self): - self.homeDir = tempfile.mkdtemp() - old_tempfile_tempdir = tempfile.tempdir + self.homeDir = os.path.join(tempfile.gettempdir(), 'db_home%d'%os.getpid()) + try: os.mkdir(self.homeDir) + except os.error: pass tempfile.tempdir = self.homeDir self.filename = os.path.split(tempfile.mktemp())[1] - tempfile.tempdir = old_tempfile_tempdir + tempfile.tempdir = None def tearDown(self): - shutil.rmtree(self.homeDir) - + test_support.rmtree(self.homeDir) def test01_close_dbenv_before_db(self): dbenv = db.DBEnv() Modified: python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_join.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_join.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_join.py Wed Apr 30 15:57:13 2008 @@ -18,6 +18,10 @@ from bsddb import db, dbshelve, StringKeys +try: + from bsddb3 import test_support +except ImportError: + from test import test_support #---------------------------------------------------------------------- @@ -48,13 +52,16 @@ def setUp(self): self.filename = self.__class__.__name__ + '.db' - self.homeDir = tempfile.mkdtemp() + homeDir = os.path.join(tempfile.gettempdir(), 'db_home%d'%os.getpid()) + self.homeDir = homeDir + try: os.mkdir(homeDir) + except os.error: pass self.env = db.DBEnv() self.env.open(self.homeDir, db.DB_CREATE | db.DB_INIT_MPOOL | db.DB_INIT_LOCK ) def tearDown(self): self.env.close() - shutil.rmtree(self.homeDir) + test_support.rmtree(self.homeDir) def test01_join(self): if verbose: Modified: python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_lock.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_lock.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_lock.py Wed Apr 30 15:57:13 2008 @@ -2,9 +2,6 @@ TestCases for testing the locking sub-system. """ -import os -from pprint import pprint -import shutil import sys import tempfile import time @@ -26,6 +23,11 @@ # For Python 2.3 from bsddb import db +try: + from bsddb3 import test_support +except ImportError: + from test import test_support + #---------------------------------------------------------------------- @@ -40,7 +42,7 @@ def tearDown(self): self.env.close() - shutil.rmtree(self.homeDir) + test_support.rmtree(self.homeDir) def test01_simple(self): Modified: python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_misc.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_misc.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_misc.py Wed Apr 30 15:57:13 2008 @@ -14,19 +14,26 @@ # For the bundled bsddb from bsddb import db, dbshelve, hashopen +try: + from bsddb3 import test_support +except ImportError: + from test import test_support + #---------------------------------------------------------------------- class MiscTestCase(unittest.TestCase): def setUp(self): self.filename = self.__class__.__name__ + '.db' - self.homeDir = tempfile.mkdtemp() - - def tearDown(self): + homeDir = os.path.join(tempfile.gettempdir(), 'db_home%d'%os.getpid()) + self.homeDir = homeDir try: - os.remove(self.filename) + os.mkdir(homeDir) except OSError: pass - shutil.rmtree(self.homeDir) + + def tearDown(self): + test_support.unlink(self.filename) + test_support.rmtree(self.homeDir) def test01_badpointer(self): dbs = dbshelve.open(self.filename) Modified: python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_pickle.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_pickle.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_pickle.py Wed Apr 30 15:57:13 2008 @@ -4,7 +4,7 @@ import pickle import tempfile import unittest -import glob +import tempfile try: # For Pythons w/distutils pybsddb @@ -13,6 +13,11 @@ # For Python 2.3 from bsddb import db +try: + from bsddb3 import test_support +except ImportError: + from test import test_support + #---------------------------------------------------------------------- @@ -21,14 +26,17 @@ db_name = 'test-dbobj.db' def setUp(self): - self.homeDir = tempfile.mkdtemp() + homeDir = os.path.join(tempfile.gettempdir(), 'db_home%d'%os.getpid()) + self.homeDir = homeDir + try: os.mkdir(homeDir) + except os.error: pass def tearDown(self): if hasattr(self, 'db'): del self.db if hasattr(self, 'env'): del self.env - shutil.rmtree(self.homeDir) + test_support.rmtree(self.homeDir) def _base_test_pickle_DBError(self, pickle): self.env = db.DBEnv() Modified: python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_recno.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_recno.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_recno.py Wed Apr 30 15:57:13 2008 @@ -18,6 +18,11 @@ # For Python 2.3 from bsddb import db +try: + from bsddb3 import test_support +except ImportError: + from test import test_support + letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' @@ -26,14 +31,12 @@ class SimpleRecnoTestCase(unittest.TestCase): def setUp(self): self.filename = tempfile.mktemp() - self.homeDir = tempfile.mkdtemp() + self.homeDir = None def tearDown(self): - try: - os.remove(self.filename) - except OSError as e: - if e.errno != errno.EEXIST: raise - shutil.rmtree(self.homeDir) + test_support.unlink(self.filename) + if self.homeDir: + test_support.rmtree(self.homeDir) def test01_basic(self): d = db.DB() @@ -206,7 +209,11 @@ just a line in the file, but you can set a different record delimiter if needed. """ - source = os.path.join(self.homeDir, 'test_recno.txt') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home%d'%os.getpid()) + self.homeDir = homeDir + source = os.path.join(homeDir, 'test_recno.txt') + if not os.path.isdir(homeDir): + os.mkdir(homeDir) f = open(source, 'w') # create the file f.close() Modified: python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_sequence.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_sequence.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_sequence.py Wed Apr 30 15:57:13 2008 @@ -3,7 +3,6 @@ import shutil import sys import tempfile -import glob try: # For Pythons w/distutils pybsddb @@ -12,16 +11,23 @@ from bsddb import db from bsddb.test.test_all import verbose +try: + from bsddb3 import test_support +except ImportError: + from test import test_support class DBSequenceTest(unittest.TestCase): def setUp(self): self.int_32_max = 0x100000000 - self.homeDir = tempfile.mkdtemp() - old_tempfile_tempdir = tempfile.tempdir + self.homeDir = os.path.join(tempfile.gettempdir(), 'db_home%d'%os.getpid()) + try: + os.mkdir(self.homeDir) + except os.error: + pass tempfile.tempdir = self.homeDir self.filename = os.path.split(tempfile.mktemp())[1] - tempfile.tempdir = old_tempfile_tempdir + tempfile.tempdir = None self.dbenv = db.DBEnv() self.dbenv.open(self.homeDir, db.DB_CREATE | db.DB_INIT_MPOOL, 0o666) @@ -39,7 +45,7 @@ self.dbenv.close() del self.dbenv - shutil.rmtree(self.homeDir) + test_support.rmtree(self.homeDir) def test_get(self): self.seq = db.DBSequence(self.d, flags=0) Modified: python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_thread.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_thread.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/bsddb/test/test_thread.py Wed Apr 30 15:57:13 2008 @@ -5,7 +5,6 @@ import sys import time import errno -import shutil import tempfile from pprint import pprint from random import random @@ -34,6 +33,11 @@ # For Python 2.3 from bsddb import db, dbutils +try: + from bsddb3 import test_support +except ImportError: + from test import test_support + #---------------------------------------------------------------------- @@ -47,7 +51,12 @@ if verbose: dbutils._deadlock_VerboseFile = sys.stdout - self.homeDir = tempfile.mkdtemp() + homeDir = os.path.join(tempfile.gettempdir(), 'db_home%d'%os.getpid()) + self.homeDir = homeDir + try: + os.mkdir(homeDir) + except OSError as e: + if e.errno != errno.EEXIST: raise self.env = db.DBEnv() self.setEnvOpts() self.env.open(self.homeDir, self.envflags | db.DB_CREATE) @@ -61,7 +70,7 @@ def tearDown(self): self.d.close() self.env.close() - shutil.rmtree(self.homeDir) + test_support.rmtree(self.homeDir) def setEnvOpts(self): pass Modified: python/branches/py3k-ctypes-pep3118/Lib/calendar.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/calendar.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/calendar.py Wed Apr 30 15:57:13 2008 @@ -179,8 +179,8 @@ def itermonthdays(self, year, month): """ - Like itermonthdates(), but will yield day numbers tuples. For days - outside the specified month the day number is 0. + Like itermonthdates(), but will yield day numbers. For days outside + the specified month the day number is 0. """ for date in self.itermonthdates(year, month): if date.month != month: Modified: python/branches/py3k-ctypes-pep3118/Lib/cgi.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/cgi.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/cgi.py Wed Apr 30 15:57:13 2008 @@ -40,7 +40,7 @@ import urllib import mimetools import rfc822 -import UserDict +import collections from io import StringIO __all__ = ["MiniFieldStorage", "FieldStorage", "FormContentDict", @@ -781,7 +781,7 @@ # Backwards Compatibility Classes # =============================== -class FormContentDict(UserDict.UserDict): +class FormContentDict(collections.Mapping): """Form content as dictionary with a list of values per field. form = FormContentDict() @@ -800,6 +800,15 @@ strict_parsing=strict_parsing) self.query_string = environ['QUERY_STRING'] + def __len__(self): + return len(self.dict) + + def __iter__(self): + return iter(self.dict) + + def __getitem__(self, key): + return self.dict[key] + class SvFormContentDict(FormContentDict): """Form content as dictionary expecting a single value per field. Modified: python/branches/py3k-ctypes-pep3118/Lib/codecs.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/codecs.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/codecs.py Wed Apr 30 15:57:13 2008 @@ -237,7 +237,7 @@ """ def __init__(self, errors='strict'): """ - Creates a IncrementalDecoder instance. + Create a IncrementalDecoder instance. The IncrementalDecoder may use different error handling schemes by providing the errors keyword argument. See the module docstring @@ -247,26 +247,35 @@ def decode(self, input, final=False): """ - Decodes input and returns the resulting object. + Decode input and returns the resulting object. """ raise NotImplementedError def reset(self): """ - Resets the decoder to the initial state. + Reset the decoder to the initial state. """ def getstate(self): """ - Return the current state of the decoder. This must be a - (buffered_input, additional_state_info) tuple. + Return the current state of the decoder. + + This must be a (buffered_input, additional_state_info) tuple. + buffered_input must be a bytes object containing bytes that + were passed to decode() that have not yet been converted. + additional_state_info must be a non-negative integer + representing the state of the decoder WITHOUT yet having + processed the contents of buffered_input. In the initial state + and after reset(), getstate() must return (b"", 0). """ return (b"", 0) def setstate(self, state): """ - Set the current state of the decoder. state must have been - returned by getstate(). + Set the current state of the decoder. + + state must have been returned by getstate(). The effect of + setstate((b"", 0)) must be equivalent to reset(). """ class BufferedIncrementalDecoder(IncrementalDecoder): Modified: python/branches/py3k-ctypes-pep3118/Lib/collections.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/collections.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/collections.py Wed Apr 30 15:57:13 2008 @@ -1,4 +1,4 @@ -__all__ = ['deque', 'defaultdict', 'namedtuple'] +__all__ = ['deque', 'defaultdict', 'namedtuple', 'UserDict'] # For bootstrapping reasons, the collection ABCs are defined in _abcoll.py. # They should however be considered an integral part of collections.py. from _abcoll import * @@ -10,6 +10,10 @@ from keyword import iskeyword as _iskeyword import sys as _sys +################################################################################ +### namedtuple +################################################################################ + def namedtuple(typename, field_names, verbose=False): """Returns a new subclass of tuple with named fields. @@ -106,7 +110,279 @@ - +################################################################################ +### UserDict +################################################################################ + +class UserDict(MutableMapping): + + # Start by filling-out the abstract methods + def __init__(self, dict=None, **kwargs): + self.data = {} + if dict is not None: + self.update(dict) + if len(kwargs): + self.update(kwargs) + def __len__(self): return len(self.data) + def __getitem__(self, key): + if key in self.data: + return self.data[key] + if hasattr(self.__class__, "__missing__"): + return self.__class__.__missing__(self, key) + raise KeyError(key) + def __setitem__(self, key, item): self.data[key] = item + def __delitem__(self, key): del self.data[key] + def __iter__(self): + return iter(self.data) + + # Modify __contains__ to work correctly when __missing__ is present + def __contains__(self, key): + return key in self.data + + # Now, add the methods in dicts but not in MutableMapping + def __repr__(self): return repr(self.data) + def copy(self): + if self.__class__ is UserDict: + return UserDict(self.data.copy()) + import copy + data = self.data + try: + self.data = {} + c = copy.copy(self) + finally: + self.data = data + c.update(self) + return c + @classmethod + def fromkeys(cls, iterable, value=None): + d = cls() + for key in iterable: + d[key] = value + return d + + + +################################################################################ +### UserList +################################################################################ + +class UserList(MutableSequence): + """A more or less complete user-defined wrapper around list objects.""" + def __init__(self, initlist=None): + self.data = [] + if initlist is not None: + # XXX should this accept an arbitrary sequence? + if type(initlist) == type(self.data): + self.data[:] = initlist + elif isinstance(initlist, UserList): + self.data[:] = initlist.data[:] + else: + self.data = list(initlist) + def __repr__(self): return repr(self.data) + def __lt__(self, other): return self.data < self.__cast(other) + def __le__(self, other): return self.data <= self.__cast(other) + def __eq__(self, other): return self.data == self.__cast(other) + def __ne__(self, other): return self.data != self.__cast(other) + def __gt__(self, other): return self.data > self.__cast(other) + def __ge__(self, other): return self.data >= self.__cast(other) + def __cast(self, other): + return other.data if isinstance(other, UserList) else other + def __cmp__(self, other): + return cmp(self.data, self.__cast(other)) + def __contains__(self, item): return item in self.data + def __len__(self): return len(self.data) + def __getitem__(self, i): return self.data[i] + def __setitem__(self, i, item): self.data[i] = item + def __delitem__(self, i): del self.data[i] + def __add__(self, other): + if isinstance(other, UserList): + return self.__class__(self.data + other.data) + elif isinstance(other, type(self.data)): + return self.__class__(self.data + other) + return self.__class__(self.data + list(other)) + def __radd__(self, other): + if isinstance(other, UserList): + return self.__class__(other.data + self.data) + elif isinstance(other, type(self.data)): + return self.__class__(other + self.data) + return self.__class__(list(other) + self.data) + def __iadd__(self, other): + if isinstance(other, UserList): + self.data += other.data + elif isinstance(other, type(self.data)): + self.data += other + else: + self.data += list(other) + return self + def __mul__(self, n): + return self.__class__(self.data*n) + __rmul__ = __mul__ + def __imul__(self, n): + self.data *= n + return self + def append(self, item): self.data.append(item) + def insert(self, i, item): self.data.insert(i, item) + def pop(self, i=-1): return self.data.pop(i) + def remove(self, item): self.data.remove(item) + def count(self, item): return self.data.count(item) + def index(self, item, *args): return self.data.index(item, *args) + def reverse(self): self.data.reverse() + def sort(self, *args, **kwds): self.data.sort(*args, **kwds) + def extend(self, other): + if isinstance(other, UserList): + self.data.extend(other.data) + else: + self.data.extend(other) + + + +################################################################################ +### UserString +################################################################################ + +class UserString(Sequence): + def __init__(self, seq): + if isinstance(seq, str): + self.data = seq + elif isinstance(seq, UserString): + self.data = seq.data[:] + else: + self.data = str(seq) + def __str__(self): return str(self.data) + def __repr__(self): return repr(self.data) + def __int__(self): return int(self.data) + def __long__(self): return int(self.data) + def __float__(self): return float(self.data) + def __complex__(self): return complex(self.data) + def __hash__(self): return hash(self.data) + + def __eq__(self, string): + if isinstance(string, UserString): + return self.data == string.data + return self.data == string + def __ne__(self, string): + if isinstance(string, UserString): + return self.data != string.data + return self.data != string + def __lt__(self, string): + if isinstance(string, UserString): + return self.data < string.data + return self.data < string + def __le__(self, string): + if isinstance(string, UserString): + return self.data <= string.data + return self.data <= string + def __gt__(self, string): + if isinstance(string, UserString): + return self.data > string.data + return self.data > string + def __ge__(self, string): + if isinstance(string, UserString): + return self.data >= string.data + return self.data >= string + + def __contains__(self, char): + if isinstance(char, UserString): + char = char.data + return char in self.data + + def __len__(self): return len(self.data) + def __getitem__(self, index): return self.__class__(self.data[index]) + def __add__(self, other): + if isinstance(other, UserString): + return self.__class__(self.data + other.data) + elif isinstance(other, str): + return self.__class__(self.data + other) + return self.__class__(self.data + str(other)) + def __radd__(self, other): + if isinstance(other, str): + return self.__class__(other + self.data) + return self.__class__(str(other) + self.data) + def __mul__(self, n): + return self.__class__(self.data*n) + __rmul__ = __mul__ + def __mod__(self, args): + return self.__class__(self.data % args) + + # the following methods are defined in alphabetical order: + def capitalize(self): return self.__class__(self.data.capitalize()) + def center(self, width, *args): + return self.__class__(self.data.center(width, *args)) + def count(self, sub, start=0, end=_sys.maxsize): + if isinstance(sub, UserString): + sub = sub.data + return self.data.count(sub, start, end) + def encode(self, encoding=None, errors=None): # XXX improve this? + if encoding: + if errors: + return self.__class__(self.data.encode(encoding, errors)) + return self.__class__(self.data.encode(encoding)) + return self.__class__(self.data.encode()) + def endswith(self, suffix, start=0, end=_sys.maxsize): + return self.data.endswith(suffix, start, end) + def expandtabs(self, tabsize=8): + return self.__class__(self.data.expandtabs(tabsize)) + def find(self, sub, start=0, end=_sys.maxsize): + if isinstance(sub, UserString): + sub = sub.data + return self.data.find(sub, start, end) + def format(self, *args, **kwds): + return self.data.format(*args, **kwds) + def index(self, sub, start=0, end=_sys.maxsize): + return self.data.index(sub, start, end) + def isalpha(self): return self.data.isalpha() + def isalnum(self): return self.data.isalnum() + def isdecimal(self): return self.data.isdecimal() + def isdigit(self): return self.data.isdigit() + def isidentifier(self): return self.data.isidentifier() + def islower(self): return self.data.islower() + def isnumeric(self): return self.data.isnumeric() + def isspace(self): return self.data.isspace() + def istitle(self): return self.data.istitle() + def isupper(self): return self.data.isupper() + def join(self, seq): return self.data.join(seq) + def ljust(self, width, *args): + return self.__class__(self.data.ljust(width, *args)) + def lower(self): return self.__class__(self.data.lower()) + def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars)) + def partition(self, sep): + return self.data.partition(sep) + def replace(self, old, new, maxsplit=-1): + if isinstance(old, UserString): + old = old.data + if isinstance(new, UserString): + new = new.data + return self.__class__(self.data.replace(old, new, maxsplit)) + def rfind(self, sub, start=0, end=_sys.maxsize): + return self.data.rfind(sub, start, end) + def rindex(self, sub, start=0, end=_sys.maxsize): + return self.data.rindex(sub, start, end) + def rjust(self, width, *args): + return self.__class__(self.data.rjust(width, *args)) + def rpartition(self, sep): + return self.data.rpartition(sep) + def rstrip(self, chars=None): + return self.__class__(self.data.rstrip(chars)) + def split(self, sep=None, maxsplit=-1): + return self.data.split(sep, maxsplit) + def rsplit(self, sep=None, maxsplit=-1): + return self.data.rsplit(sep, maxsplit) + def splitlines(self, keepends=0): return self.data.splitlines(keepends) + def startswith(self, prefix, start=0, end=_sys.maxsize): + return self.data.startswith(prefix, start, end) + def strip(self, chars=None): return self.__class__(self.data.strip(chars)) + def swapcase(self): return self.__class__(self.data.swapcase()) + def title(self): return self.__class__(self.data.title()) + def translate(self, *args): + return self.__class__(self.data.translate(*args)) + def upper(self): return self.__class__(self.data.upper()) + def zfill(self, width): return self.__class__(self.data.zfill(width)) + + + +################################################################################ +### Simple tests +################################################################################ if __name__ == '__main__': # verify that instances can be pickled Modified: python/branches/py3k-ctypes-pep3118/Lib/compileall.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/compileall.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/compileall.py Wed Apr 30 15:57:13 2008 @@ -125,7 +125,7 @@ print("-d destdir: purported directory name for error messages") print(" if no directory arguments, -l sys.path is assumed") print("-x regexp: skip files matching the regular expression regexp") - print(" the regexp is search for in the full path of the file") + print(" the regexp is searched for in the full path of the file") sys.exit(2) maxlevels = 10 ddir = None Modified: python/branches/py3k-ctypes-pep3118/Lib/cookielib.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/cookielib.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/cookielib.py Wed Apr 30 15:57:13 2008 @@ -1255,8 +1255,7 @@ """ # add cookies in order of most specific (ie. longest) path first - def decreasing_size(a, b): return cmp(len(b.path), len(a.path)) - cookies.sort(decreasing_size) + cookies.sort(key=lambda a: len(a.path), reverse=True) version_set = False Modified: python/branches/py3k-ctypes-pep3118/Lib/copy.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/copy.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/copy.py Wed Apr 30 15:57:13 2008 @@ -101,7 +101,7 @@ return x for t in (type(None), int, float, bool, str, tuple, frozenset, type, range, - types.BuiltinFunctionType, + types.BuiltinFunctionType, type(Ellipsis), types.FunctionType): d[t] = _copy_immutable t = getattr(types, "CodeType", None) @@ -180,6 +180,7 @@ def _deepcopy_atomic(x, memo): return x d[type(None)] = _deepcopy_atomic +d[type(Ellipsis)] = _deepcopy_atomic d[int] = _deepcopy_atomic d[float] = _deepcopy_atomic d[bool] = _deepcopy_atomic Modified: python/branches/py3k-ctypes-pep3118/Lib/csv.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/csv.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/csv.py Wed Apr 30 15:57:13 2008 @@ -72,6 +72,8 @@ self.restkey = restkey # key to catch long rows self.restval = restval # default value for short rows self.reader = reader(f, dialect, *args, **kwds) + self.dialect = dialect + self.line_num = 0 def __iter__(self): return self @@ -81,6 +83,7 @@ if self.fieldnames is None: self.fieldnames = row row = next(self.reader) + self.line_num = self.reader.line_num # unlike the basic reader, we prefer not to return blanks, # because we will typically wind up with a dict full of None @@ -366,7 +369,7 @@ for col in list(columnTypes.keys()): - for thisType in [int, int, float, complex]: + for thisType in [int, float, complex]: try: thisType(row[col]) break @@ -376,10 +379,6 @@ # fallback to length of string thisType = len(row[col]) - # treat longs as ints - if thisType == int: - thisType = int - if thisType != columnTypes[col]: if columnTypes[col] is None: # add new column type columnTypes[col] = thisType Modified: python/branches/py3k-ctypes-pep3118/Lib/ctypes/__init__.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/ctypes/__init__.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/ctypes/__init__.py Wed Apr 30 15:57:13 2008 @@ -237,29 +237,9 @@ _check_size(c_void_p) class c_bool(_SimpleCData): - _type_ = "t" + _type_ = "?" -# This cache maps types to pointers to them. -_pointer_type_cache = {} - -def POINTER(cls): - try: - return _pointer_type_cache[cls] - except KeyError: - pass - if type(cls) is str: - klass = type(_Pointer)("LP_%s" % cls, - (_Pointer,), - {}) - _pointer_type_cache[id(klass)] = klass - return klass - else: - name = "LP_%s" % cls.__name__ - klass = type(_Pointer)(name, - (_Pointer,), - {'_type_': cls}) - _pointer_type_cache[cls] = klass - return klass +from _ctypes import POINTER, pointer, _pointer_type_cache try: from _ctypes import set_conversion_mode @@ -309,10 +289,6 @@ _pointer_type_cache[cls] = pointer del _pointer_type_cache[id(pointer)] - -def pointer(inst): - return POINTER(type(inst))(inst) - # XXX Deprecated def ARRAY(typ, len): return typ * len Modified: python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/__init__.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/__init__.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/__init__.py Wed Apr 30 15:57:13 2008 @@ -1,4 +1,4 @@ -import glob, os, sys, unittest, getopt, time +import os, sys, unittest, getopt, time use_resources = [] Modified: python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_arrays.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_arrays.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_arrays.py Wed Apr 30 15:57:13 2008 @@ -57,11 +57,8 @@ self.failUnlessEqual(len(ca), 3) - # slicing is now supported, but not extended slicing (3-argument)! - from operator import getslice, delitem - self.assertRaises(TypeError, getslice, ca, 0, 1, -1) - # cannot delete items + from operator import delitem self.assertRaises(TypeError, delitem, ca, 0) def test_numeric_arrays(self): Modified: python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_checkretval.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_checkretval.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_checkretval.py Wed Apr 30 15:57:13 2008 @@ -1,5 +1,4 @@ import unittest -import sys from ctypes import * Modified: python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_find.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_find.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_find.py Wed Apr 30 15:57:13 2008 @@ -1,5 +1,5 @@ import unittest -import os, sys +import sys from ctypes import * from ctypes.util import find_library from ctypes.test import is_resource_enabled Modified: python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_funcptr.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_funcptr.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_funcptr.py Wed Apr 30 15:57:13 2008 @@ -123,11 +123,5 @@ self.failUnlessEqual(strtok(None, b"\n"), "c") self.failUnlessEqual(strtok(None, b"\n"), None) - def test_NULL_funcptr(self): - tp = CFUNCTYPE(c_int) - func = tp() # NULL function pointer - # raise a ValueError when we try to call it - self.assertRaises(ValueError, func) - if __name__ == '__main__': unittest.main() Modified: python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_libc.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_libc.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_libc.py Wed Apr 30 15:57:13 2008 @@ -1,4 +1,3 @@ -import sys, os import unittest from ctypes import * Modified: python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_numbers.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_numbers.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_numbers.py Wed Apr 30 15:57:13 2008 @@ -1,6 +1,6 @@ from ctypes import * import unittest -import sys, struct +import struct def valid_ranges(*types): # given a sequence of numeric types, collect their _type_ Modified: python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_pep3118.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_pep3118.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_pep3118.py Wed Apr 30 15:57:13 2008 @@ -115,7 +115,7 @@ (c_double, ": " + "(Phone) : " "expected string, int found") cls, msg = self.get_except(Person, "Someone", ("a", "b", "c")) self.failUnlessEqual(cls, RuntimeError) if issubclass(Exception, object): self.failUnlessEqual(msg, - "(Phone) : too many initializers") + "(Phone) : too many initializers") else: self.failUnlessEqual(msg, "(Phone) TypeError: too many initializers") Modified: python/branches/py3k-ctypes-pep3118/Lib/ctypes/util.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/ctypes/util.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/ctypes/util.py Wed Apr 30 15:57:13 2008 @@ -123,7 +123,7 @@ res = re.findall(expr, data) if not res: return _get_soname(_findLib_gcc(name)) - res.sort(cmp= lambda x,y: cmp(_num_version(x), _num_version(y))) + res.sort(key=_num_version) return res[-1] else: Modified: python/branches/py3k-ctypes-pep3118/Lib/curses/__init__.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/curses/__init__.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/curses/__init__.py Wed Apr 30 15:57:13 2008 @@ -14,6 +14,8 @@ from _curses import * from curses.wrapper import wrapper +import os as _os +import sys as _sys # Some constants, most notably the ACS_* ones, are only added to the C # _curses module's dictionary after initscr() is called. (Some @@ -25,6 +27,10 @@ def initscr(): import _curses, curses + # we call setupterm() here because it raises an error + # instead of calling exit() in error cases. + setupterm(term=_os.environ.get("TERM", "unknown"), + fd=_sys.__stdout__.fileno()) stdscr = _curses.initscr() for key, value in _curses.__dict__.items(): if key[0:4] == 'ACS_' or key in ('LINES', 'COLS'): Modified: python/branches/py3k-ctypes-pep3118/Lib/curses/wrapper.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/curses/wrapper.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/curses/wrapper.py Wed Apr 30 15:57:13 2008 @@ -7,7 +7,7 @@ """ -import sys, curses +import curses def wrapper(func, *args, **kwds): """Wrapper function that initializes curses and calls another function, Modified: python/branches/py3k-ctypes-pep3118/Lib/decimal.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/decimal.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/decimal.py Wed Apr 30 15:57:13 2008 @@ -35,26 +35,26 @@ useful for financial applications or for contexts where users have expectations that are at odds with binary floating point (for instance, in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead -of the expected Decimal("0.00") returned by decimal floating point). +of the expected Decimal('0.00') returned by decimal floating point). Here are some examples of using the decimal module: >>> from decimal import * >>> setcontext(ExtendedContext) >>> Decimal(0) -Decimal("0") ->>> Decimal("1") -Decimal("1") ->>> Decimal("-.0123") -Decimal("-0.0123") +Decimal('0') +>>> Decimal('1') +Decimal('1') +>>> Decimal('-.0123') +Decimal('-0.0123') >>> Decimal(123456) -Decimal("123456") ->>> Decimal("123.45e12345678901234567890") -Decimal("1.2345E+12345678901234567892") ->>> Decimal("1.33") + Decimal("1.27") -Decimal("2.60") ->>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41") -Decimal("-2.20") +Decimal('123456') +>>> Decimal('123.45e12345678901234567890') +Decimal('1.2345E+12345678901234567892') +>>> Decimal('1.33') + Decimal('1.27') +Decimal('2.60') +>>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41') +Decimal('-2.20') >>> dig = Decimal(1) >>> print(dig / Decimal(3)) 0.333333333 @@ -91,7 +91,7 @@ >>> print(c.flags[InvalidOperation]) 0 >>> c.divide(Decimal(0), Decimal(0)) -Decimal("NaN") +Decimal('NaN') >>> c.traps[InvalidOperation] = 1 >>> print(c.flags[InvalidOperation]) 1 @@ -504,7 +504,7 @@ ##### Decimal class ####################################################### -class Decimal(_numbers.Real, _numbers.Inexact): +class Decimal(_numbers.Real): """Floating point class for decimal arithmetic.""" __slots__ = ('_exp','_int','_sign', '_is_special') @@ -517,15 +517,15 @@ """Create a decimal point instance. >>> Decimal('3.14') # string input - Decimal("3.14") + Decimal('3.14') >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent) - Decimal("3.14") + Decimal('3.14') >>> Decimal(314) # int - Decimal("314") + Decimal('314') >>> Decimal(Decimal(314)) # another decimal instance - Decimal("314") + Decimal('314') >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay - Decimal("3.14") + Decimal('3.14') """ # Note that the coefficient, self._int, is actually stored as @@ -718,6 +718,39 @@ return other._fix_nan(context) return 0 + def _compare_check_nans(self, other, context): + """Version of _check_nans used for the signaling comparisons + compare_signal, __le__, __lt__, __ge__, __gt__. + + Signal InvalidOperation if either self or other is a (quiet + or signaling) NaN. Signaling NaNs take precedence over quiet + NaNs. + + Return 0 if neither operand is a NaN. + + """ + if context is None: + context = getcontext() + + if self._is_special or other._is_special: + if self.is_snan(): + return context._raise_error(InvalidOperation, + 'comparison involving sNaN', + self) + elif other.is_snan(): + return context._raise_error(InvalidOperation, + 'comparison involving sNaN', + other) + elif self.is_qnan(): + return context._raise_error(InvalidOperation, + 'comparison involving NaN', + self) + elif other.is_qnan(): + return context._raise_error(InvalidOperation, + 'comparison involving NaN', + other) + return 0 + def __bool__(self): """Return True if self is nonzero; otherwise return False. @@ -725,18 +758,13 @@ """ return self._is_special or self._int != '0' - def __cmp__(self, other): - other = _convert_other(other) - if other is NotImplemented: - # Never return NotImplemented - return 1 + def _cmp(self, other): + """Compare the two non-NaN decimal instances self and other. - if self._is_special or other._is_special: - # check for nans, without raising on a signaling nan - if self._isnan() or other._isnan(): - return 1 # Comparison involving NaN's always reports self > other + Returns -1 if self < other, 0 if self == other and 1 + if self > other. This routine is for internal use only.""" - # INF = INF + if self._is_special or other._is_special: return cmp(self._isinfinity(), other._isinfinity()) # check for zeros; note that cmp(0, -0) should return 0 @@ -765,35 +793,72 @@ else: # self_adjusted < other_adjusted return -((-1)**self._sign) + # Note: The Decimal standard doesn't cover rich comparisons for + # Decimals. In particular, the specification is silent on the + # subject of what should happen for a comparison involving a NaN. + # We take the following approach: + # + # == comparisons involving a NaN always return False + # != comparisons involving a NaN always return True + # <, >, <= and >= comparisons involving a (quiet or signaling) + # NaN signal InvalidOperation, and return False if the + # InvalidOperation is not trapped. + # + # This behavior is designed to conform as closely as possible to + # that specified by IEEE 754. + def __eq__(self, other): - if not isinstance(other, (Decimal, int)): - return NotImplemented - return self.__cmp__(other) == 0 + other = _convert_other(other) + if other is NotImplemented: + return other + if self.is_nan() or other.is_nan(): + return False + return self._cmp(other) == 0 def __ne__(self, other): - if not isinstance(other, (Decimal, int)): - return NotImplemented - return self.__cmp__(other) != 0 + other = _convert_other(other) + if other is NotImplemented: + return other + if self.is_nan() or other.is_nan(): + return True + return self._cmp(other) != 0 - def __lt__(self, other): - if not isinstance(other, (Decimal, int)): - return NotImplemented - return self.__cmp__(other) < 0 - def __le__(self, other): - if not isinstance(other, (Decimal, int)): - return NotImplemented - return self.__cmp__(other) <= 0 + def __lt__(self, other, context=None): + other = _convert_other(other) + if other is NotImplemented: + return other + ans = self._compare_check_nans(other, context) + if ans: + return False + return self._cmp(other) < 0 - def __gt__(self, other): - if not isinstance(other, (Decimal, int)): - return NotImplemented - return self.__cmp__(other) > 0 + def __le__(self, other, context=None): + other = _convert_other(other) + if other is NotImplemented: + return other + ans = self._compare_check_nans(other, context) + if ans: + return False + return self._cmp(other) <= 0 - def __ge__(self, other): - if not isinstance(other, (Decimal, int)): - return NotImplemented - return self.__cmp__(other) >= 0 + def __gt__(self, other, context=None): + other = _convert_other(other) + if other is NotImplemented: + return other + ans = self._compare_check_nans(other, context) + if ans: + return False + return self._cmp(other) > 0 + + def __ge__(self, other, context=None): + other = _convert_other(other) + if other is NotImplemented: + return other + ans = self._compare_check_nans(other, context) + if ans: + return False + return self._cmp(other) >= 0 def compare(self, other, context=None): """Compares one to another. @@ -812,7 +877,7 @@ if ans: return ans - return Decimal(self.__cmp__(other)) + return Decimal(self._cmp(other)) def __hash__(self): """x.__hash__() <==> hash(x)""" @@ -820,7 +885,7 @@ # # The hash of a nonspecial noninteger Decimal must depend only # on the value of that Decimal, and not on its representation. - # For example: hash(Decimal("100E-1")) == hash(Decimal("10")). + # For example: hash(Decimal('100E-1')) == hash(Decimal('10')). if self._is_special: if self._isnan(): raise TypeError('Cannot hash a NaN value.') @@ -854,7 +919,7 @@ def __repr__(self): """Represents the number as an instance of Decimal.""" # Invariant: eval(repr(d)) == d - return 'Decimal("%s")' % str(self) + return "Decimal('%s')" % str(self) def __str__(self, eng=False, context=None): """Return string representation of the number in scientific notation. @@ -1453,6 +1518,20 @@ __trunc__ = __int__ + @property + def real(self): + return self + + @property + def imag(self): + return Decimal(0) + + def conjugate(self): + return self + + def __complex__(self): + return complex(float(self)) + def _fix_nan(self, context): """Decapitate the payload of a NaN to fit the context""" payload = self._int @@ -1570,6 +1649,9 @@ else: return -1 + def __round__(self): + return self._round_down(0) + def _round_up(self, prec): """Rounds away from 0.""" return -self._round_down(prec) @@ -1605,6 +1687,9 @@ else: return -self._round_down(prec) + def __ceil__(self): + return self._round_ceiling(0) + def _round_floor(self, prec): """Rounds down (not towards 0 if negative)""" if not self._sign: @@ -1612,6 +1697,9 @@ else: return -self._round_down(prec) + def __floor__(self): + return self._round_floor(0) + def _round_05up(self, prec): """Round down unless digit prec-1 is 0 or 5.""" if prec and self._int[prec-1] not in '05': @@ -2293,6 +2381,29 @@ coeff = str(int(coeff)+1) return _dec_from_triple(self._sign, coeff, exp) + def _round(self, places, rounding): + """Round a nonzero, nonspecial Decimal to a fixed number of + significant figures, using the given rounding mode. + + Infinities, NaNs and zeros are returned unaltered. + + This operation is quiet: it raises no flags, and uses no + information from the context. + + """ + if places <= 0: + raise ValueError("argument should be at least 1 in _round") + if self._is_special or not self: + return Decimal(self) + ans = self._rescale(self.adjusted()+1-places, rounding) + # it can happen that the rescale alters the adjusted exponent; + # for example when rounding 99.97 to 3 significant figures. + # When this happens we end up with an extra 0 at the end of + # the number; a second rescale fixes this. + if ans.adjusted() != self.adjusted(): + ans = ans._rescale(ans.adjusted()+1-places, rounding) + return ans + def to_integral_exact(self, rounding=None, context=None): """Rounds to a nearby integer. @@ -2343,6 +2454,9 @@ def sqrt(self, context=None): """Return the square root of self.""" + if context is None: + context = getcontext() + if self._is_special: ans = self._check_nans(context=context) if ans: @@ -2356,9 +2470,6 @@ ans = _dec_from_triple(self._sign, '0', self._exp // 2) return ans._fix(context) - if context is None: - context = getcontext() - if self._sign == 1: return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0') @@ -2463,7 +2574,7 @@ return other._fix_nan(context) return self._check_nans(other, context) - c = self.__cmp__(other) + c = self._cmp(other) if c == 0: # If both operands are finite and equal in numerical value # then an ordering is applied: @@ -2505,7 +2616,7 @@ return other._fix_nan(context) return self._check_nans(other, context) - c = self.__cmp__(other) + c = self._cmp(other) if c == 0: c = self.compare_total(other) @@ -2553,23 +2664,10 @@ It's pretty much like compare(), but all NaNs signal, with signaling NaNs taking precedence over quiet NaNs. """ - if context is None: - context = getcontext() - - self_is_nan = self._isnan() - other_is_nan = other._isnan() - if self_is_nan == 2: - return context._raise_error(InvalidOperation, 'sNaN', - self) - if other_is_nan == 2: - return context._raise_error(InvalidOperation, 'sNaN', - other) - if self_is_nan: - return context._raise_error(InvalidOperation, 'NaN in compare_signal', - self) - if other_is_nan: - return context._raise_error(InvalidOperation, 'NaN in compare_signal', - other) + other = _convert_other(other, raiseit = True) + ans = self._compare_check_nans(other, context) + if ans: + return ans return self.compare(other, context=context) def compare_total(self, other): @@ -3076,7 +3174,7 @@ return other._fix_nan(context) return self._check_nans(other, context) - c = self.copy_abs().__cmp__(other.copy_abs()) + c = self.copy_abs()._cmp(other.copy_abs()) if c == 0: c = self.compare_total(other) @@ -3106,7 +3204,7 @@ return other._fix_nan(context) return self._check_nans(other, context) - c = self.copy_abs().__cmp__(other.copy_abs()) + c = self.copy_abs()._cmp(other.copy_abs()) if c == 0: c = self.compare_total(other) @@ -3181,7 +3279,7 @@ if ans: return ans - comparison = self.__cmp__(other) + comparison = self._cmp(other) if comparison == 0: return self.copy_sign(other) @@ -3357,6 +3455,95 @@ return self # My components are also immutable return self.__class__(str(self)) + # PEP 3101 support. See also _parse_format_specifier and _format_align + def __format__(self, specifier, context=None): + """Format a Decimal instance according to the given specifier. + + The specifier should be a standard format specifier, with the + form described in PEP 3101. Formatting types 'e', 'E', 'f', + 'F', 'g', 'G', and '%' are supported. If the formatting type + is omitted it defaults to 'g' or 'G', depending on the value + of context.capitals. + + At this time the 'n' format specifier type (which is supposed + to use the current locale) is not supported. + """ + + # Note: PEP 3101 says that if the type is not present then + # there should be at least one digit after the decimal point. + # We take the liberty of ignoring this requirement for + # Decimal---it's presumably there to make sure that + # format(float, '') behaves similarly to str(float). + if context is None: + context = getcontext() + + spec = _parse_format_specifier(specifier) + + # special values don't care about the type or precision... + if self._is_special: + return _format_align(str(self), spec) + + # a type of None defaults to 'g' or 'G', depending on context + # if type is '%', adjust exponent of self accordingly + if spec['type'] is None: + spec['type'] = ['g', 'G'][context.capitals] + elif spec['type'] == '%': + self = _dec_from_triple(self._sign, self._int, self._exp+2) + + # round if necessary, taking rounding mode from the context + rounding = context.rounding + precision = spec['precision'] + if precision is not None: + if spec['type'] in 'eE': + self = self._round(precision+1, rounding) + elif spec['type'] in 'gG': + if len(self._int) > precision: + self = self._round(precision, rounding) + elif spec['type'] in 'fF%': + self = self._rescale(-precision, rounding) + # special case: zeros with a positive exponent can't be + # represented in fixed point; rescale them to 0e0. + elif not self and self._exp > 0 and spec['type'] in 'fF%': + self = self._rescale(0, rounding) + + # figure out placement of the decimal point + leftdigits = self._exp + len(self._int) + if spec['type'] in 'fF%': + dotplace = leftdigits + elif spec['type'] in 'eE': + if not self and precision is not None: + dotplace = 1 - precision + else: + dotplace = 1 + elif spec['type'] in 'gG': + if self._exp <= 0 and leftdigits > -6: + dotplace = leftdigits + else: + dotplace = 1 + + # figure out main part of numeric string... + if dotplace <= 0: + num = '0.' + '0'*(-dotplace) + self._int + elif dotplace >= len(self._int): + # make sure we're not padding a '0' with extra zeros on the right + assert dotplace==len(self._int) or self._int != '0' + num = self._int + '0'*(dotplace-len(self._int)) + else: + num = self._int[:dotplace] + '.' + self._int[dotplace:] + + # ...then the trailing exponent, or trailing '%' + if leftdigits != dotplace or spec['type'] in 'eE': + echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']] + num = num + "{0}{1:+}".format(echar, leftdigits-dotplace) + elif spec['type'] == '%': + num = num + '%' + + # add sign + if self._sign == 1: + num = '-' + num + return _format_align(num, spec) + + def _dec_from_triple(sign, coefficient, exponent, special=False): """Create a decimal instance directly, without any validation, normalization (e.g. removal of leading zeros) or argument @@ -3411,7 +3598,7 @@ traps - If traps[exception] = 1, then the exception is raised when it is caused. Otherwise, a value is substituted in. - flags - When an exception is caused, flags[exception] is incremented. + flags - When an exception is caused, flags[exception] is set. (Whether or not the trap_enabler is set) Should be reset by user of Decimal instance. Emin - Minimum exponent @@ -3477,16 +3664,16 @@ """Handles an error If the flag is in _ignored_flags, returns the default response. - Otherwise, it increments the flag, then, if the corresponding + Otherwise, it sets the flag, then, if the corresponding trap_enabler is set, it reaises the exception. Otherwise, it returns - the default value after incrementing the flag. + the default value after setting the flag. """ error = _condition_map.get(condition, condition) if error in self._ignored_flags: # Don't touch the flag return error().handle(self, *args) - self.flags[error] += 1 + self.flags[error] = 1 if not self.traps[error]: # The errors define how to handle themselves. return condition().handle(self, *args) @@ -3571,13 +3758,13 @@ the plus operation on the operand. >>> ExtendedContext.abs(Decimal('2.1')) - Decimal("2.1") + Decimal('2.1') >>> ExtendedContext.abs(Decimal('-100')) - Decimal("100") + Decimal('100') >>> ExtendedContext.abs(Decimal('101.5')) - Decimal("101.5") + Decimal('101.5') >>> ExtendedContext.abs(Decimal('-101.5')) - Decimal("101.5") + Decimal('101.5') """ return a.__abs__(context=self) @@ -3585,9 +3772,9 @@ """Return the sum of the two operands. >>> ExtendedContext.add(Decimal('12'), Decimal('7.00')) - Decimal("19.00") + Decimal('19.00') >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4')) - Decimal("1.02E+4") + Decimal('1.02E+4') """ return a.__add__(b, context=self) @@ -3601,7 +3788,7 @@ received object already is in its canonical form. >>> ExtendedContext.canonical(Decimal('2.50')) - Decimal("2.50") + Decimal('2.50') """ return a.canonical(context=self) @@ -3620,17 +3807,17 @@ zero or negative zero, or '1' if the result is greater than zero. >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3')) - Decimal("-1") + Decimal('-1') >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1')) - Decimal("0") + Decimal('0') >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10')) - Decimal("0") + Decimal('0') >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1')) - Decimal("1") + Decimal('1') >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3')) - Decimal("1") + Decimal('1') >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1')) - Decimal("-1") + Decimal('-1') """ return a.compare(b, context=self) @@ -3642,21 +3829,21 @@ >>> c = ExtendedContext >>> c.compare_signal(Decimal('2.1'), Decimal('3')) - Decimal("-1") + Decimal('-1') >>> c.compare_signal(Decimal('2.1'), Decimal('2.1')) - Decimal("0") + Decimal('0') >>> c.flags[InvalidOperation] = 0 >>> print(c.flags[InvalidOperation]) 0 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1')) - Decimal("NaN") + Decimal('NaN') >>> print(c.flags[InvalidOperation]) 1 >>> c.flags[InvalidOperation] = 0 >>> print(c.flags[InvalidOperation]) 0 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1')) - Decimal("NaN") + Decimal('NaN') >>> print(c.flags[InvalidOperation]) 1 """ @@ -3670,17 +3857,17 @@ representations. >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9')) - Decimal("-1") + Decimal('-1') >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12')) - Decimal("-1") + Decimal('-1') >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3')) - Decimal("-1") + Decimal('-1') >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30')) - Decimal("0") + Decimal('0') >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300')) - Decimal("1") + Decimal('1') >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN')) - Decimal("-1") + Decimal('-1') """ return a.compare_total(b) @@ -3695,9 +3882,9 @@ """Returns a copy of the operand with the sign set to 0. >>> ExtendedContext.copy_abs(Decimal('2.1')) - Decimal("2.1") + Decimal('2.1') >>> ExtendedContext.copy_abs(Decimal('-100')) - Decimal("100") + Decimal('100') """ return a.copy_abs() @@ -3705,9 +3892,9 @@ """Returns a copy of the decimal objet. >>> ExtendedContext.copy_decimal(Decimal('2.1')) - Decimal("2.1") + Decimal('2.1') >>> ExtendedContext.copy_decimal(Decimal('-1.00')) - Decimal("-1.00") + Decimal('-1.00') """ return Decimal(a) @@ -3715,9 +3902,9 @@ """Returns a copy of the operand with the sign inverted. >>> ExtendedContext.copy_negate(Decimal('101.5')) - Decimal("-101.5") + Decimal('-101.5') >>> ExtendedContext.copy_negate(Decimal('-101.5')) - Decimal("101.5") + Decimal('101.5') """ return a.copy_negate() @@ -3728,13 +3915,13 @@ equal to the sign of the second operand. >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33')) - Decimal("1.50") + Decimal('1.50') >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33')) - Decimal("1.50") + Decimal('1.50') >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33')) - Decimal("-1.50") + Decimal('-1.50') >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33')) - Decimal("-1.50") + Decimal('-1.50') """ return a.copy_sign(b) @@ -3742,25 +3929,25 @@ """Decimal division in a specified context. >>> ExtendedContext.divide(Decimal('1'), Decimal('3')) - Decimal("0.333333333") + Decimal('0.333333333') >>> ExtendedContext.divide(Decimal('2'), Decimal('3')) - Decimal("0.666666667") + Decimal('0.666666667') >>> ExtendedContext.divide(Decimal('5'), Decimal('2')) - Decimal("2.5") + Decimal('2.5') >>> ExtendedContext.divide(Decimal('1'), Decimal('10')) - Decimal("0.1") + Decimal('0.1') >>> ExtendedContext.divide(Decimal('12'), Decimal('12')) - Decimal("1") + Decimal('1') >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2')) - Decimal("4.00") + Decimal('4.00') >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0')) - Decimal("1.20") + Decimal('1.20') >>> ExtendedContext.divide(Decimal('1000'), Decimal('100')) - Decimal("10") + Decimal('10') >>> ExtendedContext.divide(Decimal('1000'), Decimal('1')) - Decimal("1000") + Decimal('1000') >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2')) - Decimal("1.20E+6") + Decimal('1.20E+6') """ return a.__truediv__(b, context=self) @@ -3768,11 +3955,11 @@ """Divides two numbers and returns the integer part of the result. >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3')) - Decimal("0") + Decimal('0') >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3')) - Decimal("3") + Decimal('3') >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3')) - Decimal("3") + Decimal('3') """ return a.__floordiv__(b, context=self) @@ -3786,17 +3973,17 @@ >>> c.Emin = -999 >>> c.Emax = 999 >>> c.exp(Decimal('-Infinity')) - Decimal("0") + Decimal('0') >>> c.exp(Decimal('-1')) - Decimal("0.367879441") + Decimal('0.367879441') >>> c.exp(Decimal('0')) - Decimal("1") + Decimal('1') >>> c.exp(Decimal('1')) - Decimal("2.71828183") + Decimal('2.71828183') >>> c.exp(Decimal('0.693147181')) - Decimal("2.00000000") + Decimal('2.00000000') >>> c.exp(Decimal('+Infinity')) - Decimal("Infinity") + Decimal('Infinity') """ return a.exp(context=self) @@ -3808,11 +3995,11 @@ multiplication, using add, all with only one final rounding. >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7')) - Decimal("22") + Decimal('22') >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7')) - Decimal("-8") + Decimal('-8') >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578')) - Decimal("1.38435736E+12") + Decimal('1.38435736E+12') """ return a.fma(b, c, context=self) @@ -3966,15 +4153,15 @@ >>> c.Emin = -999 >>> c.Emax = 999 >>> c.ln(Decimal('0')) - Decimal("-Infinity") + Decimal('-Infinity') >>> c.ln(Decimal('1.000')) - Decimal("0") + Decimal('0') >>> c.ln(Decimal('2.71828183')) - Decimal("1.00000000") + Decimal('1.00000000') >>> c.ln(Decimal('10')) - Decimal("2.30258509") + Decimal('2.30258509') >>> c.ln(Decimal('+Infinity')) - Decimal("Infinity") + Decimal('Infinity') """ return a.ln(context=self) @@ -3985,19 +4172,19 @@ >>> c.Emin = -999 >>> c.Emax = 999 >>> c.log10(Decimal('0')) - Decimal("-Infinity") + Decimal('-Infinity') >>> c.log10(Decimal('0.001')) - Decimal("-3") + Decimal('-3') >>> c.log10(Decimal('1.000')) - Decimal("0") + Decimal('0') >>> c.log10(Decimal('2')) - Decimal("0.301029996") + Decimal('0.301029996') >>> c.log10(Decimal('10')) - Decimal("1") + Decimal('1') >>> c.log10(Decimal('70')) - Decimal("1.84509804") + Decimal('1.84509804') >>> c.log10(Decimal('+Infinity')) - Decimal("Infinity") + Decimal('Infinity') """ return a.log10(context=self) @@ -4010,13 +4197,13 @@ value of that digit and without limiting the resulting exponent). >>> ExtendedContext.logb(Decimal('250')) - Decimal("2") + Decimal('2') >>> ExtendedContext.logb(Decimal('2.50')) - Decimal("0") + Decimal('0') >>> ExtendedContext.logb(Decimal('0.03')) - Decimal("-2") + Decimal('-2') >>> ExtendedContext.logb(Decimal('0')) - Decimal("-Infinity") + Decimal('-Infinity') """ return a.logb(context=self) @@ -4026,17 +4213,17 @@ The operands must be both logical numbers. >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0')) - Decimal("0") + Decimal('0') >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1')) - Decimal("0") + Decimal('0') >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0')) - Decimal("0") + Decimal('0') >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1')) - Decimal("1") + Decimal('1') >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010')) - Decimal("1000") + Decimal('1000') >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10')) - Decimal("10") + Decimal('10') """ return a.logical_and(b, context=self) @@ -4046,13 +4233,13 @@ The operand must be a logical number. >>> ExtendedContext.logical_invert(Decimal('0')) - Decimal("111111111") + Decimal('111111111') >>> ExtendedContext.logical_invert(Decimal('1')) - Decimal("111111110") + Decimal('111111110') >>> ExtendedContext.logical_invert(Decimal('111111111')) - Decimal("0") + Decimal('0') >>> ExtendedContext.logical_invert(Decimal('101010101')) - Decimal("10101010") + Decimal('10101010') """ return a.logical_invert(context=self) @@ -4062,17 +4249,17 @@ The operands must be both logical numbers. >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0')) - Decimal("0") + Decimal('0') >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1')) - Decimal("1") + Decimal('1') >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0')) - Decimal("1") + Decimal('1') >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1')) - Decimal("1") + Decimal('1') >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010')) - Decimal("1110") + Decimal('1110') >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10')) - Decimal("1110") + Decimal('1110') """ return a.logical_or(b, context=self) @@ -4082,17 +4269,17 @@ The operands must be both logical numbers. >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0')) - Decimal("0") + Decimal('0') >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1')) - Decimal("1") + Decimal('1') >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0')) - Decimal("1") + Decimal('1') >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1')) - Decimal("0") + Decimal('0') >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010')) - Decimal("110") + Decimal('110') >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10')) - Decimal("1101") + Decimal('1101') """ return a.logical_xor(b, context=self) @@ -4106,13 +4293,13 @@ infinity) of the two operands is chosen as the result. >>> ExtendedContext.max(Decimal('3'), Decimal('2')) - Decimal("3") + Decimal('3') >>> ExtendedContext.max(Decimal('-10'), Decimal('3')) - Decimal("3") + Decimal('3') >>> ExtendedContext.max(Decimal('1.0'), Decimal('1')) - Decimal("1") + Decimal('1') >>> ExtendedContext.max(Decimal('7'), Decimal('NaN')) - Decimal("7") + Decimal('7') """ return a.max(b, context=self) @@ -4130,13 +4317,13 @@ infinity) of the two operands is chosen as the result. >>> ExtendedContext.min(Decimal('3'), Decimal('2')) - Decimal("2") + Decimal('2') >>> ExtendedContext.min(Decimal('-10'), Decimal('3')) - Decimal("-10") + Decimal('-10') >>> ExtendedContext.min(Decimal('1.0'), Decimal('1')) - Decimal("1.0") + Decimal('1.0') >>> ExtendedContext.min(Decimal('7'), Decimal('NaN')) - Decimal("7") + Decimal('7') """ return a.min(b, context=self) @@ -4152,9 +4339,9 @@ has the same exponent as the operand. >>> ExtendedContext.minus(Decimal('1.3')) - Decimal("-1.3") + Decimal('-1.3') >>> ExtendedContext.minus(Decimal('-1.3')) - Decimal("1.3") + Decimal('1.3') """ return a.__neg__(context=self) @@ -4167,15 +4354,15 @@ of the two operands. >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3')) - Decimal("3.60") + Decimal('3.60') >>> ExtendedContext.multiply(Decimal('7'), Decimal('3')) - Decimal("21") + Decimal('21') >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8')) - Decimal("0.72") + Decimal('0.72') >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0')) - Decimal("-0.0") + Decimal('-0.0') >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321')) - Decimal("4.28135971E+11") + Decimal('4.28135971E+11') """ return a.__mul__(b, context=self) @@ -4186,13 +4373,13 @@ >>> c.Emin = -999 >>> c.Emax = 999 >>> ExtendedContext.next_minus(Decimal('1')) - Decimal("0.999999999") + Decimal('0.999999999') >>> c.next_minus(Decimal('1E-1007')) - Decimal("0E-1007") + Decimal('0E-1007') >>> ExtendedContext.next_minus(Decimal('-1.00000003')) - Decimal("-1.00000004") + Decimal('-1.00000004') >>> c.next_minus(Decimal('Infinity')) - Decimal("9.99999999E+999") + Decimal('9.99999999E+999') """ return a.next_minus(context=self) @@ -4203,13 +4390,13 @@ >>> c.Emin = -999 >>> c.Emax = 999 >>> ExtendedContext.next_plus(Decimal('1')) - Decimal("1.00000001") + Decimal('1.00000001') >>> c.next_plus(Decimal('-1E-1007')) - Decimal("-0E-1007") + Decimal('-0E-1007') >>> ExtendedContext.next_plus(Decimal('-1.00000003')) - Decimal("-1.00000002") + Decimal('-1.00000002') >>> c.next_plus(Decimal('-Infinity')) - Decimal("-9.99999999E+999") + Decimal('-9.99999999E+999') """ return a.next_plus(context=self) @@ -4225,19 +4412,19 @@ >>> c.Emin = -999 >>> c.Emax = 999 >>> c.next_toward(Decimal('1'), Decimal('2')) - Decimal("1.00000001") + Decimal('1.00000001') >>> c.next_toward(Decimal('-1E-1007'), Decimal('1')) - Decimal("-0E-1007") + Decimal('-0E-1007') >>> c.next_toward(Decimal('-1.00000003'), Decimal('0')) - Decimal("-1.00000002") + Decimal('-1.00000002') >>> c.next_toward(Decimal('1'), Decimal('0')) - Decimal("0.999999999") + Decimal('0.999999999') >>> c.next_toward(Decimal('1E-1007'), Decimal('-100')) - Decimal("0E-1007") + Decimal('0E-1007') >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10')) - Decimal("-1.00000004") + Decimal('-1.00000004') >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000')) - Decimal("-0.00") + Decimal('-0.00') """ return a.next_toward(b, context=self) @@ -4248,17 +4435,17 @@ result. >>> ExtendedContext.normalize(Decimal('2.1')) - Decimal("2.1") + Decimal('2.1') >>> ExtendedContext.normalize(Decimal('-2.0')) - Decimal("-2") + Decimal('-2') >>> ExtendedContext.normalize(Decimal('1.200')) - Decimal("1.2") + Decimal('1.2') >>> ExtendedContext.normalize(Decimal('-120')) - Decimal("-1.2E+2") + Decimal('-1.2E+2') >>> ExtendedContext.normalize(Decimal('120.00')) - Decimal("1.2E+2") + Decimal('1.2E+2') >>> ExtendedContext.normalize(Decimal('0.00')) - Decimal("0") + Decimal('0') """ return a.normalize(context=self) @@ -4317,9 +4504,9 @@ has the same exponent as the operand. >>> ExtendedContext.plus(Decimal('1.3')) - Decimal("1.3") + Decimal('1.3') >>> ExtendedContext.plus(Decimal('-1.3')) - Decimal("-1.3") + Decimal('-1.3') """ return a.__pos__(context=self) @@ -4349,46 +4536,46 @@ >>> c.Emin = -999 >>> c.Emax = 999 >>> c.power(Decimal('2'), Decimal('3')) - Decimal("8") + Decimal('8') >>> c.power(Decimal('-2'), Decimal('3')) - Decimal("-8") + Decimal('-8') >>> c.power(Decimal('2'), Decimal('-3')) - Decimal("0.125") + Decimal('0.125') >>> c.power(Decimal('1.7'), Decimal('8')) - Decimal("69.7575744") + Decimal('69.7575744') >>> c.power(Decimal('10'), Decimal('0.301029996')) - Decimal("2.00000000") + Decimal('2.00000000') >>> c.power(Decimal('Infinity'), Decimal('-1')) - Decimal("0") + Decimal('0') >>> c.power(Decimal('Infinity'), Decimal('0')) - Decimal("1") + Decimal('1') >>> c.power(Decimal('Infinity'), Decimal('1')) - Decimal("Infinity") + Decimal('Infinity') >>> c.power(Decimal('-Infinity'), Decimal('-1')) - Decimal("-0") + Decimal('-0') >>> c.power(Decimal('-Infinity'), Decimal('0')) - Decimal("1") + Decimal('1') >>> c.power(Decimal('-Infinity'), Decimal('1')) - Decimal("-Infinity") + Decimal('-Infinity') >>> c.power(Decimal('-Infinity'), Decimal('2')) - Decimal("Infinity") + Decimal('Infinity') >>> c.power(Decimal('0'), Decimal('0')) - Decimal("NaN") + Decimal('NaN') >>> c.power(Decimal('3'), Decimal('7'), Decimal('16')) - Decimal("11") + Decimal('11') >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16')) - Decimal("-11") + Decimal('-11') >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16')) - Decimal("1") + Decimal('1') >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16')) - Decimal("11") + Decimal('11') >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789')) - Decimal("11729830") + Decimal('11729830') >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729')) - Decimal("-0") + Decimal('-0') >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537')) - Decimal("1") + Decimal('1') """ return a.__pow__(b, modulo, context=self) @@ -4411,35 +4598,35 @@ if the result is subnormal and inexact. >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001')) - Decimal("2.170") + Decimal('2.170') >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01')) - Decimal("2.17") + Decimal('2.17') >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1')) - Decimal("2.2") + Decimal('2.2') >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0')) - Decimal("2") + Decimal('2') >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1')) - Decimal("0E+1") + Decimal('0E+1') >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity')) - Decimal("-Infinity") + Decimal('-Infinity') >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity')) - Decimal("NaN") + Decimal('NaN') >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1')) - Decimal("-0") + Decimal('-0') >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5')) - Decimal("-0E+5") + Decimal('-0E+5') >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2')) - Decimal("NaN") + Decimal('NaN') >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2')) - Decimal("NaN") + Decimal('NaN') >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1')) - Decimal("217.0") + Decimal('217.0') >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0')) - Decimal("217") + Decimal('217') >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1')) - Decimal("2.2E+2") + Decimal('2.2E+2') >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2')) - Decimal("2E+2") + Decimal('2E+2') """ return a.quantize(b, context=self) @@ -4447,7 +4634,7 @@ """Just returns 10, as this is Decimal, :) >>> ExtendedContext.radix() - Decimal("10") + Decimal('10') """ return Decimal(10) @@ -4464,17 +4651,17 @@ remainder cannot be calculated). >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3')) - Decimal("2.1") + Decimal('2.1') >>> ExtendedContext.remainder(Decimal('10'), Decimal('3')) - Decimal("1") + Decimal('1') >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3')) - Decimal("-1") + Decimal('-1') >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1')) - Decimal("0.2") + Decimal('0.2') >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3')) - Decimal("0.1") + Decimal('0.1') >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3')) - Decimal("1.0") + Decimal('1.0') """ return a.__mod__(b, context=self) @@ -4489,19 +4676,19 @@ remainder cannot be calculated). >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3')) - Decimal("-0.9") + Decimal('-0.9') >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6')) - Decimal("-2") + Decimal('-2') >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3')) - Decimal("1") + Decimal('1') >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3')) - Decimal("-1") + Decimal('-1') >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1')) - Decimal("0.2") + Decimal('0.2') >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3')) - Decimal("0.1") + Decimal('0.1') >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3')) - Decimal("-0.3") + Decimal('-0.3') """ return a.remainder_near(b, context=self) @@ -4515,15 +4702,15 @@ positive or to the right otherwise. >>> ExtendedContext.rotate(Decimal('34'), Decimal('8')) - Decimal("400000003") + Decimal('400000003') >>> ExtendedContext.rotate(Decimal('12'), Decimal('9')) - Decimal("12") + Decimal('12') >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2')) - Decimal("891234567") + Decimal('891234567') >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0')) - Decimal("123456789") + Decimal('123456789') >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2')) - Decimal("345678912") + Decimal('345678912') """ return a.rotate(b, context=self) @@ -4548,11 +4735,11 @@ """Returns the first operand after adding the second value its exp. >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2')) - Decimal("0.0750") + Decimal('0.0750') >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0')) - Decimal("7.50") + Decimal('7.50') >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3')) - Decimal("7.50E+3") + Decimal('7.50E+3') """ return a.scaleb (b, context=self) @@ -4567,15 +4754,15 @@ coefficient are zeros. >>> ExtendedContext.shift(Decimal('34'), Decimal('8')) - Decimal("400000000") + Decimal('400000000') >>> ExtendedContext.shift(Decimal('12'), Decimal('9')) - Decimal("0") + Decimal('0') >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2')) - Decimal("1234567") + Decimal('1234567') >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0')) - Decimal("123456789") + Decimal('123456789') >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2')) - Decimal("345678900") + Decimal('345678900') """ return a.shift(b, context=self) @@ -4586,23 +4773,23 @@ algorithm. >>> ExtendedContext.sqrt(Decimal('0')) - Decimal("0") + Decimal('0') >>> ExtendedContext.sqrt(Decimal('-0')) - Decimal("-0") + Decimal('-0') >>> ExtendedContext.sqrt(Decimal('0.39')) - Decimal("0.624499800") + Decimal('0.624499800') >>> ExtendedContext.sqrt(Decimal('100')) - Decimal("10") + Decimal('10') >>> ExtendedContext.sqrt(Decimal('1')) - Decimal("1") + Decimal('1') >>> ExtendedContext.sqrt(Decimal('1.0')) - Decimal("1.0") + Decimal('1.0') >>> ExtendedContext.sqrt(Decimal('1.00')) - Decimal("1.0") + Decimal('1.0') >>> ExtendedContext.sqrt(Decimal('7')) - Decimal("2.64575131") + Decimal('2.64575131') >>> ExtendedContext.sqrt(Decimal('10')) - Decimal("3.16227766") + Decimal('3.16227766') >>> ExtendedContext.prec 9 """ @@ -4612,11 +4799,11 @@ """Return the difference between the two operands. >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07')) - Decimal("0.23") + Decimal('0.23') >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30')) - Decimal("0.00") + Decimal('0.00') >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07')) - Decimal("-0.77") + Decimal('-0.77') """ return a.__sub__(b, context=self) @@ -4645,21 +4832,21 @@ context. >>> ExtendedContext.to_integral_exact(Decimal('2.1')) - Decimal("2") + Decimal('2') >>> ExtendedContext.to_integral_exact(Decimal('100')) - Decimal("100") + Decimal('100') >>> ExtendedContext.to_integral_exact(Decimal('100.0')) - Decimal("100") + Decimal('100') >>> ExtendedContext.to_integral_exact(Decimal('101.5')) - Decimal("102") + Decimal('102') >>> ExtendedContext.to_integral_exact(Decimal('-101.5')) - Decimal("-102") + Decimal('-102') >>> ExtendedContext.to_integral_exact(Decimal('10E+5')) - Decimal("1.0E+6") + Decimal('1.0E+6') >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77')) - Decimal("7.89E+77") + Decimal('7.89E+77') >>> ExtendedContext.to_integral_exact(Decimal('-Inf')) - Decimal("-Infinity") + Decimal('-Infinity') """ return a.to_integral_exact(context=self) @@ -4673,21 +4860,21 @@ be set. The rounding mode is taken from the context. >>> ExtendedContext.to_integral_value(Decimal('2.1')) - Decimal("2") + Decimal('2') >>> ExtendedContext.to_integral_value(Decimal('100')) - Decimal("100") + Decimal('100') >>> ExtendedContext.to_integral_value(Decimal('100.0')) - Decimal("100") + Decimal('100') >>> ExtendedContext.to_integral_value(Decimal('101.5')) - Decimal("102") + Decimal('102') >>> ExtendedContext.to_integral_value(Decimal('-101.5')) - Decimal("-102") + Decimal('-102') >>> ExtendedContext.to_integral_value(Decimal('10E+5')) - Decimal("1.0E+6") + Decimal('1.0E+6') >>> ExtendedContext.to_integral_value(Decimal('7.89E+77')) - Decimal("7.89E+77") + Decimal('7.89E+77') >>> ExtendedContext.to_integral_value(Decimal('-Inf')) - Decimal("-Infinity") + Decimal('-Infinity') """ return a.to_integral_value(context=self) @@ -5136,8 +5323,7 @@ ##### crud for parsing strings ############################################# -import re - +# # Regular expression used for parsing numeric strings. Additional # comments: # @@ -5175,8 +5361,132 @@ _all_zeros = re.compile('0*$').match _exact_half = re.compile('50*$').match + +##### PEP3101 support functions ############################################## +# The functions parse_format_specifier and format_align have little to do +# with the Decimal class, and could potentially be reused for other pure +# Python numeric classes that want to implement __format__ +# +# A format specifier for Decimal looks like: +# +# [[fill]align][sign][0][minimumwidth][.precision][type] +# + +_parse_format_specifier_regex = re.compile(r"""\A +(?: + (?P.)? + (?P[<>=^]) +)? +(?P[-+ ])? +(?P0)? +(?P(?!0)\d+)? +(?:\.(?P0|(?!0)\d+))? +(?P[eEfFgG%])? +\Z +""", re.VERBOSE) + del re +def _parse_format_specifier(format_spec): + """Parse and validate a format specifier. + + Turns a standard numeric format specifier into a dict, with the + following entries: + + fill: fill character to pad field to minimum width + align: alignment type, either '<', '>', '=' or '^' + sign: either '+', '-' or ' ' + minimumwidth: nonnegative integer giving minimum width + precision: nonnegative integer giving precision, or None + type: one of the characters 'eEfFgG%', or None + unicode: either True or False (always True for Python 3.x) + + """ + m = _parse_format_specifier_regex.match(format_spec) + if m is None: + raise ValueError("Invalid format specifier: " + format_spec) + + # get the dictionary + format_dict = m.groupdict() + + # defaults for fill and alignment + fill = format_dict['fill'] + align = format_dict['align'] + if format_dict.pop('zeropad') is not None: + # in the face of conflict, refuse the temptation to guess + if fill is not None and fill != '0': + raise ValueError("Fill character conflicts with '0'" + " in format specifier: " + format_spec) + if align is not None and align != '=': + raise ValueError("Alignment conflicts with '0' in " + "format specifier: " + format_spec) + fill = '0' + align = '=' + format_dict['fill'] = fill or ' ' + format_dict['align'] = align or '<' + + if format_dict['sign'] is None: + format_dict['sign'] = '-' + + # turn minimumwidth and precision entries into integers. + # minimumwidth defaults to 0; precision remains None if not given + format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0') + if format_dict['precision'] is not None: + format_dict['precision'] = int(format_dict['precision']) + + # if format type is 'g' or 'G' then a precision of 0 makes little + # sense; convert it to 1. Same if format type is unspecified. + if format_dict['precision'] == 0: + if format_dict['type'] in 'gG' or format_dict['type'] is None: + format_dict['precision'] = 1 + + # record whether return type should be str or unicode + format_dict['unicode'] = True + + return format_dict + +def _format_align(body, spec_dict): + """Given an unpadded, non-aligned numeric string, add padding and + aligment to conform with the given format specifier dictionary (as + output from parse_format_specifier). + + It's assumed that if body is negative then it starts with '-'. + Any leading sign ('-' or '+') is stripped from the body before + applying the alignment and padding rules, and replaced in the + appropriate position. + + """ + # figure out the sign; we only examine the first character, so if + # body has leading whitespace the results may be surprising. + if len(body) > 0 and body[0] in '-+': + sign = body[0] + body = body[1:] + else: + sign = '' + + if sign != '-': + if spec_dict['sign'] in ' +': + sign = spec_dict['sign'] + else: + sign = '' + + # how much extra space do we have to play with? + minimumwidth = spec_dict['minimumwidth'] + fill = spec_dict['fill'] + padding = fill*(max(minimumwidth - (len(sign+body)), 0)) + + align = spec_dict['align'] + if align == '<': + result = padding + sign + body + elif align == '>': + result = sign + body + padding + elif align == '=': + result = sign + padding + body + else: #align == '^' + half = len(padding)//2 + result = padding[:half] + sign + body + padding[half:] + + return result ##### Useful Constants (internal use only) ################################ Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/__init__.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/__init__.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/__init__.py Wed Apr 30 15:57:13 2008 @@ -18,4 +18,7 @@ # In general, major and minor version should loosely follow the Python # version number the distutils code was shipped with. # -__version__ = "2.5.1" + +#--start constants-- +__version__ = "3.0a4" +#--end constants-- Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/bcppcompiler.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/bcppcompiler.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/bcppcompiler.py Wed Apr 30 15:57:13 2008 @@ -14,7 +14,7 @@ __revision__ = "$Id$" -import sys, os +import os from distutils.errors import \ DistutilsExecError, DistutilsPlatformError, \ CompileError, LibError, LinkError, UnknownFileError Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/ccompiler.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/ccompiler.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/ccompiler.py Wed Apr 30 15:57:13 2008 @@ -147,11 +147,11 @@ # discovered at run-time, since there are many different ways to do # basically the same things with Unix C compilers. - for key, value in kwargs.items(): + for key in kwargs: if key not in self.executables: - raise ValueError("unknown executable '%s' for class %s" % \ + raise ValueError("unknown executable '%s' for class %s" % (key, self.__class__.__name__)) - self.set_executable(key, value) + self.set_executable(key, kwargs[key]) def set_executable(self, key, value): if isinstance(value, str): Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/command/bdist.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/command/bdist.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/command/bdist.py Wed Apr 30 15:57:13 2008 @@ -91,7 +91,10 @@ def finalize_options(self): # have to finalize 'plat_name' before 'bdist_base' if self.plat_name is None: - self.plat_name = get_platform() + if self.skip_build: + self.plat_name = get_platform() + else: + self.plat_name = self.get_finalized_command('build').plat_name # 'bdist_base' -- parent of per-built-distribution-format # temporary directories (eg. we'll probably have Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/command/bdist_dumb.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/command/bdist_dumb.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/command/bdist_dumb.py Wed Apr 30 15:57:13 2008 @@ -9,7 +9,7 @@ import os from distutils.core import Command from distutils.util import get_platform -from distutils.dir_util import create_tree, remove_tree, ensure_relative +from distutils.dir_util import remove_tree, ensure_relative from distutils.errors import * from distutils.sysconfig import get_python_version from distutils import log Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/command/bdist_msi.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/command/bdist_msi.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/command/bdist_msi.py Wed Apr 30 15:57:13 2008 @@ -9,11 +9,11 @@ import sys, os from distutils.core import Command -from distutils.util import get_platform from distutils.dir_util import remove_tree from distutils.sysconfig import get_python_version from distutils.version import StrictVersion from distutils.errors import DistutilsOptionError +from distutils.util import get_platform from distutils import log import msilib from msilib import schema, sequence, text @@ -87,6 +87,9 @@ user_options = [('bdist-dir=', None, "temporary directory for creating the distribution"), + ('plat-name=', 'p', + "platform name to embed in generated filenames " + "(default: %s)" % get_platform()), ('keep-temp', 'k', "keep the pseudo-installation tree around after " + "creating the distribution archive"), @@ -116,6 +119,7 @@ def initialize_options(self): self.bdist_dir = None + self.plat_name = None self.keep_temp = 0 self.no_target_compile = 0 self.no_target_optimize = 0 @@ -139,7 +143,10 @@ else: self.target_version = short_version - self.set_undefined_options('bdist', ('dist_dir', 'dist_dir')) + self.set_undefined_options('bdist', + ('dist_dir', 'dist_dir'), + ('plat_name', 'plat_name'), + ) if self.pre_install_script: raise DistutilsOptionError( @@ -180,7 +187,7 @@ if not target_version: assert self.skip_build, "Should have already checked this" target_version = sys.version[0:3] - plat_specifier = ".%s-%s" % (get_platform(), target_version) + plat_specifier = ".%s-%s" % (self.plat_name, target_version) build = self.get_finalized_command('build') build.build_lib = os.path.join(build.build_base, 'lib' + plat_specifier) @@ -633,8 +640,7 @@ def get_installer_filename(self, fullname): # Factored out to allow overriding in subclasses - plat = get_platform() - installer_name = os.path.join(self.dist_dir, - "%s.%s-py%s.msi" % - (fullname, plat, self.target_version)) + base_name = "%s.%s-py%s.msi" % (fullname, self.plat_name, + self.target_version) + installer_name = os.path.join(self.dist_dir, base_name) return installer_name Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/command/bdist_rpm.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/command/bdist_rpm.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/command/bdist_rpm.py Wed Apr 30 15:57:13 2008 @@ -6,7 +6,6 @@ __revision__ = "$Id$" import sys, os -import glob from distutils.core import Command from distutils.debug import DEBUG from distutils.util import get_platform Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/command/bdist_wininst.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/command/bdist_wininst.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/command/bdist_wininst.py Wed Apr 30 15:57:13 2008 @@ -19,6 +19,9 @@ user_options = [('bdist-dir=', None, "temporary directory for creating the distribution"), + ('plat-name=', 'p', + "platform name to embed in generated filenames " + "(default: %s)" % get_platform()), ('keep-temp', 'k', "keep the pseudo-installation tree around after " + "creating the distribution archive"), @@ -52,6 +55,7 @@ def initialize_options(self): self.bdist_dir = None + self.plat_name = None self.keep_temp = 0 self.no_target_compile = 0 self.no_target_optimize = 0 @@ -78,7 +82,10 @@ " option must be specified" % (short_version,)) self.target_version = short_version - self.set_undefined_options('bdist', ('dist_dir', 'dist_dir')) + self.set_undefined_options('bdist', + ('dist_dir', 'dist_dir'), + ('plat_name', 'plat_name'), + ) if self.install_script: for script in self.distribution.scripts: @@ -104,6 +111,7 @@ install.root = self.bdist_dir install.skip_build = self.skip_build install.warn_dir = 0 + install.plat_name = self.plat_name install_lib = self.reinitialize_command('install_lib') # we do not want to include pyc or pyo files @@ -121,7 +129,7 @@ if not target_version: assert self.skip_build, "Should have already checked this" target_version = sys.version[0:3] - plat_specifier = ".%s-%s" % (get_platform(), target_version) + plat_specifier = ".%s-%s" % (self.plat_name, target_version) build = self.get_finalized_command('build') build.build_lib = os.path.join(build.build_base, 'lib' + plat_specifier) @@ -267,11 +275,11 @@ # if we create an installer for a specific python version, # it's better to include this in the name installer_name = os.path.join(self.dist_dir, - "%s.win32-py%s.exe" % - (fullname, self.target_version)) + "%s.%s-py%s.exe" % + (fullname, self.plat_name, self.target_version)) else: installer_name = os.path.join(self.dist_dir, - "%s.win32.exe" % fullname) + "%s.%s.exe" % (fullname, self.plat_name)) return installer_name def get_exe_bytes(self): @@ -293,9 +301,9 @@ bv = get_build_version() else: if self.target_version < "2.4": - bv = "6" + bv = 6.0 else: - bv = "7.1" + bv = 7.1 else: # for current version - use authoritative check. bv = get_build_version() @@ -304,5 +312,9 @@ directory = os.path.dirname(__file__) # we must use a wininst-x.y.exe built with the same C compiler # used for python. XXX What about mingw, borland, and so on? - filename = os.path.join(directory, "wininst-%.1f.exe" % bv) + if self.plat_name == 'win32': + sfix = '' + else: + sfix = self.plat_name[3:] # strip 'win' - leaves eg '-amd64' + filename = os.path.join(directory, "wininst-%.1f%s.exe" % (bv, sfix)) return open(filename, "rb").read() Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/command/build.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/command/build.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/command/build.py Wed Apr 30 15:57:13 2008 @@ -6,6 +6,7 @@ import sys, os from distutils.core import Command +from distutils.errors import DistutilsOptionError from distutils.util import get_platform @@ -32,6 +33,9 @@ "build directory for scripts"), ('build-temp=', 't', "temporary build directory"), + ('plat-name=', 'p', + "platform name to build for, if supported " + "(default: %s)" % get_platform()), ('compiler=', 'c', "specify the compiler type"), ('debug', 'g', @@ -59,12 +63,24 @@ self.build_temp = None self.build_scripts = None self.compiler = None + self.plat_name = None self.debug = None self.force = 0 self.executable = None def finalize_options(self): - plat_specifier = ".%s-%s" % (get_platform(), sys.version[0:3]) + if self.plat_name is None: + self.plat_name = get_platform() + else: + # plat-name only supported for windows (other platforms are + # supported via ./configure flags, if at all). Avoid misleading + # other platforms. + if os.name != 'nt': + raise DistutilsOptionError( + "--plat-name only supported on Windows (try " + "using './configure --help' on your platform)") + + plat_specifier = ".%s-%s" % (self.plat_name, sys.version[0:3]) # Make it so Python 2.x and Python 2.x with --with-pydebug don't # share the same build directories. Doing so confuses the build Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/command/build_ext.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/command/build_ext.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/command/build_ext.py Wed Apr 30 15:57:13 2008 @@ -12,6 +12,7 @@ from distutils.sysconfig import customize_compiler, get_python_version from distutils.dep_util import newer_group from distutils.extension import Extension +from distutils.util import get_platform from distutils import log if os.name == 'nt': @@ -57,6 +58,9 @@ "directory for compiled extension modules"), ('build-temp=', 't', "directory for temporary files (build by-products)"), + ('plat-name=', 'p', + "platform name to cross-compile for, if supported " + "(default: %s)" % get_platform()), ('inplace', 'i', "ignore build-lib and put compiled extensions into the source " + "directory alongside your pure Python modules"), @@ -98,6 +102,7 @@ def initialize_options(self): self.extensions = None self.build_lib = None + self.plat_name = None self.build_temp = None self.inplace = 0 self.package = None @@ -124,7 +129,9 @@ ('build_temp', 'build_temp'), ('compiler', 'compiler'), ('debug', 'debug'), - ('force', 'force')) + ('force', 'force'), + ('plat_name', 'plat_name'), + ) if self.package is None: self.package = self.distribution.ext_package @@ -167,6 +174,9 @@ # for Release and Debug builds. # also Python's library directory must be appended to library_dirs if os.name == 'nt': + # the 'libs' directory is for binary installs - we assume that + # must be the *native* platform. But we don't really support + # cross-compiling via a binary install anyway, so we let it go. self.library_dirs.append(os.path.join(sys.exec_prefix, 'libs')) if self.debug: self.build_temp = os.path.join(self.build_temp, "Debug") @@ -177,14 +187,23 @@ # this allows distutils on windows to work in the source tree self.include_dirs.append(os.path.join(sys.exec_prefix, 'PC')) if MSVC_VERSION == 9: - self.library_dirs.append(os.path.join(sys.exec_prefix, - 'PCBuild9')) + # Use the .lib files for the correct architecture + if self.plat_name == 'win32': + suffix = '' + else: + # win-amd64 or win-ia64 + suffix = self.plat_name[4:] + new_lib = os.path.join(sys.exec_prefix, 'PCbuild') + if suffix: + new_lib = os.path.join(new_lib, suffix) + self.library_dirs.append(new_lib) + elif MSVC_VERSION == 8: self.library_dirs.append(os.path.join(sys.exec_prefix, - 'PCBuild8', 'win32release')) + 'PC', 'VS8.0', 'win32release')) else: self.library_dirs.append(os.path.join(sys.exec_prefix, - 'PCBuild')) + 'PC', 'VS7.1')) # OS/2 (EMX) doesn't support Debug vs Release builds, but has the # import libraries in its "Config" subdirectory @@ -267,6 +286,11 @@ dry_run=self.dry_run, force=self.force) customize_compiler(self.compiler) + # If we are cross-compiling, init the compiler now (if we are not + # cross-compiling, init would not hurt, but people may rely on + # late initialization of compiler even if they shouldn't...) + if os.name == 'nt' and self.plat_name != get_platform(): + self.compiler.initialize(self.plat_name) # And make sure that any compile/link-related options (which might # come from the command-line or from the setup script) are set in Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/command/build_py.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/command/build_py.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/command/build_py.py Wed Apr 30 15:57:13 2008 @@ -383,3 +383,38 @@ if self.optimize > 0: byte_compile(files, optimize=self.optimize, force=self.force, prefix=prefix, dry_run=self.dry_run) + +class build_py_2to3(build_py): + def run(self): + self.updated_files = [] + + # Base class code + if self.py_modules: + self.build_modules() + if self.packages: + self.build_packages() + self.build_package_data() + + # 2to3 + from lib2to3.refactor import RefactoringTool + class Options: + pass + o = Options() + o.doctests_only = False + o.fix = [] + o.list_fixes = [] + o.print_function = False + o.verbose = False + o.write = True + r = RefactoringTool(o) + r.refactor_args(self.updated_files) + + # Remaining base class code + self.byte_compile(self.get_outputs(include_bytecode=0)) + + def build_module(self, module, module_file, package): + res = build_py.build_module(self, module, module_file, package) + if res[1]: + # file was copied + self.updated_files.append(res[0]) + return res Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/command/build_scripts.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/command/build_scripts.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/command/build_scripts.py Wed Apr 30 15:57:13 2008 @@ -4,7 +4,7 @@ __revision__ = "$Id$" -import sys, os, re +import os, re from stat import ST_MODE from distutils import sysconfig from distutils.core import Command Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/command/install.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/command/install.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/command/install.py Wed Apr 30 15:57:13 2008 @@ -13,8 +13,8 @@ from distutils.errors import DistutilsPlatformError from distutils.file_util import write_file from distutils.util import convert_path, subst_vars, change_root +from distutils.util import get_platform from distutils.errors import DistutilsOptionError -from glob import glob if sys.version < "2.2": WINDOWS_SCHEME = { @@ -486,6 +486,14 @@ # Obviously have to build before we can install if not self.skip_build: self.run_command('build') + # If we built for any other platform, we can't install. + build_plat = self.distribution.get_command_obj('build').plat_name + # check warn_dir - it is a clue that the 'install' is happening + # internally, and not to sys.path, so we don't check the platform + # matches what we are running. + if self.warn_dir and build_plat != get_platform(): + raise DistutilsPlatformError("Can't install when " + "cross-compiling") # Run all sub-commands (at least those that need to be run) for cmd_name in self.get_sub_commands(): Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/command/install_headers.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/command/install_headers.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/command/install_headers.py Wed Apr 30 15:57:13 2008 @@ -5,7 +5,6 @@ __revision__ = "$Id$" -import os from distutils.core import Command Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/command/register.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/command/register.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/command/register.py Wed Apr 30 15:57:13 2008 @@ -7,7 +7,7 @@ __revision__ = "$Id$" -import sys, os, urllib2, getpass, urlparse +import os, string, urllib2, getpass, urlparse import io, ConfigParser from distutils.core import Command Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/command/sdist.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/command/sdist.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/command/sdist.py Wed Apr 30 15:57:13 2008 @@ -325,14 +325,14 @@ * the build tree (typically "build") * the release tree itself (only an issue if we ran "sdist" previously with --keep-temp, or it aborted) - * any RCS, CVS and .svn directories + * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories """ build = self.get_finalized_command('build') base_dir = self.distribution.get_fullname() self.filelist.exclude_pattern(None, prefix=build.build_base) self.filelist.exclude_pattern(None, prefix=base_dir) - self.filelist.exclude_pattern(r'/(RCS|CVS|\.svn)/.*', is_regex=1) + self.filelist.exclude_pattern(r'(^|/)(RCS|CVS|\.svn|\.hg|\.git|\.bzr|_darcs)/.*', is_regex=1) def write_manifest(self): """Write the file list in 'self.filelist' (presumably as filled in @@ -357,6 +357,7 @@ if line[-1] == '\n': line = line[0:-1] self.filelist.append(line) + manifest.close() def make_release_tree(self, base_dir, files): """Create the directory tree that will become the source Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/core.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/core.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/core.py Wed Apr 30 15:57:13 2008 @@ -207,7 +207,7 @@ _setup_stop_after = stop_after save_argv = sys.argv - g = {} + g = {'__file__': script_name} l = {} try: try: Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/filelist.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/filelist.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/filelist.py Wed Apr 30 15:57:13 2008 @@ -8,7 +8,6 @@ import os, re import fnmatch -from glob import glob from distutils.util import convert_path from distutils.errors import DistutilsTemplateError, DistutilsInternalError from distutils import log Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/msvc9compiler.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/msvc9compiler.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/msvc9compiler.py Wed Apr 30 15:57:13 2008 @@ -22,6 +22,7 @@ from distutils.ccompiler import (CCompiler, gen_preprocess_options, gen_lib_options) from distutils import log +from distutils.util import get_platform import _winreg @@ -38,13 +39,15 @@ VS_BASE = r"Software\Microsoft\VisualStudio\%0.1f" WINSDK_BASE = r"Software\Microsoft\Microsoft SDKs\Windows" NET_BASE = r"Software\Microsoft\.NETFramework" -ARCHS = {'DEFAULT' : 'x86', - 'intel' : 'x86', 'x86' : 'x86', - 'amd64' : 'x64', 'x64' : 'x64', - 'itanium' : 'ia64', 'ia64' : 'ia64', - } -# The globals VERSION, ARCH, MACROS and VC_ENV are defined later +# A map keyed by get_platform() return values to values accepted by +# 'vcvarsall.bat'. Note a cross-compile may combine these (eg, 'x86_amd64' is +# the param to cross-compile on x86 targetting amd64.) +PLAT_TO_VCVARS = { + 'win32' : 'x86', + 'win-amd64' : 'amd64', + 'win-ia64' : 'ia64', +} class Reg: """Helper class to read values from the registry @@ -176,23 +179,6 @@ # else we don't know what version of the compiler this is return None -def get_build_architecture(): - """Return the processor architecture. - - Possible results are "x86" or "amd64". - """ - prefix = " bit (" - i = sys.version.find(prefix) - if i == -1: - return "x86" - j = sys.version.find(")", i) - sysarch = sys.version[i+len(prefix):j].lower() - arch = ARCHS.get(sysarch, None) - if arch is None: - return ARCHS['DEFAULT'] - else: - return arch - def normalize_and_reduce_paths(paths): """Return a list of normalized paths with duplicates removed. @@ -251,6 +237,7 @@ if vcvarsall is None: raise IOError("Unable to find vcvarsall.bat") + log.debug("Calling 'vcvarsall.bat %s' (version=%s)", arch, version) popen = subprocess.Popen('"%s" %s & set' % (vcvarsall, arch), stdout=subprocess.PIPE, stderr=subprocess.PIPE) @@ -281,9 +268,7 @@ VERSION = get_build_version() if VERSION < 8.0: raise DistutilsPlatformError("VC %0.1f is not supported by this module" % VERSION) -ARCH = get_build_architecture() # MACROS = MacroExpander(VERSION) -VC_ENV = query_vcvarsall(VERSION, ARCH) class MSVCCompiler(CCompiler) : """Concrete class that implements an interface to Microsoft Visual C++, @@ -318,13 +303,25 @@ def __init__(self, verbose=0, dry_run=0, force=0): CCompiler.__init__ (self, verbose, dry_run, force) self.__version = VERSION - self.__arch = ARCH self.__root = r"Software\Microsoft\VisualStudio" # self.__macros = MACROS self.__path = [] + # target platform (.plat_name is consistent with 'bdist') + self.plat_name = None + self.__arch = None # deprecated name self.initialized = False - def initialize(self): + def initialize(self, plat_name=None): + # multi-init means we would need to check platform same each time... + assert not self.initialized, "don't init multiple times" + if plat_name is None: + plat_name = get_platform() + # sanity check for platforms to prevent obscure errors later. + ok_plats = 'win32', 'win-amd64', 'win-ia64' + if plat_name not in ok_plats: + raise DistutilsPlatformError("--plat-name must be one of %s" % + (ok_plats,)) + if "DISTUTILS_USE_SDK" in os.environ and "MSSdk" in os.environ and self.find_exe("cl.exe"): # Assume that the SDK set up everything alright; don't try to be # smarter @@ -334,9 +331,24 @@ self.rc = "rc.exe" self.mc = "mc.exe" else: - self.__paths = VC_ENV['path'].split(os.pathsep) - os.environ['lib'] = VC_ENV['lib'] - os.environ['include'] = VC_ENV['include'] + # On x86, 'vcvars32.bat amd64' creates an env that doesn't work; + # to cross compile, you use 'x86_amd64'. + # On AMD64, 'vcvars32.bat amd64' is a native build env; to cross + # compile use 'x86' (ie, it runs the x86 compiler directly) + # No idea how itanium handles this, if at all. + if plat_name == get_platform() or plat_name == 'win32': + # native build or cross-compile to win32 + plat_spec = PLAT_TO_VCVARS[plat_name] + else: + # cross compile from win32 -> some 64bit + plat_spec = PLAT_TO_VCVARS[get_platform()] + '_' + \ + PLAT_TO_VCVARS[plat_name] + + vc_env = query_vcvarsall(VERSION, plat_spec) + + self.__paths = vc_env['path'].split(os.pathsep) + os.environ['lib'] = vc_env['lib'] + os.environ['include'] = vc_env['include'] if len(self.__paths) == 0: raise DistutilsPlatformError("Python was built with %s, " Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/msvccompiler.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/msvccompiler.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/msvccompiler.py Wed Apr 30 15:57:13 2008 @@ -638,5 +638,5 @@ log.debug("Importing new compiler from distutils.msvc9compiler") OldMSVCCompiler = MSVCCompiler from distutils.msvc9compiler import MSVCCompiler - from distutils.msvc9compiler import get_build_architecture + # get_build_architecture not really relevant now we support cross-compile from distutils.msvc9compiler import MacroExpander Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/sysconfig.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/sysconfig.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/sysconfig.py Wed Apr 30 15:57:13 2008 @@ -23,7 +23,8 @@ EXEC_PREFIX = os.path.normpath(sys.exec_prefix) # Path to the base directory of the project. On Windows the binary may -# live in project/PCBuild9 +# live in project/PCBuild9. If we're dealing with an x64 Windows build, +# it'll live in project/PCbuild/amd64. project_base = os.path.dirname(os.path.abspath(sys.executable)) if os.name == "nt" and "pcbuild" in project_base[-8:].lower(): project_base = os.path.abspath(os.path.join(project_base, os.path.pardir)) @@ -31,14 +32,22 @@ if os.name == "nt" and "\\pc\\v" in project_base[-10:].lower(): project_base = os.path.abspath(os.path.join(project_base, os.path.pardir, os.path.pardir)) +# PC/AMD64 +if os.name == "nt" and "\\pcbuild\\amd64" in project_base[-14:].lower(): + project_base = os.path.abspath(os.path.join(project_base, os.path.pardir, + os.path.pardir)) # python_build: (Boolean) if true, we're either building Python or # building an extension with an un-installed Python, so we use # different (hard-wired) directories. # Setup.local is available for Makefile builds including VPATH builds, # Setup.dist is available on Windows -python_build = any(os.path.isfile(os.path.join(project_base, "Modules", fn)) - for fn in ("Setup.dist", "Setup.local")) +def _python_build(): + for fn in ("Setup.dist", "Setup.local"): + if os.path.isfile(os.path.join(project_base, "Modules", fn)): + return True + return False +python_build = _python_build() def get_python_version(): """Return a string containing the major and minor Python version, Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/tests/test_dist.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/tests/test_dist.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/tests/test_dist.py Wed Apr 30 15:57:13 2008 @@ -3,10 +3,8 @@ import distutils.cmd import distutils.dist import os -import shutil import io import sys -import tempfile import unittest from test.test_support import TESTFN Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/tests/test_sysconfig.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/tests/test_sysconfig.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/tests/test_sysconfig.py Wed Apr 30 15:57:13 2008 @@ -2,7 +2,6 @@ from distutils import sysconfig import os -import sys import unittest from test.test_support import TESTFN @@ -20,7 +19,27 @@ # test for pythonxx.lib? def test_get_python_inc(self): - inc_dir = sysconfig.get_python_inc() + # The check for srcdir is copied from Python's setup.py, + # and is necessary to make this test pass when building + # Python in a directory other than the source directory. + (srcdir,) = sysconfig.get_config_vars('srcdir') + if not srcdir: + inc_dir = sysconfig.get_python_inc() + else: + # This test is not really a proper test: when building + # Python from source, even in the same directory, + # we won't be testing the same thing as when running + # distutils' tests on an installed Python. Nevertheless, + # let's try to do our best: if we are running Python's + # unittests from a build directory that is not the source + # directory, the normal inc_dir will exist, it will just not + # contain anything of interest. + inc_dir = sysconfig.get_python_inc() + self.assert_(os.path.isdir(inc_dir)) + # Now test the source location, to make sure Python.h does + # exist. + inc_dir = os.path.join(os.getcwd(), srcdir, 'Include') + inc_dir = os.path.normpath(inc_dir) self.assert_(os.path.isdir(inc_dir), inc_dir) python_h = os.path.join(inc_dir, "Python.h") self.assert_(os.path.isfile(python_h), python_h) Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/unixccompiler.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/unixccompiler.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/unixccompiler.py Wed Apr 30 15:57:13 2008 @@ -16,7 +16,6 @@ __revision__ = "$Id$" import os, sys -from copy import copy from distutils import sysconfig from distutils.dep_util import newer Modified: python/branches/py3k-ctypes-pep3118/Lib/distutils/util.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/distutils/util.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/distutils/util.py Wed Apr 30 15:57:13 2008 @@ -30,7 +30,7 @@ irix64-6.2 Windows will return one of: - win-x86_64 (64bit Windows on x86_64 (AMD64)) + win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc) win-ia64 (64bit Windows on Itanium) win32 (all others - specifically, sys.platform is returned) @@ -45,7 +45,7 @@ j = sys.version.find(")", i) look = sys.version[i+len(prefix):j].lower() if look == 'amd64': - return 'win-x86_64' + return 'win-amd64' if look == 'itanium': return 'win-ia64' return sys.platform Modified: python/branches/py3k-ctypes-pep3118/Lib/dumbdbm.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/dumbdbm.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/dumbdbm.py Wed Apr 30 15:57:13 2008 @@ -23,13 +23,13 @@ import io as _io import os as _os -import UserDict +import collections _BLOCKSIZE = 512 error = IOError # For anydbm -class _Database(UserDict.DictMixin): +class _Database(collections.MutableMapping): # The on-disk directory and data files can remain in mutually # inconsistent states for an arbitrarily long time (see comments Modified: python/branches/py3k-ctypes-pep3118/Lib/email/base64mime.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/email/base64mime.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/email/base64mime.py Wed Apr 30 15:57:13 2008 @@ -35,7 +35,6 @@ 'header_length', ] -import re from base64 import b64encode from binascii import b2a_base64, a2b_base64 Modified: python/branches/py3k-ctypes-pep3118/Lib/filecmp.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/filecmp.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/filecmp.py Wed Apr 30 15:57:13 2008 @@ -12,7 +12,7 @@ import os import stat import warnings -from itertools import ifilter, ifilterfalse, imap, izip +from itertools import filterfalse __all__ = ["cmp","dircmp","cmpfiles"] @@ -130,11 +130,11 @@ self.right_list.sort() def phase1(self): # Compute common names - a = dict(izip(imap(os.path.normcase, self.left_list), self.left_list)) - b = dict(izip(imap(os.path.normcase, self.right_list), self.right_list)) - self.common = list(map(a.__getitem__, ifilter(b.__contains__, a))) - self.left_only = list(map(a.__getitem__, ifilterfalse(b.__contains__, a))) - self.right_only = list(map(b.__getitem__, ifilterfalse(a.__contains__, b))) + a = dict(zip(map(os.path.normcase, self.left_list), self.left_list)) + b = dict(zip(map(os.path.normcase, self.right_list), self.right_list)) + self.common = list(map(a.__getitem__, filter(b.__contains__, a))) + self.left_only = list(map(a.__getitem__, filterfalse(b.__contains__, a))) + self.right_only = list(map(b.__getitem__, filterfalse(a.__contains__, b))) def phase2(self): # Distinguish files, directories, funnies self.common_dirs = [] @@ -276,7 +276,7 @@ # Return a copy with items that occur in skip removed. # def _filter(flist, skip): - return list(ifilterfalse(skip.__contains__, flist)) + return list(filterfalse(skip.__contains__, flist)) # Demonstration and testing. Modified: python/branches/py3k-ctypes-pep3118/Lib/ftplib.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/ftplib.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/ftplib.py Wed Apr 30 15:57:13 2008 @@ -65,7 +65,7 @@ # All exceptions (hopefully) that may be raised here and that aren't # (always) programming errors on our side -all_errors = (Error, socket.error, IOError, EOFError) +all_errors = (Error, IOError, EOFError) # Line terminators (we always output CRLF, but accept any of CRLF, CR, LF) Modified: python/branches/py3k-ctypes-pep3118/Lib/glob.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/glob.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/glob.py Wed Apr 30 15:57:13 2008 @@ -57,7 +57,7 @@ except os.error: return [] if pattern[0] != '.': - names = filter(lambda x: x[0] != '.', names) + names = [x for x in names if x[0] != '.'] return fnmatch.filter(names, pattern) def glob0(dirname, basename): Modified: python/branches/py3k-ctypes-pep3118/Lib/gzip.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/gzip.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/gzip.py Wed Apr 30 15:57:13 2008 @@ -17,7 +17,6 @@ def U32(i): """Return i as an unsigned integer, assuming it fits in 32 bits. - If it's >= 2GB when viewed as a 32-bit unsigned int, return a long. """ if i < 0: @@ -25,19 +24,16 @@ return i def LOWU32(i): - """Return the low-order 32 bits of an int, as a non-negative int.""" + """Return the low-order 32 bits, as a non-negative int""" return i & 0xFFFFFFFF -def write32(output, value): - output.write(struct.pack(" 0: self.size = self.size + len(data) - self.crc = zlib.crc32(data, self.crc) + self.crc = zlib.crc32(data, self.crc) & 0xffffffff self.fileobj.write( self.compress.compress(data) ) self.offset += len(data) @@ -306,7 +302,7 @@ self._new_member = True def _add_read_data(self, data): - self.crc = zlib.crc32(data, self.crc) + self.crc = zlib.crc32(data, self.crc) & 0xffffffff self.extrabuf = self.extrabuf + data self.extrasize = self.extrasize + len(data) self.size = self.size + len(data) @@ -319,24 +315,19 @@ # stored is the true file size mod 2**32. self.fileobj.seek(-8, 1) crc32 = read32(self.fileobj) - isize = U32(read32(self.fileobj)) # may exceed 2GB - if U32(crc32) != U32(self.crc): - raise IOError("CRC check failed") - elif isize != LOWU32(self.size): + isize = read32(self.fileobj) # may exceed 2GB + if crc32 != self.crc: + raise IOError("CRC check failed %s != %s" % (hex(crc32), + hex(self.crc))) + elif isize != (self.size & 0xffffffff): raise IOError("Incorrect length of data produced") def close(self): if self.mode == WRITE: self.fileobj.write(self.compress.flush()) - # The native zlib crc is an unsigned 32-bit integer, but - # the Python wrapper implicitly casts that to a signed C - # long. So, on a 32-bit box self.crc may "look negative", - # while the same crc on a 64-bit box may "look positive". - # To avoid irksome warnings from the `struct` module, force - # it to look positive on all boxes. - write32u(self.fileobj, LOWU32(self.crc)) + write32u(self.fileobj, self.crc) # self.size may exceed 2GB, or even 4GB - write32u(self.fileobj, LOWU32(self.size)) + write32u(self.fileobj, self.size & 0xffffffff) self.fileobj = None elif self.mode == READ: self.fileobj = None Modified: python/branches/py3k-ctypes-pep3118/Lib/hashlib.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/hashlib.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/hashlib.py Wed Apr 30 15:57:13 2008 @@ -18,6 +18,9 @@ More algorithms may be available on your platform but the above are guaranteed to exist. +NOTE: If you want the adler32 or crc32 hash functions they are available in +the zlib module. + Choose your hash function wisely. Some have known collision weaknesses. sha384 and sha512 will be slow on 32 bit platforms. Modified: python/branches/py3k-ctypes-pep3118/Lib/heapq.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/heapq.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/heapq.py Wed Apr 30 15:57:13 2008 @@ -127,9 +127,9 @@ """ __all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'merge', - 'nlargest', 'nsmallest'] + 'nlargest', 'nsmallest', 'heappushpop'] -from itertools import islice, repeat, count, izip, tee +from itertools import islice, repeat, count, tee from operator import itemgetter, neg import bisect @@ -165,6 +165,13 @@ _siftup(heap, 0) return returnitem +def heappushpop(heap, item): + """Fast version of a heappush followed by a heappop.""" + if heap and item > heap[0]: + item, heap[0] = heap[0], item + _siftup(heap, 0) + return item + def heapify(x): """Transform list into a heap, in-place, in O(len(heap)) time.""" n = len(x) @@ -186,13 +193,9 @@ if not result: return result heapify(result) - _heapreplace = heapreplace - sol = result[0] # sol --> smallest of the nlargest + _heappushpop = heappushpop for elem in it: - if elem <= sol: - continue - _heapreplace(result, elem) - sol = result[0] + heappushpop(result, elem) result.sort(reverse=True) return result @@ -304,7 +307,7 @@ # If available, use C implementation try: - from _heapq import heappush, heappop, heapify, heapreplace, nlargest, nsmallest + from _heapq import heappush, heappop, heapify, heapreplace, nlargest, nsmallest, heappushpop except ImportError: pass @@ -352,7 +355,7 @@ """ in1, in2 = tee(iterable) keys = in1 if key is None else map(key, in1) - it = izip(keys, count(), in2) # decorate + it = zip(keys, count(), in2) # decorate result = _nsmallest(n, it) return list(map(itemgetter(2), result)) # undecorate @@ -364,7 +367,7 @@ """ in1, in2 = tee(iterable) keys = in1 if key is None else map(key, in1) - it = izip(keys, map(neg, count()), in2) # decorate + it = zip(keys, map(neg, count()), in2) # decorate result = _nlargest(n, it) return list(map(itemgetter(2), result)) # undecorate Modified: python/branches/py3k-ctypes-pep3118/Lib/hmac.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/hmac.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/hmac.py Wed Apr 30 15:57:13 2008 @@ -39,7 +39,8 @@ if key is _secret_backdoor_key: # cheap return - assert isinstance(key, bytes), repr(key) + if not isinstance(key, bytes): + raise TypeError("expected bytes, but got %r" % type(key).__name__) if digestmod is None: import hashlib @@ -84,7 +85,8 @@ def update(self, msg): """Update this hashing object with the string msg. """ - assert isinstance(msg, bytes), repr(msg) + if not isinstance(msg, bytes): + raise TypeError("expected bytes, but got %r" % type(msg).__name__) self.inner.update(msg) def copy(self): Modified: python/branches/py3k-ctypes-pep3118/Lib/httplib.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/httplib.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/httplib.py Wed Apr 30 15:57:13 2008 @@ -66,7 +66,6 @@ Req-sent-unread-response _CS_REQ_SENT """ -import errno import io import mimetools import socket @@ -449,7 +448,12 @@ try: self.length = int(length) except ValueError: - pass + self.length = None + else: + if self.length < 0: # ignore nonsensical negative lengths + self.length = None + else: + self.length = None # does the body have a fixed length? (of zero) if (status == NO_CONTENT or status == NOT_MODIFIED or @@ -560,17 +564,23 @@ def _read_chunked(self, amt): assert self.chunked != _UNKNOWN chunk_left = self.chunk_left - value = "" + value = b"" # XXX This accumulates chunks by repeated string concatenation, # which is not efficient as the number or size of chunks gets big. while True: if chunk_left is None: line = self.fp.readline() - i = line.find(";") + i = line.find(b";") if i >= 0: line = line[:i] # strip chunk-extensions - chunk_left = int(line, 16) + try: + chunk_left = int(line, 16) + except ValueError: + # close the connection as protocol synchronisation is + # probably lost + self.close() + raise IncompleteRead(value) if chunk_left == 0: break if amt is None: @@ -596,6 +606,10 @@ ### note: we shouldn't have any trailers! while True: line = self.fp.readline() + if not line: + # a vanishingly small number of sites EOF without + # sending the trailer + break if line == b"\r\n": break Modified: python/branches/py3k-ctypes-pep3118/Lib/idlelib/AutoComplete.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/idlelib/AutoComplete.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/idlelib/AutoComplete.py Wed Apr 30 15:57:13 2008 @@ -35,10 +35,9 @@ "popupwait", type="int", default=0) def __init__(self, editwin=None): - if editwin == None: # subprocess and test - self.editwin = None - return self.editwin = editwin + if editwin is None: # subprocess and test + return self.text = editwin.text self.autocompletewindow = None Modified: python/branches/py3k-ctypes-pep3118/Lib/idlelib/EditorWindow.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/idlelib/EditorWindow.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/idlelib/EditorWindow.py Wed Apr 30 15:57:13 2008 @@ -109,16 +109,6 @@ self.width = idleConf.GetOption('main','EditorWindow','width') self.text = text = MultiCallCreator(Text)( text_frame, name='text', padx=5, wrap='none', - foreground=idleConf.GetHighlight(currentTheme, - 'normal',fgBg='fg'), - background=idleConf.GetHighlight(currentTheme, - 'normal',fgBg='bg'), - highlightcolor=idleConf.GetHighlight(currentTheme, - 'hilite',fgBg='fg'), - highlightbackground=idleConf.GetHighlight(currentTheme, - 'hilite',fgBg='bg'), - insertbackground=idleConf.GetHighlight(currentTheme, - 'cursor',fgBg='fg'), width=self.width, height=idleConf.GetOption('main','EditorWindow','height') ) self.top.focused_widget = self.text @@ -225,7 +215,6 @@ # Making the initial values larger slows things down more often. self.num_context_lines = 50, 500, 5000000 self.per = per = self.Percolator(text) - self.color = None self.undo = undo = self.UndoDelegator() per.insertfilter(undo) text.undo_block_start = undo.undo_block_start @@ -236,6 +225,7 @@ io.set_filename_change_hook(self.filename_change_hook) self.good_load = False self.set_indentation_params(False) + self.color = None # initialized below in self.ResetColorizer if filename: if os.path.exists(filename) and not os.path.isdir(filename): if io.loadfile(filename): @@ -247,6 +237,7 @@ per.insertfilter(color) else: io.set_filename(filename) + self.ResetColorizer() self.saved_change_hook() self.update_recent_files_list() self.load_extensions() @@ -561,36 +552,42 @@ self.flist.filename_changed_edit(self) self.saved_change_hook() self.top.update_windowlist_registry(self) - if self.ispythonsource(self.io.filename): - self.addcolorizer() - else: - self.rmcolorizer() + self.ResetColorizer() - def addcolorizer(self): + def _addcolorizer(self): if self.color: return - self.per.removefilter(self.undo) - self.color = self.ColorDelegator() - self.per.insertfilter(self.color) - self.per.insertfilter(self.undo) + if self.ispythonsource(self.io.filename): + self.color = self.ColorDelegator() + # can add more colorizers here... + if self.color: + self.per.removefilter(self.undo) + self.per.insertfilter(self.color) + self.per.insertfilter(self.undo) - def rmcolorizer(self): + def _rmcolorizer(self): if not self.color: return self.color.removecolors() - self.per.removefilter(self.undo) self.per.removefilter(self.color) self.color = None - self.per.insertfilter(self.undo) def ResetColorizer(self): - "Update the colour theme if it is changed" - # Called from configDialog.py - if self.color: - self.color = self.ColorDelegator() - self.per.insertfilter(self.color) + "Update the colour theme" + # Called from self.filename_change_hook and from configDialog.py + self._rmcolorizer() + self._addcolorizer() theme = idleConf.GetOption('main','Theme','name') - self.text.config(idleConf.GetHighlight(theme, "normal")) + normal_colors = idleConf.GetHighlight(theme, 'normal') + cursor_color = idleConf.GetHighlight(theme, 'cursor', fgBg='fg') + select_colors = idleConf.GetHighlight(theme, 'hilite') + self.text.config( + foreground=normal_colors['foreground'], + background=normal_colors['background'], + insertbackground=cursor_color, + selectforeground=select_colors['foreground'], + selectbackground=select_colors['background'], + ) IDENTCHARS = string.ascii_letters + string.digits + "_" @@ -1440,7 +1437,9 @@ _tokenize.tabsize = self.tabwidth try: try: - _tokenize.tokenize(self.readline, self.tokeneater) + tokens = _tokenize.generate_tokens(self.readline) + for token in tokens: + self.tokeneater(*token) except _tokenize.TokenError: # since we cut off the tokenizer early, we can trigger # spurious errors Modified: python/branches/py3k-ctypes-pep3118/Lib/idlelib/MultiCall.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/idlelib/MultiCall.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/idlelib/MultiCall.py Wed Apr 30 15:57:13 2008 @@ -30,7 +30,6 @@ """ import sys -import os import re import Tkinter @@ -125,7 +124,7 @@ statelist = [] for state in states: substates = list(set(state & x for x in states)) - substates.sort(lambda a,b: nbits(b) - nbits(a)) + substates.sort(key=nbits, reverse=True) statelist.append(substates) return statelist Modified: python/branches/py3k-ctypes-pep3118/Lib/idlelib/NEWS.txt ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/idlelib/NEWS.txt (original) +++ python/branches/py3k-ctypes-pep3118/Lib/idlelib/NEWS.txt Wed Apr 30 15:57:13 2008 @@ -1,7 +1,7 @@ What's New in IDLE 3.0a3? ========================= -*Release date: XX-XXX-2008* +*Release date: 29-Feb-2008* - help() was not paging to the shell. Issue1650. @@ -45,6 +45,12 @@ *Release date: XX-XXX-200X* UNRELEASED, but merged into 3.0 +- Configured selection highlighting colors were ignored; updating highlighting + in the config dialog would cause non-Python files to be colored as if they + were Python source; improve use of ColorDelagator. Patch 1334. Tal Einat. + +- ScriptBinding event handlers weren't returning 'break'. Patch 2050, Tal Einat. + - There was an error on exit if no sys.exitfunc was defined. Issue 1647. - Could not open files in .idlerc directory if latter was hidden on Windows. @@ -70,6 +76,13 @@ - Clean up EditorWindow close. +- Patch 1693258: Fix for duplicate "preferences" menu-OS X. Backport of r56204. + +- OSX: Avoid crash for those versions of Tcl/Tk which don't have a console + +- Bug in idlelib.MultiCall: Options dialog was crashing IDLE if there was an + option in config-extensions w/o a value. Patch #1672481, Tal Einat + - Corrected some bugs in AutoComplete. Also, Page Up/Down in ACW implemented; mouse and cursor selection in ACWindow implemented; double Tab inserts current selection and closes ACW (similar to double-click and Return); scroll Modified: python/branches/py3k-ctypes-pep3118/Lib/idlelib/PyShell.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/idlelib/PyShell.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/idlelib/PyShell.py Wed Apr 30 15:57:13 2008 @@ -922,7 +922,7 @@ "The program is still running!\n Do you want to kill it?", default="ok", parent=self.text) - if response == False: + if response is False: return "cancel" if self.reading: self.top.quit() Modified: python/branches/py3k-ctypes-pep3118/Lib/idlelib/RemoteDebugger.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/idlelib/RemoteDebugger.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/idlelib/RemoteDebugger.py Wed Apr 30 15:57:13 2008 @@ -20,7 +20,6 @@ """ -import sys import types from idlelib import rpc from idlelib import Debugger Modified: python/branches/py3k-ctypes-pep3118/Lib/idlelib/ScriptBinding.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/idlelib/ScriptBinding.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/idlelib/ScriptBinding.py Wed Apr 30 15:57:13 2008 @@ -55,11 +55,11 @@ def check_module_event(self, event): filename = self.getfilename() if not filename: - return + return 'break' if not self.checksyntax(filename): - return + return 'break' if not self.tabnanny(filename): - return + return 'break' def tabnanny(self, filename): f = open(filename, 'r') @@ -120,12 +120,12 @@ """ filename = self.getfilename() if not filename: - return + return 'break' code = self.checksyntax(filename) if not code: - return + return 'break' if not self.tabnanny(filename): - return + return 'break' shell = self.shell interp = shell.interp if PyShell.use_subprocess: @@ -148,6 +148,7 @@ # go to __stderr__. With subprocess, they go to the shell. # Need to change streams in PyShell.ModifiedInterpreter. interp.runcode(code) + return 'break' def getfilename(self): """Get source filename. If not saved, offer to save (or create) file Modified: python/branches/py3k-ctypes-pep3118/Lib/idlelib/TreeWidget.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/idlelib/TreeWidget.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/idlelib/TreeWidget.py Wed Apr 30 15:57:13 2008 @@ -15,7 +15,6 @@ # - optimize tree redraw after expand of subnode import os -import sys from Tkinter import * import imp @@ -398,7 +397,7 @@ names = os.listdir(self.path) except os.error: return [] - names.sort(lambda a, b: cmp(os.path.normcase(a), os.path.normcase(b))) + names.sort(key = os.path.normcase) sublist = [] for name in names: item = FileTreeItem(os.path.join(self.path, name)) Modified: python/branches/py3k-ctypes-pep3118/Lib/idlelib/UndoDelegator.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/idlelib/UndoDelegator.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/idlelib/UndoDelegator.py Wed Apr 30 15:57:13 2008 @@ -1,4 +1,3 @@ -import sys import string from Tkinter import * Modified: python/branches/py3k-ctypes-pep3118/Lib/idlelib/configDialog.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/idlelib/configDialog.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/idlelib/configDialog.py Wed Apr 30 15:57:13 2008 @@ -980,16 +980,11 @@ self.SetThemeType() ##load theme element option menu themeNames = list(self.themeElements.keys()) - themeNames.sort(self.__ThemeNameIndexCompare) + themeNames.sort(key=lambda x: self.themeElements[x][1]) self.optMenuHighlightTarget.SetMenu(themeNames,themeNames[0]) self.PaintThemeSample() self.SetHighlightTarget() - def __ThemeNameIndexCompare(self,a,b): - if self.themeElements[a][1] int(h2[2]): - return 1 - else: - return 0 - def GetAllExtraHelpSourcesList(self): """ Returns a list of tuples containing the details of all additional help Modified: python/branches/py3k-ctypes-pep3118/Lib/idlelib/idlever.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/idlelib/idlever.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/idlelib/idlever.py Wed Apr 30 15:57:13 2008 @@ -1 +1 @@ -IDLE_VERSION = "3.0a2" +IDLE_VERSION = "3.0a4" Modified: python/branches/py3k-ctypes-pep3118/Lib/idlelib/keybindingDialog.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/idlelib/keybindingDialog.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/idlelib/keybindingDialog.py Wed Apr 30 15:57:13 2008 @@ -3,7 +3,7 @@ """ from Tkinter import * import tkMessageBox -import string, os +import string class GetKeysDialog(Toplevel): def __init__(self,parent,title,action,currentKeySequences): Modified: python/branches/py3k-ctypes-pep3118/Lib/idlelib/run.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/idlelib/run.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/idlelib/run.py Wed Apr 30 15:57:13 2008 @@ -1,5 +1,4 @@ import sys -import os import linecache import time import socket Modified: python/branches/py3k-ctypes-pep3118/Lib/imaplib.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/imaplib.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/imaplib.py Wed Apr 30 15:57:13 2008 @@ -1145,9 +1145,10 @@ """ self.host = host self.port = port - self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.sock.connect((host, port)) - self.sslobj = ssl.wrap_socket(self.sock, self.keyfile, self.certfile) + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect((host, port)) + self.sock = ssl.wrap_socket(sock, self.keyfile, self.certfile) + self.file = self.sock.makefile('rb') def read(self, size): @@ -1156,11 +1157,11 @@ chunks = [] read = 0 while read < size: - data = self.sslobj.read(size-read) + data = self.sslobj.read(min(size-read, 16384)) read += len(data) chunks.append(data) - return ''.join(chunks) + return b''.join(chunks) def readline(self): @@ -1169,7 +1170,7 @@ while 1: char = self.sslobj.read(1) line.append(char) - if char == "\n": return ''.join(line) + if char == b"\n": return b''.join(line) def send(self, data): @@ -1201,7 +1202,7 @@ ssl = ssl.wrap_socket(.socket) """ - return self.sslobj + return self.sock __all__.append("IMAP4_SSL") Modified: python/branches/py3k-ctypes-pep3118/Lib/inspect.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/inspect.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/inspect.py Wed Apr 30 15:57:13 2008 @@ -7,8 +7,9 @@ Here are some of the useful functions provided by this module: - ismodule(), isclass(), ismethod(), isfunction(), istraceback(), - isframe(), iscode(), isbuiltin(), isroutine() - check object types + ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(), + isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(), + isroutine() - check object types getmembers() - get members of an object that satisfy a given condition getfile(), getsourcefile(), getsource() - find an object's source code @@ -29,9 +30,24 @@ __author__ = 'Ka-Ping Yee ' __date__ = '1 Jan 2001' -import sys, os, types, re, dis, imp, tokenize, linecache +import sys +import os +import types +import string +import re +import dis +import imp +import tokenize +import linecache +from abc import ABCMeta from operator import attrgetter from collections import namedtuple +# These constants are from Include/code.h. +CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 0x1, 0x2, 0x4, 0x8 +CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40 + +# See Include/object.h +TPFLAGS_IS_ABSTRACT = 1 << 20 # ----------------------------------------------------------- type-checking def ismodule(object): @@ -137,6 +153,33 @@ __kwdefaults__ dict of keyword only parameters with defaults""" return isinstance(object, types.FunctionType) +def isgeneratorfunction(object): + """Return true if the object is a user-defined generator function. + + Generator function objects provides same attributes as functions. + + See isfunction.__doc__ for attributes listing.""" + if (isfunction(object) or ismethod(object)) and \ + object.__code__.co_flags & CO_GENERATOR: + return True + +def isgenerator(object): + """Return true if the object is a generator. + + Generator objects provide these attributes: + __iter__ defined to support interation over container + close raises a new GeneratorExit exception inside the + generator to terminate the iteration + gi_code code object + gi_frame frame object or possibly None once the generator has + been exhausted + gi_running set to 1 when generator is executing, 0 otherwise + next return the next item from the container + send resumes the generator and "sends" a value that becomes + the result of the current yield-expression + throw used to raise an exception inside the generator""" + return isinstance(object, types.GeneratorType) + def istraceback(object): """Return true if the object is a traceback. @@ -198,6 +241,14 @@ or ismethod(object) or ismethoddescriptor(object)) +def isgenerator(object): + """Return true if the object is a generator object.""" + return isinstance(object, types.GeneratorType) + +def isabstract(object): + """Return true if the object is an abstract base class (ABC).""" + return isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT + def getmembers(object, predicate=None): """Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate.""" @@ -606,7 +657,9 @@ """Extract the block of code at the top of the given list of lines.""" blockfinder = BlockFinder() try: - tokenize.tokenize(iter(lines).__next__, blockfinder.tokeneater) + tokens = tokenize.generate_tokens(iter(lines).__next__) + for _token in tokens: + blockfinder.tokeneater(*_token) except (EndOfBlock, IndentationError): pass return lines[:blockfinder.last] @@ -670,9 +723,6 @@ return walktree(roots, children, None) # ------------------------------------------------ argument list extraction -# These constants are from Python's compile.h. -CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 1, 2, 4, 8 - Arguments = namedtuple('Arguments', 'args, varargs, varkw') def getargs(co): Modified: python/branches/py3k-ctypes-pep3118/Lib/io.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/io.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/io.py Wed Apr 30 15:57:13 2008 @@ -1,24 +1,50 @@ -"""New I/O library conforming to PEP 3116. +"""The io module provides the Python interfaces to stream handling. The +builtin open function is defined in this module. -This is a prototype; hopefully eventually some of this will be -reimplemented in C. - -Conformance of alternative implementations: all arguments are intended -to be positional-only except the arguments of the open() function. -Argument names except those of the open() function are not part of the -specification. Instance variables and methods whose name starts with -a leading underscore are not part of the specification (except "magic" -names like __iter__). Only the top-level names listed in the __all__ -variable are part of the specification. - -XXX edge cases when switching between reading/writing -XXX need to support 1 meaning line-buffered -XXX whenever an argument is None, use the default value -XXX read/write ops should check readable/writable -XXX buffered readinto should work with arbitrary buffer objects -XXX use incremental encoder for text output, at least for UTF-16 and UTF-8-SIG -XXX check writable, readable and seekable in appropriate places +At the top of the I/O hierarchy is the abstract base class IOBase. It +defines the basic interface to a stream. Note, however, that there is no +seperation between reading and writing to streams; implementations are +allowed to throw an IOError if they do not support a given operation. + +Extending IOBase is RawIOBase which deals simply with the reading and +writing of raw bytes to a stream. FileIO subclasses RawIOBase to provide +an interface to OS files. + +BufferedIOBase deals with buffering on a raw byte stream (RawIOBase). Its +subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer +streams that are readable, writable, and both respectively. +BufferedRandom provides a buffered interface to random access +streams. BytesIO is a simple stream of in-memory bytes. + +Another IOBase subclass, TextIOBase, deals with the encoding and decoding +of streams into text. TextIOWrapper, which extends it, is a buffered text +interface to a buffered raw stream (`BufferedIOBase`). Finally, StringIO +is a in-memory stream for text. + +Argument names are not part of the specification, and only the arguments +of open() are intended to be used as keyword arguments. + +data: + +DEFAULT_BUFFER_SIZE + + An int containing the default buffer size used by the module's buffered + I/O classes. open() uses the file's blksize (as obtained by os.stat) if + possible. """ +# New I/O library conforming to PEP 3116. + +# This is a prototype; hopefully eventually some of this will be +# reimplemented in C. + +# XXX edge cases when switching between reading/writing +# XXX need to support 1 meaning line-buffered +# XXX whenever an argument is None, use the default value +# XXX read/write ops should check readable/writable +# XXX buffered readinto should work with arbitrary buffer objects +# XXX use incremental encoder for text output, at least for UTF-16 and UTF-8-SIG +# XXX check writable, readable and seekable in appropriate places + __author__ = ("Guido van Rossum , " "Mike Verdone , " @@ -51,62 +77,103 @@ def open(file, mode="r", buffering=None, encoding=None, errors=None, newline=None, closefd=True): - r"""Replacement for the built-in open function. + r"""Open file and return a stream. If the file cannot be opened, an + IOError is raised. - Args: - file: string giving the name of the file to be opened; - or integer file descriptor of the file to be wrapped (*). - mode: optional mode string; see below. - buffering: optional int >= 0 giving the buffer size; values - can be: 0 = unbuffered, 1 = line buffered, - larger = fully buffered. - encoding: optional string giving the text encoding. - errors: optional string giving the encoding error handling. - newline: optional newlines specifier; must be None, '', '\n', '\r' - or '\r\n'; all other values are illegal. It controls the - handling of line endings. It works as follows: - - * On input, if `newline` is `None`, universal newlines - mode is enabled. Lines in the input can end in `'\n'`, - `'\r'`, or `'\r\n'`, and these are translated into - `'\n'` before being returned to the caller. If it is - `''`, universal newline mode is enabled, but line endings - are returned to the caller untranslated. If it has any of - the other legal values, input lines are only terminated by - the given string, and the line ending is returned to the - caller untranslated. - - * On output, if `newline` is `None`, any `'\n'` - characters written are translated to the system default - line separator, `os.linesep`. If `newline` is `''`, - no translation takes place. If `newline` is any of the - other legal values, any `'\n'` characters written are - translated to the given string. - - closefd: optional argument to keep the underlying file descriptor - open when the file is closed. It must not be false when - a filename is given. - - (*) If a file descriptor is given, it is closed when the returned - I/O object is closed, unless closefd=False is given. - - Mode strings characters: - 'r': open for reading (default) - 'w': open for writing, truncating the file first - 'a': open for writing, appending to the end if the file exists - 'b': binary mode - 't': text mode (default) - '+': open a disk file for updating (implies reading and writing) - 'U': universal newline mode (for backwards compatibility) - - Constraints: - - encoding or errors must not be given when a binary mode is given - - buffering must not be zero when a text mode is given - - Returns: - Depending on the mode and buffering arguments, either a raw - binary stream, a buffered binary stream, or a buffered text - stream, open for reading and/or writing. + file is either a string giving the name (and the path if the file + isn't in the current working directory) of the file to be opened or an + integer file descriptor of the file to be wrapped. (If a file + descriptor is given, it is closed when the returned I/O object is + closed, unless closefd is set to False.) + + mode is an optional string that specifies the mode in which the file + is opened. It defaults to 'r' which means open for reading in text + mode. Other common values are 'w' for writing (truncating the file if + it already exists), and 'a' for appending (which on some Unix systems, + means that all writes append to the end of the file regardless of the + current seek position). In text mode, if encoding is not specified the + encoding used is platform dependent. (For reading and writing raw + bytes use binary mode and leave encoding unspecified.) The available + modes are: + + ========= =============================================================== + Character Meaning + --------- --------------------------------------------------------------- + 'r' open for reading (default) + 'w' open for writing, truncating the file first + 'a' open for writing, appending to the end of the file if it exists + 'b' binary mode + 't' text mode (default) + '+' open a disk file for updating (reading and writing) + 'U' universal newline mode (for backwards compatibility; unneeded + for new code) + ========= =============================================================== + + The default mode is 'rt' (open for reading text). For binary random + access, the mode 'w+b' opens and truncates the file to 0 bytes, while + 'r+b' opens the file without truncation. + + Python distinguishes between files opened in binary and text modes, + even when the underlying operating system doesn't. Files opened in + binary mode (appending 'b' to the mode argument) return contents as + bytes objects without any decoding. In text mode (the default, or when + 't' is appended to the mode argument), the contents of the file are + returned as strings, the bytes having been first decoded using a + platform-dependent encoding or using the specified encoding if given. + + buffering is an optional integer used to set the buffering policy. By + default full buffering is on. Pass 0 to switch buffering off (only + allowed in binary mode), 1 to set line buffering, and an integer > 1 + for full buffering. + + encoding is the name of the encoding used to decode or encode the + file. This should only be used in text mode. The default encoding is + platform dependent, but any encoding supported by Python can be + passed. See the codecs module for the list of supported encodings. + + errors is an optional string that specifies how encoding errors are to + be handled---this argument should not be used in binary mode. Pass + 'strict' to raise a ValueError exception if there is an encoding error + (the default of None has the same effect), or pass 'ignore' to ignore + errors. (Note that ignoring encoding errors can lead to data loss.) + See the documentation for codecs.register for a list of the permitted + encoding error strings. + + newline controls how universal newlines works (it only applies to text + mode). It can be None, '', '\n', '\r', and '\r\n'. It works as + follows: + + * On input, if newline is None, universal newlines mode is + enabled. Lines in the input can end in '\n', '\r', or '\r\n', and + these are translated into '\n' before being returned to the + caller. If it is '', universal newline mode is enabled, but line + endings are returned to the caller untranslated. If it has any of + the other legal values, input lines are only terminated by the given + string, and the line ending is returned to the caller untranslated. + + * On output, if newline is None, any '\n' characters written are + translated to the system default line separator, os.linesep. If + newline is '', no translation takes place. If newline is any of the + other legal values, any '\n' characters written are translated to + the given string. + + If closefd is False, the underlying file descriptor will be kept open + when the file is closed. This does not work when a file name is given + and must be True in that case. + + open() returns a file object whose type depends on the mode, and + through which the standard file operations such as reading and writing + are performed. When open() is used to open a file in a text mode ('w', + 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open + a file in a binary mode, the returned class varies: in read binary + mode, it returns a BufferedReader; in write binary and append binary + modes, it returns a BufferedWriter, and in read/write mode, it returns + a BufferedRandom. + + It is also possible to use a string or bytearray as a file for both + reading and writing. For strings StringIO can be used like a file + opened in a text mode, and for bytes a BytesIO can be used like a file + opened in a binary mode. """ if not isinstance(file, (str, int)): raise TypeError("invalid file: %r" % file) @@ -218,18 +285,34 @@ class IOBase(metaclass=abc.ABCMeta): - """Base class for all I/O classes. + """The abstract base class for all I/O classes, acting on streams of + bytes. There is no public constructor. This class provides dummy implementations for many methods that - derived classes can override selectively; the default - implementations represent a file that cannot be read, written or - seeked. + derived classes can override selectively; the default implementations + represent a file that cannot be read, written or seeked. + + Even though IOBase does not declare read, readinto, or write because + their signatures will vary, implementations and clients should + consider those methods part of the interface. Also, implementations + may raise a IOError when operations they do not support are called. + + The basic type used for binary data read from or written to a file is + bytes. bytearrays are accepted too, and in some cases (such as + readinto) needed. Text I/O classes work with str data. + + Note that calling any method (even inquiries) on a closed stream is + undefined. Implementations may raise IOError in this case. + + IOBase (and its subclasses) support the iterator protocol, meaning + that an IOBase object can be iterated over yielding the lines in a + stream. - This does not define read(), readinto() and write(), nor - readline() and friends, since their signatures vary per layer. + IOBase also supports the :keyword:`with` statement. In this example, + fp is closed after the suite of the with statment is complete: - Not that calling any method (even inquiries) on a closed file is - undefined. Implementations may raise IOError in this case. + with open('spam.txt', 'r') as fp: + fp.write('Spam and eggs!') """ ### Internal ### @@ -244,11 +327,15 @@ def seek(self, pos: int, whence: int = 0) -> int: """seek(pos: int, whence: int = 0) -> int. Change stream position. - Seek to byte offset pos relative to position indicated by whence: - 0 Start of stream (the default). pos should be >= 0; - 1 Current position - whence may be negative; - 2 End of stream - whence usually negative. - Returns the new absolute position. + Change the stream position to byte offset offset. offset is + interpreted relative to the position indicated by whence. Values + for whence are: + + * 0 -- start of stream (the default); offset should be zero or positive + * 1 -- current stream position; offset may be negative + * 2 -- end of stream; offset is usually negative + + Return the new absolute position. """ self._unsupported("seek") @@ -257,9 +344,9 @@ return self.seek(0, 1) def truncate(self, pos: int = None) -> int: - """truncate(size: int = None) -> int. Truncate file to size bytes. + """truncate(pos: int = None) -> int. Truncate file to pos bytes. - Size defaults to the current IO position as reported by tell(). + Pos defaults to the current IO position as reported by tell(). Returns the new size. """ self._unsupported("truncate") @@ -269,7 +356,7 @@ def flush(self) -> None: """flush() -> None. Flushes write buffers, if applicable. - This is a no-op for read-only and non-blocking streams. + This is not implemented for read-only and non-blocking streams. """ # XXX Should this return the number of bytes written??? @@ -278,8 +365,7 @@ def close(self) -> None: """close() -> None. Flushes and closes the IO object. - This must be idempotent. It should also set a flag for the - 'closed' property (see below) to test. + This method has no effect if the file is already closed. """ if not self.__closed: try: @@ -365,6 +451,7 @@ def __enter__(self) -> "IOBase": # That's a forward reference """Context management protocol. Returns self.""" + self._checkClosed() return self def __exit__(self, *args) -> None: @@ -384,8 +471,6 @@ def isatty(self) -> bool: """isatty() -> int. Returns whether this is an 'interactive' stream. - - Returns False if we don't know. """ self._checkClosed() return False @@ -393,10 +478,19 @@ ### Readline[s] and writelines ### def readline(self, limit: int = -1) -> bytes: - """For backwards compatibility, a (slowish) readline().""" + r"""readline(limit: int = -1) -> bytes Read and return a line from the + stream. + + If limit is specified, at most limit bytes will be read. + + The line terminator is always b'\n' for binary files; for text + files, the newlines argument to open can be used to select the line + terminator(s) recognized. + """ + # For backwards compatibility, a (slowish) readline(). if hasattr(self, "peek"): def nreadahead(): - readahead = self.peek(1, unsafe=True) + readahead = self.peek(1) if not readahead: return 1 n = (readahead.find(b"\n") + 1) or len(readahead) @@ -429,6 +523,12 @@ return line def readlines(self, hint=None): + """readlines(hint=None) -> list Return a list of lines from the stream. + + hint can be specified to control the number of lines read: no more + lines will be read if the total size (in bytes/characters) of all + lines so far exceeds hint. + """ if hint is None: return list(self) n = 0 @@ -448,23 +548,22 @@ class RawIOBase(IOBase): - """Base class for raw binary I/O. + """Base class for raw binary I/O.""" - The read() method is implemented by calling readinto(); derived - classes that want to support read() only need to implement - readinto() as a primitive operation. In general, readinto() - can be more efficient than read(). - - (It would be tempting to also provide an implementation of - readinto() in terms of read(), in case the latter is a more - suitable primitive operation, but that would lead to nasty - recursion in case a subclass doesn't implement either.) - """ + # The read() method is implemented by calling readinto(); derived + # classes that want to support read() only need to implement + # readinto() as a primitive operation. In general, readinto() can be + # more efficient than read(). + + # (It would be tempting to also provide an implementation of + # readinto() in terms of read(), in case the latter is a more suitable + # primitive operation, but that would lead to nasty recursion in case + # a subclass doesn't implement either.) def read(self, n: int = -1) -> bytes: """read(n: int) -> bytes. Read and return up to n bytes. - Returns an empty bytes array on EOF, or None if the object is + Returns an empty bytes object on EOF, or None if the object is set not to block and has no data to read. """ if n is None: @@ -477,7 +576,7 @@ return bytes(b) def readall(self): - """readall() -> bytes. Read until EOF, using multiple read() call.""" + """readall() -> bytes. Read until EOF, using multiple read() calls.""" res = bytearray() while True: data = self.read(DEFAULT_BUFFER_SIZE) @@ -486,8 +585,8 @@ res += data return bytes(res) - def readinto(self, b: bytes) -> int: - """readinto(b: bytes) -> int. Read up to len(b) bytes into b. + def readinto(self, b: bytearray) -> int: + """readinto(b: bytearray) -> int. Read up to len(b) bytes into b. Returns number of bytes read (0 for EOF), or None if the object is set not to block as has no data to read. @@ -504,13 +603,12 @@ class FileIO(_fileio._FileIO, RawIOBase): - """Raw I/O implementation for OS files. + """Raw I/O implementation for OS files.""" - This multiply inherits from _FileIO and RawIOBase to make - isinstance(io.FileIO(), io.RawIOBase) return True without - requiring that _fileio._FileIO inherits from io.RawIOBase (which - would be hard to do since _fileio.c is written in C). - """ + # This multiply inherits from _FileIO and RawIOBase to make + # isinstance(io.FileIO(), io.RawIOBase) return True without requiring + # that _fileio._FileIO inherits from io.RawIOBase (which would be hard + # to do since _fileio.c is written in C). def close(self): _fileio._FileIO.close(self) @@ -520,6 +618,7 @@ def name(self): return self._name + # XXX(gb): _FileIO already has a mode property @property def mode(self): return self._mode @@ -562,12 +661,11 @@ """ self._unsupported("read") - def readinto(self, b: bytes) -> int: - """readinto(b: bytes) -> int. Read up to len(b) bytes into b. + def readinto(self, b: bytearray) -> int: + """readinto(b: bytearray) -> int. Read up to len(b) bytes into b. - Like read(), this may issue multiple reads to the underlying - raw stream, unless the latter is 'interactive' (XXX or a - pipe?). + Like read(), this may issue multiple reads to the underlying raw + stream, unless the latter is 'interactive'. Returns the number of bytes read (0 for EOF). @@ -669,8 +767,6 @@ """Buffered I/O implementation using an in-memory bytes buffer.""" - # XXX More docs - def __init__(self, initial_bytes=None): buf = bytearray() if initial_bytes is not None: @@ -679,6 +775,8 @@ self._pos = 0 def getvalue(self): + """getvalue() -> bytes Return the bytes value (contents) of the buffer + """ return bytes(self._buffer) def read(self, n=None): @@ -692,6 +790,8 @@ return bytes(b) def read1(self, n): + """This is the same as read. + """ return self.read(n) def write(self, b): @@ -746,7 +846,14 @@ class BufferedReader(_BufferedIOMixin): - """Buffer for a readable sequential RawIO object.""" + """BufferedReader(raw[, buffer_size]) + + A buffer for a readable, sequential BaseRawIO object. + + The constructor creates a BufferedReader for the given readable raw + stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE + is used. + """ def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE): """Create a new buffered reader using the given readable raw IO object. @@ -784,14 +891,12 @@ out = nodata_val return out - def peek(self, n=0, *, unsafe=False): + def peek(self, n=0): """Returns buffered bytes without advancing the position. The argument indicates a desired minimal number of bytes; we do at most one raw read to satisfy it. We never return more than self.buffer_size. - - Unless unsafe=True is passed, we return a copy. """ want = min(n, self.buffer_size) have = len(self._read_buf) @@ -800,21 +905,15 @@ current = self.raw.read(to_read) if current: self._read_buf += current - result = self._read_buf - if unsafe: - result = result[:] - return result + return self._read_buf def read1(self, n): - """Reads up to n bytes. - - Returns up to n bytes. If at least one byte is buffered, - we only return buffered bytes. Otherwise, we do one - raw read. - """ + """Reads up to n bytes, with at most one read() system call.""" + # Returns up to n bytes. If at least one byte is buffered, we + # only return buffered bytes. Otherwise, we do one raw read. if n <= 0: return b"" - self.peek(1, unsafe=True) + self.peek(1) return self.read(min(n, len(self._read_buf))) def tell(self): @@ -830,7 +929,15 @@ class BufferedWriter(_BufferedIOMixin): - # XXX docstring + """BufferedWriter(raw[, buffer_size[, max_buffer_size]]) + + A buffer for a writeable sequential RawIO object. + + The constructor creates a BufferedWriter for the given writeable raw + stream. If the buffer_size is not given, it defaults to + DEAFULT_BUFFER_SIZE. If max_buffer_size is omitted, it defaults to + twice the buffer size. + """ def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None): @@ -898,15 +1005,19 @@ """A buffered reader and writer object together. - A buffered reader object and buffered writer object put together - to form a sequential IO object that can read and write. - - This is typically used with a socket or two-way pipe. - - XXX The usefulness of this (compared to having two separate IO - objects) is questionable. + A buffered reader object and buffered writer object put together to + form a sequential IO object that can read and write. This is typically + used with a socket or two-way pipe. + + reader and writer are RawIOBase objects that are readable and + writeable respectively. If the buffer_size is omitted it defaults to + DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered writer) + defaults to twice the buffer size. """ + # XXX The usefulness of this (compared to having two separate IO + # objects) is questionable. + def __init__(self, reader, writer, buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None): """Constructor. @@ -929,8 +1040,8 @@ def write(self, b): return self.writer.write(b) - def peek(self, n=0, *, unsafe=False): - return self.reader.peek(n, unsafe=unsafe) + def peek(self, n=0): + return self.reader.peek(n) def read1(self, n): return self.reader.read1(n) @@ -958,7 +1069,15 @@ class BufferedRandom(BufferedWriter, BufferedReader): - # XXX docstring + """BufferedRandom(raw[, buffer_size[, max_buffer_size]]) + + A buffered interface to random access streams. + + The constructor creates a reader and writer for a seekable stream, + raw, given in the first argument. If the buffer_size is omitted it + defaults to DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered + writer) defaults to twice the buffer size. + """ def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None): @@ -990,9 +1109,9 @@ self.flush() return BufferedReader.readinto(self, b) - def peek(self, n=0, *, unsafe=False): + def peek(self, n=0): self.flush() - return BufferedReader.peek(self, n, unsafe=unsafe) + return BufferedReader.peek(self, n) def read1(self, n): self.flush() @@ -1009,9 +1128,9 @@ """Base class for text I/O. - This class provides a character and line based interface to stream I/O. - - There is no readinto() method, as character strings are immutable. + This class provides a character and line based interface to stream + I/O. There is no readinto method because Python's character strings + are immutable. There is no public constructor. """ def read(self, n: int = -1) -> str: @@ -1059,11 +1178,11 @@ class IncrementalNewlineDecoder(codecs.IncrementalDecoder): - """Codec used when reading a file in universal newlines mode. - It wraps another incremental decoder, translating \\r\\n and \\r into \\n. - It also records the types of newlines encountered. - When used with translate=False, it ensures that the newline sequence is - returned in one piece. + r"""Codec used when reading a file in universal newlines mode. It wraps + another incremental decoder, translating \r\n and \r into \n. It also + records the types of newlines encountered. When used with + translate=False, it ensures that the newline sequence is returned in + one piece. """ def __init__(self, decoder, translate, errors='strict'): codecs.IncrementalDecoder.__init__(self, errors=errors) @@ -1139,9 +1258,28 @@ class TextIOWrapper(TextIOBase): - """Buffered text stream. + r"""TextIOWrapper(buffer[, encoding[, errors[, newline[, line_buffering]]]]) - Character and line based layer over a BufferedIOBase object. + Character and line based layer over a BufferedIOBase object, buffer. + + encoding gives the name of the encoding that the stream will be + decoded or encoded with. It defaults to locale.getpreferredencoding. + + errors determines the strictness of encoding and decoding (see the + codecs.register) and defaults to "strict". + + newline can be None, '', '\n', '\r', or '\r\n'. It controls the + handling of line endings. If it is None, universal newlines is + enabled. With this enabled, on input, the lines endings '\n', '\r', + or '\r\n' are translated to '\n' before being returned to the + caller. Conversely, on output, '\n' is translated to the system + default line seperator, os.linesep. If newline is any other of its + legal values, that newline becomes the newline when the file is read + and it is returned untranslated. On output, '\n' is converted to the + newline. + + If line_buffering is True, a call to flush is implied when a call to + write contains a newline character. """ _CHUNK_SIZE = 128 @@ -1184,10 +1322,20 @@ self._writenl = newline or os.linesep self._encoder = None self._decoder = None - self._pending = "" - self._snapshot = None + self._decoded_chars = '' # buffer for text returned from decoder + self._decoded_chars_used = 0 # offset into _decoded_chars for read() + self._snapshot = None # info for reconstructing decoder state self._seekable = self._telling = self.buffer.seekable() + # self._snapshot is either None, or a tuple (dec_flags, next_input) + # where dec_flags is the second (integer) item of the decoder state + # and next_input is the chunk of input bytes that comes next after the + # snapshot point. We use this to reconstruct decoder states in tell(). + + # Naming convention: + # - "bytes_..." for integer variables that count input bytes + # - "chars_..." for integer variables that count decoded characters + @property def encoding(self): return self._encoding @@ -1200,14 +1348,7 @@ def line_buffering(self): return self._line_buffering - # A word about _snapshot. This attribute is either None, or a - # tuple (decoder_state, readahead, pending) where decoder_state is - # the second (integer) item of the decoder state, readahead is the - # chunk of bytes that was read, and pending is the characters that - # were rendered by the decoder after feeding it those bytes. We - # use this to reconstruct intermediate decoder states in tell(). - - def _seekable(self): + def seekable(self): return self._seekable def flush(self): @@ -1265,127 +1406,220 @@ self._decoder = decoder return decoder + # The following three methods implement an ADT for _decoded_chars. + # Text returned from the decoder is buffered here until the client + # requests it by calling our read() or readline() method. + def _set_decoded_chars(self, chars): + """Set the _decoded_chars buffer.""" + self._decoded_chars = chars + self._decoded_chars_used = 0 + + def _get_decoded_chars(self, n=None): + """Advance into the _decoded_chars buffer.""" + offset = self._decoded_chars_used + if n is None: + chars = self._decoded_chars[offset:] + else: + chars = self._decoded_chars[offset:offset + n] + self._decoded_chars_used += len(chars) + return chars + + def _rewind_decoded_chars(self, n): + """Rewind the _decoded_chars buffer.""" + if self._decoded_chars_used < n: + raise AssertionError("rewind decoded_chars out of bounds") + self._decoded_chars_used -= n + def _read_chunk(self): + """ + Read and decode the next chunk of data from the BufferedReader. + """ + + # The return value is True unless EOF was reached. The decoded + # string is placed in self._decoded_chars (replacing its previous + # value). The entire input chunk is sent to the decoder, though + # some of it may remain buffered in the decoder, yet to be + # converted. + if self._decoder is None: raise ValueError("no decoder") - if not self._telling: - readahead = self.buffer.read1(self._CHUNK_SIZE) - pending = self._decoder.decode(readahead, not readahead) - return readahead, pending - decoder_buffer, decoder_state = self._decoder.getstate() - readahead = self.buffer.read1(self._CHUNK_SIZE) - pending = self._decoder.decode(readahead, not readahead) - self._snapshot = (decoder_state, decoder_buffer + readahead, pending) - return readahead, pending - - def _encode_decoder_state(self, ds, pos): - x = 0 - for i in bytes(ds): - x = x<<8 | i - return (x<<64) | pos - - def _decode_decoder_state(self, pos): - x, pos = divmod(pos, 1<<64) - if not x: - return None, pos - b = b"" - while x: - b.append(x&0xff) - x >>= 8 - return str(b[::-1]), pos + + if self._telling: + # To prepare for tell(), we need to snapshot a point in the + # file where the decoder's input buffer is empty. + + dec_buffer, dec_flags = self._decoder.getstate() + # Given this, we know there was a valid snapshot point + # len(dec_buffer) bytes ago with decoder state (b'', dec_flags). + + # Read a chunk, decode it, and put the result in self._decoded_chars. + input_chunk = self.buffer.read1(self._CHUNK_SIZE) + eof = not input_chunk + self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) + + if self._telling: + # At the snapshot point, len(dec_buffer) bytes before the read, + # the next input to be decoded is dec_buffer + input_chunk. + self._snapshot = (dec_flags, dec_buffer + input_chunk) + + return not eof + + def _pack_cookie(self, position, dec_flags=0, + bytes_to_feed=0, need_eof=0, chars_to_skip=0): + # The meaning of a tell() cookie is: seek to position, set the + # decoder flags to dec_flags, read bytes_to_feed bytes, feed them + # into the decoder with need_eof as the EOF flag, then skip + # chars_to_skip characters of the decoded result. For most simple + # decoders, tell() will often just give a byte offset in the file. + return (position | (dec_flags<<64) | (bytes_to_feed<<128) | + (chars_to_skip<<192) | bool(need_eof)<<256) + + def _unpack_cookie(self, bigint): + rest, position = divmod(bigint, 1<<64) + rest, dec_flags = divmod(rest, 1<<64) + rest, bytes_to_feed = divmod(rest, 1<<64) + need_eof, chars_to_skip = divmod(rest, 1<<64) + return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip def tell(self): if not self._seekable: - raise IOError("Underlying stream is not seekable") + raise IOError("underlying stream is not seekable") if not self._telling: - raise IOError("Telling position disabled by next() call") + raise IOError("telling position disabled by next() call") self.flush() position = self.buffer.tell() decoder = self._decoder if decoder is None or self._snapshot is None: - if self._pending: - raise ValueError("pending data") + if self._decoded_chars: + # This should never happen. + raise AssertionError("pending decoded text") return position - decoder_state, readahead, pending = self._snapshot - position -= len(readahead) - needed = len(pending) - len(self._pending) - if not needed: - return self._encode_decoder_state(decoder_state, position) + + # Skip backward to the snapshot point (see _read_chunk). + dec_flags, next_input = self._snapshot + position -= len(next_input) + + # How many decoded characters have been used up since the snapshot? + chars_to_skip = self._decoded_chars_used + if chars_to_skip == 0: + # We haven't moved from the snapshot point. + return self._pack_cookie(position, dec_flags) + + # Starting from the snapshot position, we will walk the decoder + # forward until it gives us enough decoded characters. saved_state = decoder.getstate() try: - decoder.setstate((b"", decoder_state)) - n = 0 - bb = bytearray(1) - for i, bb[0] in enumerate(readahead): - n += len(decoder.decode(bb)) - if n >= needed: - decoder_buffer, decoder_state = decoder.getstate() - return self._encode_decoder_state( - decoder_state, - position + (i+1) - len(decoder_buffer) - (n - needed)) - raise IOError("Can't reconstruct logical file position") + # Note our initial start point. + decoder.setstate((b'', dec_flags)) + start_pos = position + start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0 + need_eof = 0 + + # Feed the decoder one byte at a time. As we go, note the + # nearest "safe start point" before the current location + # (a point where the decoder has nothing buffered, so seek() + # can safely start from there and advance to this location). + next_byte = bytearray(1) + for next_byte[0] in next_input: + bytes_fed += 1 + chars_decoded += len(decoder.decode(next_byte)) + dec_buffer, dec_flags = decoder.getstate() + if not dec_buffer and chars_decoded <= chars_to_skip: + # Decoder buffer is empty, so this is a safe start point. + start_pos += bytes_fed + chars_to_skip -= chars_decoded + start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0 + if chars_decoded >= chars_to_skip: + break + else: + # We didn't get enough decoded data; signal EOF to get more. + chars_decoded += len(decoder.decode(b'', final=True)) + need_eof = 1 + if chars_decoded < chars_to_skip: + raise IOError("can't reconstruct logical file position") + + # The returned cookie corresponds to the last safe start point. + return self._pack_cookie( + start_pos, start_flags, bytes_fed, need_eof, chars_to_skip) finally: decoder.setstate(saved_state) - def seek(self, pos, whence=0): + def seek(self, cookie, whence=0): if not self._seekable: - raise IOError("Underlying stream is not seekable") - if whence == 1: - if pos != 0: - raise IOError("Can't do nonzero cur-relative seeks") - pos = self.tell() + raise IOError("underlying stream is not seekable") + if whence == 1: # seek relative to current position + if cookie != 0: + raise IOError("can't do nonzero cur-relative seeks") + # Seeking to the current position should attempt to + # sync the underlying buffer with the current position. whence = 0 - if whence == 2: - if pos != 0: - raise IOError("Can't do nonzero end-relative seeks") + cookie = self.tell() + if whence == 2: # seek relative to end of file + if cookie != 0: + raise IOError("can't do nonzero end-relative seeks") self.flush() - pos = self.buffer.seek(0, 2) + position = self.buffer.seek(0, 2) + self._set_decoded_chars('') self._snapshot = None - self._pending = "" if self._decoder: self._decoder.reset() - return pos + return position if whence != 0: - raise ValueError("Invalid whence (%r, should be 0, 1 or 2)" % + raise ValueError("invalid whence (%r, should be 0, 1 or 2)" % (whence,)) - if pos < 0: - raise ValueError("Negative seek position %r" % (pos,)) + if cookie < 0: + raise ValueError("negative seek position %r" % (cookie,)) self.flush() - orig_pos = pos - ds, pos = self._decode_decoder_state(pos) - if not ds: - self.buffer.seek(pos) - self._snapshot = None - self._pending = "" - if self._decoder: - self._decoder.reset() - return pos - decoder = self._decoder or self._get_decoder() - decoder.set_state(("", ds)) - self.buffer.seek(pos) - self._snapshot = (ds, b"", "") - self._pending = "" - self._decoder = decoder - return orig_pos + + # The strategy of seek() is to go back to the safe start point + # and replay the effect of read(chars_to_skip) from there. + start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \ + self._unpack_cookie(cookie) + + # Seek back to the safe start point. + self.buffer.seek(start_pos) + self._set_decoded_chars('') + self._snapshot = None + + # Restore the decoder to its state from the safe start point. + if self._decoder or dec_flags or chars_to_skip: + self._decoder = self._decoder or self._get_decoder() + self._decoder.setstate((b'', dec_flags)) + self._snapshot = (dec_flags, b'') + + if chars_to_skip: + # Just like _read_chunk, feed the decoder and save a snapshot. + input_chunk = self.buffer.read(bytes_to_feed) + self._set_decoded_chars( + self._decoder.decode(input_chunk, need_eof)) + self._snapshot = (dec_flags, input_chunk) + + # Skip chars_to_skip of the decoded characters. + if len(self._decoded_chars) < chars_to_skip: + raise IOError("can't restore logical file position") + self._decoded_chars_used = chars_to_skip + + return cookie def read(self, n=None): if n is None: n = -1 decoder = self._decoder or self._get_decoder() - res = self._pending if n < 0: - res += decoder.decode(self.buffer.read(), True) - self._pending = "" + # Read everything. + result = (self._get_decoded_chars() + + decoder.decode(self.buffer.read(), final=True)) + self._set_decoded_chars('') self._snapshot = None - return res + return result else: - while len(res) < n: - readahead, pending = self._read_chunk() - res += pending - if not readahead: - break - self._pending = res[n:] - return res[:n] + # Keep reading chunks until we have n characters to return. + eof = False + result = self._get_decoded_chars(n) + while len(result) < n and not eof: + eof = not self._read_chunk() + result += self._get_decoded_chars(n - len(result)) + return result def __next__(self): self._telling = False @@ -1399,15 +1633,10 @@ def readline(self, limit=None): if limit is None: limit = -1 - if limit >= 0: - # XXX Hack to support limit argument, for backwards compatibility - line = self.readline() - if len(line) <= limit: - return line - line, self._pending = line[:limit], line[limit:] + self._pending - return line - line = self._pending + # Grab all the decoded text (we will rewind any extra bits later). + line = self._get_decoded_chars() + start = 0 decoder = self._decoder or self._get_decoder() @@ -1460,22 +1689,28 @@ endpos = pos + len(self._readnl) break + if limit >= 0 and len(line) >= limit: + endpos = limit # reached length limit + break + # No line ending seen yet - get more data more_line = '' - while True: - readahead, pending = self._read_chunk() - more_line = pending - if more_line or not readahead: + while self._read_chunk(): + if self._decoded_chars: break - if more_line: - line += more_line + if self._decoded_chars: + line += self._get_decoded_chars() else: # end of file - self._pending = '' + self._set_decoded_chars('') self._snapshot = None return line - self._pending = line[endpos:] + if limit >= 0 and endpos > limit: + endpos = limit # don't exceed limit + + # Rewind _decoded_chars to just after the line ending we found. + self._rewind_decoded_chars(len(line) - endpos) return line[:endpos] @property @@ -1483,6 +1718,12 @@ return self._decoder.newlines if self._decoder else None class StringIO(TextIOWrapper): + """StringIO([initial_value[, encoding, [errors, [newline]]]]) + + An in-memory stream for text. The initial_value argument sets the + value of object. The other arguments are like those of TextIOWrapper's + constructor. + """ # XXX This is really slow, but fully functional Modified: python/branches/py3k-ctypes-pep3118/Lib/lib-tk/Tkinter.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/lib-tk/Tkinter.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/lib-tk/Tkinter.py Wed Apr 30 15:57:13 2008 @@ -187,7 +187,7 @@ else: self._name = 'PY_VAR' + repr(_varnum) _varnum += 1 - if value != None: + if value is not None: self.set(value) elif not self._tk.call("info", "exists", self._name): self.set(self._default) Modified: python/branches/py3k-ctypes-pep3118/Lib/lib-tk/tkSimpleDialog.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/lib-tk/tkSimpleDialog.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/lib-tk/tkSimpleDialog.py Wed Apr 30 15:57:13 2008 @@ -26,7 +26,6 @@ ''' from Tkinter import * -import os class Dialog(Toplevel): Modified: python/branches/py3k-ctypes-pep3118/Lib/lib-tk/turtle.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/lib-tk/turtle.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/lib-tk/turtle.py Wed Apr 30 15:57:13 2008 @@ -749,25 +749,25 @@ global _width, _height, _startx, _starty width = geometry.get('width',_width) - if width is None or width >= 0: + if width >= 0 or width is None: _width = width else: raise ValueError("width can not be less than 0") height = geometry.get('height',_height) - if height is None or height >= 0: + if height >= 0 or height is None: _height = height else: raise ValueError("height can not be less than 0") startx = geometry.get('startx', _startx) - if startx is None or startx >= 0: + if startx >= 0 or startx is None: _startx = _startx else: raise ValueError("startx can not be less than 0") starty = geometry.get('starty', _starty) - if starty is None or starty >= 0: + if starty >= 0 or starty is None: _starty = starty else: raise ValueError("startx can not be less than 0") Modified: python/branches/py3k-ctypes-pep3118/Lib/locale.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/locale.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/locale.py Wed Apr 30 15:57:13 2008 @@ -26,6 +26,18 @@ "normalize", "LC_CTYPE", "LC_COLLATE", "LC_TIME", "LC_MONETARY", "LC_NUMERIC", "LC_ALL", "CHAR_MAX"] +def _strcoll(a,b): + """ strcoll(string,string) -> int. + Compares two strings according to the locale. + """ + return cmp(a,b) + +def _strxfrm(s): + """ strxfrm(string) -> string. + Returns a string that behaves for cmp locale-aware. + """ + return s + try: from _locale import * @@ -76,17 +88,11 @@ raise Error('_locale emulation only supports "C" locale') return 'C' - def strcoll(a,b): - """ strcoll(string,string) -> int. - Compares two strings according to the locale. - """ - return cmp(a,b) - - def strxfrm(s): - """ strxfrm(string) -> string. - Returns a string that behaves for cmp locale-aware. - """ - return s +# These may or may not exist in _locale, so be sure to set them. +if 'strxfrm' not in globals(): + strxfrm = _strxfrm +if 'strcoll' not in globals(): + strcoll = _strcoll ### Number formatting APIs @@ -505,7 +511,11 @@ def getpreferredencoding(do_setlocale = True): """Return the charset that the user is likely using, by looking at environment variables.""" - return getdefaultlocale()[1] + res = getdefaultlocale()[1] + if res is None: + # LANG not set, default conservatively to ASCII + res = 'ascii' + return res else: def getpreferredencoding(do_setlocale = True): """Return the charset that the user is likely using, Modified: python/branches/py3k-ctypes-pep3118/Lib/logging/__init__.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/logging/__init__.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/logging/__init__.py Wed Apr 30 15:57:13 2008 @@ -24,6 +24,10 @@ """ import sys, os, time, io, traceback +__all__ = ['BASIC_FORMAT', 'BufferingFormatter', 'CRITICAL', 'DEBUG', 'ERROR', + 'FATAL', 'FileHandler', 'Filter', 'Filterer', 'Formatter', 'Handler', + 'INFO', 'LogRecord', 'Logger', 'Manager', 'NOTSET', 'PlaceHolder', + 'RootLogger', 'StreamHandler', 'WARN', 'WARNING'] try: import codecs Modified: python/branches/py3k-ctypes-pep3118/Lib/logging/handlers.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/logging/handlers.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/logging/handlers.py Wed Apr 30 15:57:13 2008 @@ -19,13 +19,12 @@ based on PEP 282 and comments thereto in comp.lang.python, and influenced by Apache's log4j system. -Copyright (C) 2001-2007 Vinay Sajip. All Rights Reserved. +Copyright (C) 2001-2008 Vinay Sajip. All Rights Reserved. To use, simply 'import logging' and log away! """ -import sys, logging, socket, os, struct, time, glob -import pickle +import logging, socket, os, pickle, struct, time, re from stat import ST_DEV, ST_INO try: @@ -174,15 +173,19 @@ if self.when == 'S': self.interval = 1 # one second self.suffix = "%Y-%m-%d_%H-%M-%S" + self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$" elif self.when == 'M': self.interval = 60 # one minute self.suffix = "%Y-%m-%d_%H-%M" + self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}$" elif self.when == 'H': self.interval = 60 * 60 # one hour self.suffix = "%Y-%m-%d_%H" + self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}$" elif self.when == 'D' or self.when == 'MIDNIGHT': self.interval = 60 * 60 * 24 # one day self.suffix = "%Y-%m-%d" + self.extMatch = r"^\d{4}-\d{2}-\d{2}$" elif self.when.startswith('W'): self.interval = 60 * 60 * 24 * 7 # one week if len(self.when) != 2: @@ -191,9 +194,11 @@ raise ValueError("Invalid day specified for weekly rollover: %s" % self.when) self.dayOfWeek = int(self.when[1]) self.suffix = "%Y-%m-%d" + self.extMatch = r"^\d{4}-\d{2}-\d{2}$" else: raise ValueError("Invalid rollover interval specified: %s" % self.when) + self.extMatch = re.compile(self.extMatch) self.interval = self.interval * interval # multiply by units requested self.rolloverAt = currentTime + self.interval @@ -236,16 +241,24 @@ daysToWait = self.dayOfWeek - day else: daysToWait = 6 - day + self.dayOfWeek + 1 - self.rolloverAt = self.rolloverAt + (daysToWait * (60 * 60 * 24)) + newRolloverAt = self.rolloverAt + (daysToWait * (60 * 60 * 24)) + dstNow = t[-1] + dstAtRollover = time.localtime(newRolloverAt)[-1] + if dstNow != dstAtRollover: + if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour + newRolloverAt = newRolloverAt - 3600 + else: # DST bows out before next rollover, so we need to add an hour + newRolloverAt = newRolloverAt + 3600 + self.rolloverAt = newRolloverAt #print "Will rollover at %d, %d seconds from now" % (self.rolloverAt, self.rolloverAt - currentTime) def shouldRollover(self, record): """ - Determine if rollover should occur + Determine if rollover should occur. record is not used, as we are just comparing times, but it is needed so - the method siguratures are the same + the method signatures are the same """ t = int(time.time()) if t >= self.rolloverAt: @@ -253,6 +266,29 @@ #print "No need to rollover: %d, %d" % (t, self.rolloverAt) return 0 + def getFilesToDelete(self): + """ + Determine the files to delete when rolling over. + + More specific than the earlier method, which just used glob.glob(). + """ + dirName, baseName = os.path.split(self.baseFilename) + fileNames = os.listdir(dirName) + result = [] + prefix = baseName + "." + plen = len(prefix) + for fileName in fileNames: + if fileName[:plen] == prefix: + suffix = fileName[plen:] + if self.extMatch.match(suffix): + result.append(fileName) + result.sort() + if len(result) < self.backupCount: + result = [] + else: + result = result[:len(result) - self.backupCount] + return result + def doRollover(self): """ do a rollover; in this case, a date/time stamp is appended to the filename @@ -271,14 +307,29 @@ os.rename(self.baseFilename, dfn) if self.backupCount > 0: # find the oldest log file and delete it - s = glob.glob(self.baseFilename + ".20*") - if len(s) > self.backupCount: - s.sort() - os.remove(s[0]) + #s = glob.glob(self.baseFilename + ".20*") + #if len(s) > self.backupCount: + # s.sort() + # os.remove(s[0]) + for s in self.getFilesToDelete(): + os.remove(s) #print "%s -> %s" % (self.baseFilename, dfn) self.mode = 'w' self.stream = self._open() - self.rolloverAt = self.rolloverAt + self.interval + newRolloverAt = self.rolloverAt + self.interval + currentTime = int(time.time()) + while newRolloverAt <= currentTime: + newRolloverAt = newRolloverAt + self.interval + #If DST changes and midnight or weekly rollover, adjust for this. + if self.when == 'MIDNIGHT' or self.when.startswith('W'): + dstNow = time.localtime(currentTime)[-1] + dstAtRollover = time.localtime(newRolloverAt)[-1] + if dstNow != dstAtRollover: + if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour + newRolloverAt = newRolloverAt - 3600 + else: # DST bows out before next rollover, so we need to add an hour + newRolloverAt = newRolloverAt + 3600 + self.rolloverAt = newRolloverAt class WatchedFileHandler(logging.FileHandler): """ Modified: python/branches/py3k-ctypes-pep3118/Lib/mailbox.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/mailbox.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/mailbox.py Wed Apr 30 15:57:13 2008 @@ -311,7 +311,7 @@ def get_message(self, key): """Return a Message representation or raise a KeyError.""" subpath = self._lookup(key) - f = open(os.path.join(self._path, subpath), 'r') + f = open(os.path.join(self._path, subpath), 'r', newline='') try: if self._factory: msg = self._factory(f) @@ -328,7 +328,7 @@ def get_string(self, key): """Return a string representation or raise a KeyError.""" - f = open(os.path.join(self._path, self._lookup(key)), 'r') + f = open(os.path.join(self._path, self._lookup(key)), 'r', newline='') try: return f.read() finally: @@ -336,7 +336,7 @@ def get_file(self, key): """Return a file-like representation or raise a KeyError.""" - f = open(os.path.join(self._path, self._lookup(key)), 'r') + f = open(os.path.join(self._path, self._lookup(key)), 'r', newline='') return _ProxyFile(f) def iterkeys(self): @@ -502,15 +502,15 @@ """Initialize a single-file mailbox.""" Mailbox.__init__(self, path, factory, create) try: - f = open(self._path, 'r+') + f = open(self._path, 'r+', newline='') except IOError as e: if e.errno == errno.ENOENT: if create: - f = open(self._path, 'w+') + f = open(self._path, 'w+', newline='') else: raise NoSuchMailboxError(self._path) elif e.errno == errno.EACCES: - f = open(self._path, 'r') + f = open(self._path, 'r', newline='') else: raise self._file = f @@ -866,7 +866,7 @@ """Replace the keyed message; raise KeyError if it doesn't exist.""" path = os.path.join(self._path, str(key)) try: - f = open(path, 'r+') + f = open(path, 'r+', newline='') except IOError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) @@ -890,9 +890,9 @@ """Return a Message representation or raise a KeyError.""" try: if self._locked: - f = open(os.path.join(self._path, str(key)), 'r+') + f = open(os.path.join(self._path, str(key)), 'r+', newline='') else: - f = open(os.path.join(self._path, str(key)), 'r') + f = open(os.path.join(self._path, str(key)), 'r', newline='') except IOError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) @@ -917,9 +917,9 @@ """Return a string representation or raise a KeyError.""" try: if self._locked: - f = open(os.path.join(self._path, str(key)), 'r+') + f = open(os.path.join(self._path, str(key)), 'r+', newline='') else: - f = open(os.path.join(self._path, str(key)), 'r') + f = open(os.path.join(self._path, str(key)), 'r', newline='') except IOError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) @@ -939,7 +939,7 @@ def get_file(self, key): """Return a file-like representation or raise a KeyError.""" try: - f = open(os.path.join(self._path, str(key)), 'r') + f = open(os.path.join(self._path, str(key)), 'r', newline='') except IOError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) @@ -1017,7 +1017,7 @@ def get_sequences(self): """Return a name-to-key-list dictionary to define each sequence.""" results = {} - f = open(os.path.join(self._path, '.mh_sequences'), 'r') + f = open(os.path.join(self._path, '.mh_sequences'), 'r', newline='') try: all_keys = set(self.keys()) for line in f: @@ -1043,7 +1043,7 @@ def set_sequences(self, sequences): """Set sequences using the given name-to-key-list dictionary.""" - f = open(os.path.join(self._path, '.mh_sequences'), 'r+') + f = open(os.path.join(self._path, '.mh_sequences'), 'r+', newline='') try: os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC)) for name, keys in sequences.items(): @@ -1904,7 +1904,7 @@ """Create a file if it doesn't exist and open for reading and writing.""" fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR) try: - return open(path, 'r+') + return open(path, 'r+', newline='') finally: os.close(fd) @@ -2072,7 +2072,7 @@ if not self.boxes: return None fn = self.boxes.pop() - fp = open(os.path.join(self.dirname, fn)) + fp = open(os.path.join(self.dirname, fn), newline='') msg = self.factory(fp) try: msg._mh_msgno = fn Modified: python/branches/py3k-ctypes-pep3118/Lib/ntpath.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/ntpath.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/ntpath.py Wed Apr 30 15:57:13 2008 @@ -6,8 +6,8 @@ """ import os -import stat import sys +import stat import genericpath from genericpath import * Modified: python/branches/py3k-ctypes-pep3118/Lib/numbers.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/numbers.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/numbers.py Wed Apr 30 15:57:13 2008 @@ -7,10 +7,7 @@ from abc import ABCMeta, abstractmethod, abstractproperty -__all__ = ["Number", "Exact", "Inexact", - "Complex", "Real", "Rational", "Integral", - ] - +__all__ = ["Number", "Complex", "Real", "Rational", "Integral"] class Number(metaclass=ABCMeta): """All numbers inherit from this class. @@ -20,31 +17,13 @@ """ -class Exact(Number): - """Operations on instances of this type are exact. - - As long as the result of a homogenous operation is of the same - type, you can assume that it was computed exactly, and there are - no round-off errors. Laws like commutativity and associativity - hold. - """ - -Exact.register(int) - - -class Inexact(Number): - """Operations on instances of this type are inexact. - - Given X, an instance of Inexact, it is possible that (X + -X) + 3 - == 3, but X + (-X + 3) == 0. The exact form this error takes will - vary by type, but it's generally unsafe to compare this type for - equality. - """ - -Inexact.register(complex) -Inexact.register(float) -# Inexact.register(decimal.Decimal) - +## Notes on Decimal +## ---------------- +## Decimal has all of the methods specified by the Real abc, but it should +## not be registered as a Real because decimals do not interoperate with +## binary floats (i.e. Decimal('3.14') + 2.71828 is undefined). But, +## abstract reals are expected to interoperate (i.e. R1 + R2 should be +## expected to work if R1 and R2 are both Reals). class Complex(Number): """Complex defines the operations that work on the builtin complex type. @@ -154,7 +133,10 @@ """self == other""" raise NotImplementedError - # __ne__ is inherited from object and negates whatever __eq__ does. + def __ne__(self, other): + """self != other""" + # The default __ne__ doesn't negate __eq__ until 3.0. + return not (self == other) Complex.register(complex) @@ -275,10 +257,9 @@ return +self Real.register(float) -# Real.register(decimal.Decimal) -class Rational(Real, Exact): +class Rational(Real): """.numerator and .denominator should be in lowest terms.""" @abstractproperty @@ -291,7 +272,13 @@ # Concrete implementation of Real's conversion to float. def __float__(self): - """float(self) = self.numerator / self.denominator""" + """float(self) = self.numerator / self.denominator + + It's important that this conversion use the integer's "true" + division rather than casting one side to float before dividing + so that ratios of huge integers convert without overflowing. + + """ return self.numerator / self.denominator Modified: python/branches/py3k-ctypes-pep3118/Lib/opcode.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/opcode.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/opcode.py Wed Apr 30 15:57:13 2008 @@ -112,7 +112,7 @@ name_op('DELETE_NAME', 91) # "" def_op('UNPACK_SEQUENCE', 92) # Number of tuple items jrel_op('FOR_ITER', 93) - +def_op('UNPACK_EX', 94) name_op('STORE_ATTR', 95) # Index in name list name_op('DELETE_ATTR', 96) # "" name_op('STORE_GLOBAL', 97) # "" Modified: python/branches/py3k-ctypes-pep3118/Lib/pdb.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/pdb.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/pdb.py Wed Apr 30 15:57:13 2008 @@ -1193,7 +1193,16 @@ # Post-Mortem interface -def post_mortem(t): +def post_mortem(t=None): + # handling the default + if t is None: + # sys.exc_info() returns (type, value, traceback) if an exception is + # being handled, otherwise it returns None + t = sys.exc_info()[2] + if t is None: + raise ValueError("A valid traceback must be passed if no " + "exception is being handled") + p = Pdb() p.reset() while t.tb_next is not None: @@ -1224,7 +1233,7 @@ print('along the Python search path') def main(): - if not sys.argv[1:]: + if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"): print("usage: pdb.py scriptfile [arg] ...") sys.exit(2) Modified: python/branches/py3k-ctypes-pep3118/Lib/pickle.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/pickle.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/pickle.py Wed Apr 30 15:57:13 2008 @@ -42,19 +42,22 @@ bytes_types = (bytes, bytearray, memoryview) # These are purely informational; no code uses these. -format_version = "2.0" # File format version we write +format_version = "3.0" # File format version we write compatible_formats = ["1.0", # Original protocol 0 "1.1", # Protocol 0 with INST added "1.2", # Original protocol 1 "1.3", # Protocol 1 with BINFLOAT added "2.0", # Protocol 2 + "3.0", # Protocol 3 ] # Old format versions we can read # This is the highest protocol number we know how to read. -HIGHEST_PROTOCOL = 2 +HIGHEST_PROTOCOL = 3 # The protocol we write by default. May be less than HIGHEST_PROTOCOL. -DEFAULT_PROTOCOL = 2 +# We intentionally write a protocol that Python 2.x cannot read; +# there are too many issues with that. +DEFAULT_PROTOCOL = 3 # Why use struct.pack() for pickling but marshal.loads() for # unpickling? struct.pack() is 40% faster than marshal.dumps(), but @@ -161,6 +164,10 @@ _tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3] +# Protocol 3 (Python 3.x) + +BINBYTES = b'B' # push bytes; counted binary string argument +SHORT_BINBYTES = b'C' # " " ; " " " " < 256 bytes __all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)]) @@ -494,20 +501,19 @@ self.write(FLOAT + repr(obj).encode("ascii") + b'\n') dispatch[float] = save_float - def save_string(self, obj, pack=struct.pack): - if self.bin: - n = len(obj) - if n < 256: - self.write(SHORT_BINSTRING + bytes([n]) + bytes(obj)) - else: - self.write(BINSTRING + pack(">> import pickle ->>> x = [1, 2, (3, 4), {bytes(b'abc'): "def"}] ->>> pkl = pickle.dumps(x, 0) ->>> dis(pkl) +>>> x = [1, 2, (3, 4), {b'abc': "def"}] +>>> pkl0 = pickle.dumps(x, 0) +>>> dis(pkl0) 0: ( MARK 1: l LIST (MARK at 0) 2: p PUT 0 @@ -2000,19 +2064,32 @@ 25: ( MARK 26: d DICT (MARK at 25) 27: p PUT 2 - 30: S STRING 'abc' - 37: p PUT 3 - 40: V UNICODE 'def' - 45: p PUT 4 - 48: s SETITEM - 49: a APPEND - 50: . STOP + 30: c GLOBAL 'builtins bytes' + 46: p PUT 3 + 49: ( MARK + 50: ( MARK + 51: l LIST (MARK at 50) + 52: p PUT 4 + 55: L LONG 97 + 59: a APPEND + 60: L LONG 98 + 64: a APPEND + 65: L LONG 99 + 69: a APPEND + 70: t TUPLE (MARK at 49) + 71: p PUT 5 + 74: R REDUCE + 75: V UNICODE 'def' + 80: p PUT 6 + 83: s SETITEM + 84: a APPEND + 85: . STOP highest protocol among opcodes = 0 Try again with a "binary" pickle. ->>> pkl = pickle.dumps(x, 1) ->>> dis(pkl) +>>> pkl1 = pickle.dumps(x, 1) +>>> dis(pkl1) 0: ] EMPTY_LIST 1: q BINPUT 0 3: ( MARK @@ -2025,13 +2102,24 @@ 14: q BINPUT 1 16: } EMPTY_DICT 17: q BINPUT 2 - 19: U SHORT_BINSTRING 'abc' - 24: q BINPUT 3 - 26: X BINUNICODE 'def' - 34: q BINPUT 4 - 36: s SETITEM - 37: e APPENDS (MARK at 3) - 38: . STOP + 19: c GLOBAL 'builtins bytes' + 35: q BINPUT 3 + 37: ( MARK + 38: ] EMPTY_LIST + 39: q BINPUT 4 + 41: ( MARK + 42: K BININT1 97 + 44: K BININT1 98 + 46: K BININT1 99 + 48: e APPENDS (MARK at 41) + 49: t TUPLE (MARK at 37) + 50: q BINPUT 5 + 52: R REDUCE + 53: X BINUNICODE 'def' + 61: q BINPUT 6 + 63: s SETITEM + 64: e APPENDS (MARK at 3) + 65: . STOP highest protocol among opcodes = 1 Exercise the INST/OBJ/BUILD family. Modified: python/branches/py3k-ctypes-pep3118/Lib/pkgutil.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/pkgutil.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/pkgutil.py Wed Apr 30 15:57:13 2008 @@ -542,3 +542,40 @@ f.close() return path + +def get_data(package, resource): + """Get a resource from a package. + + This is a wrapper round the PEP 302 loader get_data API. The package + argument should be the name of a package, in standard module format + (foo.bar). The resource argument should be in the form of a relative + filename, using '/' as the path separator. The parent directory name '..' + is not allowed, and nor is a rooted name (starting with a '/'). + + The function returns a binary string, which is the contents of the + specified resource. + + For packages located in the filesystem, which have already been imported, + this is the rough equivalent of + + d = os.path.dirname(sys.modules[package].__file__) + data = open(os.path.join(d, resource), 'rb').read() + + If the package cannot be located or loaded, or it uses a PEP 302 loader + which does not support get_data(), then None is returned. + """ + + loader = get_loader(package) + if loader is None or not hasattr(loader, 'get_data'): + return None + mod = sys.modules.get(package) or loader.load_module(package) + if mod is None or not hasattr(mod, '__file__'): + return None + + # Modify the resource name to be compatible with the loader.get_data + # signature - an os.path format "filename" starting with the dirname of + # the package's __file__ + parts = resource.split('/') + parts.insert(0, os.path.dirname(mod.__file__)) + resource_name = os.path.join(*parts) + return loader.get_data(resource_name) Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/EasyDialogs.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/EasyDialogs.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/EasyDialogs.py Wed Apr 30 15:57:13 2008 @@ -78,7 +78,7 @@ return h = d.GetDialogItemAsControl(2) SetDialogItemText(h, lf2cr(msg)) - if ok != None: + if ok is not None: h = d.GetDialogItemAsControl(1) h.SetControlTitle(ok) d.SetDialogDefaultItem(1) @@ -115,10 +115,10 @@ SetDialogItemText(h, lf2cr(default)) d.SelectDialogItemText(4, 0, 999) # d.SetDialogItem(4, 0, 255) - if ok != None: + if ok is not None: h = d.GetDialogItemAsControl(1) h.SetControlTitle(ok) - if cancel != None: + if cancel is not None: h = d.GetDialogItemAsControl(2) h.SetControlTitle(cancel) d.SetDialogDefaultItem(1) @@ -159,10 +159,10 @@ SetControlData(pwd, kControlEditTextPart, kControlEditTextPasswordTag, default) d.SelectDialogItemText(4, 0, 999) Ctl.SetKeyboardFocus(d.GetDialogWindow(), pwd, kControlEditTextPart) - if ok != None: + if ok is not None: h = d.GetDialogItemAsControl(1) h.SetControlTitle(ok) - if cancel != None: + if cancel is not None: h = d.GetDialogItemAsControl(2) h.SetControlTitle(cancel) d.SetDialogDefaultItem(Dialogs.ok) @@ -203,19 +203,19 @@ # The question string is item 5 h = d.GetDialogItemAsControl(5) SetDialogItemText(h, lf2cr(question)) - if yes != None: + if yes is not None: if yes == '': d.HideDialogItem(2) else: h = d.GetDialogItemAsControl(2) h.SetControlTitle(yes) - if no != None: + if no is not None: if no == '': d.HideDialogItem(3) else: h = d.GetDialogItemAsControl(3) h.SetControlTitle(no) - if cancel != None: + if cancel is not None: if cancel == '': d.HideDialogItem(4) else: @@ -316,7 +316,7 @@ def set(self, value, max=None): """set(value) - Set progress bar position""" - if max != None: + if max is not None: self.maxval = max bar = self.d.GetDialogItemAsControl(3) if max <= 0: # indeterminate bar Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/FrameWork.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/FrameWork.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/FrameWork.py Wed Apr 30 15:57:13 2008 @@ -92,7 +92,7 @@ def setwatchcursor(): global _watch - if _watch == None: + if _watch is None: _watch = GetCursor(4).data SetCursor(_watch) @@ -129,7 +129,7 @@ self._quititem = MenuItem(m, "Quit", "Q", self._quit) def gethelpmenu(self): - if self._helpmenu == None: + if self._helpmenu is None: self._helpmenu = HelpMenu(self.menubar) return self._helpmenu @@ -266,7 +266,7 @@ else: name = "do_%d" % partcode - if wid == None: + if wid is None: # No window, or a non-python window try: handler = getattr(self, name) @@ -475,7 +475,7 @@ self.menus = None def addmenu(self, title, after = 0, id=None): - if id == None: + if id is None: id = self.getnextid() if DEBUG: print('Newmenu', title, id) # XXXX m = NewMenu(id, title) @@ -907,8 +907,8 @@ self.barx_enabled = self.bary_enabled = 1 x0, y0, x1, y1 = self.wid.GetWindowPort().GetPortBounds() vx, vy = self.getscrollbarvalues() - if vx == None: self.barx_enabled, vx = 0, 0 - if vy == None: self.bary_enabled, vy = 0, 0 + if vx is None: self.barx_enabled, vx = 0, 0 + if vy is None: self.bary_enabled, vy = 0, 0 if wantx: rect = x0-1, y1-(SCROLLBARWIDTH-1), x1-(SCROLLBARWIDTH-2), y1+1 self.barx = NewControl(self.wid, rect, "", 1, vx, 0, 32767, 16, 0) @@ -1007,7 +1007,7 @@ SetPort(self.wid) vx, vy = self.getscrollbarvalues() if self.barx: - if vx == None: + if vx is None: self.barx.HiliteControl(255) self.barx_enabled = 0 else: @@ -1017,7 +1017,7 @@ self.barx.HiliteControl(0) self.barx.SetControlValue(vx) if self.bary: - if vy == None: + if vy is None: self.bary.HiliteControl(255) self.bary_enabled = 0 else: Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/MiniAEFrame.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/MiniAEFrame.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/MiniAEFrame.py Wed Apr 30 15:57:13 2008 @@ -6,7 +6,6 @@ only suitable for the simplest of AppleEvent servers. """ -import sys import traceback import MacOS from Carbon import AE @@ -160,7 +159,7 @@ #Same try/except comment as above rv = _function(**_parameters) - if rv == None: + if rv is None: aetools.packevent(_reply, {}) else: aetools.packevent(_reply, {'----':rv}) Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/PixMapWrapper.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/PixMapWrapper.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/PixMapWrapper.py Wed Apr 30 15:57:13 2008 @@ -147,9 +147,9 @@ """Draw this pixmap into the given (default current) grafport.""" src = self.bounds dest = [x1,y1,x2,y2] - if x2 == None: + if x2 is None: dest[2] = x1 + src[2]-src[0] - if y2 == None: + if y2 is None: dest[3] = y1 + src[3]-src[1] if not port: port = Qd.GetPort() Qd.CopyBits(self.PixMap(), port.GetPortBitMapForCopyBits(), src, tuple(dest), Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/aepack.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/aepack.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/aepack.py Wed Apr 30 15:57:13 2008 @@ -20,7 +20,6 @@ import io import aetypes from aetypes import mkenum, ObjectSpecifier -import os # These ones seem to be missing from AppleEvents # (they're in AERegistry.h) @@ -83,7 +82,7 @@ else: return pack(x).AECoerceDesc(forcetype) - if x == None: + if x is None: return AE.AECreateDesc(b'null', '') if isinstance(x, AEDescType): Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/bgenlocations.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/bgenlocations.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/bgenlocations.py Wed Apr 30 15:57:13 2008 @@ -5,7 +5,7 @@ # but mac-style for MacPython, whether running on OS9 or OSX. # -import sys, os +import os Error = "bgenlocations.Error" # Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/buildtools.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/buildtools.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/buildtools.py Wed Apr 30 15:57:13 2008 @@ -203,13 +203,13 @@ dummy, tmplowner = copyres(input, output, skiptypes, 1, progress) Res.CloseResFile(input) -## if ownertype == None: +## if ownertype is None: ## raise BuildError, "No owner resource found in either resource file or template" # Make sure we're manipulating the output resource file now Res.UseResFile(output) - if ownertype == None: + if ownertype is None: # No owner resource in the template. We have skipped the # Python owner resource, so we have to add our own. The relevant # bundle stuff is already included in the interpret/applet template. Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/findertools.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/findertools.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/findertools.py Wed Apr 30 15:57:13 2008 @@ -124,7 +124,7 @@ """comment: get or set the Finder-comment of the item, displayed in the 'Get Info' window.""" object = Carbon.File.FSRef(object) object_alias = object.FSNewAliasMonimal() - if comment == None: + if comment is None: return _getcomment(object_alias) else: return _setcomment(object_alias, comment) @@ -329,7 +329,7 @@ """label: set or get the label of the item. Specify file by name or fsspec.""" object = Carbon.File.FSRef(object) object_alias = object.FSNewAliasMinimal() - if index == None: + if index is None: return _getlabel(object_alias) if index < 0 or index > 7: index = 0 @@ -375,7 +375,7 @@ """ fsr = Carbon.File.FSRef(folder) folder_alias = fsr.FSNewAliasMinimal() - if view == None: + if view is None: return _getwindowview(folder_alias) return _setwindowview(folder_alias, view) @@ -535,7 +535,7 @@ Development opportunity: get and set the data as PICT.""" fsr = Carbon.File.FSRef(object) object_alias = fsr.FSNewAliasMinimal() - if icondata == None: + if icondata is None: return _geticon(object_alias) return _seticon(object_alias, icondata) Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/gensuitemodule.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/gensuitemodule.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/gensuitemodule.py Wed Apr 30 15:57:13 2008 @@ -770,7 +770,7 @@ fp.write(" if _object:\n") fp.write(" _arguments['----'] = _object\n") else: - fp.write(" if _no_object != None: raise TypeError, 'No direct arg expected'\n") + fp.write(" if _no_object is not None: raise TypeError, 'No direct arg expected'\n") fp.write("\n") # # Do enum-name substitution Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/ic.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/ic.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/ic.py Wed Apr 30 15:57:13 2008 @@ -198,12 +198,12 @@ self.ic.ICLaunchURL(hint, url, 0, len(url)) def parseurl(self, data, start=None, end=None, hint=""): - if start == None: + if start is None: selStart = 0 selEnd = len(data) else: selStart = selEnd = start - if end != None: + if end is not None: selEnd = end selStart, selEnd = self.ic.ICParseURL(hint, data, selStart, selEnd, self.h) return self.h.data, selStart, selEnd @@ -227,27 +227,27 @@ def launchurl(url, hint=""): global _dft_ic - if _dft_ic == None: _dft_ic = IC() + if _dft_ic is None: _dft_ic = IC() return _dft_ic.launchurl(url, hint) def parseurl(data, start=None, end=None, hint=""): global _dft_ic - if _dft_ic == None: _dft_ic = IC() + if _dft_ic is None: _dft_ic = IC() return _dft_ic.parseurl(data, start, end, hint) def mapfile(filename): global _dft_ic - if _dft_ic == None: _dft_ic = IC() + if _dft_ic is None: _dft_ic = IC() return _dft_ic.mapfile(filename) def maptypecreator(type, creator, filename=""): global _dft_ic - if _dft_ic == None: _dft_ic = IC() + if _dft_ic is None: _dft_ic = IC() return _dft_ic.maptypecreator(type, creator, filename) def settypecreator(file): global _dft_ic - if _dft_ic == None: _dft_ic = IC() + if _dft_ic is None: _dft_ic = IC() return _dft_ic.settypecreator(file) def _test(): Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/CodeWarrior/CodeWarrior_suite.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/CodeWarrior/CodeWarrior_suite.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/CodeWarrior/CodeWarrior_suite.py Wed Apr 30 15:57:13 2008 @@ -51,7 +51,7 @@ _subcode = 'MAKE' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -135,7 +135,8 @@ _subcode = 'EXPT' aetools.keysubst(_arguments, self._argmap_export) - if _no_object != None: raise TypeError('No direct arg expected') + if _arguments: raise TypeError('No optional args expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -154,7 +155,7 @@ _subcode = 'RMOB' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -193,7 +194,7 @@ _subcode = 'RUN ' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -232,7 +233,7 @@ _subcode = 'UP2D' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py Wed Apr 30 15:57:13 2008 @@ -72,7 +72,7 @@ _subcode = 'ClsP' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -190,7 +190,7 @@ _subcode = 'GDoc' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -217,7 +217,8 @@ _subcode = 'Gref' aetools.keysubst(_arguments, self._argmap_Get_Preferences) - if _no_object != None: raise TypeError('No direct arg expected') + if _arguments: raise TypeError('No optional args expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -263,7 +264,7 @@ _subcode = 'GetP' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -283,7 +284,7 @@ _subcode = 'GSeg' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -324,7 +325,7 @@ _subcode = 'NsCl' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -410,7 +411,8 @@ _subcode = 'Make' aetools.keysubst(_arguments, self._argmap_Make_Project) - if _no_object != None: raise TypeError('No direct arg expected') + if _arguments: raise TypeError('No optional args expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -503,7 +505,7 @@ _subcode = 'RemB' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -543,7 +545,7 @@ _subcode = 'ReFP' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -570,7 +572,8 @@ _subcode = 'RunP' aetools.keysubst(_arguments, self._argmap_Run_Project) - if _no_object != None: raise TypeError('No direct arg expected') + if _arguments: raise TypeError('No optional args expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -682,7 +685,8 @@ _subcode = 'Pref' aetools.keysubst(_arguments, self._argmap_Set_Preferences) - if _no_object != None: raise TypeError('No direct arg expected') + if _arguments: raise TypeError('No optional args expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -778,7 +782,8 @@ _subcode = 'UpdP' aetools.keysubst(_arguments, self._argmap_Update_Project) - if _no_object != None: raise TypeError('No direct arg expected') + if _arguments: raise TypeError('No optional args expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Standard_Suite.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Standard_Suite.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Standard_Suite.py Wed Apr 30 15:57:13 2008 @@ -115,7 +115,7 @@ _subcode = 'crel' aetools.keysubst(_arguments, self._argmap_make) - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Explorer/Required_Suite.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Explorer/Required_Suite.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Explorer/Required_Suite.py Wed Apr 30 15:57:13 2008 @@ -61,7 +61,7 @@ _subcode = 'quit' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -80,7 +80,7 @@ _subcode = 'oapp' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Explorer/Web_Browser_Suite.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Explorer/Web_Browser_Suite.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Explorer/Web_Browser_Suite.py Wed Apr 30 15:57:13 2008 @@ -42,7 +42,7 @@ _subcode = 'CLSA' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -69,7 +69,8 @@ _subcode = 'CLOS' aetools.keysubst(_arguments, self._argmap_CloseWindow) - if _no_object != None: raise TypeError('No direct arg expected') + if _arguments: raise TypeError('No optional args expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -110,7 +111,7 @@ _subcode = 'LSTW' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Finder/Finder_Basics.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Finder/Finder_Basics.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Finder/Finder_Basics.py Wed Apr 30 15:57:13 2008 @@ -20,7 +20,7 @@ _subcode = 'copy' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Finder/Legacy_suite.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Finder/Legacy_suite.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Finder/Legacy_suite.py Wed Apr 30 15:57:13 2008 @@ -20,7 +20,7 @@ _subcode = 'rest' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -39,7 +39,7 @@ _subcode = 'shut' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -58,7 +58,7 @@ _subcode = 'slep' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Finder/Standard_Suite.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Finder/Standard_Suite.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Finder/Standard_Suite.py Wed Apr 30 15:57:13 2008 @@ -179,7 +179,7 @@ _subcode = 'crel' aetools.keysubst(_arguments, self._argmap_make) - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -285,7 +285,7 @@ _subcode = 'quit' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Netscape/Mozilla_suite.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Netscape/Mozilla_suite.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Netscape/Mozilla_suite.py Wed Apr 30 15:57:13 2008 @@ -21,7 +21,7 @@ _subcode = 'Impt' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -41,7 +41,7 @@ _subcode = 'upro' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -61,7 +61,7 @@ _subcode = 'wurl' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -126,7 +126,7 @@ _subcode = 'addr' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -165,7 +165,7 @@ _subcode = 'prfl' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Netscape/PowerPlant.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Netscape/PowerPlant.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Netscape/PowerPlant.py Wed Apr 30 15:57:13 2008 @@ -25,7 +25,7 @@ _subcode = 'sttg' aetools.keysubst(_arguments, self._argmap_SwitchTellTarget) - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Netscape/Required_suite.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Netscape/Required_suite.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Netscape/Required_suite.py Wed Apr 30 15:57:13 2008 @@ -61,7 +61,7 @@ _subcode = 'quit' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -80,7 +80,7 @@ _subcode = 'oapp' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Netscape/WorldWideWeb_suite.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Netscape/WorldWideWeb_suite.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Netscape/WorldWideWeb_suite.py Wed Apr 30 15:57:13 2008 @@ -154,7 +154,7 @@ _subcode = 'LSTW' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py Wed Apr 30 15:57:13 2008 @@ -268,7 +268,7 @@ _subcode = 'actv' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -371,7 +371,7 @@ _subcode = 'tend' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -443,7 +443,7 @@ _subcode = 'idle' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -462,7 +462,7 @@ _subcode = 'noop' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -585,7 +585,7 @@ _subcode = 'log1' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -625,7 +625,8 @@ _subcode = 'log0' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') + _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -644,7 +645,7 @@ _subcode = 'tell' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py Wed Apr 30 15:57:13 2008 @@ -255,7 +255,7 @@ _subcode = 'crel' aetools.keysubst(_arguments, self._argmap_make) - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -345,7 +345,7 @@ _subcode = 'quit' aetools.keysubst(_arguments, self._argmap_quit) - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') aetools.enumsubst(_arguments, 'savo', _Enum_savo) @@ -365,7 +365,7 @@ _subcode = 'rapp' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -384,7 +384,7 @@ _subcode = 'oapp' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/SystemEvents/Standard_Suite.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/SystemEvents/Standard_Suite.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/SystemEvents/Standard_Suite.py Wed Apr 30 15:57:13 2008 @@ -175,7 +175,7 @@ _subcode = 'crel' aetools.keysubst(_arguments, self._argmap_make) - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Terminal/Standard_Suite.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Terminal/Standard_Suite.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/Terminal/Standard_Suite.py Wed Apr 30 15:57:13 2008 @@ -175,7 +175,7 @@ _subcode = 'crel' aetools.keysubst(_arguments, self._argmap_make) - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/_builtinSuites/builtin_Suite.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/_builtinSuites/builtin_Suite.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/lib-scriptpackages/_builtinSuites/builtin_Suite.py Wed Apr 30 15:57:13 2008 @@ -37,8 +37,7 @@ _subcode = 'oapp' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') - + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) @@ -56,7 +55,7 @@ _subcode = 'rapp' if _arguments: raise TypeError('No optional args expected') - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, @@ -100,7 +99,7 @@ _subcode = 'quit' aetools.keysubst(_arguments, self._argmap_quit) - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') aetools.enumsubst(_arguments, 'savo', _Enum_savo) Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/macostools.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/macostools.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/macostools.py Wed Apr 30 15:57:13 2008 @@ -7,9 +7,7 @@ from Carbon import Res from Carbon import File, Files import os -import sys import MacOS -import time try: openrf = MacOS.openrf except AttributeError: @@ -108,7 +106,7 @@ sf = srcfss.FSpGetFInfo() df = dstfss.FSpGetFInfo() df.Creator, df.Type = sf.Creator, sf.Type - if forcetype != None: + if forcetype is not None: df.Type = forcetype df.Flags = (sf.Flags & COPY_FLAGS) dstfss.FSpSetFInfo(df) Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-mac/videoreader.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-mac/videoreader.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-mac/videoreader.py Wed Apr 30 15:57:13 2008 @@ -188,7 +188,7 @@ def GetVideoFrameRate(self): tv = self.videocurtime - if tv == None: + if tv is None: tv = 0 flags = QuickTime.nextTimeStep|QuickTime.nextTimeEdgeOK tv, dur = self.videomedia.GetMediaNextInterestingTime(flags, tv, 1.0) @@ -199,7 +199,7 @@ if not time is None: self.audiocurtime = time flags = QuickTime.nextTimeStep|QuickTime.nextTimeEdgeOK - if self.audiocurtime == None: + if self.audiocurtime is None: self.audiocurtime = 0 tv = self.audiomedia.GetMediaNextInterestingTimeOnly(flags, self.audiocurtime, 1.0) if tv < 0 or (self.audiocurtime and tv < self.audiocurtime): @@ -215,7 +215,7 @@ if not time is None: self.videocurtime = time flags = QuickTime.nextTimeStep - if self.videocurtime == None: + if self.videocurtime is None: flags = flags | QuickTime.nextTimeEdgeOK self.videocurtime = 0 tv = self.videomedia.GetMediaNextInterestingTimeOnly(flags, self.videocurtime, 1.0) Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-os2emx/grp.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-os2emx/grp.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-os2emx/grp.py Wed Apr 30 15:57:13 2008 @@ -143,7 +143,7 @@ while 1: entry = group.readline().strip() if len(entry) > 3: - if sep == None: + if sep is None: sep = __get_field_sep(entry) fields = entry.split(sep) fields[2] = int(fields[2]) Modified: python/branches/py3k-ctypes-pep3118/Lib/plat-os2emx/pwd.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plat-os2emx/pwd.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plat-os2emx/pwd.py Wed Apr 30 15:57:13 2008 @@ -167,7 +167,7 @@ while True: entry = passwd.readline().strip() if len(entry) > 6: - if sep == None: + if sep is None: sep = __get_field_sep(entry) fields = entry.split(sep) for i in (2, 3): Modified: python/branches/py3k-ctypes-pep3118/Lib/platform.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/platform.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/platform.py Wed Apr 30 15:57:13 2008 @@ -89,7 +89,7 @@ __copyright__ = """ Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal at lemburg.com - Copyright (c) 2000-2007, eGenix.com Software GmbH; mailto:info at egenix.com + Copyright (c) 2000-2008, eGenix.com Software GmbH; mailto:info at egenix.com Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee or royalty is hereby granted, @@ -238,9 +238,10 @@ # and http://data.linux-ntfs.org/rpm/whichrpm # and http://www.die.net/doc/linux/man/man1/lsb_release.1.html -_supported_dists = ('SuSE', 'debian', 'fedora', 'redhat', 'centos', - 'mandrake', 'rocks', 'slackware', 'yellowdog', - 'gentoo', 'UnitedLinux', 'turbolinux') +_supported_dists = ( + 'SuSE', 'debian', 'fedora', 'redhat', 'centos', + 'mandrake', 'mandriva', 'rocks', 'slackware', 'yellowdog', 'gentoo', + 'UnitedLinux', 'turbolinux') def _parse_release_file(firstline): @@ -524,7 +525,13 @@ In case this fails, default is returned. """ - from win32api import RegQueryValueEx + try: + # Use win32api if available + from win32api import RegQueryValueEx + except ImportError: + # On Python 2.0 and later, emulate using _winreg + import _winreg + RegQueryValueEx = _winreg.QueryValueEx try: return RegQueryValueEx(key,name) except: @@ -544,9 +551,9 @@ means the OS version uses debugging code, i.e. code that checks arguments, ranges, etc. (Thomas Heller). - Note: this function only works if Mark Hammond's win32 - package is installed and obviously only runs on Win32 - compatible platforms. + Note: this function works best with Mark Hammond's win32 + package installed, but also on Python 2.3 and later. It + obviously only runs on Win32 compatible platforms. """ # XXX Is there any way to find out the processor type on WinXX ? @@ -560,11 +567,29 @@ # Import the needed APIs try: import win32api + from win32api import RegQueryValueEx, RegOpenKeyEx, \ + RegCloseKey, GetVersionEx + from win32con import HKEY_LOCAL_MACHINE, VER_PLATFORM_WIN32_NT, \ + VER_PLATFORM_WIN32_WINDOWS, VER_NT_WORKSTATION except ImportError: - return release,version,csd,ptype - from win32api import RegQueryValueEx,RegOpenKeyEx,RegCloseKey,GetVersionEx - from win32con import HKEY_LOCAL_MACHINE,VER_PLATFORM_WIN32_NT,\ - VER_PLATFORM_WIN32_WINDOWS + # Emulate the win32api module using Python APIs + try: + sys.getwindowsversion + except AttributeError: + # No emulation possible, so return the defaults... + return release,version,csd,ptype + else: + # Emulation using _winreg (added in Python 2.0) and + # sys.getwindowsversion() (added in Python 2.3) + import _winreg + GetVersionEx = sys.getwindowsversion + RegQueryValueEx = _winreg.QueryValueEx + RegOpenKeyEx = _winreg.OpenKeyEx + RegCloseKey = _winreg.CloseKey + HKEY_LOCAL_MACHINE = _winreg.HKEY_LOCAL_MACHINE + VER_PLATFORM_WIN32_WINDOWS = 1 + VER_PLATFORM_WIN32_NT = 2 + VER_NT_WORKSTATION = 1 # Find out the registry key and some general version infos maj,min,buildno,plat,csd = GetVersionEx() @@ -601,11 +626,18 @@ elif maj == 6: if min == 0: # Per http://msdn2.microsoft.com/en-us/library/ms724429.aspx - productType = GetVersionEx(1)[8] - if productType == 1: # VER_NT_WORKSTATION + try: + productType = GetVersionEx(1)[8] + except TypeError: + # sys.getwindowsversion() doesn't take any arguments, so + # we cannot detect 2008 Server that way. + # XXX Add some other means of detecting 2008 Server ?! release = 'Vista' else: - release = '2008Server' + if productType == VER_NT_WORKSTATION: + release = 'Vista' + else: + release = '2008Server' else: release = 'post2008Server' else: @@ -616,9 +648,9 @@ # Open the registry key try: - keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE,regkey) + keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey) # Get a value to make sure the key exists... - RegQueryValueEx(keyCurVer,'SystemRoot') + RegQueryValueEx(keyCurVer, 'SystemRoot') except: return release,version,csd,ptype @@ -1043,10 +1075,12 @@ release,version,csd,ptype = win32_ver() if release and version: use_syscmd_ver = 0 - # XXX Should try to parse the PROCESSOR_* environment variables + # Try to use the PROCESSOR_* environment variables # available on Win XP and later; see # http://support.microsoft.com/kb/888731 and # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM + machine = os.environ.get('PROCESSOR_ARCHITECTURE', '') + processor = os.environ.get('PROCESSOR_IDENTIFIER', machine) # Try the 'ver' system command available on some # platforms Modified: python/branches/py3k-ctypes-pep3118/Lib/plistlib.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/plistlib.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/plistlib.py Wed Apr 30 15:57:13 2008 @@ -1,6 +1,6 @@ """plistlib.py -- a tool to generate and parse MacOSX .plist files. -The PropertyList (.plist) file format is a simple XML pickle supporting +The PropertList (.plist) file format is a simple XML pickle supporting basic object types, like dictionaries, lists, numbers and strings. Usually the top level object is a dictionary. @@ -12,8 +12,8 @@ with a file name or a (readable) file object as the only argument. It returns the top level object (again, usually a dictionary). -To work with plist data in strings, you can use readPlistFromString() -and writePlistToString(). +To work with plist data in bytes objects, you can use readPlistFromBytes() +and writePlistToBytes(). Values can be strings, integers, floats, booleans, tuples, lists, dictionaries, Data or datetime.datetime objects. String values (including @@ -21,24 +21,24 @@ UTF-8. The plist type is supported through the Data class. This is a -thin wrapper around a Python string. +thin wrapper around a Python bytes object. Generate Plist example: pl = dict( aString="Doodah", aList=["A", "B", 12, 32.1, [1, 2, 3]], - aFloat=0.1, - anInt=728, + aFloat = 0.1, + anInt = 728, aDict=dict( anotherString="", aUnicodeValue=u'M\xe4ssig, Ma\xdf', aTrueValue=True, aFalseValue=False, ), - someData=Data(""), - someMoreData=Data("" * 10), - aDate=datetime.datetime.fromtimestamp(time.mktime(time.gmtime())), + someData = Data(b""), + someMoreData = Data(b"" * 10), + aDate = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())), ) # unicode keys are possible, but a little awkward to use: pl[u'\xc5benraa'] = "That was a unicode key." @@ -52,7 +52,7 @@ __all__ = [ - "readPlist", "writePlist", "readPlistFromString", "writePlistToString", + "readPlist", "writePlist", "readPlistFromBytes", "writePlistToBytes", "readPlistFromResource", "writePlistToResource", "Plist", "Data", "Dict" ] @@ -60,7 +60,7 @@ import binascii import datetime -from io import StringIO +from io import BytesIO import re @@ -69,10 +69,10 @@ (readable) file object. Return the unpacked root object (which usually is a dictionary). """ - didOpen = 0 + didOpen = False if isinstance(pathOrFile, str): - pathOrFile = open(pathOrFile) - didOpen = 1 + pathOrFile = open(pathOrFile, 'rb') + didOpen = True p = PlistParser() rootObject = p.parse(pathOrFile) if didOpen: @@ -84,10 +84,10 @@ """Write 'rootObject' to a .plist file. 'pathOrFile' may either be a file name or a (writable) file object. """ - didOpen = 0 + didOpen = False if isinstance(pathOrFile, str): - pathOrFile = open(pathOrFile, "w") - didOpen = 1 + pathOrFile = open(pathOrFile, 'wb') + didOpen = True writer = PlistWriter(pathOrFile) writer.writeln("") writer.writeValue(rootObject) @@ -96,16 +96,16 @@ pathOrFile.close() -def readPlistFromString(data): - """Read a plist data from a string. Return the root object. +def readPlistFromBytes(data): + """Read a plist data from a bytes object. Return the root object. """ - return readPlist(StringIO(data)) + return readPlist(BytesIO(data)) -def writePlistToString(rootObject): - """Return 'rootObject' as a plist-formatted string. +def writePlistToBytes(rootObject): + """Return 'rootObject' as a plist-formatted bytes object. """ - f = StringIO() + f = BytesIO() writePlist(rootObject, f) return f.getvalue() @@ -145,7 +145,6 @@ class DumbXMLWriter: - def __init__(self, file, indentLevel=0, indent="\t"): self.file = file self.stack = [] @@ -165,16 +164,19 @@ def simpleElement(self, element, value=None): if value is not None: - value = _escapeAndEncode(value) + value = _escape(value) self.writeln("<%s>%s" % (element, value, element)) else: self.writeln("<%s/>" % element) def writeln(self, line): if line: - self.file.write(self.indentLevel * self.indent + line + "\n") - else: - self.file.write("\n") + # plist has fixed encoding of utf-8 + if isinstance(line, str): + line = line.encode('utf-8') + self.file.write(self.indentLevel * self.indent) + self.file.write(line) + self.file.write(b'\n') # Contents should conform to a subset of ISO 8601 @@ -205,7 +207,7 @@ r"[\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x0e\x0f" r"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]") -def _escapeAndEncode(text): +def _escape(text): m = _controlCharPat.search(text) if m is not None: raise ValueError("strings can't contains control characters; " @@ -215,17 +217,17 @@ text = text.replace("&", "&") # escape '&' text = text.replace("<", "<") # escape '<' text = text.replace(">", ">") # escape '>' - return text.encode("utf-8") # encode as UTF-8 + return text -PLISTHEADER = """\ +PLISTHEADER = b"""\ """ class PlistWriter(DumbXMLWriter): - def __init__(self, file, indentLevel=0, indent="\t", writeHeader=1): + def __init__(self, file, indentLevel=0, indent=b"\t", writeHeader=1): if writeHeader: file.write(PLISTHEADER) DumbXMLWriter.__init__(self, file, indentLevel, indent) @@ -258,9 +260,9 @@ def writeData(self, data): self.beginElement("data") self.indentLevel -= 1 - maxlinelength = 76 - len(self.indent.replace("\t", " " * 8) * + maxlinelength = 76 - len(self.indent.replace(b"\t", b" " * 8) * self.indentLevel) - for line in data.asBase64(maxlinelength).split("\n"): + for line in data.asBase64(maxlinelength).split(b"\n"): if line: self.writeln(line) self.indentLevel += 1 @@ -268,8 +270,7 @@ def writeDict(self, d): self.beginElement("dict") - items = list(d.items()) - items.sort() + items = sorted(d.items()) for key, value in items: if not isinstance(key, str): raise TypeError("keys must be strings") @@ -321,7 +322,7 @@ from warnings import warn warn("The plistlib.Dict class is deprecated, use builtin dict instead", PendingDeprecationWarning) - super(Dict, self).__init__(**kwargs) + super().__init__(**kwargs) class Plist(_InternalDict): @@ -334,7 +335,7 @@ from warnings import warn warn("The Plist class is deprecated, use the readPlist() and " "writePlist() functions instead", PendingDeprecationWarning) - super(Plist, self).__init__(**kwargs) + super().__init__(**kwargs) def fromFile(cls, pathOrFile): """Deprecated. Use the readPlist() function instead.""" @@ -356,31 +357,33 @@ for i in range(0, len(s), maxbinsize): chunk = s[i : i + maxbinsize] pieces.append(binascii.b2a_base64(chunk)) - return "".join(pieces) + return b''.join(pieces) class Data: """Wrapper for binary data.""" def __init__(self, data): + if not isinstance(data, bytes): + raise TypeError("data must be as bytes") self.data = data + @classmethod def fromBase64(cls, data): # base64.decodestring just calls binascii.a2b_base64; # it seems overkill to use both base64 and binascii. return cls(binascii.a2b_base64(data)) - fromBase64 = classmethod(fromBase64) def asBase64(self, maxlinelength=76): return _encodeBase64(self.data, maxlinelength) - def __cmp__(self, other): + def __eq__(self, other): if isinstance(other, self.__class__): - return cmp(self.data, other.data) + return self.data == other.data elif isinstance(other, str): - return cmp(self.data, other) + return self.data == other else: - return cmp(id(self), id(other)) + return id(self) == id(other) def __repr__(self): return "%s(%s)" % (self.__class__.__name__, repr(self.data)) @@ -427,11 +430,7 @@ self.stack[-1].append(value) def getData(self): - data = "".join(self.data) - try: - data = data.encode("ascii") - except UnicodeError: - pass + data = ''.join(self.data) self.data = [] return data @@ -465,6 +464,6 @@ def end_string(self): self.addObject(self.getData()) def end_data(self): - self.addObject(Data.fromBase64(self.getData())) + self.addObject(Data.fromBase64(self.getData().encode("utf-8"))) def end_date(self): self.addObject(_dateFromString(self.getData())) Modified: python/branches/py3k-ctypes-pep3118/Lib/pprint.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/pprint.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/pprint.py Wed Apr 30 15:57:13 2008 @@ -175,13 +175,12 @@ write('{') endchar = '}' object = sorted(object) - indent += 4 elif issubclass(typ, frozenset): if not length: write('frozenset()') return - write('frozenset([') - endchar = '])' + write('frozenset({') + endchar = '})' object = sorted(object) indent += 10 else: Modified: python/branches/py3k-ctypes-pep3118/Lib/pstats.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/pstats.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/pstats.py Wed Apr 30 15:57:13 2008 @@ -238,7 +238,7 @@ stats_list.append((cc, nc, tt, ct) + func + (func_std_string(func), func)) - stats_list.sort(TupleComp(sort_tuple).compare) + stats_list.sort(key=CmpToKey(TupleComp(sort_tuple).compare)) self.fcn_list = fcn_list = [] for tuple in stats_list: @@ -470,6 +470,16 @@ return direction return 0 +def CmpToKey(mycmp): + 'Convert a cmp= function into a key= function' + class K(object): + def __init__(self, obj): + self.obj = obj + def __lt__(self, other): + return mycmp(self.obj, other.obj) == -1 + return K + + #************************************************************************** # func_name is a triple (file:string, line:int, name:string) Modified: python/branches/py3k-ctypes-pep3118/Lib/py_compile.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/py_compile.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/py_compile.py Wed Apr 30 15:57:13 2008 @@ -171,11 +171,15 @@ """ if args is None: args = sys.argv[1:] + rv = 0 for filename in args: try: compile(filename, doraise=True) except PyCompileError as err: + # return value to indicate at least one failure + rv = 1 sys.stderr.write(err.msg) + return rv if __name__ == "__main__": - main() + sys.exit(main()) Modified: python/branches/py3k-ctypes-pep3118/Lib/pyclbr.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/pyclbr.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/pyclbr.py Wed Apr 30 15:57:13 2008 @@ -324,8 +324,7 @@ path = [] dict = readmodule_ex(mod, path) objs = dict.values() - objs.sort(lambda a, b: cmp(getattr(a, 'lineno', 0), - getattr(b, 'lineno', 0))) + objs.sort(key=lambda a: getattr(a, 'lineno', 0)) for obj in objs: if isinstance(obj, Class): print("class", obj.name, obj.super, obj.lineno) Modified: python/branches/py3k-ctypes-pep3118/Lib/pydoc.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/pydoc.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/pydoc.py Wed Apr 30 15:57:13 2008 @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: Latin-1 -*- +# -*- coding: latin-1 -*- """Generate Python documentation in HTML or text for interactive use. In the Python interpreter, do "from pydoc import help" to provide online @@ -536,7 +536,7 @@ url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc) results.append('%s' % (url, escape(all))) elif pep: - url = 'http://www.python.org/peps/pep-%04d' % int(pep) + url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep) results.append('%s' % (url, escape(all))) elif text[end:end+1] == '(': results.append(self.namelink(name, methods, funcs, classes)) @@ -660,7 +660,7 @@ contents = self.multicolumn( modules, lambda t: self.modulelink(t[1])) result = result + self.bigsection( - 'Modules', '#fffff', '#aa55cc', contents) + 'Modules', '#ffffff', '#aa55cc', contents) if classes: classlist = [value for (key, value) in classes] @@ -797,10 +797,7 @@ tag += ':
\n' # Sort attrs by name. - try: - attrs.sort(key=lambda t: t[0]) - except TypeError: - attrs.sort(lambda t1, t2: cmp(t1[0], t2[0])) # 2.3 compat + attrs.sort(key=lambda t: t[0]) # Pump out the attrs, segregated by kind. attrs = spill('Methods %s' % tag, attrs, @@ -1077,7 +1074,7 @@ if submodules: submodules.sort() result = result + self.section( - 'SUBMODULES', join(submodules, '\n')) + 'SUBMODULES', '\n'.join(submodules)) if classes: classlist = [value for key, value in classes] @@ -1203,7 +1200,6 @@ else: tag = "inherited from %s" % classname(thisclass, object.__module__) - filter(lambda t: not t[0].startswith('_'), attrs) # Sort attrs by name. attrs.sort() @@ -1488,7 +1484,8 @@ desc += ' in ' + name[:name.rfind('.')] elif module and module is not object: desc += ' in module ' + module.__name__ - elif not (inspect.ismodule(object) or + + if not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or inspect.isgetsetdescriptor(object) or @@ -1503,23 +1500,6 @@ def doc(thing, title='Python Library Documentation: %s', forceload=0): """Display text documentation, given an object or a path to an object.""" try: - object, name = resolve(thing, forceload) - desc = describe(object) - module = inspect.getmodule(object) - if name and '.' in name: - desc += ' in ' + name[:name.rfind('.')] - elif module and module is not object: - desc += ' in module ' + module.__name__ - elif not (inspect.ismodule(object) or - inspect.isclass(object) or - inspect.isroutine(object) or - inspect.isgetsetdescriptor(object) or - inspect.ismemberdescriptor(object) or - isinstance(object, property)): - # If the passed object is a piece of data or an instance, - # document its available methods instead of its value. - object = type(object) - desc += ' object' pager(render_doc(thing, title, forceload)) except (ImportError, ErrorDuringImport) as value: print(value) @@ -1983,9 +1963,8 @@ '#ffffff', '#7799ee') def bltinlink(name): return '%s' % (name, name) - names = filter(lambda x: x != '__main__', - sys.builtin_module_names) - contents = html.multicolumn(list(names), bltinlink) + names = [x for x in sys.builtin_module_names if x != '__main__'] + contents = html.multicolumn(names, bltinlink) indices = ['

' + html.bigsection( 'Built-in Modules', '#ffffff', '#ee77aa', contents)] Modified: python/branches/py3k-ctypes-pep3118/Lib/random.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/random.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/random.py Wed Apr 30 15:57:13 2008 @@ -13,6 +13,7 @@ distributions on the real line: ------------------------------ uniform + triangular normal (Gaussian) lognormal negative exponential @@ -35,6 +36,7 @@ """ +from __future__ import division from warnings import warn as _warn from types import MethodType as _MethodType, BuiltinMethodType as _BuiltinMethodType from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil @@ -44,7 +46,7 @@ __all__ = ["Random","seed","random","uniform","randint","choice","sample", "randrange","shuffle","normalvariate","lognormvariate", - "expovariate","vonmisesvariate","gammavariate", + "expovariate","vonmisesvariate","gammavariate","triangular", "gauss","betavariate","paretovariate","weibullvariate", "getstate","setstate", "getrandbits", "SystemRandom"] @@ -333,6 +335,25 @@ """Get a random number in the range [a, b).""" return a + (b-a) * self.random() +## -------------------- triangular -------------------- + + def triangular(self, low=0.0, high=1.0, mode=None): + """Triangular distribution. + + Continuous distribution bounded by given lower and upper limits, + and having a given mode value in-between. + + http://en.wikipedia.org/wiki/Triangular_distribution + + """ + u = self.random() + c = 0.5 if mode is None else (mode - low) / (high - low) + if u > c: + u = 1.0 - u + c = 1.0 - c + low, high = high, low + return low + (high - low) * (u * c) ** 0.5 + ## -------------------- normal distribution -------------------- def normalvariate(self, mu, sigma): @@ -671,6 +692,7 @@ _test_generator(N, gammavariate, (200.0, 1.0)) _test_generator(N, gauss, (0.0, 1.0)) _test_generator(N, betavariate, (3.0, 3.0)) + _test_generator(N, triangular, (0.0, 1.0, 1.0/3.0)) # Create one instance, seeded from current time, and export its methods # as module-level functions. The functions share state across all uses @@ -682,6 +704,7 @@ seed = _inst.seed random = _inst.random uniform = _inst.uniform +triangular = _inst.triangular randint = _inst.randint choice = _inst.choice randrange = _inst.randrange Deleted: python/branches/py3k-ctypes-pep3118/Lib/rational.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/rational.py Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,507 +0,0 @@ -# Originally contributed by Sjoerd Mullender. -# Significantly modified by Jeffrey Yasskin . - -"""Rational, infinite-precision, real numbers.""" - -import math -import numbers -import operator -import re - -__all__ = ["Rational"] - -RationalAbc = numbers.Rational - - -def _gcd(a, b): # XXX This is a useful function. Consider making it public. - """Calculate the Greatest Common Divisor. - - Unless b==0, the result will have the same sign as b (so that when - b is divided by it, the result comes out positive). - """ - while b: - a, b = b, a%b - return a - - -def _binary_float_to_ratio(x): - """x -> (top, bot), a pair of ints s.t. x = top/bot. - - The conversion is done exactly, without rounding. - bot > 0 guaranteed. - Some form of binary fp is assumed. - Pass NaNs or infinities at your own risk. - - >>> _binary_float_to_ratio(10.0) - (10, 1) - >>> _binary_float_to_ratio(0.0) - (0, 1) - >>> _binary_float_to_ratio(-.25) - (-1, 4) - """ - # XXX Consider moving this to to floatobject.c - # with a name like float.as_intger_ratio() - - if x == 0: - return 0, 1 - f, e = math.frexp(x) - signbit = 1 - if f < 0: - f = -f - signbit = -1 - assert 0.5 <= f < 1.0 - # x = signbit * f * 2**e exactly - - # Suck up CHUNK bits at a time; 28 is enough so that we suck - # up all bits in 2 iterations for all known binary double- - # precision formats, and small enough to fit in an int. - CHUNK = 28 - top = 0 - # invariant: x = signbit * (top + f) * 2**e exactly - while f: - f = math.ldexp(f, CHUNK) - digit = trunc(f) - assert digit >> CHUNK == 0 - top = (top << CHUNK) | digit - f = f - digit - assert 0.0 <= f < 1.0 - e = e - CHUNK - assert top - - # Add in the sign bit. - top = signbit * top - - # now x = top * 2**e exactly; fold in 2**e - if e>0: - return (top * 2**e, 1) - else: - return (top, 2 ** -e) - - -_RATIONAL_FORMAT = re.compile( - r'^\s*(?P[-+]?)(?P\d+)(?:/(?P\d+))?\s*$') - -# XXX Consider accepting decimal strings as input since they are exact. -# Rational("2.01") --> s="2.01" ; Rational.from_decimal(Decimal(s)) --> Rational(201, 100)" -# If you want to avoid going through the decimal module, just parse the string directly: -# s.partition('.') --> ('2', '.', '01') --> Rational(int('2'+'01'), 10**len('01')) --> Rational(201, 100) - -class Rational(RationalAbc): - """This class implements rational numbers. - - Rational(8, 6) will produce a rational number equivalent to - 4/3. Both arguments must be Integral. The numerator defaults to 0 - and the denominator defaults to 1 so that Rational(3) == 3 and - Rational() == 0. - - Rationals can also be constructed from strings of the form - '[-+]?[0-9]+(/[0-9]+)?', optionally surrounded by spaces. - - """ - - __slots__ = ('numerator', 'denominator') - - # We're immutable, so use __new__ not __init__ - def __new__(cls, numerator=0, denominator=1): - """Constructs a Rational. - - Takes a string, another Rational, or a numerator/denominator pair. - - """ - self = super(Rational, cls).__new__(cls) - - if denominator == 1: - if isinstance(numerator, str): - # Handle construction from strings. - input = numerator - m = _RATIONAL_FORMAT.match(input) - if m is None: - raise ValueError('Invalid literal for Rational: ' + input) - numerator = int(m.group('num')) - # Default denominator to 1. That's the only optional group. - denominator = int(m.group('denom') or 1) - if m.group('sign') == '-': - numerator = -numerator - - elif (not isinstance(numerator, numbers.Integral) and - isinstance(numerator, RationalAbc)): - # Handle copies from other rationals. - other_rational = numerator - numerator = other_rational.numerator - denominator = other_rational.denominator - - if (not isinstance(numerator, numbers.Integral) or - not isinstance(denominator, numbers.Integral)): - raise TypeError("Rational(%(numerator)s, %(denominator)s):" - " Both arguments must be integral." % locals()) - - if denominator == 0: - raise ZeroDivisionError('Rational(%s, 0)' % numerator) - - g = _gcd(numerator, denominator) - self.numerator = int(numerator // g) - self.denominator = int(denominator // g) - return self - - @classmethod - def from_float(cls, f): - """Converts a finite float to a rational number, exactly. - - Beware that Rational.from_float(0.3) != Rational(3, 10). - - """ - if not isinstance(f, float): - raise TypeError("%s.from_float() only takes floats, not %r (%s)" % - (cls.__name__, f, type(f).__name__)) - if math.isnan(f) or math.isinf(f): - raise TypeError("Cannot convert %r to %s." % (f, cls.__name__)) - return cls(*_binary_float_to_ratio(f)) - - @classmethod - def from_decimal(cls, dec): - """Converts a finite Decimal instance to a rational number, exactly.""" - from decimal import Decimal - if not isinstance(dec, Decimal): - raise TypeError( - "%s.from_decimal() only takes Decimals, not %r (%s)" % - (cls.__name__, dec, type(dec).__name__)) - if not dec.is_finite(): - # Catches infinities and nans. - raise TypeError("Cannot convert %s to %s." % (dec, cls.__name__)) - sign, digits, exp = dec.as_tuple() - digits = int(''.join(map(str, digits))) - if sign: - digits = -digits - if exp >= 0: - return cls(digits * 10 ** exp) - else: - return cls(digits, 10 ** -exp) - - @classmethod - def from_continued_fraction(cls, seq): - 'Build a Rational from a continued fraction expessed as a sequence' - n, d = 1, 0 - for e in reversed(seq): - n, d = d, n - n += e * d - return cls(n, d) if seq else cls(0) - - def as_continued_fraction(self): - 'Return continued fraction expressed as a list' - n = self.numerator - d = self.denominator - cf = [] - while d: - e = int(n // d) - cf.append(e) - n -= e * d - n, d = d, n - return cf - - def approximate(self, max_denominator): - 'Best rational approximation with a denominator <= max_denominator' - # XXX First cut at algorithm - # Still needs rounding rules as specified at - # http://en.wikipedia.org/wiki/Continued_fraction - if self.denominator <= max_denominator: - return self - cf = self.as_continued_fraction() - result = Rational(0) - for i in range(1, len(cf)): - new = self.from_continued_fraction(cf[:i]) - if new.denominator > max_denominator: - break - result = new - return result - - def __repr__(self): - """repr(self)""" - return ('Rational(%r,%r)' % (self.numerator, self.denominator)) - - def __str__(self): - """str(self)""" - if self.denominator == 1: - return str(self.numerator) - else: - return '%s/%s' % (self.numerator, self.denominator) - - """ XXX This section needs a lot more commentary - - * Explain the typical sequence of checks, calls, and fallbacks. - * Explain the subtle reasons why this logic was needed. - * It is not clear how common cases are handled (for example, how - does the ratio of two huge integers get converted to a float - without overflowing the long-->float conversion. - - """ - - def _operator_fallbacks(monomorphic_operator, fallback_operator): - """Generates forward and reverse operators given a purely-rational - operator and a function from the operator module. - - Use this like: - __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) - - """ - def forward(a, b): - if isinstance(b, RationalAbc): - # Includes ints. - return monomorphic_operator(a, b) - elif isinstance(b, float): - return fallback_operator(float(a), b) - elif isinstance(b, complex): - return fallback_operator(complex(a), b) - else: - return NotImplemented - forward.__name__ = '__' + fallback_operator.__name__ + '__' - forward.__doc__ = monomorphic_operator.__doc__ - - def reverse(b, a): - if isinstance(a, RationalAbc): - # Includes ints. - return monomorphic_operator(a, b) - elif isinstance(a, numbers.Real): - return fallback_operator(float(a), float(b)) - elif isinstance(a, numbers.Complex): - return fallback_operator(complex(a), complex(b)) - else: - return NotImplemented - reverse.__name__ = '__r' + fallback_operator.__name__ + '__' - reverse.__doc__ = monomorphic_operator.__doc__ - - return forward, reverse - - def _add(a, b): - """a + b""" - return Rational(a.numerator * b.denominator + - b.numerator * a.denominator, - a.denominator * b.denominator) - - __add__, __radd__ = _operator_fallbacks(_add, operator.add) - - def _sub(a, b): - """a - b""" - return Rational(a.numerator * b.denominator - - b.numerator * a.denominator, - a.denominator * b.denominator) - - __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) - - def _mul(a, b): - """a * b""" - return Rational(a.numerator * b.numerator, a.denominator * b.denominator) - - __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) - - def _div(a, b): - """a / b""" - return Rational(a.numerator * b.denominator, - a.denominator * b.numerator) - - __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) - - def __floordiv__(a, b): - """a // b""" - return math.floor(a / b) - - def __rfloordiv__(b, a): - """a // b""" - return math.floor(a / b) - - def __mod__(a, b): - """a % b""" - div = a // b - return a - b * div - - def __rmod__(b, a): - """a % b""" - div = a // b - return a - b * div - - def __pow__(a, b): - """a ** b - - If b is not an integer, the result will be a float or complex - since roots are generally irrational. If b is an integer, the - result will be rational. - - """ - if isinstance(b, RationalAbc): - if b.denominator == 1: - power = b.numerator - if power >= 0: - return Rational(a.numerator ** power, - a.denominator ** power) - else: - return Rational(a.denominator ** -power, - a.numerator ** -power) - else: - # A fractional power will generally produce an - # irrational number. - return float(a) ** float(b) - else: - return float(a) ** b - - def __rpow__(b, a): - """a ** b""" - if b.denominator == 1 and b.numerator >= 0: - # If a is an int, keep it that way if possible. - return a ** b.numerator - - if isinstance(a, RationalAbc): - return Rational(a.numerator, a.denominator) ** b - - if b.denominator == 1: - return a ** b.numerator - - return a ** float(b) - - def __pos__(a): - """+a: Coerces a subclass instance to Rational""" - return Rational(a.numerator, a.denominator) - - def __neg__(a): - """-a""" - return Rational(-a.numerator, a.denominator) - - def __abs__(a): - """abs(a)""" - return Rational(abs(a.numerator), a.denominator) - - def __trunc__(a): - """trunc(a)""" - if a.numerator < 0: - return -(-a.numerator // a.denominator) - else: - return a.numerator // a.denominator - - __int__ = __trunc__ - - def __floor__(a): - """Will be math.floor(a) in 3.0.""" - return a.numerator // a.denominator - - def __ceil__(a): - """Will be math.ceil(a) in 3.0.""" - # The negations cleverly convince floordiv to return the ceiling. - return -(-a.numerator // a.denominator) - - def __round__(self, ndigits=None): - """Will be round(self, ndigits) in 3.0. - - Rounds half toward even. - """ - if ndigits is None: - floor, remainder = divmod(self.numerator, self.denominator) - if remainder * 2 < self.denominator: - return floor - elif remainder * 2 > self.denominator: - return floor + 1 - # Deal with the half case: - elif floor % 2 == 0: - return floor - else: - return floor + 1 - shift = 10**abs(ndigits) - # See _operator_fallbacks.forward to check that the results of - # these operations will always be Rational and therefore have - # round(). - if ndigits > 0: - return Rational(round(self * shift), shift) - else: - return Rational(round(self / shift) * shift) - - def __hash__(self): - """hash(self) - - Tricky because values that are exactly representable as a - float must have the same hash as that float. - - """ - # XXX since this method is expensive, consider caching the result - if self.denominator == 1: - # Get integers right. - return hash(self.numerator) - # Expensive check, but definitely correct. - if self == float(self): - return hash(float(self)) - else: - # Use tuple's hash to avoid a high collision rate on - # simple fractions. - return hash((self.numerator, self.denominator)) - - def __eq__(a, b): - """a == b""" - if isinstance(b, RationalAbc): - return (a.numerator == b.numerator and - a.denominator == b.denominator) - if isinstance(b, numbers.Complex) and b.imag == 0: - b = b.real - if isinstance(b, float): - return a == a.from_float(b) - else: - # XXX: If b.__eq__ is implemented like this method, it may - # give the wrong answer after float(a) changes a's - # value. Better ways of doing this are welcome. - return float(a) == b - - def _subtractAndCompareToZero(a, b, op): - """Helper function for comparison operators. - - Subtracts b from a, exactly if possible, and compares the - result with 0 using op, in such a way that the comparison - won't recurse. If the difference raises a TypeError, returns - NotImplemented instead. - - """ - if isinstance(b, numbers.Complex) and b.imag == 0: - b = b.real - if isinstance(b, float): - b = a.from_float(b) - try: - # XXX: If b <: Real but not <: RationalAbc, this is likely - # to fall back to a float. If the actual values differ by - # less than MIN_FLOAT, this could falsely call them equal, - # which would make <= inconsistent with ==. Better ways of - # doing this are welcome. - diff = a - b - except TypeError: - return NotImplemented - if isinstance(diff, RationalAbc): - return op(diff.numerator, 0) - return op(diff, 0) - - def __lt__(a, b): - """a < b""" - return a._subtractAndCompareToZero(b, operator.lt) - - def __gt__(a, b): - """a > b""" - return a._subtractAndCompareToZero(b, operator.gt) - - def __le__(a, b): - """a <= b""" - return a._subtractAndCompareToZero(b, operator.le) - - def __ge__(a, b): - """a >= b""" - return a._subtractAndCompareToZero(b, operator.ge) - - def __bool__(a): - """a != 0""" - return a.numerator != 0 - - # support for pickling, copy, and deepcopy - - def __reduce__(self): - return (self.__class__, (str(self),)) - - def __copy__(self): - if type(self) == Rational: - return self # I'm immutable; therefore I am my own clone - return self.__class__(self.numerator, self.denominator) - - def __deepcopy__(self, memo): - if type(self) == Rational: - return self # My components are also immutable - return self.__class__(self.numerator, self.denominator) Modified: python/branches/py3k-ctypes-pep3118/Lib/re.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/re.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/re.py Wed Apr 30 15:57:13 2008 @@ -38,7 +38,7 @@ *?,+?,?? Non-greedy versions of the previous three special characters. {m,n} Matches from m to n repetitions of the preceding RE. {m,n}? Non-greedy version of the above. - "\\" Either escapes special characters or signals a special sequence. + "\\" Either escapes special characters or signals a special sequence. [] Indicates a set of characters. A "^" as the first character indicates a complementing set. "|" A|B, creates an RE that will match either A or B. @@ -51,6 +51,10 @@ (?#...) A comment; ignored. (?=...) Matches if ... matches next, but doesn't consume the string. (?!...) Matches if ... doesn't match next. + (?<=...) Matches if preceded by ... (must be fixed length). + (? 0: print('connect:', (host, port), file=stderr) - return socket.create_connection((port, host), timeout) + return socket.create_connection((host, port), timeout) def connect(self, host='localhost', port = 0): """Connect to a host on a given port. @@ -298,7 +299,7 @@ def send(self, s): """Send `s' to the server.""" if self.debuglevel > 0: print('send:', repr(s), file=stderr) - if self.sock: + if hasattr(self, 'sock') and self.sock: if isinstance(s, str): s = s.encode("ascii") try: @@ -489,7 +490,7 @@ vrfy=verify def expn(self, address): - """SMTP 'verify' command -- checks for address validity.""" + """SMTP 'expn' command -- expands a mailing list.""" self.putcmd("expn", quoteaddr(address)) return self.getreply() @@ -728,8 +729,9 @@ def quit(self): """Terminate the SMTP session.""" - self.docmd("quit") + res = self.docmd("quit") self.close() + return res if _have_ssl: Modified: python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/dbapi.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/dbapi.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/dbapi.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,7 @@ #-*- coding: ISO-8859-1 -*- # pysqlite2/test/dbapi.py: tests for DB-API compliance # -# Copyright (C) 2004-2005 Gerhard H?ring +# Copyright (C) 2004-2007 Gerhard H?ring # # This file is part of pysqlite. # @@ -223,12 +223,41 @@ except sqlite.ProgrammingError: pass + def CheckExecuteParamList(self): + self.cu.execute("insert into test(name) values ('foo')") + self.cu.execute("select name from test where name=?", ["foo"]) + row = self.cu.fetchone() + self.failUnlessEqual(row[0], "foo") + + def CheckExecuteParamSequence(self): + class L(object): + def __len__(self): + return 1 + def __getitem__(self, x): + assert x == 0 + return "foo" + + self.cu.execute("insert into test(name) values ('foo')") + self.cu.execute("select name from test where name=?", L()) + row = self.cu.fetchone() + self.failUnlessEqual(row[0], "foo") + def CheckExecuteDictMapping(self): self.cu.execute("insert into test(name) values ('foo')") self.cu.execute("select name from test where name=:name", {"name": "foo"}) row = self.cu.fetchone() self.failUnlessEqual(row[0], "foo") + def CheckExecuteDictMapping_Mapping(self): + class D(dict): + def __missing__(self, key): + return "foo" + + self.cu.execute("insert into test(name) values ('foo')") + self.cu.execute("select name from test where name=:name", D()) + row = self.cu.fetchone() + self.failUnlessEqual(row[0], "foo") + def CheckExecuteDictMappingTooLittleArgs(self): self.cu.execute("insert into test(name) values ('foo')") try: @@ -378,6 +407,12 @@ res = self.cu.fetchmany(100) self.failUnlessEqual(res, []) + def CheckFetchmanyKwArg(self): + """Checks if fetchmany works with keyword arguments""" + self.cu.execute("select name from test") + res = self.cu.fetchmany(size=100) + self.failUnlessEqual(len(res), 1) + def CheckFetchall(self): self.cu.execute("select name from test") res = self.cu.fetchall() @@ -609,20 +644,6 @@ res = cur.fetchone()[0] self.failUnlessEqual(res, 5) - def CheckScriptStringUnicode(self): - con = sqlite.connect(":memory:") - cur = con.cursor() - cur.executescript(""" - create table a(i); - insert into a(i) values (5); - select i from a; - delete from a; - insert into a(i) values (6); - """) - cur.execute("select i from a") - res = cur.fetchone()[0] - self.failUnlessEqual(res, 6) - def CheckScriptErrorIncomplete(self): con = sqlite.connect(":memory:") cur = con.cursor() Modified: python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/factory.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/factory.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/factory.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,7 @@ #-*- coding: ISO-8859-1 -*- # pysqlite2/test/factory.py: tests for the various factories in pysqlite # -# Copyright (C) 2005 Gerhard H?ring +# Copyright (C) 2005-2007 Gerhard H?ring # # This file is part of pysqlite. # Modified: python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/hooks.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/hooks.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/hooks.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,7 @@ #-*- coding: ISO-8859-1 -*- # pysqlite2/test/hooks.py: tests for various SQLite-specific hooks # -# Copyright (C) 2006 Gerhard H?ring +# Copyright (C) 2006-2007 Gerhard H?ring # # This file is part of pysqlite. # @@ -21,7 +21,7 @@ # misrepresented as being the original software. # 3. This notice may not be removed or altered from any source distribution. -import os, unittest +import unittest import sqlite3 as sqlite class CollationTests(unittest.TestCase): @@ -105,9 +105,80 @@ if not e.args[0].startswith("no such collation sequence"): self.fail("wrong OperationalError raised") +class ProgressTests(unittest.TestCase): + def CheckProgressHandlerUsed(self): + """ + Test that the progress handler is invoked once it is set. + """ + con = sqlite.connect(":memory:") + progress_calls = [] + def progress(): + progress_calls.append(None) + return 0 + con.set_progress_handler(progress, 1) + con.execute(""" + create table foo(a, b) + """) + self.failUnless(progress_calls) + + + def CheckOpcodeCount(self): + """ + Test that the opcode argument is respected. + """ + con = sqlite.connect(":memory:") + progress_calls = [] + def progress(): + progress_calls.append(None) + return 0 + con.set_progress_handler(progress, 1) + curs = con.cursor() + curs.execute(""" + create table foo (a, b) + """) + first_count = len(progress_calls) + progress_calls = [] + con.set_progress_handler(progress, 2) + curs.execute(""" + create table bar (a, b) + """) + second_count = len(progress_calls) + self.failUnless(first_count > second_count) + + def CheckCancelOperation(self): + """ + Test that returning a non-zero value stops the operation in progress. + """ + con = sqlite.connect(":memory:") + progress_calls = [] + def progress(): + progress_calls.append(None) + return 1 + con.set_progress_handler(progress, 1) + curs = con.cursor() + self.assertRaises( + sqlite.OperationalError, + curs.execute, + "create table bar (a, b)") + + def CheckClearHandler(self): + """ + Test that setting the progress handler to None clears the previously set handler. + """ + con = sqlite.connect(":memory:") + action = 0 + def progress(): + action = 1 + return 0 + con.set_progress_handler(progress, 1) + con.set_progress_handler(None, 1) + con.execute("select 1 union select 2 union select 3").fetchall() + self.failUnlessEqual(action, 0, "progress handler was not cleared") + def suite(): collation_suite = unittest.makeSuite(CollationTests, "Check") - return unittest.TestSuite((collation_suite,)) + progress_suite = unittest.makeSuite(ProgressTests, "Check") + return unittest.TestSuite((collation_suite, progress_suite)) def test(): runner = unittest.TextTestRunner() Modified: python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/regression.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/regression.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/regression.py Wed Apr 30 15:57:13 2008 @@ -21,6 +21,7 @@ # misrepresented as being the original software. # 3. This notice may not be removed or altered from any source distribution. +import datetime import unittest import sqlite3 as sqlite @@ -79,6 +80,81 @@ cur.fetchone() cur.fetchone() + def CheckStatementFinalizationOnCloseDb(self): + # pysqlite versions <= 2.3.3 only finalized statements in the statement + # cache when closing the database. statements that were still + # referenced in cursors weren't closed an could provoke " + # "OperationalError: Unable to close due to unfinalised statements". + con = sqlite.connect(":memory:") + cursors = [] + # default statement cache size is 100 + for i in range(105): + cur = con.cursor() + cursors.append(cur) + cur.execute("select 1 x union select " + str(i)) + con.close() + + def CheckOnConflictRollback(self): + if sqlite.sqlite_version_info < (3, 2, 2): + return + con = sqlite.connect(":memory:") + con.execute("create table foo(x, unique(x) on conflict rollback)") + con.execute("insert into foo(x) values (1)") + try: + con.execute("insert into foo(x) values (1)") + except sqlite.DatabaseError: + pass + con.execute("insert into foo(x) values (2)") + try: + con.commit() + except sqlite.OperationalError: + self.fail("pysqlite knew nothing about the implicit ROLLBACK") + + def CheckWorkaroundForBuggySqliteTransferBindings(self): + """ + pysqlite would crash with older SQLite versions unless + a workaround is implemented. + """ + self.con.execute("create table foo(bar)") + self.con.execute("drop table foo") + self.con.execute("create table foo(bar)") + + def CheckEmptyStatement(self): + """ + pysqlite used to segfault with SQLite versions 3.5.x. These return NULL + for "no-operation" statements + """ + self.con.execute("") + + def CheckTypeMapUsage(self): + """ + pysqlite until 2.4.1 did not rebuild the row_cast_map when recompiling + a statement. This test exhibits the problem. + """ + SELECT = "select * from foo" + con = sqlite.connect(":memory:",detect_types=sqlite.PARSE_DECLTYPES) + con.execute("create table foo(bar timestamp)") + con.execute("insert into foo(bar) values (?)", (datetime.datetime.now(),)) + con.execute(SELECT) + con.execute("drop table foo") + con.execute("create table foo(bar integer)") + con.execute("insert into foo(bar) values (5)") + con.execute(SELECT) + + def CheckErrorMsgDecodeError(self): + # When porting the module to Python 3.0, the error message about + # decoding errors disappeared. This verifies they're back again. + failure = None + try: + self.con.execute("select 'xxx' || ? || 'yyy' colname", (bytes(bytearray([250])),)).fetchone() + failure = "should have raised an OperationalError with detailed description" + except sqlite.OperationalError as e: + msg = e.args[0] + if not msg.startswith("Could not decode to UTF-8 column 'colname' with text 'xxx"): + failure = "OperationalError did not have expected description text" + if failure: + self.fail(failure) + def suite(): regression_suite = unittest.makeSuite(RegressionTests, "Check") return unittest.TestSuite((regression_suite,)) Modified: python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/transactions.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/transactions.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/transactions.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,7 @@ #-*- coding: ISO-8859-1 -*- # pysqlite2/test/transactions.py: tests transactions # -# Copyright (C) 2005 Gerhard H?ring +# Copyright (C) 2005-2007 Gerhard H?ring # # This file is part of pysqlite. # @@ -31,7 +31,7 @@ def setUp(self): try: os.remove(get_db_path()) - except: + except OSError: pass self.con1 = sqlite.connect(get_db_path(), timeout=0.1) @@ -47,7 +47,10 @@ self.cur2.close() self.con2.close() - os.unlink(get_db_path()) + try: + os.unlink(get_db_path()) + except OSError: + pass def CheckDMLdoesAutoCommitBefore(self): self.cur1.execute("create table test(i)") @@ -109,6 +112,29 @@ self.failUnlessEqual(len(res), 1) def CheckRaiseTimeout(self): + if sqlite.sqlite_version_info < (3, 2, 2): + # This will fail (hang) on earlier versions of sqlite. + # Determine exact version it was fixed. 3.2.1 hangs. + return + self.cur1.execute("create table test(i)") + self.cur1.execute("insert into test(i) values (5)") + try: + self.cur2.execute("insert into test(i) values (5)") + self.fail("should have raised an OperationalError") + except sqlite.OperationalError: + pass + except: + self.fail("should have raised an OperationalError") + + def CheckLocking(self): + """ + This tests the improved concurrency with pysqlite 2.3.4. You needed + to roll back con2 before you could commit con1. + """ + if sqlite.sqlite_version_info < (3, 2, 2): + # This will fail (hang) on earlier versions of sqlite. + # Determine exact version it was fixed. 3.2.1 hangs. + return self.cur1.execute("create table test(i)") self.cur1.execute("insert into test(i) values (5)") try: @@ -118,6 +144,8 @@ pass except: self.fail("should have raised an OperationalError") + # NO self.con2.rollback() HERE!!! + self.con1.commit() class SpecialCommandTests(unittest.TestCase): def setUp(self): Modified: python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/types.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/types.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/types.py Wed Apr 30 15:57:13 2008 @@ -21,7 +21,7 @@ # misrepresented as being the original software. # 3. This notice may not be removed or altered from any source distribution. -import bz2, datetime +import zlib, datetime import unittest import sqlite3 as sqlite @@ -221,11 +221,13 @@ self.cur = self.con.cursor() self.cur.execute("create table test(x foo)") - sqlite.converters["BAR"] = lambda x: b"<" + x + b">" + sqlite.converters["FOO"] = lambda x: "[%s]" % x.decode("ascii") + sqlite.converters["BAR"] = lambda x: "<%s>" % x.decode("ascii") sqlite.converters["EXC"] = lambda x: 5/0 sqlite.converters["B1B1"] = lambda x: "MARKER" def tearDown(self): + del sqlite.converters["FOO"] del sqlite.converters["BAR"] del sqlite.converters["EXC"] del sqlite.converters["B1B1"] @@ -252,7 +254,7 @@ self.cur.execute("insert into test(x) values (?)", ("xxx",)) self.cur.execute('select x as "x [bar]" from test') val = self.cur.fetchone()[0] - self.failUnlessEqual(val, b"") + self.failUnlessEqual(val, "") # Check if the stripping of colnames works. Everything after the first # whitespace should be stripped. @@ -297,7 +299,7 @@ class BinaryConverterTests(unittest.TestCase): def convert(s): - return bz2.decompress(s) + return zlib.decompress(s) convert = staticmethod(convert) def setUp(self): @@ -309,7 +311,7 @@ def CheckBinaryInputForConverter(self): testdata = b"abcdefg" * 10 - result = self.con.execute('select ? as "x [bin]"', (memoryview(bz2.compress(testdata)),)).fetchone()[0] + result = self.con.execute('select ? as "x [bin]"', (memoryview(zlib.compress(testdata)),)).fetchone()[0] self.failUnlessEqual(testdata, result) class DateTimeTests(unittest.TestCase): @@ -341,7 +343,8 @@ if sqlite.sqlite_version_info < (3, 1): return - now = datetime.datetime.utcnow() + # SQLite's current_timestamp uses UTC time, while datetime.datetime.now() uses local time. + now = datetime.datetime.now() self.cur.execute("insert into test(ts) values (current_timestamp)") self.cur.execute("select ts from test") ts = self.cur.fetchone()[0] Modified: python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/userfunctions.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/userfunctions.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/sqlite3/test/userfunctions.py Wed Apr 30 15:57:13 2008 @@ -2,7 +2,7 @@ # pysqlite2/test/userfunctions.py: tests for user-defined functions and # aggregates. # -# Copyright (C) 2005 Gerhard H?ring +# Copyright (C) 2005-2007 Gerhard H?ring # # This file is part of pysqlite. # Modified: python/branches/py3k-ctypes-pep3118/Lib/sre_compile.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/sre_compile.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/sre_compile.py Wed Apr 30 15:57:13 2008 @@ -11,7 +11,7 @@ """Internal support module for sre""" import _sre, sys - +import sre_parse from sre_constants import * assert _sre.MAGIC == MAGIC, "SRE module mismatch" @@ -472,7 +472,7 @@ code[skip] = len(code) - skip def isstring(obj): - return isinstance(obj, str) + return isinstance(obj, (str, bytes)) def _code(p, flags): @@ -493,7 +493,6 @@ # internal: convert pattern list to internal format if isstring(p): - import sre_parse pattern = p p = sre_parse.parse(p, flags) else: Modified: python/branches/py3k-ctypes-pep3118/Lib/sre_parse.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/sre_parse.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/sre_parse.py Wed Apr 30 15:57:13 2008 @@ -192,8 +192,8 @@ char = self.string[self.index:self.index+1] # Special case for the str8, since indexing returns a integer # XXX This is only needed for test_bug_926075 in test_re.py - if isinstance(self.string, bytes): - char = chr(char) + if char and isinstance(char, bytes): + char = chr(char[0]) if char == "\\": try: c = self.string[self.index + 1] Modified: python/branches/py3k-ctypes-pep3118/Lib/ssl.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/ssl.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/ssl.py Wed Apr 30 15:57:13 2008 @@ -54,7 +54,7 @@ PROTOCOL_TLSv1 """ -import os, sys, textwrap +import textwrap import _ssl # if we can't import it, let the error propagate Modified: python/branches/py3k-ctypes-pep3118/Lib/stat.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/stat.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/stat.py Wed Apr 30 15:57:13 2008 @@ -3,12 +3,7 @@ Suggested usage: from stat import * """ -# XXX Strictly spoken, this module may have to be adapted for each POSIX -# implementation; in practice, however, the numeric constants used by -# stat() are almost universal (even for stat() emulations on non-UNIX -# systems like MS-DOS). - -# Indices for stat struct members in tuple returned by os.stat() +# Indices for stat struct members in the tuple returned by os.stat() ST_MODE = 0 ST_INO = 1 Modified: python/branches/py3k-ctypes-pep3118/Lib/subprocess.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/subprocess.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/subprocess.py Wed Apr 30 15:57:13 2008 @@ -290,6 +290,7 @@ import os import traceback import gc +import signal # Exception classes used by this module. class CalledProcessError(Exception): @@ -317,6 +318,7 @@ from win32process import CreateProcess, STARTUPINFO, \ GetExitCodeProcess, STARTF_USESTDHANDLES, \ STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE + from win32process import TerminateProcess from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0 else: from _subprocess import * @@ -828,6 +830,21 @@ self.wait() return (stdout, stderr) + def send_signal(self, sig): + """Send a signal to the process + """ + if sig == signal.SIGTERM: + self.terminate() + else: + raise ValueError("Only SIGTERM is supported on Windows") + + def terminate(self): + """Terminates the process + """ + TerminateProcess(self._handle, 1) + + kill = terminate + else: # # POSIX methods @@ -1115,6 +1132,21 @@ self.wait() return (stdout, stderr) + def send_signal(self, sig): + """Send a signal to the process + """ + os.kill(self.pid, sig) + + def terminate(self): + """Terminate the process with SIGTERM + """ + self.send_signal(signal.SIGTERM) + + def kill(self): + """Kill the process with SIGKILL + """ + self.send_signal(signal.SIGKILL) + def _demo_posix(): # Modified: python/branches/py3k-ctypes-pep3118/Lib/tarfile.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/tarfile.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/tarfile.py Wed Apr 30 15:57:13 2008 @@ -767,7 +767,7 @@ self.fileobj = _FileInFile(tarfile.fileobj, tarinfo.offset_data, tarinfo.size, - getattr(tarinfo, "sparse", None)) + tarinfo.sparse) self.name = tarinfo.name self.mode = "r" self.closed = False @@ -906,6 +906,12 @@ usually created internally. """ + __slots__ = ("name", "mode", "uid", "gid", "size", "mtime", + "chksum", "type", "linkname", "uname", "gname", + "devmajor", "devminor", + "offset", "offset_data", "pax_headers", "sparse", + "tarfile", "_sparse_structs", "_link_target") + def __init__(self, name=""): """Construct a TarInfo object. name is the optional name of the member. @@ -927,6 +933,7 @@ self.offset = 0 # the tar header starts here self.offset_data = 0 # the file's data starts here + self.sparse = None # sparse member information self.pax_headers = {} # pax header information # In pax headers the "name" and "linkname" field are called @@ -1181,7 +1188,6 @@ raise HeaderError("bad checksum") obj = cls() - obj.buf = buf obj.name = nts(buf[0:100], encoding, errors) obj.mode = nti(buf[100:108]) obj.uid = nti(buf[108:116]) @@ -1202,6 +1208,24 @@ if obj.type == AREGTYPE and obj.name.endswith("/"): obj.type = DIRTYPE + # The old GNU sparse format occupies some of the unused + # space in the buffer for up to 4 sparse structures. + # Save the them for later processing in _proc_sparse(). + if obj.type == GNUTYPE_SPARSE: + pos = 386 + structs = [] + for i in range(4): + try: + offset = nti(buf[pos:pos + 12]) + numbytes = nti(buf[pos + 12:pos + 24]) + except ValueError: + break + structs.append((offset, numbytes)) + pos += 24 + isextended = bool(buf[482]) + origsize = nti(buf[483:495]) + obj._sparse_structs = (structs, isextended, origsize) + # Remove redundant slashes from directories. if obj.isdir(): obj.name = obj.name.rstrip("/") @@ -1288,31 +1312,11 @@ def _proc_sparse(self, tarfile): """Process a GNU sparse header plus extra headers. """ - buf = self.buf - sp = _ringbuffer() - pos = 386 - lastpos = 0 - realpos = 0 - # There are 4 possible sparse structs in the - # first header. - for i in range(4): - try: - offset = nti(buf[pos:pos + 12]) - numbytes = nti(buf[pos + 12:pos + 24]) - except ValueError: - break - if offset > lastpos: - sp.append(_hole(lastpos, offset - lastpos)) - sp.append(_data(offset, numbytes, realpos)) - realpos += numbytes - lastpos = offset + numbytes - pos += 24 + # We already collected some sparse structures in frombuf(). + structs, isextended, origsize = self._sparse_structs + del self._sparse_structs - isextended = bool(buf[482]) - origsize = nti(buf[483:495]) - - # If the isextended flag is given, - # there are extra headers to process. + # Collect sparse structures from extended header blocks. while isextended: buf = tarfile.fileobj.read(BLOCKSIZE) pos = 0 @@ -1322,18 +1326,23 @@ numbytes = nti(buf[pos + 12:pos + 24]) except ValueError: break - if offset > lastpos: - sp.append(_hole(lastpos, offset - lastpos)) - sp.append(_data(offset, numbytes, realpos)) - realpos += numbytes - lastpos = offset + numbytes + structs.append((offset, numbytes)) pos += 24 isextended = bool(buf[504]) + # Transform the sparse structures to something we can use + # in ExFileObject. + self.sparse = _ringbuffer() + lastpos = 0 + realpos = 0 + for offset, numbytes in structs: + if offset > lastpos: + self.sparse.append(_hole(lastpos, offset - lastpos)) + self.sparse.append(_data(offset, numbytes, realpos)) + realpos += numbytes + lastpos = offset + numbytes if lastpos < origsize: - sp.append(_hole(lastpos, origsize - lastpos)) - - self.sparse = sp + self.sparse.append(_hole(lastpos, origsize - lastpos)) self.offset_data = tarfile.fileobj.tell() tarfile.offset = self.offset_data + self._block(self.size) @@ -2005,18 +2014,14 @@ for tarinfo in members: if tarinfo.isdir(): - # Extract directory with a safe mode, so that - # all files below can be extracted as well. - try: - os.makedirs(os.path.join(path, tarinfo.name), 0o700) - except EnvironmentError: - pass + # Extract directories with a safe mode. directories.append(tarinfo) - else: - self.extract(tarinfo, path) + tarinfo = copy.copy(tarinfo) + tarinfo.mode = 0o700 + self.extract(tarinfo, path) # Reverse sort directories. - directories.sort(lambda a, b: cmp(a.name, b.name)) + directories.sort(key=lambda a: a.name) directories.reverse() # Set correct owner, mtime and filemode on directories. @@ -2118,6 +2123,8 @@ # Create all upper directories. upperdirs = os.path.dirname(targetpath) if upperdirs and not os.path.exists(upperdirs): + # Create directories that are not part of the archive with + # default permissions. os.makedirs(upperdirs) if tarinfo.islnk() or tarinfo.issym(): @@ -2154,7 +2161,9 @@ """Make a directory called targetpath. """ try: - os.mkdir(targetpath) + # Use a safe mode for the directory, the real mode is set + # later in _extract_member(). + os.mkdir(targetpath, 0o700) except EnvironmentError as e: if e.errno != errno.EEXIST: raise Modified: python/branches/py3k-ctypes-pep3118/Lib/tempfile.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/tempfile.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/tempfile.py Wed Apr 30 15:57:13 2008 @@ -363,6 +363,7 @@ raise IOError(_errno.EEXIST, "No usable temporary filename found") + class _TemporaryFileWrapper: """Temporary file wrapper @@ -378,17 +379,29 @@ self.delete = delete def __getattr__(self, name): + # Attribute lookups are delegated to the underlying file + # and cached for non-numeric results + # (i.e. methods are cached, closed and friends are not) file = self.__dict__['file'] a = getattr(file, name) - if type(a) != type(0): + if not isinstance(a, int): setattr(self, name, a) return a + # The underlying __enter__ method returns the wrong object + # (self.file) so override it to return the wrapper + def __enter__(self): + self.file.__enter__() + return self + + # iter() doesn't use __getattr__ to find the __iter__ method + def __iter__(self): + return iter(self.file) + # NT provides delete-on-close as a primitive, so we don't need # the wrapper to do anything special. We still use it so that # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile. if _os.name != 'nt': - # Cache the unlinker so we don't get spurious errors at # shutdown when the module-level "os" is None'd out. Note # that this must be referenced as self.unlink, because the @@ -406,6 +419,14 @@ def __del__(self): self.close() + # Need to trap __exit__ as well to ensure the file gets + # deleted when used in a with statement + def __exit__(self, exc, value, tb): + result = self.file.__exit__(exc, value, tb) + self.close() + return result + + def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix="", prefix=template, dir=None, delete=True): @@ -523,6 +544,20 @@ self._rolled = True + # The method caching trick from NamedTemporaryFile + # won't work here, because _file may change from a + # _StringIO instance to a real file. So we list + # all the methods directly. + + # Context management protocol + def __enter__(self): + if self._file.closed: + raise ValueError("Cannot enter context with closed file") + return self + + def __exit__(self, exc, value, tb): + self._file.close() + # file protocol def __iter__(self): return self._file.__iter__() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/cjkencodings_test.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/cjkencodings_test.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/cjkencodings_test.py Wed Apr 30 15:57:13 2008 @@ -64,8 +64,10 @@ b"\xab\x96\xe7\x9a\x84\xe5\x95\x8f\xe9\xa1\x8c\xe5\xb0\xb1\xe6\x98" b"\xaf\x3a\x0a\x0a"), 'big5hkscs': ( -b"\x88\x45\x88\x5c\x8a\x73\x8b\xda\x8d\xd8\x0a", -b"\xf0\xa0\x84\x8c\xc4\x9a\xe9\xb5\xae\xe7\xbd\x93\xe6\xb4\x86\x0a"), +b"\x88\x45\x88\x5c\x8a\x73\x8b\xda\x8d\xd8\x0a\x88\x66\x88\x62\x88" +b"\xa7\x20\x88\xa7\x88\xa3\x0a", +b"\xf0\xa0\x84\x8c\xc4\x9a\xe9\xb5\xae\xe7\xbd\x93\xe6\xb4\x86\x0a" +b"\xc3\x8a\xc3\x8a\xcc\x84\xc3\xaa\x20\xc3\xaa\xc3\xaa\xcc\x84\x0a"), 'cp949': ( b"\x8c\x63\xb9\xe6\xb0\xa2\xc7\xcf\x20\xbc\x84\xbd\xc3\xc4\xdd\xb6" b"\xf3\x0a\x0a\xa8\xc0\xa8\xc0\xb3\xb3\x21\x21\x20\xec\xd7\xce\xfa" Modified: python/branches/py3k-ctypes-pep3118/Lib/test/fork_wait.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/fork_wait.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/fork_wait.py Wed Apr 30 15:57:13 2008 @@ -10,7 +10,6 @@ """ import os, sys, time, thread, unittest -from test.test_support import TestSkipped LONGSLEEP = 2 SHORTSLEEP = 0.5 Modified: python/branches/py3k-ctypes-pep3118/Lib/test/list_tests.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/list_tests.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/list_tests.py Wed Apr 30 15:57:13 2008 @@ -5,9 +5,17 @@ import sys import os -import unittest from test import test_support, seq_tests +def CmpToKey(mycmp): + 'Convert a cmp= function into a key= function' + class K(object): + def __init__(self, obj): + self.obj = obj + def __lt__(self, other): + return mycmp(self.obj, other.obj) == -1 + return K + class CommonTest(seq_tests.CommonTest): def test_init(self): @@ -430,23 +438,21 @@ def revcmp(a, b): return cmp(b, a) - u.sort(revcmp) + u.sort(key=CmpToKey(revcmp)) self.assertEqual(u, self.type2test([2,1,0,-1,-2])) # The following dumps core in unpatched Python 1.5: def myComparison(x,y): return cmp(x%3, y%7) z = self.type2test(range(12)) - z.sort(myComparison) + z.sort(key=CmpToKey(myComparison)) self.assertRaises(TypeError, z.sort, 2) def selfmodifyingComparison(x,y): z.append(1) return cmp(x, y) - self.assertRaises(ValueError, z.sort, selfmodifyingComparison) - - self.assertRaises(TypeError, z.sort, lambda x, y: 's') + self.assertRaises(ValueError, z.sort, key=CmpToKey(selfmodifyingComparison)) self.assertRaises(TypeError, z.sort, 42, 42, 42, 42) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/mapping_tests.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/mapping_tests.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/mapping_tests.py Wed Apr 30 15:57:13 2008 @@ -1,6 +1,6 @@ # tests common to dict and UserDict import unittest -import UserDict +import collections class BasicTestMappingProtocol(unittest.TestCase): @@ -438,11 +438,11 @@ # self.assert_(type(dictlike.fromkeys('a')) is dictlike) class mydict(self.type2test): def __new__(cls): - return UserDict.UserDict() + return collections.UserDict() ud = mydict.fromkeys('ab') self.assertEqual(ud, {'a':None, 'b':None}) # FIXME: the following won't work with UserDict, because it's an old style class - # self.assert_(isinstance(ud, UserDict.UserDict)) + # self.assert_(isinstance(ud, collections.UserDict)) self.assertRaises(TypeError, dict.fromkeys) class Exc(Exception): pass @@ -574,10 +574,10 @@ TestMappingProtocol.test_fromkeys(self) class mydict(self.type2test): def __new__(cls): - return UserDict.UserDict() + return collections.UserDict() ud = mydict.fromkeys('ab') self.assertEqual(ud, {'a':None, 'b':None}) - self.assert_(isinstance(ud, UserDict.UserDict)) + self.assert_(isinstance(ud, collections.UserDict)) def test_pop(self): TestMappingProtocol.test_pop(self) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/outstanding_bugs.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/outstanding_bugs.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/outstanding_bugs.py Wed Apr 30 15:57:13 2008 @@ -13,38 +13,6 @@ # One test case for outstanding bugs at the moment: # -class TestDifflibLongestMatch(unittest.TestCase): - # From Patch #1678339: - # The find_longest_match method in the difflib's SequenceMatcher has a bug. - - # The bug is in turn caused by a problem with creating a b2j mapping which - # should contain a list of indices for each of the list elements in b. - # However, when the b2j mapping is being created (this is being done in - # __chain_b method in the SequenceMatcher) the mapping becomes broken. The - # cause of this is that for the frequently used elements the list of indices - # is removed and the element is being enlisted in the populardict mapping. - - # The test case tries to match two strings like: - # abbbbbb.... and ...bbbbbbc - - # The number of b is equal and the find_longest_match should have returned - # the proper amount. However, in case the number of "b"s is large enough, the - # method reports that the length of the longest common substring is 0. It - # simply can't find it. - - # A bug was raised some time ago on this matter. It's ID is 1528074. - - def test_find_longest_match(self): - import difflib - for i in (190, 200, 210): - text1 = "a" + "b"*i - text2 = "b"*i + "c" - m = difflib.SequenceMatcher(None, text1, text2) - (aptr, bptr, l) = m.find_longest_match(0, len(text1), 0, len(text2)) - self.assertEquals(i, l) - self.assertEquals(aptr, 1) - self.assertEquals(bptr, 0) - # test_io import io class TextIOWrapperTest(unittest.TestCase): @@ -114,7 +82,6 @@ def test_main(): test_support.run_unittest( - TestDifflibLongestMatch, TextIOWrapperTest) if __name__ == "__main__": Modified: python/branches/py3k-ctypes-pep3118/Lib/test/pickletester.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/pickletester.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/pickletester.py Wed Apr 30 15:57:13 2008 @@ -490,6 +490,12 @@ u2 = self.loads(p) self.assertEqual(u2, u) + def test_bytes(self): + for proto in protocols: + for u in b'', b'xyz', b'xyz'*100: + p = self.dumps(u) + self.assertEqual(self.loads(p), u) + def test_ints(self): import sys for proto in protocols: @@ -532,8 +538,8 @@ @run_with_locale('LC_ALL', 'de_DE', 'fr_FR') def test_float_format(self): - # make sure that floats are formatted locale independent - self.assertEqual(self.dumps(1.2)[0:3], b'F1.') + # make sure that floats are formatted locale independent with proto 0 + self.assertEqual(self.dumps(1.2, 0)[0:3], b'F1.') def test_reduce(self): pass @@ -624,6 +630,12 @@ (2, 2): pickle.TUPLE2, (2, 3): pickle.TUPLE3, (2, 4): pickle.TUPLE, + + (3, 0): pickle.EMPTY_TUPLE, + (3, 1): pickle.TUPLE1, + (3, 2): pickle.TUPLE2, + (3, 3): pickle.TUPLE3, + (3, 4): pickle.TUPLE, } a = () b = (1,) @@ -643,14 +655,17 @@ expected_opcode = {(0, None): pickle.NONE, (1, None): pickle.NONE, (2, None): pickle.NONE, + (3, None): pickle.NONE, (0, True): pickle.INT, (1, True): pickle.INT, (2, True): pickle.NEWTRUE, + (3, True): pickle.NEWTRUE, (0, False): pickle.INT, (1, False): pickle.INT, (2, False): pickle.NEWFALSE, + (3, False): pickle.NEWFALSE, } for proto in protocols: for x in None, False, True: @@ -955,7 +970,7 @@ def test_highest_protocol(self): # Of course this needs to be changed when HIGHEST_PROTOCOL changes. - self.assertEqual(self.module.HIGHEST_PROTOCOL, 2) + self.assertEqual(self.module.HIGHEST_PROTOCOL, 3) def test_callapi(self): from io import BytesIO Modified: python/branches/py3k-ctypes-pep3118/Lib/test/regrtest.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/regrtest.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/regrtest.py Wed Apr 30 15:57:13 2008 @@ -12,10 +12,9 @@ -w: verbose2 -- re-run failed tests in verbose mode -d: debug -- print traceback for failed tests -q: quiet -- don't print anything except if a test fails --g: generate -- write the output file for a test instead of comparing it -x: exclude -- arguments are tests to *exclude* -s: single -- run only a single test (see below) --S: start -- start running all the tests with the specified one first +-S: slow -- print the slowest 10 tests -r: random -- randomize test execution order -f: fromfile -- read names of tests to run from a file (see below) -l: findleaks -- if GC is available detect tests that leak memory @@ -127,14 +126,16 @@ option '-uall,-bsddb'. """ -import os -import sys import getopt +import os import random -import warnings import re import io +import sys +import time import traceback +import warnings +from inspect import isabstract # I see no other way to suppress these warnings; # putting them in test_grammar.py has no effect: @@ -185,8 +186,7 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False, exclude=False, single=False, randomize=False, fromfile=None, findleaks=False, use_resources=None, trace=False, coverdir='coverage', - runleaks=False, huntrleaks=None, verbose2=False, debug=False, - start=None): + runleaks=False, huntrleaks=False, verbose2=False, print_slow=False): """Execute a test suite. This also parses command-line options and modifies its behavior @@ -203,17 +203,17 @@ command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. - The other default arguments (verbose, quiet, generate, exclude, single, - randomize, findleaks, use_resources, trace and coverdir) allow programmers - calling main() directly to set the values that would normally be set by - flags on the command line. + The other default arguments (verbose, quiet, generate, exclude, + single, randomize, findleaks, use_resources, trace, coverdir, and + print_slow) allow programmers calling main() directly to set the + values that would normally be set by flags on the command line. """ test_support.record_original_stdout(sys.stdout) try: - opts, args = getopt.getopt(sys.argv[1:], 'dhvgqxsS:rf:lu:t:TD:NLR:wM:n', - ['help', 'verbose', 'quiet', 'generate', - 'exclude', 'single', 'random', 'fromfile', + opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsSrf:lu:t:TD:NLR:wM:n', + ['help', 'verbose', 'quiet', 'exclude', + 'single', 'slow', 'random', 'fromfile', 'findleaks', 'use=', 'threshold=', 'trace', 'coverdir=', 'nocoverdir', 'runleaks', 'huntrleaks=', 'verbose2', 'memlimit=', @@ -225,6 +225,8 @@ # Defaults if use_resources is None: use_resources = [] + debug = False + start = None for o, a in opts: if o in ('-h', '--help'): print(__doc__) @@ -238,14 +240,14 @@ elif o in ('-q', '--quiet'): quiet = True; verbose = 0 - elif o in ('-g', '--generate'): - generate = True elif o in ('-x', '--exclude'): exclude = True elif o in ('-S', '--start'): start = a elif o in ('-s', '--single'): single = True + elif o in ('-S', '--slow'): + print_slow = True elif o in ('-r', '--randomize'): randomize = True elif o in ('-f', '--fromfile'): @@ -387,6 +389,7 @@ import trace tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix], trace=False, count=True) + test_times = [] test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_resources = use_resources save_modules = sys.modules.keys() @@ -397,12 +400,13 @@ if trace: # If we're tracing code coverage, then we don't exit with status # if on a false return value from main. - tracer.runctx('runtest(test, generate, verbose, quiet, testdir)', + tracer.runctx('runtest(test, generate, verbose, quiet,' + ' test_times, testdir)', globals=globals(), locals=vars()) else: try: - ok = runtest(test, generate, verbose, quiet, testdir, - huntrleaks) + ok = runtest(test, generate, verbose, quiet, test_times, + testdir, huntrleaks) except KeyboardInterrupt: # print a newline separate from the ^C print() @@ -443,6 +447,11 @@ if verbose: print("CAUTION: stdout isn't compared in verbose mode:") print("a test that passes in verbose mode may fail without it.") + if print_slow: + test_times.sort(reverse=True) + print("10 slowest tests:") + for time, test in test_times[:10]: + print("%s: %.1fs" % (test, time)) if bad: print(count(len(bad), "test"), "failed:") printlist(bad) @@ -470,8 +479,8 @@ print("Re-running test %r in verbose mode" % test) sys.stdout.flush() try: - test_support.verbose = 1 - ok = runtest(test, generate, 1, quiet, testdir, + test_support.verbose = True + ok = runtest(test, generate, True, quiet, test_times, testdir, huntrleaks, debug) except KeyboardInterrupt: # print a newline separate from the ^C @@ -520,7 +529,6 @@ 'test_support', 'test_future1', 'test_future2', - 'test_future3', } def findtests(testdir=None, stdtests=STDTESTS, nottests=NOTTESTS): @@ -536,15 +544,14 @@ tests.sort() return stdtests + tests -def runtest(test, generate, verbose, quiet, testdir=None, - huntrleaks=None, debug=False): +def runtest(test, generate, verbose, quiet, test_times, + testdir=None, huntrleaks=False, debug=False): """Run a single test. test -- the name of the test - generate -- if true, generate output, instead of running the test - and comparing it to a previously created output file verbose -- if true, print more messages quiet -- if true, don't print 'skipped' messages (probably redundant) + test_times -- a list of (time, test_name) pairs testdir -- test directory huntrleaks -- run multiple times to test for leaks; requires a debug build; a triple corresponding to -R's three arguments @@ -558,18 +565,16 @@ """ try: - return runtest_inner(test, generate, verbose, quiet, testdir, - huntrleaks, debug) + return runtest_inner(test, generate, verbose, quiet, test_times, + testdir, huntrleaks) finally: cleanup_test_droppings(test, verbose) -def runtest_inner(test, generate, verbose, quiet, - testdir=None, huntrleaks=None, debug=False): +def runtest_inner(test, generate, verbose, quiet, test_times, + testdir=None, huntrleaks=False, debug=False): test_support.unload(test) if not testdir: testdir = findtestdir() - outputdir = os.path.join(testdir, "output") - outputfile = os.path.join(outputdir, test) if verbose: cfp = None else: @@ -586,6 +591,7 @@ else: # Always import it from the test package abstest = 'test.' + test + start_time = time.time() the_package = __import__(abstest, globals(), locals(), []) the_module = getattr(the_package, test) # Old tests run to completion simply as a side-effect of @@ -596,6 +602,8 @@ indirect_test() if huntrleaks: dash_R(the_module, test, indirect_test, huntrleaks) + test_time = time.time() - start_time + test_times.append((test_time, test)) finally: sys.stdout = save_stdout except test_support.ResourceDenied as msg: @@ -626,27 +634,7 @@ if not cfp: return 1 output = cfp.getvalue() - if generate: - if output == test + "\n": - if os.path.exists(outputfile): - # Write it since it already exists (and the contents - # may have changed), but let the user know it isn't - # needed: - print("output file", outputfile, \ - "is no longer needed; consider removing it") - else: - # We don't need it, so don't create it. - return 1 - fp = open(outputfile, "w") - fp.write(output) - fp.close() - return 1 - if os.path.exists(outputfile): - fp = open(outputfile, "r") - expected = fp.read() - fp.close() - else: - expected = test + "\n" + expected = test + "\n" if output == expected or huntrleaks: return 1 print("test", test, "produced unexpected output:") @@ -689,7 +677,6 @@ def dash_R(the_module, test, indirect_test, huntrleaks): # This code is hackish and inelegant, but it seems to do the job. import copy_reg, _abcoll - from abc import _Abstract if not hasattr(sys, 'gettotalrefcount'): raise Exception("Tracking reference leaks requires a debug build " @@ -701,7 +688,7 @@ pic = sys.path_importer_cache.copy() abcs = {} for abc in [getattr(_abcoll, a) for a in _abcoll.__all__]: - if not issubclass(abc, _Abstract): + if not isabstract(abc): continue for obj in abc.__subclasses__() + [abc]: abcs[obj] = obj._abc_registry.copy() @@ -741,10 +728,14 @@ import _strptime, linecache, dircache import urlparse, urllib, urllib2, mimetypes, doctest import struct, filecmp, _abcoll - from abc import _Abstract from distutils.dir_util import _path_created from weakref import WeakSet + # Clear the warnings registry, so they can be displayed again + for mod in sys.modules.values(): + if hasattr(mod, '__warningregistry__'): + del mod.__warningregistry__ + # Restore some original values. warnings.filters[:] = fs copy_reg.dispatch_table.clear() @@ -752,9 +743,12 @@ sys.path_importer_cache.clear() sys.path_importer_cache.update(pic) + # clear type cache + sys._clear_type_cache() + # Clear ABC registries, restoring previously saved ABC registries. for abc in [getattr(_abcoll, a) for a in _abcoll.__all__]: - if not issubclass(abc, _Abstract): + if not isabstract(abc): continue for obj in abc.__subclasses__() + [abc]: obj._abc_registry = abcs.get(obj, WeakSet()).copy() @@ -883,10 +877,12 @@ test_dl test_fcntl test_fork1 + test_epoll test_gdbm test_grp test_ioctl test_largefile + test_kqueue test_mhlib test_openpty test_ossaudiodev @@ -907,6 +903,7 @@ test_curses test_dl test_largefile + test_kqueue test_ossaudiodev """, 'mac': @@ -922,10 +919,12 @@ test_dl test_fcntl test_fork1 + test_epoll test_grp test_ioctl test_largefile test_locale + test_kqueue test_mmap test_openpty test_ossaudiodev @@ -943,7 +942,9 @@ """ test_bsddb test_dl + test_epoll test_largefile + test_kqueue test_minidom test_openpty test_pyexpat @@ -954,7 +955,9 @@ """ test_bsddb test_dl + test_epoll test_largefile + test_kqueue test_minidom test_openpty test_pyexpat @@ -967,9 +970,11 @@ test_bsddb test_dl test_fork1 + test_epoll test_gettext test_largefile test_locale + test_kqueue test_minidom test_openpty test_pyexpat @@ -987,9 +992,11 @@ test_bsddb test_bsddb3 test_curses + test_epoll test_gdbm test_largefile test_locale + test_minidom test_ossaudiodev test_poll """, @@ -998,6 +1005,8 @@ test_bsddb test_curses test_dbm + test_epoll + test_kqueue test_gdbm test_gzip test_openpty @@ -1009,10 +1018,12 @@ test_bsddb test_curses test_dl + test_epoll test_gdbm test_gzip test_largefile test_locale + test_kqueue test_minidom test_openpty test_pyexpat @@ -1025,8 +1036,10 @@ test_curses test_dl test_gdbm + test_epoll test_largefile test_locale + test_kqueue test_mhlib test_mmap test_poll @@ -1037,7 +1050,9 @@ test_bsddb3 test_curses test_dbm + test_epoll test_ioctl + test_kqueue test_largefile test_locale test_ossaudiodev @@ -1050,6 +1065,8 @@ test_commands test_curses test_dl + test_epoll + test_kqueue test_largefile test_mhlib test_mmap @@ -1063,6 +1080,7 @@ """ test_bsddb test_bsddb3 + test_epoll test_gdbm test_locale test_ossaudiodev @@ -1079,8 +1097,10 @@ test_bsddb3 test_bz2 test_dl + test_epoll test_gdbm test_gzip + test_kqueue test_ossaudiodev test_tcl test_zipimport @@ -1092,6 +1112,7 @@ test_bsddb3 test_ctypes test_dl + test_epoll test_gdbm test_locale test_normalization @@ -1106,6 +1127,7 @@ test_ctypes test_curses test_dl + test_epoll test_gdbm test_locale test_ossaudiodev @@ -1128,13 +1150,17 @@ s = _expectations[sys.platform] self.expected = set(s.split()) + # These are broken tests, for now skipped on every platform. + # XXX Fix these! + self.expected.add('test_cProfile') + # expected to be skipped on every platform, even Linux if not os.path.supports_unicode_filenames: self.expected.add('test_pep277') - # doctest, profile and cProfile tests fail when the codec for the fs - # encoding isn't built in because PyUnicode_Decode() adds two calls - # into Python. + # doctest, profile and cProfile tests fail when the codec for the + # fs encoding isn't built in because PyUnicode_Decode() adds two + # calls into Python. encs = ("utf-8", "latin-1", "ascii", "mbcs", "utf-16", "utf-32") if sys.getfilesystemencoding().lower() not in encs: self.expected.add('test_profile') Modified: python/branches/py3k-ctypes-pep3118/Lib/test/seq_tests.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/seq_tests.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/seq_tests.py Wed Apr 30 15:57:13 2008 @@ -3,7 +3,7 @@ """ import unittest -from test import test_support +import sys # Various iterables # This is used for checking the constructor (here and in test_deque.py) @@ -79,10 +79,10 @@ def __next__(self): raise StopIteration -from itertools import chain, imap +from itertools import chain def itermulti(seqn): 'Test multiple tiers of iterators' - return chain(imap(lambda x:x, iterfunc(IterGen(Sequence(seqn))))) + return chain(map(lambda x:x, iterfunc(IterGen(Sequence(seqn))))) class CommonTest(unittest.TestCase): # The type to be tested @@ -326,3 +326,64 @@ self.assertEqual(a.__getitem__(slice(3,5)), self.type2test([])) self.assertRaises(ValueError, a.__getitem__, slice(0, 10, 0)) self.assertRaises(TypeError, a.__getitem__, 'x') + + def test_count(self): + a = self.type2test([0, 1, 2])*3 + self.assertEqual(a.count(0), 3) + self.assertEqual(a.count(1), 3) + self.assertEqual(a.count(3), 0) + + self.assertRaises(TypeError, a.count) + + class BadExc(Exception): + pass + + class BadCmp: + def __eq__(self, other): + if other == 2: + raise BadExc() + return False + + self.assertRaises(BadExc, a.count, BadCmp()) + + def test_index(self): + u = self.type2test([0, 1]) + self.assertEqual(u.index(0), 0) + self.assertEqual(u.index(1), 1) + self.assertRaises(ValueError, u.index, 2) + + u = self.type2test([-2, -1, 0, 0, 1, 2]) + self.assertEqual(u.count(0), 2) + self.assertEqual(u.index(0), 2) + self.assertEqual(u.index(0, 2), 2) + self.assertEqual(u.index(-2, -10), 0) + self.assertEqual(u.index(0, 3), 3) + self.assertEqual(u.index(0, 3, 4), 3) + self.assertRaises(ValueError, u.index, 2, 0, -10) + + self.assertRaises(TypeError, u.index) + + class BadExc(Exception): + pass + + class BadCmp: + def __eq__(self, other): + if other == 2: + raise BadExc() + return False + + a = self.type2test([0, 1, 2, 3]) + self.assertRaises(BadExc, a.index, BadCmp()) + + a = self.type2test([-2, -1, 0, 0, 1, 2]) + self.assertEqual(a.index(0), 2) + self.assertEqual(a.index(0, 2), 2) + self.assertEqual(a.index(0, -4), 2) + self.assertEqual(a.index(-2, -10), 0) + self.assertEqual(a.index(0, 3), 3) + self.assertEqual(a.index(0, -3), 3) + self.assertEqual(a.index(0, 3, 4), 3) + self.assertEqual(a.index(0, -3, -2), 3) + self.assertEqual(a.index(0, -4*sys.maxsize, 4*sys.maxsize), 2) + self.assertRaises(ValueError, a.index, 0, 4*sys.maxsize,-4*sys.maxsize) + self.assertRaises(ValueError, a.index, 2, 0, -10) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/string_tests.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/string_tests.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/string_tests.py Wed Apr 30 15:57:13 2008 @@ -4,7 +4,7 @@ import unittest, string, sys, struct from test import test_support -from UserList import UserList +from collections import UserList class Sequence: def __init__(self, seq='wxyz'): self.seq = seq @@ -1053,7 +1053,13 @@ # unicode raises ValueError, str raises OverflowError self.checkraises((ValueError, OverflowError), '%c', '__mod__', ordinal) + longvalue = sys.maxsize + 10 + slongvalue = str(longvalue) + if slongvalue[-1] in ("L","l"): slongvalue = slongvalue[:-1] self.checkequal(' 42', '%3ld', '__mod__', 42) + self.checkequal('42', '%d', '__mod__', 42.0) + self.checkequal(slongvalue, '%d', '__mod__', longvalue) + self.checkcall('%d', '__mod__', float(longvalue)) self.checkequal('0042.00', '%07.2f', '__mod__', 42) self.checkequal('0042.00', '%07.2F', '__mod__', 42) @@ -1063,6 +1069,8 @@ self.checkraises(TypeError, '%c', '__mod__', (None,)) self.checkraises(ValueError, '%(foo', '__mod__', {}) self.checkraises(TypeError, '%(foo)s %(bar)s', '__mod__', ('foo', 42)) + self.checkraises(TypeError, '%d', '__mod__', "42") # not numeric + self.checkraises(TypeError, '%d', '__mod__', (42+0j)) # no int/long conversion provided # argument names with properly nested brackets are supported self.checkequal('bar', '%((foo))s', '__mod__', {'(foo)': 'bar'}) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test___all__.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test___all__.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test___all__.py Wed Apr 30 15:57:13 2008 @@ -1,5 +1,5 @@ import unittest -from test.test_support import verbose, run_unittest +from test.test_support import run_unittest import sys @@ -36,7 +36,6 @@ self.check_all("Queue") self.check_all("SimpleHTTPServer") self.check_all("SocketServer") - self.check_all("UserString") self.check_all("aifc") self.check_all("base64") self.check_all("bdb") Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test__locale.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test__locale.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test__locale.py Wed Apr 30 15:57:13 2008 @@ -1,5 +1,5 @@ from test.test_support import verbose, TestSkipped, run_unittest -from _locale import (setlocale, LC_NUMERIC, RADIXCHAR, THOUSEP, nl_langinfo, +from _locale import (setlocale, LC_ALL, LC_CTYPE, LC_NUMERIC, RADIXCHAR, THOUSEP, nl_langinfo, localeconv, Error) import unittest from platform import uname @@ -28,10 +28,10 @@ class _LocaleTests(unittest.TestCase): def setUp(self): - self.oldlocale = setlocale(LC_NUMERIC) + self.oldlocale = setlocale(LC_ALL) def tearDown(self): - setlocale(LC_NUMERIC, self.oldlocale) + setlocale(LC_ALL, self.oldlocale) # Want to know what value was calculated, what it was compared against, # what function was used for the calculation, what type of data was used, @@ -58,6 +58,7 @@ for loc in candidate_locales: try: setlocale(LC_NUMERIC, loc) + setlocale(LC_CTYPE, loc) except Error: continue for li, lc in ((RADIXCHAR, "decimal_point"), @@ -69,6 +70,7 @@ for loc in candidate_locales: try: setlocale(LC_NUMERIC, loc) + setlocale(LC_CTYPE, loc) except Error: continue for li, lc in ((RADIXCHAR, "decimal_point"), @@ -80,6 +82,7 @@ for loc in candidate_locales: try: setlocale(LC_NUMERIC, loc) + setlocale(LC_CTYPE, loc) except Error: continue for li, lc in ((RADIXCHAR, "decimal_point"), @@ -102,6 +105,7 @@ for loc in candidate_locales: try: setlocale(LC_NUMERIC, loc) + setlocale(LC_CTYPE, loc) except Error: continue Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_abc.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_abc.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_abc.py Wed Apr 30 15:57:13 2008 @@ -3,11 +3,11 @@ """Unit tests for abc.py.""" -import sys import unittest from test import test_support import abc +from inspect import isabstract class TestABC(unittest.TestCase): @@ -42,19 +42,23 @@ def bar(self): pass # concrete self.assertEqual(C.__abstractmethods__, {"foo"}) self.assertRaises(TypeError, C) # because foo is abstract + self.assert_(isabstract(C)) class D(C): def bar(self): pass # concrete override of concrete self.assertEqual(D.__abstractmethods__, {"foo"}) self.assertRaises(TypeError, D) # because foo is still abstract + self.assert_(isabstract(D)) class E(D): def foo(self): pass self.assertEqual(E.__abstractmethods__, set()) E() # now foo is concrete, too + self.failIf(isabstract(E)) class F(E): @abstractthing def bar(self): pass # abstract override of concrete self.assertEqual(F.__abstractmethods__, {"bar"}) self.assertRaises(TypeError, F) # because bar is abstract now + self.assert_(isabstract(F)) def test_subclass_oldstyle_class(self): class A: @@ -81,6 +85,16 @@ self.assertEqual(issubclass(C, A), True) self.assertEqual(isinstance(c, A), True) + def test_isinstance_invalidation(self): + class A(metaclass=abc.ABCMeta): + pass + class B: + pass + b = B() + self.assertEqual(isinstance(b, A), False) + A.register(B) + self.assertEqual(isinstance(b, A), True) + def test_registration_builtins(self): class A(metaclass=abc.ABCMeta): pass Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_abstract_numbers.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_abstract_numbers.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_abstract_numbers.py Wed Apr 30 15:57:13 2008 @@ -1,18 +1,16 @@ """Unit tests for numbers.py.""" +import math +import operator import unittest -from test import test_support -from numbers import Number -from numbers import Exact, Inexact from numbers import Complex, Real, Rational, Integral -import operator +from numbers import Number +from test import test_support class TestNumbers(unittest.TestCase): def test_int(self): self.failUnless(issubclass(int, Integral)) self.failUnless(issubclass(int, Complex)) - self.failUnless(issubclass(int, Exact)) - self.failIf(issubclass(int, Inexact)) self.assertEqual(7, int(7).real) self.assertEqual(0, int(7).imag) @@ -23,8 +21,6 @@ def test_float(self): self.failIf(issubclass(float, Rational)) self.failUnless(issubclass(float, Real)) - self.failIf(issubclass(float, Exact)) - self.failUnless(issubclass(float, Inexact)) self.assertEqual(7.3, float(7.3).real) self.assertEqual(0, float(7.3).imag) @@ -33,11 +29,10 @@ def test_complex(self): self.failIf(issubclass(complex, Real)) self.failUnless(issubclass(complex, Complex)) - self.failIf(issubclass(complex, Exact)) - self.failUnless(issubclass(complex, Inexact)) c1, c2 = complex(3, 2), complex(4,1) - self.assertRaises(TypeError, trunc, c1) + # XXX: This is not ideal, but see the comment in math_trunc(). + self.assertRaises(TypeError, math.trunc, c1) self.assertRaises(TypeError, operator.mod, c1, c2) self.assertRaises(TypeError, divmod, c1, c2) self.assertRaises(TypeError, operator.floordiv, c1, c2) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_applesingle.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_applesingle.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_applesingle.py Wed Apr 30 15:57:13 2008 @@ -5,7 +5,6 @@ import Carbon.File import MacOS import os -import sys from test import test_support import struct import applesingle Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_array.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_array.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_array.py Wed Apr 30 15:57:13 2008 @@ -162,6 +162,7 @@ def test_tofromfile(self): a = array.array(self.typecode, 2*self.example) self.assertRaises(TypeError, a.tofile) + test_support.unlink(test_support.TESTFN) f = open(test_support.TESTFN, 'wb') try: a.tofile(f) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_ast.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_ast.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_ast.py Wed Apr 30 15:57:13 2008 @@ -1,4 +1,5 @@ -import sys, itertools +import sys, unittest +from test import test_support import _ast def to_tuple(t): @@ -15,6 +16,7 @@ result.append(to_tuple(getattr(t, f))) return tuple(result) + # These tests are compiled through "exec" # There should be atleast one test per statement exec_tests = [ @@ -112,47 +114,88 @@ # TODO: expr_context, slice, boolop, operator, unaryop, cmpop, comprehension # excepthandler, arguments, keywords, alias -if __name__=='__main__' and sys.argv[1:] == ['-g']: - for statements, kind in ((exec_tests, "exec"), (single_tests, "single"), - (eval_tests, "eval")): - print(kind+"_results = [") - for s in statements: - print(repr(to_tuple(compile(s, "?", kind, 0x400)))+",") - print("]") - print("run_tests()") - raise SystemExit +class AST_Tests(unittest.TestCase): + + def _assert_order(self, ast_node, parent_pos): + if not isinstance(ast_node, _ast.AST) or ast_node._fields is None: + return + if isinstance(ast_node, (_ast.expr, _ast.stmt, _ast.excepthandler)): + node_pos = (ast_node.lineno, ast_node.col_offset) + self.assert_(node_pos >= parent_pos) + parent_pos = (ast_node.lineno, ast_node.col_offset) + for name in ast_node._fields: + value = getattr(ast_node, name) + if isinstance(value, list): + for child in value: + self._assert_order(child, parent_pos) + elif value is not None: + self._assert_order(value, parent_pos) + + def test_snippets(self): + for input, output, kind in ((exec_tests, exec_results, "exec"), + (single_tests, single_results, "single"), + (eval_tests, eval_results, "eval")): + for i, o in zip(input, output): + ast_tree = compile(i, "?", kind, _ast.PyCF_ONLY_AST) + self.assertEquals(to_tuple(ast_tree), o) + self._assert_order(ast_tree, (0, 0)) + + def test_nodeclasses(self): + x = _ast.BinOp(1, 2, 3, lineno=0) + self.assertEquals(x.left, 1) + self.assertEquals(x.op, 2) + self.assertEquals(x.right, 3) + self.assertEquals(x.lineno, 0) + + # node raises exception when not given enough arguments + self.assertRaises(TypeError, _ast.BinOp, 1, 2) + + # can set attributes through kwargs too + x = _ast.BinOp(left=1, op=2, right=3, lineno=0) + self.assertEquals(x.left, 1) + self.assertEquals(x.op, 2) + self.assertEquals(x.right, 3) + self.assertEquals(x.lineno, 0) + + # this used to fail because Sub._fields was None + x = _ast.Sub() + + def test_pickling(self): + import pickle + mods = [pickle] + try: + import cPickle + mods.append(cPickle) + except ImportError: + pass + protocols = [0, 1, 2] + for mod in mods: + for protocol in protocols: + for ast in (compile(i, "?", "exec", 0x400) for i in exec_tests): + ast2 = mod.loads(mod.dumps(ast, protocol)) + self.assertEquals(to_tuple(ast2), to_tuple(ast)) -def test_order(ast_node, parent_pos): +def test_main(): + test_support.run_unittest(AST_Tests) - if not isinstance(ast_node, _ast.AST) or ast_node._fields == None: +def main(): + if __name__ != '__main__': return - if isinstance(ast_node, (_ast.expr, _ast.stmt, _ast.excepthandler)): - node_pos = (ast_node.lineno, ast_node.col_offset) - assert node_pos >= parent_pos, (node_pos, parent_pos) - parent_pos = (ast_node.lineno, ast_node.col_offset) - for name in ast_node._fields: - value = getattr(ast_node, name) - if isinstance(value, list): - for child in value: - test_order(child, parent_pos) - elif value != None: - test_order(value, parent_pos) - -def run_tests(): - for input, output, kind in ((exec_tests, exec_results, "exec"), - (single_tests, single_results, "single"), - (eval_tests, eval_results, "eval")): - for i, o in itertools.izip(input, output): - ast_tree = compile(i, "?", kind, 0x400) - tup = to_tuple(ast_tree) - assert tup == o, ("kind=%r\ninput=%r\nexpected=%r\ngot=%r" % - (kind, i, o, tup)) - test_order(ast_tree, (0, 0)) + if sys.argv[1:] == ['-g']: + for statements, kind in ((exec_tests, "exec"), (single_tests, "single"), + (eval_tests, "eval")): + print(kind+"_results = [") + for s in statements: + print(repr(to_tuple(compile(s, "?", kind, 0x400)))+",") + print("]") + print("main()") + raise SystemExit + test_main() #### EVERYTHING BELOW IS GENERATED ##### exec_results = [ ('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, [], None, None, [], []), [('Pass', (1, 9))], [], None)]), -('Module', [('ClassDef', (1, 0), 'C', [], [], None, None, [('Pass', (1, 8))], [], )]), +('Module', [('ClassDef', (1, 0), 'C', [], [], None, None, [('Pass', (1, 8))], [])]), ('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, [], None, None, [], []), [('Return', (1, 8), ('Num', (1, 15), 1))], [], None)]), ('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])]), ('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Num', (1, 4), 1))]), @@ -161,7 +204,7 @@ ('Module', [('While', (1, 0), ('Name', (1, 6), 'v', ('Load',)), [('Pass', (1, 8))], [])]), ('Module', [('If', (1, 0), ('Name', (1, 3), 'v', ('Load',)), [('Pass', (1, 5))], [])]), ('Module', [('Raise', (1, 0), ('Call', (1, 6), ('Name', (1, 6), 'Exception', ('Load',)), [('Str', (1, 16), 'string')], [], None, None), None)]), -('Module', [('TryExcept', (1, 0), [('Pass', (2, 2))], [('excepthandler', (3, 0), ('Name', (3, 7), 'Exception', ('Load',)), None, [('Pass', (4, 2))], 3, 0)], [])]), +('Module', [('TryExcept', (1, 0), [('Pass', (2, 2))], [('ExceptHandler', (3, 0), ('Name', (3, 7), 'Exception', ('Load',)), None, [('Pass', (4, 2))])], [])]), ('Module', [('TryFinally', (1, 0), [('Pass', (2, 2))], [('Pass', (4, 2))])]), ('Module', [('Assert', (1, 0), ('Name', (1, 7), 'v', ('Load',)), None)]), ('Module', [('Import', (1, 0), [('alias', 'sys', None)])]), @@ -194,4 +237,4 @@ ('Expression', ('Tuple', (1, 0), [('Num', (1, 0), 1), ('Num', (1, 2), 2), ('Num', (1, 4), 3)], ('Load',))), ('Expression', ('Call', (1, 0), ('Attribute', (1, 0), ('Attribute', (1, 0), ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',)), 'c', ('Load',)), 'd', ('Load',)), [('Subscript', (1, 8), ('Attribute', (1, 8), ('Name', (1, 8), 'a', ('Load',)), 'b', ('Load',)), ('Slice', ('Num', (1, 12), 1), ('Num', (1, 14), 2), None), ('Load',))], [], None, None)), ] -run_tests() +main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_asynchat.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_asynchat.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_asynchat.py Wed Apr 30 15:57:13 2008 @@ -6,8 +6,7 @@ import sys from test import test_support -HOST = "127.0.0.1" -PORT = 54322 +HOST = test_support.HOST SERVER_QUIT = b'QUIT\n' class echo_server(threading.Thread): @@ -15,13 +14,16 @@ # client each send chunk_size = 1 + def __init__(self, event): + threading.Thread.__init__(self) + self.event = event + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.port = test_support.bind_port(self.sock) + def run(self): - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - global PORT - PORT = test_support.bind_port(sock, HOST, PORT) - sock.listen(1) - conn, client = sock.accept() + self.sock.listen(1) + self.event.set() + conn, client = self.sock.accept() self.buffer = b"" # collect data until quit message is seen while SERVER_QUIT not in self.buffer: @@ -45,15 +47,15 @@ pass conn.close() - sock.close() + self.sock.close() class echo_client(asynchat.async_chat): - def __init__(self, terminator): + def __init__(self, terminator, server_port): asynchat.async_chat.__init__(self) self.contents = [] self.create_socket(socket.AF_INET, socket.SOCK_STREAM) - self.connect((HOST, PORT)) + self.connect((HOST, server_port)) self.set_terminator(terminator) self.buffer = b"" @@ -74,6 +76,16 @@ self.buffer = b"" +def start_echo_server(): + event = threading.Event() + s = echo_server(event) + s.start() + event.wait() + event.clear() + time.sleep(0.01) # Give server time to start accepting. + return s, event + + class TestAsynchat(unittest.TestCase): usepoll = False @@ -84,11 +96,14 @@ pass def line_terminator_check(self, term, server_chunk): - s = echo_server() + event = threading.Event() + s = echo_server(event) s.chunk_size = server_chunk s.start() - time.sleep(0.5) # Give server time to initialize - c = echo_client(term) + event.wait() + event.clear() + time.sleep(0.01) # Give server time to start accepting. + c = echo_client(term, s.port) c.push(b"hello ") c.push(bytes("world%s" % term, "ascii")) c.push(bytes("I'm not dead yet!%s" % term, "ascii")) @@ -119,10 +134,8 @@ def numeric_terminator_check(self, termlen): # Try reading a fixed number of bytes - s = echo_server() - s.start() - time.sleep(0.5) # Give server time to initialize - c = echo_client(termlen) + s, event = start_echo_server() + c = echo_client(termlen, s.port) data = b"hello world, I'm not dead yet!\n" c.push(data) c.push(SERVER_QUIT) @@ -141,10 +154,8 @@ def test_none_terminator(self): # Try reading a fixed number of bytes - s = echo_server() - s.start() - time.sleep(0.5) # Give server time to initialize - c = echo_client(None) + s, event = start_echo_server() + c = echo_client(None, s.port) data = b"hello world, I'm not dead yet!\n" c.push(data) c.push(SERVER_QUIT) @@ -155,10 +166,8 @@ self.assertEqual(c.buffer, data) def test_simple_producer(self): - s = echo_server() - s.start() - time.sleep(0.5) # Give server time to initialize - c = echo_client(b'\n') + s, event = start_echo_server() + c = echo_client(b'\n', s.port) data = b"hello world\nI'm not dead yet!\n" p = asynchat.simple_producer(data+SERVER_QUIT, buffer_size=8) c.push_with_producer(p) @@ -168,10 +177,8 @@ self.assertEqual(c.contents, [b"hello world", b"I'm not dead yet!"]) def test_string_producer(self): - s = echo_server() - s.start() - time.sleep(0.5) # Give server time to initialize - c = echo_client(b'\n') + s, event = start_echo_server() + c = echo_client(b'\n', s.port) data = b"hello world\nI'm not dead yet!\n" c.push_with_producer(data+SERVER_QUIT) asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01) @@ -181,11 +188,9 @@ def test_empty_line(self): # checks that empty lines are handled correctly - s = echo_server() - s.start() - time.sleep(0.5) # Give server time to initialize - c = echo_client(b'\n') - c.push(b"hello world\n\nI'm not dead yet!\n") + s, event = start_echo_server() + c = echo_client(b'\n', s.port) + c.push("hello world\n\nI'm not dead yet!\n") c.push(SERVER_QUIT) asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01) s.join() @@ -194,11 +199,9 @@ [b"hello world", b"", b"I'm not dead yet!"]) def test_close_when_done(self): - s = echo_server() - s.start() - time.sleep(0.5) # Give server time to initialize - c = echo_client(b'\n') - c.push(b"hello world\nI'm not dead yet!\n") + s, event = start_echo_server() + c = echo_client(b'\n', s.port) + c.push("hello world\nI'm not dead yet!\n") c.push(SERVER_QUIT) c.close_when_done() asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_asyncore.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_asyncore.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_asyncore.py Wed Apr 30 15:57:13 2008 @@ -9,10 +9,10 @@ from test import test_support from test.test_support import TESTFN, run_unittest, unlink -from io import StringIO, BytesIO +from io import BytesIO +from io import StringIO -HOST = "127.0.0.1" -PORT = None +HOST = test_support.HOST class dummysocket: def __init__(self): @@ -52,14 +52,8 @@ self.error_handled = True # used when testing senders; just collects what it gets until newline is sent -def capture_server(evt, buf): +def capture_server(evt, buf, serv): try: - serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - serv.settimeout(3) - serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - serv.bind(("", 0)) - global PORT - PORT = serv.getsockname()[1] serv.listen(5) conn, addr = serv.accept() except socket.timeout: @@ -80,7 +74,6 @@ conn.close() finally: serv.close() - PORT = None evt.set() @@ -339,14 +332,13 @@ def test_send(self): self.evt = threading.Event() - cap = BytesIO() - threading.Thread(target=capture_server, args=(self.evt, cap)).start() + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.sock.settimeout(3) + self.port = test_support.bind_port(self.sock) - # wait until server thread has assigned a port number - n = 1000 - while PORT is None and n > 0: - time.sleep(0.01) - n -= 1 + cap = BytesIO() + args = (self.evt, cap, self.sock) + threading.Thread(target=capture_server, args=args).start() # wait a little longer for the server to initialize (it sometimes # refuses connections on slow machines without this wait) @@ -355,7 +347,7 @@ data = b"Suppose there isn't a 16-ton weight?" d = dispatcherwithsend_noread() d.create_socket(socket.AF_INET, socket.SOCK_STREAM) - d.connect((HOST, PORT)) + d.connect((HOST, self.port)) # give time for socket to connect time.sleep(0.1) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_audioop.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_audioop.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_audioop.py Wed Apr 30 15:57:13 2008 @@ -271,7 +271,7 @@ if not rv: print('Test FAILED for audioop.'+name+'()') -def testall(): +def test_main(): data = [gendata1(), gendata2(), gendata4()] names = dir(audioop) # We know there is a routine 'add' @@ -281,4 +281,8 @@ routines.append(n) for n in routines: testone(n, data) -testall() + + + +if __name__ == '__main__': + test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_bisect.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_bisect.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_bisect.py Wed Apr 30 15:57:13 2008 @@ -1,91 +1,113 @@ +import sys import unittest from test import test_support -from bisect import bisect_right, bisect_left, insort_left, insort_right, insort, bisect -from UserList import UserList +from collections import UserList + +# We do a bit of trickery here to be able to test both the C implementation +# and the Python implementation of the module. + +# Make it impossible to import the C implementation anymore. +sys.modules['_bisect'] = 0 +# We must also handle the case that bisect was imported before. +if 'bisect' in sys.modules: + del sys.modules['bisect'] + +# Now we can import the module and get the pure Python implementation. +import bisect as py_bisect + +# Restore everything to normal. +del sys.modules['_bisect'] +del sys.modules['bisect'] + +# This is now the module with the C implementation. +import bisect as c_bisect + class TestBisect(unittest.TestCase): + module = None - precomputedCases = [ - (bisect_right, [], 1, 0), - (bisect_right, [1], 0, 0), - (bisect_right, [1], 1, 1), - (bisect_right, [1], 2, 1), - (bisect_right, [1, 1], 0, 0), - (bisect_right, [1, 1], 1, 2), - (bisect_right, [1, 1], 2, 2), - (bisect_right, [1, 1, 1], 0, 0), - (bisect_right, [1, 1, 1], 1, 3), - (bisect_right, [1, 1, 1], 2, 3), - (bisect_right, [1, 1, 1, 1], 0, 0), - (bisect_right, [1, 1, 1, 1], 1, 4), - (bisect_right, [1, 1, 1, 1], 2, 4), - (bisect_right, [1, 2], 0, 0), - (bisect_right, [1, 2], 1, 1), - (bisect_right, [1, 2], 1.5, 1), - (bisect_right, [1, 2], 2, 2), - (bisect_right, [1, 2], 3, 2), - (bisect_right, [1, 1, 2, 2], 0, 0), - (bisect_right, [1, 1, 2, 2], 1, 2), - (bisect_right, [1, 1, 2, 2], 1.5, 2), - (bisect_right, [1, 1, 2, 2], 2, 4), - (bisect_right, [1, 1, 2, 2], 3, 4), - (bisect_right, [1, 2, 3], 0, 0), - (bisect_right, [1, 2, 3], 1, 1), - (bisect_right, [1, 2, 3], 1.5, 1), - (bisect_right, [1, 2, 3], 2, 2), - (bisect_right, [1, 2, 3], 2.5, 2), - (bisect_right, [1, 2, 3], 3, 3), - (bisect_right, [1, 2, 3], 4, 3), - (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 0, 0), - (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 1, 1), - (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 1.5, 1), - (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 2, 3), - (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 2.5, 3), - (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 3, 6), - (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 3.5, 6), - (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 4, 10), - (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 5, 10), - - (bisect_left, [], 1, 0), - (bisect_left, [1], 0, 0), - (bisect_left, [1], 1, 0), - (bisect_left, [1], 2, 1), - (bisect_left, [1, 1], 0, 0), - (bisect_left, [1, 1], 1, 0), - (bisect_left, [1, 1], 2, 2), - (bisect_left, [1, 1, 1], 0, 0), - (bisect_left, [1, 1, 1], 1, 0), - (bisect_left, [1, 1, 1], 2, 3), - (bisect_left, [1, 1, 1, 1], 0, 0), - (bisect_left, [1, 1, 1, 1], 1, 0), - (bisect_left, [1, 1, 1, 1], 2, 4), - (bisect_left, [1, 2], 0, 0), - (bisect_left, [1, 2], 1, 0), - (bisect_left, [1, 2], 1.5, 1), - (bisect_left, [1, 2], 2, 1), - (bisect_left, [1, 2], 3, 2), - (bisect_left, [1, 1, 2, 2], 0, 0), - (bisect_left, [1, 1, 2, 2], 1, 0), - (bisect_left, [1, 1, 2, 2], 1.5, 2), - (bisect_left, [1, 1, 2, 2], 2, 2), - (bisect_left, [1, 1, 2, 2], 3, 4), - (bisect_left, [1, 2, 3], 0, 0), - (bisect_left, [1, 2, 3], 1, 0), - (bisect_left, [1, 2, 3], 1.5, 1), - (bisect_left, [1, 2, 3], 2, 1), - (bisect_left, [1, 2, 3], 2.5, 2), - (bisect_left, [1, 2, 3], 3, 2), - (bisect_left, [1, 2, 3], 4, 3), - (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 0, 0), - (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 1, 0), - (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 1.5, 1), - (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 2, 1), - (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 2.5, 3), - (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 3, 3), - (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 3.5, 6), - (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 4, 6), - (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 5, 10) - ] + def setUp(self): + self.precomputedCases = [ + (self.module.bisect_right, [], 1, 0), + (self.module.bisect_right, [1], 0, 0), + (self.module.bisect_right, [1], 1, 1), + (self.module.bisect_right, [1], 2, 1), + (self.module.bisect_right, [1, 1], 0, 0), + (self.module.bisect_right, [1, 1], 1, 2), + (self.module.bisect_right, [1, 1], 2, 2), + (self.module.bisect_right, [1, 1, 1], 0, 0), + (self.module.bisect_right, [1, 1, 1], 1, 3), + (self.module.bisect_right, [1, 1, 1], 2, 3), + (self.module.bisect_right, [1, 1, 1, 1], 0, 0), + (self.module.bisect_right, [1, 1, 1, 1], 1, 4), + (self.module.bisect_right, [1, 1, 1, 1], 2, 4), + (self.module.bisect_right, [1, 2], 0, 0), + (self.module.bisect_right, [1, 2], 1, 1), + (self.module.bisect_right, [1, 2], 1.5, 1), + (self.module.bisect_right, [1, 2], 2, 2), + (self.module.bisect_right, [1, 2], 3, 2), + (self.module.bisect_right, [1, 1, 2, 2], 0, 0), + (self.module.bisect_right, [1, 1, 2, 2], 1, 2), + (self.module.bisect_right, [1, 1, 2, 2], 1.5, 2), + (self.module.bisect_right, [1, 1, 2, 2], 2, 4), + (self.module.bisect_right, [1, 1, 2, 2], 3, 4), + (self.module.bisect_right, [1, 2, 3], 0, 0), + (self.module.bisect_right, [1, 2, 3], 1, 1), + (self.module.bisect_right, [1, 2, 3], 1.5, 1), + (self.module.bisect_right, [1, 2, 3], 2, 2), + (self.module.bisect_right, [1, 2, 3], 2.5, 2), + (self.module.bisect_right, [1, 2, 3], 3, 3), + (self.module.bisect_right, [1, 2, 3], 4, 3), + (self.module.bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 0, 0), + (self.module.bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 1, 1), + (self.module.bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 1.5, 1), + (self.module.bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 2, 3), + (self.module.bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 2.5, 3), + (self.module.bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 3, 6), + (self.module.bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 3.5, 6), + (self.module.bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 4, 10), + (self.module.bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 5, 10), + + (self.module.bisect_left, [], 1, 0), + (self.module.bisect_left, [1], 0, 0), + (self.module.bisect_left, [1], 1, 0), + (self.module.bisect_left, [1], 2, 1), + (self.module.bisect_left, [1, 1], 0, 0), + (self.module.bisect_left, [1, 1], 1, 0), + (self.module.bisect_left, [1, 1], 2, 2), + (self.module.bisect_left, [1, 1, 1], 0, 0), + (self.module.bisect_left, [1, 1, 1], 1, 0), + (self.module.bisect_left, [1, 1, 1], 2, 3), + (self.module.bisect_left, [1, 1, 1, 1], 0, 0), + (self.module.bisect_left, [1, 1, 1, 1], 1, 0), + (self.module.bisect_left, [1, 1, 1, 1], 2, 4), + (self.module.bisect_left, [1, 2], 0, 0), + (self.module.bisect_left, [1, 2], 1, 0), + (self.module.bisect_left, [1, 2], 1.5, 1), + (self.module.bisect_left, [1, 2], 2, 1), + (self.module.bisect_left, [1, 2], 3, 2), + (self.module.bisect_left, [1, 1, 2, 2], 0, 0), + (self.module.bisect_left, [1, 1, 2, 2], 1, 0), + (self.module.bisect_left, [1, 1, 2, 2], 1.5, 2), + (self.module.bisect_left, [1, 1, 2, 2], 2, 2), + (self.module.bisect_left, [1, 1, 2, 2], 3, 4), + (self.module.bisect_left, [1, 2, 3], 0, 0), + (self.module.bisect_left, [1, 2, 3], 1, 0), + (self.module.bisect_left, [1, 2, 3], 1.5, 1), + (self.module.bisect_left, [1, 2, 3], 2, 1), + (self.module.bisect_left, [1, 2, 3], 2.5, 2), + (self.module.bisect_left, [1, 2, 3], 3, 2), + (self.module.bisect_left, [1, 2, 3], 4, 3), + (self.module.bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 0, 0), + (self.module.bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 1, 0), + (self.module.bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 1.5, 1), + (self.module.bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 2, 1), + (self.module.bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 2.5, 3), + (self.module.bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 3, 3), + (self.module.bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 3.5, 6), + (self.module.bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 4, 6), + (self.module.bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 5, 10) + ] def test_precomputed(self): for func, data, elem, expected in self.precomputedCases: @@ -98,12 +120,12 @@ data = [randrange(0, n, 2) for j in range(i)] data.sort() elem = randrange(-1, n+1) - ip = bisect_left(data, elem) + ip = self.module.bisect_left(data, elem) if ip < len(data): self.failUnless(elem <= data[ip]) if ip > 0: self.failUnless(data[ip-1] < elem) - ip = bisect_right(data, elem) + ip = self.module.bisect_right(data, elem) if ip < len(data): self.failUnless(elem < data[ip]) if ip > 0: @@ -117,32 +139,39 @@ hi = min(len(data), hi) ip = func(data, elem, lo, hi) self.failUnless(lo <= ip <= hi) - if func is bisect_left and ip < hi: + if func is self.module.bisect_left and ip < hi: self.failUnless(elem <= data[ip]) - if func is bisect_left and ip > lo: + if func is self.module.bisect_left and ip > lo: self.failUnless(data[ip-1] < elem) - if func is bisect_right and ip < hi: + if func is self.module.bisect_right and ip < hi: self.failUnless(elem < data[ip]) - if func is bisect_right and ip > lo: + if func is self.module.bisect_right and ip > lo: self.failUnless(data[ip-1] <= elem) self.assertEqual(ip, max(lo, min(hi, expected))) def test_backcompatibility(self): - self.assertEqual(bisect, bisect_right) + self.assertEqual(self.module.bisect, self.module.bisect_right) def test_keyword_args(self): data = [10, 20, 30, 40, 50] - self.assertEqual(bisect_left(a=data, x=25, lo=1, hi=3), 2) - self.assertEqual(bisect_right(a=data, x=25, lo=1, hi=3), 2) - self.assertEqual(bisect(a=data, x=25, lo=1, hi=3), 2) - insort_left(a=data, x=25, lo=1, hi=3) - insort_right(a=data, x=25, lo=1, hi=3) - insort(a=data, x=25, lo=1, hi=3) + self.assertEqual(self.module.bisect_left(a=data, x=25, lo=1, hi=3), 2) + self.assertEqual(self.module.bisect_right(a=data, x=25, lo=1, hi=3), 2) + self.assertEqual(self.module.bisect(a=data, x=25, lo=1, hi=3), 2) + self.module.insort_left(a=data, x=25, lo=1, hi=3) + self.module.insort_right(a=data, x=25, lo=1, hi=3) + self.module.insort(a=data, x=25, lo=1, hi=3) self.assertEqual(data, [10, 20, 25, 25, 25, 30, 40, 50]) +class TestBisectPython(TestBisect): + module = py_bisect + +class TestBisectC(TestBisect): + module = c_bisect + #============================================================================== class TestInsort(unittest.TestCase): + module = None def test_vsBuiltinSort(self, n=500): from random import choice @@ -150,14 +179,20 @@ for i in range(n): digit = choice("0123456789") if digit in "02468": - f = insort_left + f = self.module.insort_left else: - f = insort_right + f = self.module.insort_right f(insorted, digit) self.assertEqual(sorted(insorted), insorted) def test_backcompatibility(self): - self.assertEqual(insort, insort_right) + self.assertEqual(self.module.insort, self.module.insort_right) + +class TestInsortPython(TestInsort): + module = py_bisect + +class TestInsortC(TestInsort): + module = c_bisect #============================================================================== @@ -183,32 +218,44 @@ __ne__ = __lt__ class TestErrorHandling(unittest.TestCase): + module = None def test_non_sequence(self): - for f in (bisect_left, bisect_right, insort_left, insort_right): + for f in (self.module.bisect_left, self.module.bisect_right, + self.module.insort_left, self.module.insort_right): self.assertRaises(TypeError, f, 10, 10) def test_len_only(self): - for f in (bisect_left, bisect_right, insort_left, insort_right): + for f in (self.module.bisect_left, self.module.bisect_right, + self.module.insort_left, self.module.insort_right): self.assertRaises(TypeError, f, LenOnly(), 10) def test_get_only(self): - for f in (bisect_left, bisect_right, insort_left, insort_right): + for f in (self.module.bisect_left, self.module.bisect_right, + self.module.insort_left, self.module.insort_right): self.assertRaises(TypeError, f, GetOnly(), 10) def test_cmp_err(self): seq = [CmpErr(), CmpErr(), CmpErr()] - for f in (bisect_left, bisect_right, insort_left, insort_right): + for f in (self.module.bisect_left, self.module.bisect_right, + self.module.insort_left, self.module.insort_right): self.assertRaises(ZeroDivisionError, f, seq, 10) def test_arg_parsing(self): - for f in (bisect_left, bisect_right, insort_left, insort_right): + for f in (self.module.bisect_left, self.module.bisect_right, + self.module.insort_left, self.module.insort_right): self.assertRaises(TypeError, f, 10) +class TestErrorHandlingPython(TestErrorHandling): + module = py_bisect + +class TestErrorHandlingC(TestErrorHandling): + module = c_bisect + #============================================================================== libreftest = """ -Example from the Library Reference: Doc/lib/libbisect.tex +Example from the Library Reference: Doc/library/bisect.rst The bisect() function is generally useful for categorizing numeric data. This example uses bisect() to look up a letter grade for an exam total @@ -234,12 +281,10 @@ def test_main(verbose=None): from test import test_bisect - from types import BuiltinFunctionType - import sys - test_classes = [TestBisect, TestInsort] - if isinstance(bisect_left, BuiltinFunctionType): - test_classes.append(TestErrorHandling) + test_classes = [TestBisectPython, TestBisectC, + TestInsortPython, TestInsortC, + TestErrorHandlingPython, TestErrorHandlingC] test_support.run_unittest(*test_classes) test_support.run_doctest(test_bisect, verbose) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_bsddb3.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_bsddb3.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_bsddb3.py Wed Apr 30 15:57:13 2008 @@ -2,10 +2,12 @@ """ Run all test cases. """ +import os import sys +import tempfile +import time import unittest -import test.test_support -from test.test_support import requires, run_unittest, unlink +from test.test_support import requires, verbose, run_unittest, unlink, rmtree # When running as a script instead of within the regrtest framework, skip the # requires test, since it's obvious we want to run them. @@ -22,6 +24,30 @@ sys.argv.remove('silent') +class TimingCheck(unittest.TestCase): + + """This class is not a real test. Its purpose is to print a message + periodically when the test runs slowly. This will prevent the buildbots + from timing out on slow machines.""" + + # How much time in seconds before printing a 'Still working' message. + # Since this is run at most once between each test module, use a smaller + # interval than other tests. + _PRINT_WORKING_MSG_INTERVAL = 4 * 60 + + # next_time is used as a global variable that survives each instance. + # This is necessary since a new instance will be created for each test. + next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL + + def testCheckElapsedTime(self): + # Print still working message since these tests can be really slow. + now = time.time() + if self.next_time <= now: + TimingCheck.next_time = now + self._PRINT_WORKING_MSG_INTERVAL + sys.__stdout__.write(' test_bsddb3 still working, be patient...\n') + sys.__stdout__.flush() + + def suite(): try: # this is special, it used to segfault the interpreter @@ -56,12 +82,22 @@ module = __import__("bsddb.test."+name, globals(), locals(), name) #print module,name alltests.addTest(module.test_suite()) + alltests.addTest(unittest.makeSuite(TimingCheck)) return alltests # For invocation through regrtest def test_main(): run_unittest(suite()) + db_home = os.path.join(tempfile.gettempdir(), 'db_home') + # The only reason to remove db_home is in case if there is an old + # one lying around. This might be by a different user, so just + # ignore errors. We should always make a unique name now. + try: + rmtree(db_home) + except: + pass + rmtree('db_home%d' % os.getpid()) # For invocation as a script if __name__ == '__main__': Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_builtin.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_builtin.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_builtin.py Wed Apr 30 15:57:13 2008 @@ -5,7 +5,7 @@ run_with_locale from operator import neg -import sys, warnings, random, UserDict, io +import sys, warnings, random, collections, io, fractions warnings.filterwarnings("ignore", "hex../oct.. of negative int", FutureWarning, __name__) warnings.filterwarnings("ignore", "integer argument expected", @@ -210,7 +210,7 @@ # verify that circular objects are not handled a = []; a.append(a) b = []; b.append(b) - from UserList import UserList + from collections import UserList c = UserList(); c.append(c) self.assertRaises(RuntimeError, cmp, a, b) self.assertRaises(RuntimeError, cmp, b, c) @@ -400,7 +400,7 @@ # Verify locals stores (used by list comps) eval('[locals() for i in (2,3)]', g, d) - eval('[locals() for i in (2,3)]', g, UserDict.UserDict()) + eval('[locals() for i in (2,3)]', g, collections.UserDict()) class SpreadSheet: "Sample application showing nested, calculated lookups." @@ -448,6 +448,17 @@ del l['__builtins__'] self.assertEqual((g, l), ({'a': 1}, {'b': 2})) + def test_exec_redirected(self): + savestdout = sys.stdout + sys.stdout = None # Whatever that cannot flush() + try: + # Used to raise SystemError('error return without exception set') + exec('a') + except NameError: + pass + finally: + sys.stdout = savestdout + def test_filter(self): self.assertEqual(list(filter(lambda c: 'a' <= c <= 'z', 'Hello World')), list('elloorld')) self.assertEqual(list(filter(None, [1, 'hello', [], [3], '', None, 9, 0])), [1, 'hello', [3], 9]) @@ -541,24 +552,58 @@ self.assertRaises(TypeError, float, Foo4(42)) def test_format(self): - class A: - def __init__(self, x): - self.x = x - def __format__(self, format_spec): - return str(self.x) + format_spec + # Test the basic machinery of the format() builtin. Don't test + # the specifics of the various formatters + self.assertEqual(format(3, ''), '3') - # class that returns a bad type from __format__ - class B: - def __format__(self, format_spec): - return 1.0 + # Returns some classes to use for various tests. There's + # an old-style version, and a new-style version + def classes_new(): + class A(object): + def __init__(self, x): + self.x = x + def __format__(self, format_spec): + return str(self.x) + format_spec + class DerivedFromA(A): + pass - # class that is derived from string, used - # as a format spec - class C(str): - pass + class Simple(object): pass + class DerivedFromSimple(Simple): + def __init__(self, x): + self.x = x + def __format__(self, format_spec): + return str(self.x) + format_spec + class DerivedFromSimple2(DerivedFromSimple): pass + return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2 + + # In 3.0, classes_classic has the same meaning as classes_new + def classes_classic(): + class A: + def __init__(self, x): + self.x = x + def __format__(self, format_spec): + return str(self.x) + format_spec + class DerivedFromA(A): + pass - self.assertEqual(format(3, ''), '3') - self.assertEqual(format(A(3), 'spec'), '3spec') + class Simple: pass + class DerivedFromSimple(Simple): + def __init__(self, x): + self.x = x + def __format__(self, format_spec): + return str(self.x) + format_spec + class DerivedFromSimple2(DerivedFromSimple): pass + return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2 + + def class_test(A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2): + self.assertEqual(format(A(3), 'spec'), '3spec') + self.assertEqual(format(DerivedFromA(4), 'spec'), '4spec') + self.assertEqual(format(DerivedFromSimple(5), 'abc'), '5abc') + self.assertEqual(format(DerivedFromSimple2(10), 'abcdef'), + '10abcdef') + + class_test(*classes_new()) + class_test(*classes_classic()) def empty_format_spec(value): # test that: @@ -578,19 +623,61 @@ empty_format_spec(None) # TypeError because self.__format__ returns the wrong type - self.assertRaises(TypeError, format, B(), "") + class BadFormatResult: + def __format__(self, format_spec): + return 1.0 + self.assertRaises(TypeError, format, BadFormatResult(), "") - # TypeError because format_spec is not unicode + # TypeError because format_spec is not unicode or str self.assertRaises(TypeError, format, object(), 4) self.assertRaises(TypeError, format, object(), object()) + # tests for object.__format__ really belong elsewhere, but + # there's no good place to put them + x = object().__format__('') + self.assert_(x.startswith(' y))) - self.assertNotEqual(data, copy) - random.shuffle(copy) self.assertEqual(data, sorted(copy, key=lambda x: -x)) self.assertNotEqual(data, copy) random.shuffle(copy) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_bytes.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_bytes.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_bytes.py Wed Apr 30 15:57:13 2008 @@ -18,7 +18,7 @@ import test.buffer_tests -class BytesTest(unittest.TestCase): +class BaseBytesTest(unittest.TestCase): def setUp(self): self.warning_filters = warnings.filters[:] @@ -27,12 +27,12 @@ warnings.filters = self.warning_filters def test_basics(self): - b = bytearray() - self.assertEqual(type(b), bytearray) - self.assertEqual(b.__class__, bytearray) + b = self.type2test() + self.assertEqual(type(b), self.type2test) + self.assertEqual(b.__class__, self.type2test) def test_empty_sequence(self): - b = bytearray() + b = self.type2test() self.assertEqual(len(b), 0) self.assertRaises(IndexError, lambda: b[0]) self.assertRaises(IndexError, lambda: b[1]) @@ -48,7 +48,7 @@ def test_from_list(self): ints = list(range(256)) - b = bytearray(i for i in ints) + b = self.type2test(i for i in ints) self.assertEqual(len(b), 256) self.assertEqual(list(b), ints) @@ -58,7 +58,7 @@ self.i = i def __index__(self): return self.i - b = bytearray([C(), C(1), C(254), C(255)]) + b = self.type2test([C(), C(1), C(254), C(255)]) self.assertEqual(list(b), [0, 1, 254, 255]) self.assertRaises(ValueError, bytearray, [C(-1)]) self.assertRaises(ValueError, bytearray, [C(256)]) @@ -73,42 +73,30 @@ self.assertEqual(bytearray(b'0'), b'0') def test_constructor_type_errors(self): - self.assertRaises(TypeError, bytearray, 0.0) + self.assertRaises(TypeError, self.type2test, 0.0) class C: pass - self.assertRaises(TypeError, bytearray, ["0"]) - self.assertRaises(TypeError, bytearray, [0.0]) - self.assertRaises(TypeError, bytearray, [None]) - self.assertRaises(TypeError, bytearray, [C()]) + self.assertRaises(TypeError, self.type2test, ["0"]) + self.assertRaises(TypeError, self.type2test, [0.0]) + self.assertRaises(TypeError, self.type2test, [None]) + self.assertRaises(TypeError, self.type2test, [C()]) def test_constructor_value_errors(self): - self.assertRaises(ValueError, bytearray, [-1]) - self.assertRaises(ValueError, bytearray, [-sys.maxsize]) - self.assertRaises(ValueError, bytearray, [-sys.maxsize-1]) - self.assertRaises(ValueError, bytearray, [-sys.maxsize-2]) - self.assertRaises(ValueError, bytearray, [-10**100]) - self.assertRaises(ValueError, bytearray, [256]) - self.assertRaises(ValueError, bytearray, [257]) - self.assertRaises(ValueError, bytearray, [sys.maxsize]) - self.assertRaises(ValueError, bytearray, [sys.maxsize+1]) - self.assertRaises(ValueError, bytearray, [10**100]) - - def test_repr_str(self): - warnings.simplefilter('ignore', BytesWarning) - for f in str, repr: - self.assertEqual(f(bytearray()), "bytearray(b'')") - self.assertEqual(f(bytearray([0])), "bytearray(b'\\x00')") - self.assertEqual(f(bytearray([0, 1, 254, 255])), - "bytearray(b'\\x00\\x01\\xfe\\xff')") - self.assertEqual(f(b"abc"), "b'abc'") - self.assertEqual(f(b"'"), '''b"'"''') - self.assertEqual(f(b"'\""), r"""b'\'"'""") - + self.assertRaises(ValueError, self.type2test, [-1]) + self.assertRaises(ValueError, self.type2test, [-sys.maxsize]) + self.assertRaises(ValueError, self.type2test, [-sys.maxsize-1]) + self.assertRaises(ValueError, self.type2test, [-sys.maxsize-2]) + self.assertRaises(ValueError, self.type2test, [-10**100]) + self.assertRaises(ValueError, self.type2test, [256]) + self.assertRaises(ValueError, self.type2test, [257]) + self.assertRaises(ValueError, self.type2test, [sys.maxsize]) + self.assertRaises(ValueError, self.type2test, [sys.maxsize+1]) + self.assertRaises(ValueError, self.type2test, [10**100]) def test_compare(self): - b1 = bytearray([1, 2, 3]) - b2 = bytearray([1, 2, 3]) - b3 = bytearray([1, 3]) + b1 = self.type2test([1, 2, 3]) + b2 = self.type2test([1, 2, 3]) + b3 = self.type2test([1, 3]) self.assertEqual(b1, b2) self.failUnless(b2 != b3) @@ -128,102 +116,27 @@ self.failIf(b3 < b2) self.failIf(b3 <= b2) - def test_compare_bytes_to_bytearray(self): - self.assertEqual(b"abc" == bytes(b"abc"), True) - self.assertEqual(b"ab" != bytes(b"abc"), True) - self.assertEqual(b"ab" <= bytes(b"abc"), True) - self.assertEqual(b"ab" < bytes(b"abc"), True) - self.assertEqual(b"abc" >= bytes(b"ab"), True) - self.assertEqual(b"abc" > bytes(b"ab"), True) - - self.assertEqual(b"abc" != bytes(b"abc"), False) - self.assertEqual(b"ab" == bytes(b"abc"), False) - self.assertEqual(b"ab" > bytes(b"abc"), False) - self.assertEqual(b"ab" >= bytes(b"abc"), False) - self.assertEqual(b"abc" < bytes(b"ab"), False) - self.assertEqual(b"abc" <= bytes(b"ab"), False) - - self.assertEqual(bytes(b"abc") == b"abc", True) - self.assertEqual(bytes(b"ab") != b"abc", True) - self.assertEqual(bytes(b"ab") <= b"abc", True) - self.assertEqual(bytes(b"ab") < b"abc", True) - self.assertEqual(bytes(b"abc") >= b"ab", True) - self.assertEqual(bytes(b"abc") > b"ab", True) - - self.assertEqual(bytes(b"abc") != b"abc", False) - self.assertEqual(bytes(b"ab") == b"abc", False) - self.assertEqual(bytes(b"ab") > b"abc", False) - self.assertEqual(bytes(b"ab") >= b"abc", False) - self.assertEqual(bytes(b"abc") < b"ab", False) - self.assertEqual(bytes(b"abc") <= b"ab", False) - def test_compare_to_str(self): warnings.simplefilter('ignore', BytesWarning) # Byte comparisons with unicode should always fail! # Test this for all expected byte orders and Unicode character sizes - self.assertEqual(b"\0a\0b\0c" == "abc", False) - self.assertEqual(b"\0\0\0a\0\0\0b\0\0\0c" == "abc", False) - self.assertEqual(b"a\0b\0c\0" == "abc", False) - self.assertEqual(b"a\0\0\0b\0\0\0c\0\0\0" == "abc", False) - self.assertEqual(bytearray() == str(), False) - self.assertEqual(bytearray() != str(), True) - - def test_nohash(self): - self.assertRaises(TypeError, hash, bytearray()) - - def test_doc(self): - self.failUnless(bytearray.__doc__ != None) - self.failUnless(bytearray.__doc__.startswith("bytearray("), bytearray.__doc__) - self.failUnless(bytes.__doc__ != None) - self.failUnless(bytes.__doc__.startswith("bytes("), bytes.__doc__) - - def test_bytearray_api(self): - short_sample = b"Hello world\n" - sample = short_sample + b"\0"*(20 - len(short_sample)) - tfn = tempfile.mktemp() - try: - # Prepare - with open(tfn, "wb") as f: - f.write(short_sample) - # Test readinto - with open(tfn, "rb") as f: - b = bytearray(20) - n = f.readinto(b) - self.assertEqual(n, len(short_sample)) - self.assertEqual(list(b), list(sample)) - # Test writing in binary mode - with open(tfn, "wb") as f: - f.write(b) - with open(tfn, "rb") as f: - self.assertEqual(f.read(), sample) - # Text mode is ambiguous; don't test - finally: - try: - os.remove(tfn) - except os.error: - pass + self.assertEqual(self.type2test(b"\0a\0b\0c") == "abc", False) + self.assertEqual(self.type2test(b"\0\0\0a\0\0\0b\0\0\0c") == "abc", False) + self.assertEqual(self.type2test(b"a\0b\0c\0") == "abc", False) + self.assertEqual(self.type2test(b"a\0\0\0b\0\0\0c\0\0\0") == "abc", False) + self.assertEqual(self.type2test() == str(), False) + self.assertEqual(self.type2test() != str(), True) def test_reversed(self): input = list(map(ord, "Hello")) - b = bytearray(input) + b = self.type2test(input) output = list(reversed(b)) input.reverse() self.assertEqual(output, input) - def test_reverse(self): - b = bytearray(b'hello') - self.assertEqual(b.reverse(), None) - self.assertEqual(b, b'olleh') - b = bytearray(b'hello1') # test even number of items - b.reverse() - self.assertEqual(b, b'1olleh') - b = bytearray() - b.reverse() - self.assertFalse(b) - def test_getslice(self): def by(s): - return bytearray(map(ord, s)) + return self.type2test(map(ord, s)) b = by("Hello, world") self.assertEqual(b[:5], by("Hello")) @@ -244,159 +157,44 @@ def test_extended_getslice(self): # Test extended slicing by comparing with list slicing. L = list(range(255)) - b = bytearray(L) + b = self.type2test(L) indices = (0, None, 1, 3, 19, 100, -1, -2, -31, -100) for start in indices: for stop in indices: # Skip step 0 (invalid) for step in indices[1:]: - self.assertEqual(b[start:stop:step], bytearray(L[start:stop:step])) - - def test_regexps(self): - def by(s): - return bytearray(map(ord, s)) - b = by("Hello, world") - self.assertEqual(re.findall(r"\w+", b), [by("Hello"), by("world")]) - - def test_setitem(self): - b = bytearray([1, 2, 3]) - b[1] = 100 - self.assertEqual(b, bytearray([1, 100, 3])) - b[-1] = 200 - self.assertEqual(b, bytearray([1, 100, 200])) - class C: - def __init__(self, i=0): - self.i = i - def __index__(self): - return self.i - b[0] = C(10) - self.assertEqual(b, bytearray([10, 100, 200])) - try: - b[3] = 0 - self.fail("Didn't raise IndexError") - except IndexError: - pass - try: - b[-10] = 0 - self.fail("Didn't raise IndexError") - except IndexError: - pass - try: - b[0] = 256 - self.fail("Didn't raise ValueError") - except ValueError: - pass - try: - b[0] = C(-1) - self.fail("Didn't raise ValueError") - except ValueError: - pass - try: - b[0] = None - self.fail("Didn't raise TypeError") - except TypeError: - pass - - def test_delitem(self): - b = bytearray(range(10)) - del b[0] - self.assertEqual(b, bytearray(range(1, 10))) - del b[-1] - self.assertEqual(b, bytearray(range(1, 9))) - del b[4] - self.assertEqual(b, bytearray([1, 2, 3, 4, 6, 7, 8])) - - def test_setslice(self): - b = bytearray(range(10)) - self.assertEqual(list(b), list(range(10))) - - b[0:5] = bytearray([1, 1, 1, 1, 1]) - self.assertEqual(b, bytearray([1, 1, 1, 1, 1, 5, 6, 7, 8, 9])) - - del b[0:-5] - self.assertEqual(b, bytearray([5, 6, 7, 8, 9])) - - b[0:0] = bytearray([0, 1, 2, 3, 4]) - self.assertEqual(b, bytearray(range(10))) - - b[-7:-3] = bytearray([100, 101]) - self.assertEqual(b, bytearray([0, 1, 2, 100, 101, 7, 8, 9])) - - b[3:5] = [3, 4, 5, 6] - self.assertEqual(b, bytearray(range(10))) - - b[3:0] = [42, 42, 42] - self.assertEqual(b, bytearray([0, 1, 2, 42, 42, 42, 3, 4, 5, 6, 7, 8, 9])) - - def test_extended_set_del_slice(self): - indices = (0, None, 1, 3, 19, 300, -1, -2, -31, -300) - for start in indices: - for stop in indices: - # Skip invalid step 0 - for step in indices[1:]: - L = list(range(255)) - b = bytearray(L) - # Make sure we have a slice of exactly the right length, - # but with different data. - data = L[start:stop:step] - data.reverse() - L[start:stop:step] = data - b[start:stop:step] = data - self.assertEquals(b, bytearray(L)) - - del L[start:stop:step] - del b[start:stop:step] - self.assertEquals(b, bytearray(L)) - - def test_setslice_trap(self): - # This test verifies that we correctly handle assigning self - # to a slice of self (the old Lambert Meertens trap). - b = bytearray(range(256)) - b[8:] = b - self.assertEqual(b, bytearray(list(range(8)) + list(range(256)))) + self.assertEqual(b[start:stop:step], self.type2test(L[start:stop:step])) def test_encoding(self): sample = "Hello world\n\u1234\u5678\u9abc\udef0" for enc in ("utf8", "utf16"): - b = bytearray(sample, enc) - self.assertEqual(b, bytearray(sample.encode(enc))) - self.assertRaises(UnicodeEncodeError, bytearray, sample, "latin1") - b = bytearray(sample, "latin1", "ignore") - self.assertEqual(b, bytearray(sample[:-4], "utf-8")) + b = self.type2test(sample, enc) + self.assertEqual(b, self.type2test(sample.encode(enc))) + self.assertRaises(UnicodeEncodeError, self.type2test, sample, "latin1") + b = self.type2test(sample, "latin1", "ignore") + self.assertEqual(b, self.type2test(sample[:-4], "utf-8")) def test_decode(self): sample = "Hello world\n\u1234\u5678\u9abc\def0\def0" for enc in ("utf8", "utf16"): - b = bytearray(sample, enc) + b = self.type2test(sample, enc) self.assertEqual(b.decode(enc), sample) sample = "Hello world\n\x80\x81\xfe\xff" - b = bytearray(sample, "latin1") + b = self.type2test(sample, "latin1") self.assertRaises(UnicodeDecodeError, b.decode, "utf8") self.assertEqual(b.decode("utf8", "ignore"), "Hello world\n") - def test_from_bytearray(self): - sample = bytes(b"Hello world\n\x80\x81\xfe\xff") - buf = memoryview(sample) - b = bytearray(buf) - self.assertEqual(b, bytearray(sample)) - - def test_to_str(self): - warnings.simplefilter('ignore', BytesWarning) - self.assertEqual(str(b''), "b''") - self.assertEqual(str(b'x'), "b'x'") - self.assertEqual(str(b'\x80'), "b'\\x80'") - def test_from_int(self): - b = bytearray(0) - self.assertEqual(b, bytearray()) - b = bytearray(10) - self.assertEqual(b, bytearray([0]*10)) - b = bytearray(10000) - self.assertEqual(b, bytearray([0]*10000)) + b = self.type2test(0) + self.assertEqual(b, self.type2test()) + b = self.type2test(10) + self.assertEqual(b, self.type2test([0]*10)) + b = self.type2test(10000) + self.assertEqual(b, self.type2test([0]*10000)) def test_concat(self): - b1 = b"abc" - b2 = b"def" + b1 = self.type2test(b"abc") + b2 = self.type2test(b"def") self.assertEqual(b1 + b2, b"abcdef") self.assertEqual(b1 + bytes(b"def"), b"abcdef") self.assertEqual(bytes(b"def") + b1, b"defabc") @@ -404,7 +202,7 @@ self.assertRaises(TypeError, lambda: "abc" + b2) def test_repeat(self): - for b in b"abc", bytearray(b"abc"): + for b in b"abc", self.type2test(b"abc"): self.assertEqual(b * 3, b"abcabcabc") self.assertEqual(b * 0, b"") self.assertEqual(b * -1, b"") @@ -415,200 +213,74 @@ lambda: b * sys.maxsize) def test_repeat_1char(self): - self.assertEqual(b'x'*100, bytearray([ord('x')]*100)) - - def test_iconcat(self): - b = bytearray(b"abc") - b1 = b - b += b"def" - self.assertEqual(b, b"abcdef") - self.assertEqual(b, b1) - self.failUnless(b is b1) - b += b"xyz" - self.assertEqual(b, b"abcdefxyz") - try: - b += "" - except TypeError: - pass - else: - self.fail("bytes += unicode didn't raise TypeError") - - def test_irepeat(self): - b = bytearray(b"abc") - b1 = b - b *= 3 - self.assertEqual(b, b"abcabcabc") - self.assertEqual(b, b1) - self.failUnless(b is b1) - - def test_irepeat_1char(self): - b = bytearray(b"x") - b1 = b - b *= 100 - self.assertEqual(b, b"x"*100) - self.assertEqual(b, b1) - self.failUnless(b is b1) + self.assertEqual(self.type2test(b'x')*100, self.type2test([ord('x')]*100)) def test_contains(self): - for b in b"abc", bytearray(b"abc"): - self.failUnless(ord('a') in b) - self.failUnless(int(ord('a')) in b) - self.failIf(200 in b) - self.failIf(200 in b) - self.assertRaises(ValueError, lambda: 300 in b) - self.assertRaises(ValueError, lambda: -1 in b) - self.assertRaises(TypeError, lambda: None in b) - self.assertRaises(TypeError, lambda: float(ord('a')) in b) - self.assertRaises(TypeError, lambda: "a" in b) - for f in bytes, bytearray: - self.failUnless(f(b"") in b) - self.failUnless(f(b"a") in b) - self.failUnless(f(b"b") in b) - self.failUnless(f(b"c") in b) - self.failUnless(f(b"ab") in b) - self.failUnless(f(b"bc") in b) - self.failUnless(f(b"abc") in b) - self.failIf(f(b"ac") in b) - self.failIf(f(b"d") in b) - self.failIf(f(b"dab") in b) - self.failIf(f(b"abd") in b) - - def test_alloc(self): - b = bytearray() - alloc = b.__alloc__() - self.assert_(alloc >= 0) - seq = [alloc] - for i in range(100): - b += b"x" - alloc = b.__alloc__() - self.assert_(alloc >= len(b)) - if alloc not in seq: - seq.append(alloc) + b = self.type2test(b"abc") + self.failUnless(ord('a') in b) + self.failUnless(int(ord('a')) in b) + self.failIf(200 in b) + self.failIf(200 in b) + self.assertRaises(ValueError, lambda: 300 in b) + self.assertRaises(ValueError, lambda: -1 in b) + self.assertRaises(TypeError, lambda: None in b) + self.assertRaises(TypeError, lambda: float(ord('a')) in b) + self.assertRaises(TypeError, lambda: "a" in b) + for f in bytes, bytearray: + self.failUnless(f(b"") in b) + self.failUnless(f(b"a") in b) + self.failUnless(f(b"b") in b) + self.failUnless(f(b"c") in b) + self.failUnless(f(b"ab") in b) + self.failUnless(f(b"bc") in b) + self.failUnless(f(b"abc") in b) + self.failIf(f(b"ac") in b) + self.failIf(f(b"d") in b) + self.failIf(f(b"dab") in b) + self.failIf(f(b"abd") in b) def test_fromhex(self): - self.assertRaises(TypeError, bytearray.fromhex) - self.assertRaises(TypeError, bytearray.fromhex, 1) - self.assertEquals(bytearray.fromhex(''), bytearray()) + self.assertRaises(TypeError, self.type2test.fromhex) + self.assertRaises(TypeError, self.type2test.fromhex, 1) + self.assertEquals(self.type2test.fromhex(''), self.type2test()) b = bytearray([0x1a, 0x2b, 0x30]) - self.assertEquals(bytearray.fromhex('1a2B30'), b) - self.assertEquals(bytearray.fromhex(' 1A 2B 30 '), b) - self.assertEquals(bytearray.fromhex('0000'), b'\0\0') - self.assertRaises(TypeError, bytearray.fromhex, b'1B') - self.assertRaises(ValueError, bytearray.fromhex, 'a') - self.assertRaises(ValueError, bytearray.fromhex, 'rt') - self.assertRaises(ValueError, bytearray.fromhex, '1a b cd') - self.assertRaises(ValueError, bytearray.fromhex, '\x00') - self.assertRaises(ValueError, bytearray.fromhex, '12 \x00 34') + self.assertEquals(self.type2test.fromhex('1a2B30'), b) + self.assertEquals(self.type2test.fromhex(' 1A 2B 30 '), b) + self.assertEquals(self.type2test.fromhex('0000'), b'\0\0') + self.assertRaises(TypeError, self.type2test.fromhex, b'1B') + self.assertRaises(ValueError, self.type2test.fromhex, 'a') + self.assertRaises(ValueError, self.type2test.fromhex, 'rt') + self.assertRaises(ValueError, self.type2test.fromhex, '1a b cd') + self.assertRaises(ValueError, self.type2test.fromhex, '\x00') + self.assertRaises(ValueError, self.type2test.fromhex, '12 \x00 34') def test_join(self): - self.assertEqual(b"".join([]), b"") - self.assertEqual(b"".join([b""]), b"") + self.assertEqual(self.type2test(b"").join([]), b"") + self.assertEqual(self.type2test(b"").join([b""]), b"") for lst in [[b"abc"], [b"a", b"bc"], [b"ab", b"c"], [b"a", b"b", b"c"]]: - self.assertEqual(b"".join(lst), b"abc") - self.assertEqual(b"".join(tuple(lst)), b"abc") - self.assertEqual(b"".join(iter(lst)), b"abc") - self.assertEqual(b".".join([b"ab", b"cd"]), b"ab.cd") + lst = list(map(self.type2test, lst)) + self.assertEqual(self.type2test(b"").join(lst), b"abc") + self.assertEqual(self.type2test(b"").join(tuple(lst)), b"abc") + self.assertEqual(self.type2test(b"").join(iter(lst)), b"abc") + self.assertEqual(self.type2test(b".").join([b"ab", b"cd"]), b"ab.cd") # XXX more... - def test_literal(self): - tests = [ - (b"Wonderful spam", "Wonderful spam"), - (br"Wonderful spam too", "Wonderful spam too"), - (b"\xaa\x00\000\200", "\xaa\x00\000\200"), - (br"\xaa\x00\000\200", r"\xaa\x00\000\200"), - ] - for b, s in tests: - self.assertEqual(b, bytearray(s, 'latin-1')) - for c in range(128, 256): - self.assertRaises(SyntaxError, eval, - 'b"%s"' % chr(c)) - - def test_extend(self): - orig = b'hello' - a = bytearray(orig) - a.extend(a) - self.assertEqual(a, orig + orig) - self.assertEqual(a[5:], orig) - a = bytearray(b'') - # Test iterators that don't have a __length_hint__ - a.extend(map(int, orig * 25)) - a.extend(int(x) for x in orig * 25) - self.assertEqual(a, orig * 50) - self.assertEqual(a[-5:], orig) - a = bytearray(b'') - a.extend(iter(map(int, orig * 50))) - self.assertEqual(a, orig * 50) - self.assertEqual(a[-5:], orig) - a = bytearray(b'') - a.extend(list(map(int, orig * 50))) - self.assertEqual(a, orig * 50) - self.assertEqual(a[-5:], orig) - a = bytearray(b'') - self.assertRaises(ValueError, a.extend, [0, 1, 2, 256]) - self.assertRaises(ValueError, a.extend, [0, 1, 2, -1]) - self.assertEqual(len(a), 0) - - def test_remove(self): - b = bytearray(b'hello') - b.remove(ord('l')) - self.assertEqual(b, b'helo') - b.remove(ord('l')) - self.assertEqual(b, b'heo') - self.assertRaises(ValueError, lambda: b.remove(ord('l'))) - self.assertRaises(ValueError, lambda: b.remove(400)) - self.assertRaises(TypeError, lambda: b.remove('e')) - # remove first and last - b.remove(ord('o')) - b.remove(ord('h')) - self.assertEqual(b, b'e') - self.assertRaises(TypeError, lambda: b.remove(b'e')) - - def test_pop(self): - b = bytearray(b'world') - self.assertEqual(b.pop(), ord('d')) - self.assertEqual(b.pop(0), ord('w')) - self.assertEqual(b.pop(-2), ord('r')) - self.assertRaises(IndexError, lambda: b.pop(10)) - self.assertRaises(OverflowError, lambda: bytearray().pop()) - - def test_nosort(self): - self.assertRaises(AttributeError, lambda: bytearray().sort()) - def test_index(self): - b = b'parrot' + b = self.type2test(b'parrot') self.assertEqual(b.index('p'), 0) self.assertEqual(b.index('rr'), 2) self.assertEqual(b.index('t'), 5) self.assertRaises(ValueError, lambda: b.index('w')) def test_count(self): - b = b'mississippi' + b = self.type2test(b'mississippi') self.assertEqual(b.count(b'i'), 4) self.assertEqual(b.count(b'ss'), 2) self.assertEqual(b.count(b'w'), 0) - def test_append(self): - b = bytearray(b'hell') - b.append(ord('o')) - self.assertEqual(b, b'hello') - self.assertEqual(b.append(100), None) - b = bytearray() - b.append(ord('A')) - self.assertEqual(len(b), 1) - self.assertRaises(TypeError, lambda: b.append(b'o')) - - def test_insert(self): - b = bytearray(b'msssspp') - b.insert(1, ord('i')) - b.insert(4, ord('i')) - b.insert(-2, ord('i')) - b.insert(1000, ord('i')) - self.assertEqual(b, b'mississippi') - self.assertRaises(TypeError, lambda: b.insert(0, b'1')) - def test_startswith(self): - b = b'hello' - self.assertFalse(bytearray().startswith(b"anything")) + b = self.type2test(b'hello') + self.assertFalse(self.type2test().startswith(b"anything")) self.assertTrue(b.startswith(b"hello")) self.assertTrue(b.startswith(b"hel")) self.assertTrue(b.startswith(b"h")) @@ -616,7 +288,7 @@ self.assertFalse(b.startswith(b"ha")) def test_endswith(self): - b = b'hello' + b = self.type2test(b'hello') self.assertFalse(bytearray().endswith(b"anything")) self.assertTrue(b.endswith(b"hello")) self.assertTrue(b.endswith(b"llo")) @@ -625,7 +297,7 @@ self.assertFalse(b.endswith(b"no")) def test_find(self): - b = b'mississippi' + b = self.type2test(b'mississippi') self.assertEqual(b.find(b'ss'), 2) self.assertEqual(b.find(b'ss', 3), 5) self.assertEqual(b.find(b'ss', 1, 7), 2) @@ -634,7 +306,7 @@ self.assertEqual(b.find(b'mississippian'), -1) def test_rfind(self): - b = b'mississippi' + b = self.type2test(b'mississippi') self.assertEqual(b.rfind(b'ss'), 5) self.assertEqual(b.rfind(b'ss', 3), 5) self.assertEqual(b.rfind(b'ss', 0, 6), 2) @@ -642,7 +314,7 @@ self.assertEqual(b.rfind(b'mississippian'), -1) def test_index(self): - b = b'world' + b = self.type2test(b'world') self.assertEqual(b.index(b'w'), 0) self.assertEqual(b.index(b'orl'), 1) self.assertRaises(ValueError, b.index, b'worm') @@ -650,27 +322,19 @@ def test_rindex(self): # XXX could be more rigorous - b = b'world' + b = self.type2test(b'world') self.assertEqual(b.rindex(b'w'), 0) self.assertEqual(b.rindex(b'orl'), 1) self.assertRaises(ValueError, b.rindex, b'worm') self.assertRaises(ValueError, b.rindex, b'ldo') def test_replace(self): - b = b'mississippi' + b = self.type2test(b'mississippi') self.assertEqual(b.replace(b'i', b'a'), b'massassappa') self.assertEqual(b.replace(b'ss', b'x'), b'mixixippi') - def test_translate(self): - b = b'hello' - rosetta = bytearray(range(0, 256)) - rosetta[ord('o')] = ord('e') - c = b.translate(rosetta, b'l') - self.assertEqual(b, b'hello') - self.assertEqual(c, b'hee') - def test_split(self): - b = b'mississippi' + b = self.type2test(b'mississippi') self.assertEqual(b.split(b'i'), [b'm', b'ss', b'ss', b'pp', b'']) self.assertEqual(b.split(b'ss'), [b'mi', b'i', b'ippi']) self.assertEqual(b.split(b'w'), [b]) @@ -678,22 +342,23 @@ def test_split_whitespace(self): for b in (b' arf barf ', b'arf\tbarf', b'arf\nbarf', b'arf\rbarf', b'arf\fbarf', b'arf\vbarf'): + b = self.type2test(b) self.assertEqual(b.split(), [b'arf', b'barf']) self.assertEqual(b.split(None), [b'arf', b'barf']) self.assertEqual(b.split(None, 2), [b'arf', b'barf']) - self.assertEqual(b' a bb c '.split(None, 0), [b'a bb c ']) - self.assertEqual(b' a bb c '.split(None, 1), [b'a', b'bb c ']) - self.assertEqual(b' a bb c '.split(None, 2), [b'a', b'bb', b'c ']) - self.assertEqual(b' a bb c '.split(None, 3), [b'a', b'bb', b'c']) - - def test_split_bytearray(self): - self.assertEqual(b'a b'.split(memoryview(b' ')), [b'a', b'b']) + for b in (b'a\x1Cb', b'a\x1Db', b'a\x1Eb', b'a\x1Fb'): + b = self.type2test(b) + self.assertEqual(b.split(), [b]) + self.assertEqual(self.type2test(b' a bb c ').split(None, 0), [b'a bb c ']) + self.assertEqual(self.type2test(b' a bb c ').split(None, 1), [b'a', b'bb c ']) + self.assertEqual(self.type2test(b' a bb c ').split(None, 2), [b'a', b'bb', b'c ']) + self.assertEqual(self.type2test(b' a bb c ').split(None, 3), [b'a', b'bb', b'c']) def test_split_string_error(self): - self.assertRaises(TypeError, b'a b'.split, ' ') + self.assertRaises(TypeError, self.type2test(b'a b').split, ' ') def test_rsplit(self): - b = b'mississippi' + b = self.type2test(b'mississippi') self.assertEqual(b.rsplit(b'i'), [b'm', b'ss', b'ss', b'pp', b'']) self.assertEqual(b.rsplit(b'ss'), [b'mi', b'i', b'ippi']) self.assertEqual(b.rsplit(b'w'), [b]) @@ -701,39 +366,43 @@ def test_rsplit_whitespace(self): for b in (b' arf barf ', b'arf\tbarf', b'arf\nbarf', b'arf\rbarf', b'arf\fbarf', b'arf\vbarf'): + b = self.type2test(b) self.assertEqual(b.rsplit(), [b'arf', b'barf']) self.assertEqual(b.rsplit(None), [b'arf', b'barf']) self.assertEqual(b.rsplit(None, 2), [b'arf', b'barf']) - self.assertEqual(b' a bb c '.rsplit(None, 0), [b' a bb c']) - self.assertEqual(b' a bb c '.rsplit(None, 1), [b' a bb', b'c']) - self.assertEqual(b' a bb c '.rsplit(None,2), [b' a', b'bb', b'c']) - self.assertEqual(b' a bb c '.rsplit(None, 3), [b'a', b'bb', b'c']) - - def test_rsplit_bytearray(self): - self.assertEqual(b'a b'.rsplit(memoryview(b' ')), [b'a', b'b']) + self.assertEqual(self.type2test(b' a bb c ').rsplit(None, 0), [b' a bb c']) + self.assertEqual(self.type2test(b' a bb c ').rsplit(None, 1), [b' a bb', b'c']) + self.assertEqual(self.type2test(b' a bb c ').rsplit(None, 2), [b' a', b'bb', b'c']) + self.assertEqual(self.type2test(b' a bb c ').rsplit(None, 3), [b'a', b'bb', b'c']) def test_rsplit_string_error(self): - self.assertRaises(TypeError, b'a b'.rsplit, ' ') + self.assertRaises(TypeError, self.type2test(b'a b').rsplit, ' ') + + def test_rsplit_unicodewhitespace(self): + b = self.type2test(b"\x09\x0A\x0B\x0C\x0D\x1C\x1D\x1E\x1F") + self.assertEqual(b.split(), [b'\x1c\x1d\x1e\x1f']) + self.assertEqual(b.rsplit(), [b'\x1c\x1d\x1e\x1f']) def test_partition(self): - b = b'mississippi' + b = self.type2test(b'mississippi') self.assertEqual(b.partition(b'ss'), (b'mi', b'ss', b'issippi')) self.assertEqual(b.rpartition(b'w'), (b'', b'', b'mississippi')) def test_rpartition(self): - b = b'mississippi' + b = self.type2test(b'mississippi') self.assertEqual(b.rpartition(b'ss'), (b'missi', b'ss', b'ippi')) self.assertEqual(b.rpartition(b'i'), (b'mississipp', b'i', b'')) def test_pickling(self): for proto in range(pickle.HIGHEST_PROTOCOL): for b in b"", b"a", b"abc", b"\xffab\x80", b"\0\0\377\0\0": + b = self.type2test(b) ps = pickle.dumps(b, proto) q = pickle.loads(ps) self.assertEqual(b, q) def test_strip(self): - b = b'mississippi' + b = self.type2test(b'mississippi') self.assertEqual(b.strip(b'i'), b'mississipp') self.assertEqual(b.strip(b'm'), b'ississippi') self.assertEqual(b.strip(b'pi'), b'mississ') @@ -742,7 +411,7 @@ self.assertEqual(b.strip(b), b'') def test_lstrip(self): - b = b'mississippi' + b = self.type2test(b'mississippi') self.assertEqual(b.lstrip(b'i'), b'mississippi') self.assertEqual(b.lstrip(b'm'), b'ississippi') self.assertEqual(b.lstrip(b'pi'), b'mississippi') @@ -750,7 +419,7 @@ self.assertEqual(b.lstrip(b'pim'), b'ssissippi') def test_rstrip(self): - b = b'mississippi' + b = self.type2test(b'mississippi') self.assertEqual(b.rstrip(b'i'), b'mississipp') self.assertEqual(b.rstrip(b'm'), b'mississippi') self.assertEqual(b.rstrip(b'pi'), b'mississ') @@ -758,26 +427,290 @@ self.assertEqual(b.rstrip(b'pim'), b'mississ') def test_strip_whitespace(self): - b = b' \t\n\r\f\vabc \t\n\r\f\v' + b = self.type2test(b' \t\n\r\f\vabc \t\n\r\f\v') self.assertEqual(b.strip(), b'abc') self.assertEqual(b.lstrip(), b'abc \t\n\r\f\v') self.assertEqual(b.rstrip(), b' \t\n\r\f\vabc') def test_strip_bytearray(self): - self.assertEqual(b'abc'.strip(memoryview(b'ac')), b'b') - self.assertEqual(b'abc'.lstrip(memoryview(b'ac')), b'bc') - self.assertEqual(b'abc'.rstrip(memoryview(b'ac')), b'ab') + self.assertEqual(self.type2test(b'abc').strip(memoryview(b'ac')), b'b') + self.assertEqual(self.type2test(b'abc').lstrip(memoryview(b'ac')), b'bc') + self.assertEqual(self.type2test(b'abc').rstrip(memoryview(b'ac')), b'ab') def test_strip_string_error(self): - self.assertRaises(TypeError, b'abc'.strip, 'b') - self.assertRaises(TypeError, b'abc'.lstrip, 'b') - self.assertRaises(TypeError, b'abc'.rstrip, 'b') + self.assertRaises(TypeError, self.type2test(b'abc').strip, 'b') + self.assertRaises(TypeError, self.type2test(b'abc').lstrip, 'b') + self.assertRaises(TypeError, self.type2test(b'abc').rstrip, 'b') def test_ord(self): - b = b'\0A\x7f\x80\xff' + b = self.type2test(b'\0A\x7f\x80\xff') self.assertEqual([ord(b[i:i+1]) for i in range(len(b))], [0, 65, 127, 128, 255]) + +class BytesTest(BaseBytesTest): + type2test = bytes + +class ByteArrayTest(BaseBytesTest): + type2test = bytearray + + def test_nohash(self): + self.assertRaises(TypeError, hash, bytearray()) + + def test_bytearray_api(self): + short_sample = b"Hello world\n" + sample = short_sample + b"\0"*(20 - len(short_sample)) + tfn = tempfile.mktemp() + try: + # Prepare + with open(tfn, "wb") as f: + f.write(short_sample) + # Test readinto + with open(tfn, "rb") as f: + b = bytearray(20) + n = f.readinto(b) + self.assertEqual(n, len(short_sample)) + self.assertEqual(list(b), list(sample)) + # Test writing in binary mode + with open(tfn, "wb") as f: + f.write(b) + with open(tfn, "rb") as f: + self.assertEqual(f.read(), sample) + # Text mode is ambiguous; don't test + finally: + try: + os.remove(tfn) + except os.error: + pass + + def test_reverse(self): + b = bytearray(b'hello') + self.assertEqual(b.reverse(), None) + self.assertEqual(b, b'olleh') + b = bytearray(b'hello1') # test even number of items + b.reverse() + self.assertEqual(b, b'1olleh') + b = bytearray() + b.reverse() + self.assertFalse(b) + + def test_regexps(self): + def by(s): + return bytearray(map(ord, s)) + b = by("Hello, world") + self.assertEqual(re.findall(r"\w+", b), [by("Hello"), by("world")]) + + def test_setitem(self): + b = bytearray([1, 2, 3]) + b[1] = 100 + self.assertEqual(b, bytearray([1, 100, 3])) + b[-1] = 200 + self.assertEqual(b, bytearray([1, 100, 200])) + class C: + def __init__(self, i=0): + self.i = i + def __index__(self): + return self.i + b[0] = C(10) + self.assertEqual(b, bytearray([10, 100, 200])) + try: + b[3] = 0 + self.fail("Didn't raise IndexError") + except IndexError: + pass + try: + b[-10] = 0 + self.fail("Didn't raise IndexError") + except IndexError: + pass + try: + b[0] = 256 + self.fail("Didn't raise ValueError") + except ValueError: + pass + try: + b[0] = C(-1) + self.fail("Didn't raise ValueError") + except ValueError: + pass + try: + b[0] = None + self.fail("Didn't raise TypeError") + except TypeError: + pass + + def test_delitem(self): + b = bytearray(range(10)) + del b[0] + self.assertEqual(b, bytearray(range(1, 10))) + del b[-1] + self.assertEqual(b, bytearray(range(1, 9))) + del b[4] + self.assertEqual(b, bytearray([1, 2, 3, 4, 6, 7, 8])) + + def test_setslice(self): + b = bytearray(range(10)) + self.assertEqual(list(b), list(range(10))) + + b[0:5] = bytearray([1, 1, 1, 1, 1]) + self.assertEqual(b, bytearray([1, 1, 1, 1, 1, 5, 6, 7, 8, 9])) + + del b[0:-5] + self.assertEqual(b, bytearray([5, 6, 7, 8, 9])) + + b[0:0] = bytearray([0, 1, 2, 3, 4]) + self.assertEqual(b, bytearray(range(10))) + + b[-7:-3] = bytearray([100, 101]) + self.assertEqual(b, bytearray([0, 1, 2, 100, 101, 7, 8, 9])) + + b[3:5] = [3, 4, 5, 6] + self.assertEqual(b, bytearray(range(10))) + + b[3:0] = [42, 42, 42] + self.assertEqual(b, bytearray([0, 1, 2, 42, 42, 42, 3, 4, 5, 6, 7, 8, 9])) + + def test_extended_set_del_slice(self): + indices = (0, None, 1, 3, 19, 300, -1, -2, -31, -300) + for start in indices: + for stop in indices: + # Skip invalid step 0 + for step in indices[1:]: + L = list(range(255)) + b = bytearray(L) + # Make sure we have a slice of exactly the right length, + # but with different data. + data = L[start:stop:step] + data.reverse() + L[start:stop:step] = data + b[start:stop:step] = data + self.assertEquals(b, bytearray(L)) + + del L[start:stop:step] + del b[start:stop:step] + self.assertEquals(b, bytearray(L)) + + def test_setslice_trap(self): + # This test verifies that we correctly handle assigning self + # to a slice of self (the old Lambert Meertens trap). + b = bytearray(range(256)) + b[8:] = b + self.assertEqual(b, bytearray(list(range(8)) + list(range(256)))) + + def test_iconcat(self): + b = bytearray(b"abc") + b1 = b + b += b"def" + self.assertEqual(b, b"abcdef") + self.assertEqual(b, b1) + self.failUnless(b is b1) + b += b"xyz" + self.assertEqual(b, b"abcdefxyz") + try: + b += "" + except TypeError: + pass + else: + self.fail("bytes += unicode didn't raise TypeError") + + def test_irepeat(self): + b = bytearray(b"abc") + b1 = b + b *= 3 + self.assertEqual(b, b"abcabcabc") + self.assertEqual(b, b1) + self.failUnless(b is b1) + + def test_irepeat_1char(self): + b = bytearray(b"x") + b1 = b + b *= 100 + self.assertEqual(b, b"x"*100) + self.assertEqual(b, b1) + self.failUnless(b is b1) + + def test_alloc(self): + b = bytearray() + alloc = b.__alloc__() + self.assert_(alloc >= 0) + seq = [alloc] + for i in range(100): + b += b"x" + alloc = b.__alloc__() + self.assert_(alloc >= len(b)) + if alloc not in seq: + seq.append(alloc) + + def test_extend(self): + orig = b'hello' + a = bytearray(orig) + a.extend(a) + self.assertEqual(a, orig + orig) + self.assertEqual(a[5:], orig) + a = bytearray(b'') + # Test iterators that don't have a __length_hint__ + a.extend(map(int, orig * 25)) + a.extend(int(x) for x in orig * 25) + self.assertEqual(a, orig * 50) + self.assertEqual(a[-5:], orig) + a = bytearray(b'') + a.extend(iter(map(int, orig * 50))) + self.assertEqual(a, orig * 50) + self.assertEqual(a[-5:], orig) + a = bytearray(b'') + a.extend(list(map(int, orig * 50))) + self.assertEqual(a, orig * 50) + self.assertEqual(a[-5:], orig) + a = bytearray(b'') + self.assertRaises(ValueError, a.extend, [0, 1, 2, 256]) + self.assertRaises(ValueError, a.extend, [0, 1, 2, -1]) + self.assertEqual(len(a), 0) + + def test_remove(self): + b = bytearray(b'hello') + b.remove(ord('l')) + self.assertEqual(b, b'helo') + b.remove(ord('l')) + self.assertEqual(b, b'heo') + self.assertRaises(ValueError, lambda: b.remove(ord('l'))) + self.assertRaises(ValueError, lambda: b.remove(400)) + self.assertRaises(TypeError, lambda: b.remove('e')) + # remove first and last + b.remove(ord('o')) + b.remove(ord('h')) + self.assertEqual(b, b'e') + self.assertRaises(TypeError, lambda: b.remove(b'e')) + + def test_pop(self): + b = bytearray(b'world') + self.assertEqual(b.pop(), ord('d')) + self.assertEqual(b.pop(0), ord('w')) + self.assertEqual(b.pop(-2), ord('r')) + self.assertRaises(IndexError, lambda: b.pop(10)) + self.assertRaises(OverflowError, lambda: bytearray().pop()) + + def test_nosort(self): + self.assertRaises(AttributeError, lambda: bytearray().sort()) + + def test_append(self): + b = bytearray(b'hell') + b.append(ord('o')) + self.assertEqual(b, b'hello') + self.assertEqual(b.append(100), None) + b = bytearray() + b.append(ord('A')) + self.assertEqual(len(b), 1) + self.assertRaises(TypeError, lambda: b.append(b'o')) + + def test_insert(self): + b = bytearray(b'msssspp') + b.insert(1, ord('i')) + b.insert(4, ord('i')) + b.insert(-2, ord('i')) + b.insert(1000, ord('i')) + self.assertEqual(b, b'mississippi') + self.assertRaises(TypeError, lambda: b.insert(0, b'1')) + def test_partition_bytearray_doesnt_share_nullstring(self): a, b, c = bytearray(b"x").partition(b"y") self.assertEqual(b, b"") @@ -800,6 +733,105 @@ self.assertEqual(c, b"") +class AssortedBytesTest(unittest.TestCase): + # + # Test various combinations of bytes and bytearray + # + + def setUp(self): + self.warning_filters = warnings.filters[:] + + def tearDown(self): + warnings.filters = self.warning_filters + + def test_repr_str(self): + warnings.simplefilter('ignore', BytesWarning) + for f in str, repr: + self.assertEqual(f(bytearray()), "bytearray(b'')") + self.assertEqual(f(bytearray([0])), "bytearray(b'\\x00')") + self.assertEqual(f(bytearray([0, 1, 254, 255])), + "bytearray(b'\\x00\\x01\\xfe\\xff')") + self.assertEqual(f(b"abc"), "b'abc'") + self.assertEqual(f(b"'"), '''b"'"''') # ''' + self.assertEqual(f(b"'\""), r"""b'\'"'""") # ' + + def test_compare_bytes_to_bytearray(self): + self.assertEqual(b"abc" == bytes(b"abc"), True) + self.assertEqual(b"ab" != bytes(b"abc"), True) + self.assertEqual(b"ab" <= bytes(b"abc"), True) + self.assertEqual(b"ab" < bytes(b"abc"), True) + self.assertEqual(b"abc" >= bytes(b"ab"), True) + self.assertEqual(b"abc" > bytes(b"ab"), True) + + self.assertEqual(b"abc" != bytes(b"abc"), False) + self.assertEqual(b"ab" == bytes(b"abc"), False) + self.assertEqual(b"ab" > bytes(b"abc"), False) + self.assertEqual(b"ab" >= bytes(b"abc"), False) + self.assertEqual(b"abc" < bytes(b"ab"), False) + self.assertEqual(b"abc" <= bytes(b"ab"), False) + + self.assertEqual(bytes(b"abc") == b"abc", True) + self.assertEqual(bytes(b"ab") != b"abc", True) + self.assertEqual(bytes(b"ab") <= b"abc", True) + self.assertEqual(bytes(b"ab") < b"abc", True) + self.assertEqual(bytes(b"abc") >= b"ab", True) + self.assertEqual(bytes(b"abc") > b"ab", True) + + self.assertEqual(bytes(b"abc") != b"abc", False) + self.assertEqual(bytes(b"ab") == b"abc", False) + self.assertEqual(bytes(b"ab") > b"abc", False) + self.assertEqual(bytes(b"ab") >= b"abc", False) + self.assertEqual(bytes(b"abc") < b"ab", False) + self.assertEqual(bytes(b"abc") <= b"ab", False) + + def test_doc(self): + self.failUnless(bytearray.__doc__ != None) + self.failUnless(bytearray.__doc__.startswith("bytearray("), bytearray.__doc__) + self.failUnless(bytes.__doc__ != None) + self.failUnless(bytes.__doc__.startswith("bytes("), bytes.__doc__) + + def test_from_bytearray(self): + sample = bytes(b"Hello world\n\x80\x81\xfe\xff") + buf = memoryview(sample) + b = bytearray(buf) + self.assertEqual(b, bytearray(sample)) + + def test_to_str(self): + warnings.simplefilter('ignore', BytesWarning) + self.assertEqual(str(b''), "b''") + self.assertEqual(str(b'x'), "b'x'") + self.assertEqual(str(b'\x80'), "b'\\x80'") + self.assertEqual(str(bytearray(b'')), "bytearray(b'')") + self.assertEqual(str(bytearray(b'x')), "bytearray(b'x')") + self.assertEqual(str(bytearray(b'\x80')), "bytearray(b'\\x80')") + + def test_literal(self): + tests = [ + (b"Wonderful spam", "Wonderful spam"), + (br"Wonderful spam too", "Wonderful spam too"), + (b"\xaa\x00\000\200", "\xaa\x00\000\200"), + (br"\xaa\x00\000\200", r"\xaa\x00\000\200"), + ] + for b, s in tests: + self.assertEqual(b, bytearray(s, 'latin-1')) + for c in range(128, 256): + self.assertRaises(SyntaxError, eval, + 'b"%s"' % chr(c)) + + def test_translate(self): + b = b'hello' + rosetta = bytearray(range(0, 256)) + rosetta[ord('o')] = ord('e') + c = b.translate(rosetta, b'l') + self.assertEqual(b, b'hello') + self.assertEqual(c, b'hee') + + def test_split_bytearray(self): + self.assertEqual(b'a b'.split(memoryview(b' ')), [b'a', b'b']) + + def test_rsplit_bytearray(self): + self.assertEqual(b'a b'.rsplit(memoryview(b' ')), [b'a', b'b']) + # Optimizations: # __iter__? (optimization) # __reversed__? (optimization) @@ -832,8 +864,7 @@ methname+' returned self on a mutable object') -class BytesAsStringTest(test.string_tests.BaseTest): - type2test = bytearray +class FixedStringTest(test.string_tests.BaseTest): def fixtype(self, obj): if isinstance(obj, str): @@ -852,6 +883,12 @@ def test_lower(self): pass +class ByteArrayAsStringTest(FixedStringTest): + type2test = bytearray + +class BytesAsStringTest(FixedStringTest): + type2test = bytes + class ByteArraySubclass(bytearray): pass @@ -933,7 +970,10 @@ def test_main(): test.test_support.run_unittest(BytesTest) + test.test_support.run_unittest(ByteArrayTest) + test.test_support.run_unittest(AssortedBytesTest) test.test_support.run_unittest(BytesAsStringTest) + test.test_support.run_unittest(ByteArrayAsStringTest) test.test_support.run_unittest(ByteArraySubclassTest) test.test_support.run_unittest(BytearrayPEP3137Test) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_cProfile.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_cProfile.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_cProfile.py Wed Apr 30 15:57:13 2008 @@ -119,5 +119,11 @@ ticks += 1 raise AttributeError + +def test_main(): + from test.test_support import TestSkipped + raise TestSkipped('test_cProfile test is current broken') + + if __name__ == "__main__": test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_capi.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_capi.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_capi.py Wed Apr 30 15:57:13 2008 @@ -16,9 +16,6 @@ # some extra thread-state tests driven via _testcapi def TestThreadState(): - import thread - import time - if test_support.verbose: print("auto-thread-state") @@ -42,6 +39,8 @@ have_thread_state = False if have_thread_state: + import thread + import time TestThreadState() import threading t=threading.Thread(target=TestThreadState) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_cfgparser.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_cfgparser.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_cfgparser.py Wed Apr 30 15:57:13 2008 @@ -1,11 +1,11 @@ import ConfigParser import io import unittest -import UserDict +import collections from test import test_support -class SortedDict(UserDict.UserDict): +class SortedDict(collections.UserDict): def items(self): return sorted(self.data.items()) @@ -436,6 +436,14 @@ self.assertRaises(TypeError, cf.set, "sect", "option2", 1.0) self.assertRaises(TypeError, cf.set, "sect", "option2", object()) + def test_add_section_default_1(self): + cf = self.newconfig() + self.assertRaises(ValueError, cf.add_section, "default") + + def test_add_section_default_2(self): + cf = self.newconfig() + self.assertRaises(ValueError, cf.add_section, "DEFAULT") + class SortedTestCase(RawConfigParserTestCase): def newconfig(self, defaults=None): self.cf = self.config_class(defaults=defaults, dict_type=SortedDict) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_class.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_class.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_class.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,6 @@ "Test the functionality of Python classes implementing operators." import unittest -import sys from test import test_support Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_cmath.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_cmath.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_cmath.py Wed Apr 30 15:57:13 2008 @@ -1,6 +1,81 @@ from test.test_support import run_unittest +from test.test_math import parse_testfile, test_file import unittest +import os, sys import cmath, math +from cmath import phase, polar, rect, pi + +INF = float('inf') +NAN = float('nan') + +complex_zeros = [complex(x, y) for x in [0.0, -0.0] for y in [0.0, -0.0]] +complex_infinities = [complex(x, y) for x, y in [ + (INF, 0.0), # 1st quadrant + (INF, 2.3), + (INF, INF), + (2.3, INF), + (0.0, INF), + (-0.0, INF), # 2nd quadrant + (-2.3, INF), + (-INF, INF), + (-INF, 2.3), + (-INF, 0.0), + (-INF, -0.0), # 3rd quadrant + (-INF, -2.3), + (-INF, -INF), + (-2.3, -INF), + (-0.0, -INF), + (0.0, -INF), # 4th quadrant + (2.3, -INF), + (INF, -INF), + (INF, -2.3), + (INF, -0.0) + ]] +complex_nans = [complex(x, y) for x, y in [ + (NAN, -INF), + (NAN, -2.3), + (NAN, -0.0), + (NAN, 0.0), + (NAN, 2.3), + (NAN, INF), + (-INF, NAN), + (-2.3, NAN), + (-0.0, NAN), + (0.0, NAN), + (2.3, NAN), + (INF, NAN) + ]] + +def almostEqualF(a, b, rel_err=2e-15, abs_err = 5e-323): + """Determine whether floating-point values a and b are equal to within + a (small) rounding error. The default values for rel_err and + abs_err are chosen to be suitable for platforms where a float is + represented by an IEEE 754 double. They allow an error of between + 9 and 19 ulps.""" + + # special values testing + if math.isnan(a): + return math.isnan(b) + if math.isinf(a): + return a == b + + # if both a and b are zero, check whether they have the same sign + # (in theory there are examples where it would be legitimate for a + # and b to have opposite signs; in practice these hardly ever + # occur). + if not a and not b: + return math.copysign(1., a) == math.copysign(1., b) + + # if a-b overflows, or b is infinite, return False. Again, in + # theory there are examples where a is within a few ulps of the + # max representable float, and then b could legitimately be + # infinite. In practice these examples are rare. + try: + absolute_error = abs(b-a) + except OverflowError: + return False + else: + return absolute_error <= max(abs_err, rel_err * abs(a)) class CMathTests(unittest.TestCase): # list of all functions in cmath @@ -12,25 +87,51 @@ test_functions.append(lambda x : cmath.log(x, 1729. + 0j)) test_functions.append(lambda x : cmath.log(14.-27j, x)) - def cAssertAlmostEqual(self, a, b, rel_eps = 1e-10, abs_eps = 1e-100): - """Check that two complex numbers are almost equal.""" - # the two complex numbers are considered almost equal if - # either the relative error is <= rel_eps or the absolute error - # is tiny, <= abs_eps. - if a == b == 0: - return - absolute_error = abs(a-b) - relative_error = absolute_error/max(abs(a), abs(b)) - if relative_error > rel_eps and absolute_error > abs_eps: - self.fail("%s and %s are not almost equal" % (a, b)) + def setUp(self): + self.test_values = open(test_file) + + def tearDown(self): + self.test_values.close() + + def rAssertAlmostEqual(self, a, b, rel_err = 2e-15, abs_err = 5e-323): + """Check that two floating-point numbers are almost equal.""" + + # special values testing + if math.isnan(a): + if math.isnan(b): + return + self.fail("%s should be nan" % repr(b)) + + if math.isinf(a): + if a == b: + return + self.fail("finite result where infinity excpected: " + "expected %s, got %s" % (repr(a), repr(b))) + + if not a and not b: + if math.atan2(a, -1.) != math.atan2(b, -1.): + self.fail("zero has wrong sign: expected %s, got %s" % + (repr(a), repr(b))) + + # test passes if either the absolute error or the relative + # error is sufficiently small. The defaults amount to an + # error of between 9 ulps and 19 ulps on an IEEE-754 compliant + # machine. + + try: + absolute_error = abs(b-a) + except OverflowError: + pass + else: + if absolute_error <= max(abs_err, rel_err * abs(a)): + return + self.fail("%s and %s are not sufficiently close" % (repr(a), repr(b))) def test_constants(self): e_expected = 2.71828182845904523536 pi_expected = 3.14159265358979323846 - self.assertAlmostEqual(cmath.pi, pi_expected, places=9, - msg="cmath.pi is %s; should be %s" % (cmath.pi, pi_expected)) - self.assertAlmostEqual(cmath.e, e_expected, places=9, - msg="cmath.e is %s; should be %s" % (cmath.e, e_expected)) + self.assertAlmostEqual(cmath.pi, pi_expected) + self.assertAlmostEqual(cmath.e, e_expected) def test_user_object(self): # Test automatic calling of __complex__ and __float__ by cmath @@ -109,13 +210,13 @@ for f in self.test_functions: # usual usage - self.cAssertAlmostEqual(f(MyComplex(cx_arg)), f(cx_arg)) - self.cAssertAlmostEqual(f(MyComplexOS(cx_arg)), f(cx_arg)) + self.assertEqual(f(MyComplex(cx_arg)), f(cx_arg)) + self.assertEqual(f(MyComplexOS(cx_arg)), f(cx_arg)) # other combinations of __float__ and __complex__ - self.cAssertAlmostEqual(f(FloatAndComplex()), f(cx_arg)) - self.cAssertAlmostEqual(f(FloatAndComplexOS()), f(cx_arg)) - self.cAssertAlmostEqual(f(JustFloat()), f(flt_arg)) - self.cAssertAlmostEqual(f(JustFloatOS()), f(flt_arg)) + self.assertEqual(f(FloatAndComplex()), f(cx_arg)) + self.assertEqual(f(FloatAndComplexOS()), f(cx_arg)) + self.assertEqual(f(JustFloat()), f(flt_arg)) + self.assertEqual(f(JustFloatOS()), f(flt_arg)) # TypeError should be raised for classes not providing # either __complex__ or __float__, even if they provide # __int__, __long__ or __index__. An old-style class @@ -138,7 +239,7 @@ # functions, by virtue of providing a __float__ method for f in self.test_functions: for arg in [2, 2.]: - self.cAssertAlmostEqual(f(arg), f(arg.__float__())) + self.assertEqual(f(arg), f(arg.__float__())) # but strings should give a TypeError for f in self.test_functions: @@ -182,12 +283,201 @@ float_fn = getattr(math, fn) complex_fn = getattr(cmath, fn) for v in values: - self.cAssertAlmostEqual(float_fn(v), complex_fn(v)) + z = complex_fn(v) + self.rAssertAlmostEqual(float_fn(v), z.real) + self.assertEqual(0., z.imag) # test two-argument version of log with various bases for base in [0.5, 2., 10.]: for v in positive: - self.cAssertAlmostEqual(cmath.log(v, base), math.log(v, base)) + z = cmath.log(v, base) + self.rAssertAlmostEqual(math.log(v, base), z.real) + self.assertEqual(0., z.imag) + + def test_specific_values(self): + if not float.__getformat__("double").startswith("IEEE"): + return + + def rect_complex(z): + """Wrapped version of rect that accepts a complex number instead of + two float arguments.""" + return cmath.rect(z.real, z.imag) + + def polar_complex(z): + """Wrapped version of polar that returns a complex number instead of + two floats.""" + return complex(*polar(z)) + + for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file): + arg = complex(ar, ai) + expected = complex(er, ei) + if fn == 'rect': + function = rect_complex + elif fn == 'polar': + function = polar_complex + else: + function = getattr(cmath, fn) + if 'divide-by-zero' in flags or 'invalid' in flags: + try: + actual = function(arg) + except ValueError: + continue + else: + test_str = "%s: %s(complex(%r, %r))" % (id, fn, ar, ai) + self.fail('ValueError not raised in test %s' % test_str) + + if 'overflow' in flags: + try: + actual = function(arg) + except OverflowError: + continue + else: + test_str = "%s: %s(complex(%r, %r))" % (id, fn, ar, ai) + self.fail('OverflowError not raised in test %s' % test_str) + + actual = function(arg) + + if 'ignore-real-sign' in flags: + actual = complex(abs(actual.real), actual.imag) + expected = complex(abs(expected.real), expected.imag) + if 'ignore-imag-sign' in flags: + actual = complex(actual.real, abs(actual.imag)) + expected = complex(expected.real, abs(expected.imag)) + + # for the real part of the log function, we allow an + # absolute error of up to 2e-15. + if fn in ('log', 'log10'): + real_abs_err = 2e-15 + else: + real_abs_err = 5e-323 + + if not (almostEqualF(expected.real, actual.real, + abs_err = real_abs_err) and + almostEqualF(expected.imag, actual.imag)): + error_message = ( + "%s: %s(complex(%r, %r))\n" % (id, fn, ar, ai) + + "Expected: complex(%r, %r)\n" % + (expected.real, expected.imag) + + "Received: complex(%r, %r)\n" % + (actual.real, actual.imag) + + "Received value insufficiently close to expected value.") + self.fail(error_message) + + def assertCISEqual(self, a, b): + eps = 1E-7 + if abs(a[0] - b[0]) > eps or abs(a[1] - b[1]) > eps: + self.fail((a ,b)) + + def test_polar(self): + self.assertCISEqual(polar(0), (0., 0.)) + self.assertCISEqual(polar(1.), (1., 0.)) + self.assertCISEqual(polar(-1.), (1., pi)) + self.assertCISEqual(polar(1j), (1., pi/2)) + self.assertCISEqual(polar(-1j), (1., -pi/2)) + + def test_phase(self): + self.assertAlmostEqual(phase(0), 0.) + self.assertAlmostEqual(phase(1.), 0.) + self.assertAlmostEqual(phase(-1.), pi) + self.assertAlmostEqual(phase(-1.+1E-300j), pi) + self.assertAlmostEqual(phase(-1.-1E-300j), -pi) + self.assertAlmostEqual(phase(1j), pi/2) + self.assertAlmostEqual(phase(-1j), -pi/2) + + # zeros + self.assertEqual(phase(complex(0.0, 0.0)), 0.0) + self.assertEqual(phase(complex(0.0, -0.0)), -0.0) + self.assertEqual(phase(complex(-0.0, 0.0)), pi) + self.assertEqual(phase(complex(-0.0, -0.0)), -pi) + + # infinities + self.assertAlmostEqual(phase(complex(-INF, -0.0)), -pi) + self.assertAlmostEqual(phase(complex(-INF, -2.3)), -pi) + self.assertAlmostEqual(phase(complex(-INF, -INF)), -0.75*pi) + self.assertAlmostEqual(phase(complex(-2.3, -INF)), -pi/2) + self.assertAlmostEqual(phase(complex(-0.0, -INF)), -pi/2) + self.assertAlmostEqual(phase(complex(0.0, -INF)), -pi/2) + self.assertAlmostEqual(phase(complex(2.3, -INF)), -pi/2) + self.assertAlmostEqual(phase(complex(INF, -INF)), -pi/4) + self.assertEqual(phase(complex(INF, -2.3)), -0.0) + self.assertEqual(phase(complex(INF, -0.0)), -0.0) + self.assertEqual(phase(complex(INF, 0.0)), 0.0) + self.assertEqual(phase(complex(INF, 2.3)), 0.0) + self.assertAlmostEqual(phase(complex(INF, INF)), pi/4) + self.assertAlmostEqual(phase(complex(2.3, INF)), pi/2) + self.assertAlmostEqual(phase(complex(0.0, INF)), pi/2) + self.assertAlmostEqual(phase(complex(-0.0, INF)), pi/2) + self.assertAlmostEqual(phase(complex(-2.3, INF)), pi/2) + self.assertAlmostEqual(phase(complex(-INF, INF)), 0.75*pi) + self.assertAlmostEqual(phase(complex(-INF, 2.3)), pi) + self.assertAlmostEqual(phase(complex(-INF, 0.0)), pi) + + # real or imaginary part NaN + for z in complex_nans: + self.assert_(math.isnan(phase(z))) + + def test_abs(self): + # zeros + for z in complex_zeros: + self.assertEqual(abs(z), 0.0) + + # infinities + for z in complex_infinities: + self.assertEqual(abs(z), INF) + + # real or imaginary part NaN + self.assertEqual(abs(complex(NAN, -INF)), INF) + self.assert_(math.isnan(abs(complex(NAN, -2.3)))) + self.assert_(math.isnan(abs(complex(NAN, -0.0)))) + self.assert_(math.isnan(abs(complex(NAN, 0.0)))) + self.assert_(math.isnan(abs(complex(NAN, 2.3)))) + self.assertEqual(abs(complex(NAN, INF)), INF) + self.assertEqual(abs(complex(-INF, NAN)), INF) + self.assert_(math.isnan(abs(complex(-2.3, NAN)))) + self.assert_(math.isnan(abs(complex(-0.0, NAN)))) + self.assert_(math.isnan(abs(complex(0.0, NAN)))) + self.assert_(math.isnan(abs(complex(2.3, NAN)))) + self.assertEqual(abs(complex(INF, NAN)), INF) + self.assert_(math.isnan(abs(complex(NAN, NAN)))) + + # result overflows + if float.__getformat__("double").startswith("IEEE"): + self.assertRaises(OverflowError, abs, complex(1.4e308, 1.4e308)) + + def assertCEqual(self, a, b): + eps = 1E-7 + if abs(a.real - b[0]) > eps or abs(a.imag - b[1]) > eps: + self.fail((a ,b)) + + def test_rect(self): + self.assertCEqual(rect(0, 0), (0, 0)) + self.assertCEqual(rect(1, 0), (1., 0)) + self.assertCEqual(rect(1, -pi), (-1., 0)) + self.assertCEqual(rect(1, pi/2), (0, 1.)) + self.assertCEqual(rect(1, -pi/2), (0, -1.)) + + def test_isnan(self): + self.failIf(cmath.isnan(1)) + self.failIf(cmath.isnan(1j)) + self.failIf(cmath.isnan(INF)) + self.assert_(cmath.isnan(NAN)) + self.assert_(cmath.isnan(complex(NAN, 0))) + self.assert_(cmath.isnan(complex(0, NAN))) + self.assert_(cmath.isnan(complex(NAN, NAN))) + self.assert_(cmath.isnan(complex(NAN, INF))) + self.assert_(cmath.isnan(complex(INF, NAN))) + + def test_isinf(self): + self.failIf(cmath.isinf(1)) + self.failIf(cmath.isinf(1j)) + self.failIf(cmath.isinf(NAN)) + self.assert_(cmath.isinf(INF)) + self.assert_(cmath.isinf(complex(INF, 0))) + self.assert_(cmath.isinf(complex(0, INF))) + self.assert_(cmath.isinf(complex(INF, INF))) + self.assert_(cmath.isinf(complex(NAN, INF))) + self.assert_(cmath.isinf(complex(INF, NAN))) + def test_main(): run_unittest(CMathTests) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_cmd.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_cmd.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_cmd.py Wed Apr 30 15:57:13 2008 @@ -5,7 +5,6 @@ """ -from test import test_support import cmd import sys import trace Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_cmd_line.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_cmd_line.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_cmd_line.py Wed Apr 30 15:57:13 2008 @@ -13,18 +13,25 @@ stdout=subprocess.PIPE, stderr=subprocess.STDOUT) def _kill_python(p): + return _kill_python_and_exit_code(p)[0] + +def _kill_python_and_exit_code(p): p.stdin.close() data = p.stdout.read() p.stdout.close() # try to cleanup the child so we don't appear to leak when running # with regrtest -R. This should be a no-op on Windows. subprocess._cleanup() - return data + returncode = p.wait() + return data, returncode class CmdLineTest(unittest.TestCase): def start_python(self, *args): + return self.start_python_and_exit_code(*args)[0] + + def start_python_and_exit_code(self, *args): p = _spawn_python(*args) - return _kill_python(p) + return _kill_python_and_exit_code(p) def exit_code(self, *args): cmd_line = [sys.executable, '-E'] @@ -61,6 +68,17 @@ version = ('Python %d.%d' % sys.version_info[:2]).encode("ascii") self.assertTrue(self.start_python('-V').startswith(version)) + def test_verbose(self): + # -v causes imports to write to stderr. If the write to + # stderr itself causes an import to happen (for the output + # codec), a recursion loop can occur. + data, rc = self.start_python_and_exit_code('-v') + self.assertEqual(rc, 0) + self.assertTrue(b'stack overflow' not in data) + data, rc = self.start_python_and_exit_code('-vv') + self.assertEqual(rc, 0) + self.assertTrue(b'stack overflow' not in data) + def test_run_module(self): # Test expected operation of the '-m' switch # Switch needs an argument Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_code.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_code.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_code.py Wed Apr 30 15:57:13 2008 @@ -122,3 +122,7 @@ from test.test_support import run_doctest from test import test_code run_doctest(test_code, verbose) + + +if __name__ == '__main__': + test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_codecmaps_hk.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_codecmaps_hk.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_codecmaps_hk.py Wed Apr 30 15:57:13 2008 @@ -11,10 +11,11 @@ class TestBig5HKSCSMap(test_multibytecodec_support.TestBase_Mapping, unittest.TestCase): encoding = 'big5hkscs' - mapfileurl = 'http://people.freebsd.org/~perky/i18n/BIG5HKSCS.TXT' + mapfileurl = 'http://people.freebsd.org/~perky/i18n/BIG5HKSCS-2004.TXT' def test_main(): test_support.run_unittest(__name__) if __name__ == "__main__": + test_support.use_resources = ['urlfetch'] test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_coding.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_coding.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_coding.py Wed Apr 30 15:57:13 2008 @@ -1,6 +1,6 @@ import test.test_support, unittest -from test.test_support import TESTFN +from test.test_support import TESTFN, unlink import os, sys class CodingTest(unittest.TestCase): @@ -45,8 +45,8 @@ __import__(TESTFN) finally: f.close() - os.remove(TESTFN+".py") - os.remove(TESTFN+".pyc") + unlink(TESTFN+".py") + unlink(TESTFN+".pyc") sys.path.pop(0) def test_main(): Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_collections.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_collections.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_collections.py Wed Apr 30 15:57:13 2008 @@ -317,13 +317,12 @@ self.failIf(issubclass(str, MutableSequence)) import doctest, collections -NamedTupleDocs = doctest.DocTestSuite(module=collections) def test_main(verbose=None): - import collections as CollectionsModule + NamedTupleDocs = doctest.DocTestSuite(module=collections) test_classes = [TestNamedTuple, NamedTupleDocs, TestOneTrickPonyABCs, TestCollectionABCs] test_support.run_unittest(*test_classes) - test_support.run_doctest(CollectionsModule, verbose) + test_support.run_doctest(collections, verbose) if __name__ == "__main__": Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_compare.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_compare.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_compare.py Wed Apr 30 15:57:13 2008 @@ -1,4 +1,3 @@ -import sys import unittest from test import test_support Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_compile.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_compile.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_compile.py Wed Apr 30 15:57:13 2008 @@ -1,5 +1,6 @@ import unittest import sys +import _ast from test import test_support class TestSpecifics(unittest.TestCase): @@ -406,6 +407,42 @@ self.assert_("_A__mangled_mod" in A.f.__code__.co_varnames) self.assert_("__package__" in A.f.__code__.co_varnames) + def test_compile_ast(self): + fname = __file__ + if fname.lower().endswith(('pyc', 'pyo')): + fname = fname[:-1] + with open(fname, 'r') as f: + fcontents = f.read() + sample_code = [ + ['', 'x = 5'], + ['', """if True:\n pass\n"""], + ['', """for n in [1, 2, 3]:\n print(n)\n"""], + ['', """def foo():\n pass\nfoo()\n"""], + [fname, fcontents], + ] + + for fname, code in sample_code: + co1 = compile(code, '%s1' % fname, 'exec') + ast = compile(code, '%s2' % fname, 'exec', _ast.PyCF_ONLY_AST) + self.assert_(type(ast) == _ast.Module) + co2 = compile(ast, '%s3' % fname, 'exec') + self.assertEqual(co1, co2) + # the code object's filename comes from the second compilation step + self.assertEqual(co2.co_filename, '%s3' % fname) + + # raise exception when node type doesn't match with compile mode + co1 = compile('print(1)', '', 'exec', _ast.PyCF_ONLY_AST) + self.assertRaises(TypeError, compile, co1, '', 'eval') + + # raise exception when node type is no start node + self.assertRaises(TypeError, compile, _ast.If(), '', 'exec') + + # raise exception when node has invalid children + ast = _ast.Module() + ast.body = [_ast.BoolOp()] + self.assertRaises(TypeError, compile, ast, '', 'exec') + + def test_main(): test_support.run_unittest(TestSpecifics) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_complex.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_complex.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_complex.py Wed Apr 30 15:57:13 2008 @@ -4,6 +4,8 @@ from random import random from math import atan2 +INF = float("inf") +NAN = float("nan") # These tests ensure that complex math does the right thing class ComplexTest(unittest.TestCase): @@ -316,6 +318,18 @@ self.assertEqual(-6j,complex(repr(-6j))) self.assertEqual(6j,complex(repr(6j))) + self.assertEqual(repr(complex(1., INF)), "(1+inf*j)") + self.assertEqual(repr(complex(1., -INF)), "(1-inf*j)") + self.assertEqual(repr(complex(INF, 1)), "(inf+1j)") + self.assertEqual(repr(complex(-INF, INF)), "(-inf+inf*j)") + self.assertEqual(repr(complex(NAN, 1)), "(nan+1j)") + self.assertEqual(repr(complex(1, NAN)), "(1+nan*j)") + self.assertEqual(repr(complex(NAN, NAN)), "(nan+nan*j)") + + self.assertEqual(repr(complex(0, INF)), "inf*j") + self.assertEqual(repr(complex(0, -INF)), "-inf*j") + self.assertEqual(repr(complex(0, NAN)), "nan*j") + def test_neg(self): self.assertEqual(-(1+6j), -1-6j) @@ -338,6 +352,13 @@ except (OSError, IOError): pass + if float.__getformat__("double").startswith("IEEE"): + def test_plus_minus_0j(self): + # test that -0j and 0j literals are not identified + z1, z2 = 0j, -0j + self.assertEquals(atan2(z1.imag, -1.), atan2(0., -1.)) + self.assertEquals(atan2(z2.imag, -1.), atan2(-0., -1.)) + def test_main(): test_support.run_unittest(ComplexTest) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_contains.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_contains.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_contains.py Wed Apr 30 15:57:13 2008 @@ -1,103 +1,88 @@ -from test.test_support import TestFailed +from test.test_support import run_unittest +import unittest -class base_set: +class base_set: def __init__(self, el): self.el = el class set(base_set): - def __contains__(self, el): return self.el == el class seq(base_set): - def __getitem__(self, n): return [self.el][n] -def check(ok, *args): - if not ok: - raise TestFailed(" ".join(map(str, args))) - -a = base_set(1) -b = set(1) -c = seq(1) - -check(1 in b, "1 not in set(1)") -check(0 not in b, "0 in set(1)") -check(1 in c, "1 not in seq(1)") -check(0 not in c, "0 in seq(1)") - -try: - 1 in a - check(0, "in base_set did not raise error") -except TypeError: - pass - -try: - 1 not in a - check(0, "not in base_set did not raise error") -except TypeError: - pass - -# Test char in string - -check('c' in 'abc', "'c' not in 'abc'") -check('d' not in 'abc', "'d' in 'abc'") - -check('' in '', "'' not in ''") -check('' in 'abc', "'' not in 'abc'") - -try: - None in 'abc' - check(0, "None in 'abc' did not raise error") -except TypeError: - pass - - -# A collection of tests on builtin sequence types -a = list(range(10)) -for i in a: - check(i in a, "%r not in %r" % (i, a)) -check(16 not in a, "16 not in %r" % (a,)) -check(a not in a, "%s not in %r" % (a, a)) - -a = tuple(a) -for i in a: - check(i in a, "%r not in %r" % (i, a)) -check(16 not in a, "16 not in %r" % (a,)) -check(a not in a, "%r not in %r" % (a, a)) - -class Deviant1: - """Behaves strangely when compared - - This class is designed to make sure that the contains code - works when the list is modified during the check. - """ - - aList = list(range(15)) - - def __cmp__(self, other): - if other == 12: - self.aList.remove(12) - self.aList.remove(13) - self.aList.remove(14) - return 1 - -check(Deviant1() not in Deviant1.aList, "Deviant1 failed") - -class Deviant2: - """Behaves strangely when compared - - This class raises an exception during comparison. That in - turn causes the comparison to fail with a TypeError. - """ - - def __cmp__(self, other): - if other == 4: - raise RuntimeError("gotcha") - -try: - check(Deviant2() not in a, "oops") -except TypeError: - pass +class TestContains(unittest.TestCase): + def test_common_tests(self): + a = base_set(1) + b = set(1) + c = seq(1) + self.assert_(1 in b) + self.assert_(0 not in b) + self.assert_(1 in c) + self.assert_(0 not in c) + self.assertRaises(TypeError, lambda: 1 in a) + self.assertRaises(TypeError, lambda: 1 not in a) + + # test char in string + self.assert_('c' in 'abc') + self.assert_('d' not in 'abc') + + self.assert_('' in '') + self.assert_('' in 'abc') + + self.assertRaises(TypeError, lambda: None in 'abc') + + def test_builtin_sequence_types(self): + # a collection of tests on builtin sequence types + a = range(10) + for i in a: + self.assert_(i in a) + self.assert_(16 not in a) + self.assert_(a not in a) + + a = tuple(a) + for i in a: + self.assert_(i in a) + self.assert_(16 not in a) + self.assert_(a not in a) + + class Deviant1: + """Behaves strangely when compared + + This class is designed to make sure that the contains code + works when the list is modified during the check. + """ + aList = range(15) + def __cmp__(self, other): + if other == 12: + self.aList.remove(12) + self.aList.remove(13) + self.aList.remove(14) + return 1 + + self.assert_(Deviant1() not in Deviant1.aList) + + class Deviant2: + """Behaves strangely when compared + + This class raises an exception during comparison. That in + turn causes the comparison to fail with a TypeError. + """ + def __cmp__(self, other): + if other == 4: + raise RuntimeError("gotcha") + + try: + self.assert_(Deviant2() not in a) + except TypeError: + pass + + +def test_main(): + run_unittest(TestContains) + +if __name__ == '__main__': + test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_copy.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_copy.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_copy.py Wed Apr 30 15:57:13 2008 @@ -1,6 +1,5 @@ """Unit tests for the copy module.""" -import sys import copy import copy_reg Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_crypt.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_crypt.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_crypt.py Wed Apr 30 15:57:13 2008 @@ -1,11 +1,16 @@ -#! /usr/bin/env python -"""Simple test script for cryptmodule.c - Roger E. Masse -""" - -from test.test_support import verbose +from test import test_support +import unittest import crypt -c = crypt.crypt('mypassword', 'ab') -if verbose: - print('Test encryption: ', c) +class CryptTestCase(unittest.TestCase): + + def test_crypt(self): + c = crypt.crypt('mypassword', 'ab') + if test_support.verbose: + print('Test encryption: ', c) + +def test_main(): + test_support.run_unittest(CryptTestCase) + +if __name__ == "__main__": + test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_curses.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_curses.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_curses.py Wed Apr 30 15:57:13 2008 @@ -269,13 +269,12 @@ curses.wrapper(main) unit_tests() else: + # testing setupterm() inside initscr/endwin + # causes terminal breakage + curses.setupterm(fd=sys.__stdout__.fileno()) try: - # testing setupterm() inside initscr/endwin - # causes terminal breakage - curses.setupterm(fd=sys.__stdout__.fileno()) stdscr = curses.initscr() main(stdscr) finally: curses.endwin() - unit_tests() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_datetime.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_datetime.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_datetime.py Wed Apr 30 15:57:13 2008 @@ -4,7 +4,6 @@ """ import os -import sys import pickle import unittest @@ -851,29 +850,29 @@ def test_format(self): dt = self.theclass(2007, 9, 10) - self.assertEqual(format(dt, ''), str(dt)) + self.assertEqual(dt.__format__(''), str(dt)) # check that a derived class's __str__() gets called class A(self.theclass): def __str__(self): return 'A' a = A(2007, 9, 10) - self.assertEqual(format(a, ''), 'A') + self.assertEqual(a.__format__(''), 'A') # check that a derived class's strftime gets called class B(self.theclass): def strftime(self, format_spec): return 'B' b = B(2007, 9, 10) - self.assertEqual(format(b, ''), str(dt)) + self.assertEqual(b.__format__(''), str(dt)) for fmt in ["m:%m d:%d y:%y", "m:%m d:%d y:%y H:%H M:%M S:%S", "%z %Z", ]: - self.assertEqual(format(dt, fmt), dt.strftime(fmt)) - self.assertEqual(format(a, fmt), dt.strftime(fmt)) - self.assertEqual(format(b, fmt), 'B') + self.assertEqual(dt.__format__(fmt), dt.strftime(fmt)) + self.assertEqual(a.__format__(fmt), dt.strftime(fmt)) + self.assertEqual(b.__format__(fmt), 'B') def test_resolution_info(self): self.assert_(isinstance(self.theclass.min, self.theclass)) @@ -1178,31 +1177,29 @@ def test_format(self): dt = self.theclass(2007, 9, 10, 4, 5, 1, 123) - self.assertEqual(format(dt, ''), str(dt)) + self.assertEqual(dt.__format__(''), str(dt)) # check that a derived class's __str__() gets called class A(self.theclass): def __str__(self): return 'A' a = A(2007, 9, 10, 4, 5, 1, 123) - self.assertEqual(format(a, ''), 'A') + self.assertEqual(a.__format__(''), 'A') # check that a derived class's strftime gets called class B(self.theclass): def strftime(self, format_spec): return 'B' b = B(2007, 9, 10, 4, 5, 1, 123) - self.assertEqual(format(b, ''), str(dt)) + self.assertEqual(b.__format__(''), str(dt)) for fmt in ["m:%m d:%d y:%y", "m:%m d:%d y:%y H:%H M:%M S:%S", "%z %Z", ]: - self.assertEqual(format(dt, fmt), dt.strftime(fmt)) - self.assertEqual(format(a, fmt), dt.strftime(fmt)) - self.assertEqual(format(b, fmt), 'B') - - + self.assertEqual(dt.__format__(fmt), dt.strftime(fmt)) + self.assertEqual(a.__format__(fmt), dt.strftime(fmt)) + self.assertEqual(b.__format__(fmt), 'B') def test_more_ctime(self): # Test fields that TestDate doesn't touch. @@ -1524,11 +1521,12 @@ self.failUnless(abs(from_timestamp - from_now) <= tolerance) def test_strptime(self): - import time + import _strptime - string = '2004-12-01 13:02:47' - format = '%Y-%m-%d %H:%M:%S' - expected = self.theclass(*(time.strptime(string, format)[0:6])) + string = '2004-12-01 13:02:47.197' + format = '%Y-%m-%d %H:%M:%S.%f' + result, frac = _strptime._strptime(string, format) + expected = self.theclass(*(result[0:6]+(frac,))) got = self.theclass.strptime(string, format) self.assertEqual(expected, got) @@ -1556,9 +1554,9 @@ def test_more_strftime(self): # This tests fields beyond those tested by the TestDate.test_strftime. - t = self.theclass(2004, 12, 31, 6, 22, 33) - self.assertEqual(t.strftime("%m %d %y %S %M %H %j"), - "12 31 04 33 22 06 366") + t = self.theclass(2004, 12, 31, 6, 22, 33, 47) + self.assertEqual(t.strftime("%m %d %y %f %S %M %H %j"), + "12 31 04 000047 33 22 06 366") def test_extract(self): dt = self.theclass(2002, 3, 4, 18, 45, 3, 1234) @@ -1831,33 +1829,33 @@ def test_strftime(self): t = self.theclass(1, 2, 3, 4) - self.assertEqual(t.strftime('%H %M %S'), "01 02 03") + self.assertEqual(t.strftime('%H %M %S %f'), "01 02 03 000004") # A naive object replaces %z and %Z with empty strings. self.assertEqual(t.strftime("'%z' '%Z'"), "'' ''") def test_format(self): t = self.theclass(1, 2, 3, 4) - self.assertEqual(format(t, ''), str(t)) + self.assertEqual(t.__format__(''), str(t)) # check that a derived class's __str__() gets called class A(self.theclass): def __str__(self): return 'A' a = A(1, 2, 3, 4) - self.assertEqual(format(a, ''), 'A') + self.assertEqual(a.__format__(''), 'A') # check that a derived class's strftime gets called class B(self.theclass): def strftime(self, format_spec): return 'B' b = B(1, 2, 3, 4) - self.assertEqual(format(b, ''), str(t)) + self.assertEqual(b.__format__(''), str(t)) for fmt in ['%H %M %S', ]: - self.assertEqual(format(t, fmt), t.strftime(fmt)) - self.assertEqual(format(a, fmt), t.strftime(fmt)) - self.assertEqual(format(b, fmt), 'B') + self.assertEqual(t.__format__(fmt), t.strftime(fmt)) + self.assertEqual(a.__format__(fmt), t.strftime(fmt)) + self.assertEqual(b.__format__(fmt), 'B') def test_str(self): self.assertEqual(str(self.theclass(1, 2, 3, 4)), "01:02:03.000004") Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_dbm.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_dbm.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_dbm.py Wed Apr 30 15:57:13 2008 @@ -1,56 +1,40 @@ -#! /usr/bin/env python -"""Test script for the dbm module - Roger E. Masse -""" +from test import test_support +import unittest import os import random import dbm from dbm import error -from test.test_support import verbose, verify, TestSkipped, TESTFN -# make filename unique to allow multiple concurrent tests -# and to minimize the likelihood of a problem from an old file -filename = TESTFN - -def cleanup(): - for suffix in ['', '.pag', '.dir', '.db']: - try: - os.unlink(filename + suffix) - except OSError as e: - (errno, strerror) = e.errno, e.strerror - # if we can't delete the file because of permissions, - # nothing will work, so skip the test - if errno == 1: - raise TestSkipped('unable to remove: ' + filename + suffix) - -def test_keys(): - d = dbm.open(filename, 'c') - verify(d.keys() == []) - d[b'a'] = b'b' - d[b'12345678910'] = b'019237410982340912840198242' - d.keys() - if b'a' in d: - if verbose: - print('Test dbm keys: ', d.keys()) - - d.close() - -def test_modes(): - d = dbm.open(filename, 'r') - d.close() - d = dbm.open(filename, 'rw') - d.close() - d = dbm.open(filename, 'w') - d.close() - d = dbm.open(filename, 'n') - d.close() - -cleanup() -try: - test_keys() - test_modes() -except: - cleanup() - raise +class DbmTestCase(unittest.TestCase): -cleanup() + def setUp(self): + self.filename = test_support.TESTFN + self.d = dbm.open(self.filename, 'c') + self.d.close() + + def tearDown(self): + for suffix in ['', '.pag', '.dir', '.db']: + test_support.unlink(self.filename + suffix) + + def test_keys(self): + self.d = dbm.open(self.filename, 'c') + self.assert_(self.d.keys() == []) + self.d['a'] = 'b' + self.d['12345678910'] = '019237410982340912840198242' + self.d.keys() + self.assert_(b'a' in self.d) + self.d.close() + + def test_modes(self): + for mode in ['r', 'rw', 'w', 'n']: + try: + self.d = dbm.open(self.filename, mode) + self.d.close() + except dbm.error: + self.fail() + +def test_main(): + test_support.run_unittest(DbmTestCase) + +if __name__ == '__main__': + test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_decimal.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_decimal.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_decimal.py Wed Apr 30 15:57:13 2008 @@ -25,10 +25,11 @@ """ from __future__ import with_statement -import unittest import glob +import math import os, sys import pickle, copy +import unittest from decimal import * from test.test_support import (TestSkipped, run_unittest, run_doctest, is_resource_enabled) @@ -609,6 +610,98 @@ self.assertEqual(eval('Decimal(10)' + sym + 'E()'), '10' + rop + 'str') +class DecimalFormatTest(unittest.TestCase): + '''Unit tests for the format function.''' + def test_formatting(self): + # triples giving a format, a Decimal, and the expected result + test_values = [ + ('e', '0E-15', '0e-15'), + ('e', '2.3E-15', '2.3e-15'), + ('e', '2.30E+2', '2.30e+2'), # preserve significant zeros + ('e', '2.30000E-15', '2.30000e-15'), + ('e', '1.23456789123456789e40', '1.23456789123456789e+40'), + ('e', '1.5', '1.5e+0'), + ('e', '0.15', '1.5e-1'), + ('e', '0.015', '1.5e-2'), + ('e', '0.0000000000015', '1.5e-12'), + ('e', '15.0', '1.50e+1'), + ('e', '-15', '-1.5e+1'), + ('e', '0', '0e+0'), + ('e', '0E1', '0e+1'), + ('e', '0.0', '0e-1'), + ('e', '0.00', '0e-2'), + ('.6e', '0E-15', '0.000000e-9'), + ('.6e', '0', '0.000000e+6'), + ('.6e', '9.999999', '9.999999e+0'), + ('.6e', '9.9999999', '1.000000e+1'), + ('.6e', '-1.23e5', '-1.230000e+5'), + ('.6e', '1.23456789e-3', '1.234568e-3'), + ('f', '0', '0'), + ('f', '0.0', '0.0'), + ('f', '0E-2', '0.00'), + ('f', '0.00E-8', '0.0000000000'), + ('f', '0E1', '0'), # loses exponent information + ('f', '3.2E1', '32'), + ('f', '3.2E2', '320'), + ('f', '3.20E2', '320'), + ('f', '3.200E2', '320.0'), + ('f', '3.2E-6', '0.0000032'), + ('.6f', '0E-15', '0.000000'), # all zeros treated equally + ('.6f', '0E1', '0.000000'), + ('.6f', '0', '0.000000'), + ('.0f', '0', '0'), # no decimal point + ('.0f', '0e-2', '0'), + ('.0f', '3.14159265', '3'), + ('.1f', '3.14159265', '3.1'), + ('.4f', '3.14159265', '3.1416'), + ('.6f', '3.14159265', '3.141593'), + ('.7f', '3.14159265', '3.1415926'), # round-half-even! + ('.8f', '3.14159265', '3.14159265'), + ('.9f', '3.14159265', '3.141592650'), + + ('g', '0', '0'), + ('g', '0.0', '0.0'), + ('g', '0E1', '0e+1'), + ('G', '0E1', '0E+1'), + ('g', '0E-5', '0.00000'), + ('g', '0E-6', '0.000000'), + ('g', '0E-7', '0e-7'), + ('g', '-0E2', '-0e+2'), + ('.0g', '3.14159265', '3'), # 0 sig fig -> 1 sig fig + ('.1g', '3.14159265', '3'), + ('.2g', '3.14159265', '3.1'), + ('.5g', '3.14159265', '3.1416'), + ('.7g', '3.14159265', '3.141593'), + ('.8g', '3.14159265', '3.1415926'), # round-half-even! + ('.9g', '3.14159265', '3.14159265'), + ('.10g', '3.14159265', '3.14159265'), # don't pad + + ('%', '0E1', '0%'), + ('%', '0E0', '0%'), + ('%', '0E-1', '0%'), + ('%', '0E-2', '0%'), + ('%', '0E-3', '0.0%'), + ('%', '0E-4', '0.00%'), + + ('.3%', '0', '0.000%'), # all zeros treated equally + ('.3%', '0E10', '0.000%'), + ('.3%', '0E-10', '0.000%'), + ('.3%', '2.34', '234.000%'), + ('.3%', '1.234567', '123.457%'), + ('.0%', '1.23', '123%'), + + ('e', 'NaN', 'NaN'), + ('f', '-NaN123', '-NaN123'), + ('+g', 'NaN456', '+NaN456'), + ('.3e', 'Inf', 'Infinity'), + ('.16f', '-Inf', '-Infinity'), + ('.0g', '-sNaN', '-sNaN'), + + ('', '1.00', '1.00'), + ] + for fmt, d, result in test_values: + self.assertEqual(format(Decimal(d), fmt), result) + class DecimalArithmeticOperatorsTest(unittest.TestCase): '''Unit tests for all arithmetic operators, binary and unary.''' @@ -832,27 +925,46 @@ self.assertEqual(-Decimal(45), Decimal(-45)) # - self.assertEqual(abs(Decimal(45)), abs(Decimal(-45))) # abs + def test_nan_comparisons(self): + n = Decimal('NaN') + s = Decimal('sNaN') + i = Decimal('Inf') + f = Decimal('2') + for x, y in [(n, n), (n, i), (i, n), (n, f), (f, n), + (s, n), (n, s), (s, i), (i, s), (s, f), (f, s), (s, s)]: + self.assert_(x != y) + self.assert_(not (x == y)) + self.assert_(not (x < y)) + self.assert_(not (x <= y)) + self.assert_(not (x > y)) + self.assert_(not (x >= y)) # The following are two functions used to test threading in the next class def thfunc1(cls): d1 = Decimal(1) d3 = Decimal(3) - cls.assertEqual(d1/d3, Decimal('0.333333333')) + test1 = d1/d3 cls.synchro.wait() - cls.assertEqual(d1/d3, Decimal('0.333333333')) + test2 = d1/d3 cls.finish1.set() + + cls.assertEqual(test1, Decimal('0.333333333')) + cls.assertEqual(test2, Decimal('0.333333333')) return def thfunc2(cls): d1 = Decimal(1) d3 = Decimal(3) - cls.assertEqual(d1/d3, Decimal('0.333333333')) + test1 = d1/d3 thiscontext = getcontext() thiscontext.prec = 18 - cls.assertEqual(d1/d3, Decimal('0.333333333333333333')) + test2 = d1/d3 cls.synchro.set() cls.finish2.set() + + cls.assertEqual(test1, Decimal('0.333333333')) + cls.assertEqual(test2, Decimal('0.333333333333333333')) return @@ -1026,7 +1138,7 @@ d = Decimal('15.32') self.assertEqual(str(d), '15.32') # str - self.assertEqual(repr(d), 'Decimal("15.32")') # repr + self.assertEqual(repr(d), "Decimal('15.32')") # repr def test_tonum_methods(self): #Test float, int and long methods. @@ -1136,7 +1248,12 @@ checkSameDec("__abs__") checkSameDec("__add__", True) checkSameDec("__divmod__", True) - checkSameDec("__cmp__", True) + checkSameDec("__eq__", True) + checkSameDec("__ne__", True) + checkSameDec("__le__", True) + checkSameDec("__lt__", True) + checkSameDec("__ge__", True) + checkSameDec("__gt__", True) checkSameDec("__float__") checkSameDec("__floordiv__", True) checkSameDec("__hash__") @@ -1186,6 +1303,12 @@ d = d1.max(d2) self.assertTrue(type(d) is Decimal) + def test_implicit_context(self): + # Check results when context given implicitly. (Issue 2478) + c = getcontext() + self.assertEqual(str(Decimal(0).sqrt()), + str(c.sqrt(Decimal(0)))) + class DecimalPythonAPItests(unittest.TestCase): @@ -1213,7 +1336,7 @@ # should work the same as to_integral in the ROUND_DOWN mode d = Decimal(s) r = d.to_integral(ROUND_DOWN) - self.assertEqual(Decimal(trunc(d)), r) + self.assertEqual(Decimal(math.trunc(d)), r) class ContextAPItests(unittest.TestCase): @@ -1332,6 +1455,7 @@ DecimalExplicitConstructionTest, DecimalImplicitConstructionTest, DecimalArithmeticOperatorsTest, + DecimalFormatTest, DecimalUseOfContextTest, DecimalUsabilityTest, DecimalPythonAPItests, Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_defaultdict.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_defaultdict.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_defaultdict.py Wed Apr 30 15:57:13 2008 @@ -64,7 +64,7 @@ d2 = defaultdict(int) self.assertEqual(d2.default_factory, int) d2[12] = 42 - self.assertEqual(repr(d2), "defaultdict(, {12: 42})") + self.assertEqual(repr(d2), "defaultdict(, {12: 42})") def foo(): return 43 d3 = defaultdict(foo) self.assert_(d3.default_factory is foo) @@ -141,6 +141,29 @@ else: self.fail("expected KeyError") + def test_recursive_repr(self): + # Issue2045: stack overflow when default_factory is a bound method + class sub(defaultdict): + def __init__(self): + self.default_factory = self._factory + def _factory(self): + return [] + d = sub() + self.assert_(repr(d).startswith( + "defaultdict(>', + 'and': '&', + 'xor': '^', + 'or': '|', + 'cmp': 'cmp', + 'lt': '<', + 'le': '<=', + 'eq': '==', + 'ne': '!=', + 'gt': '>', + 'ge': '>=', + } + + for name, expr in list(self.binops.items()): + if expr.islower(): + expr = expr + "(a, b)" + else: + expr = 'a %s b' % expr + self.binops[name] = expr + + self.unops = { + 'pos': '+', + 'neg': '-', + 'abs': 'abs', + 'invert': '~', + 'int': 'int', + 'float': 'float', + 'oct': 'oct', + 'hex': 'hex', + } + + for name, expr in list(self.unops.items()): + if expr.islower(): + expr = expr + "(a)" + else: + expr = '%s a' % expr + self.unops[name] = expr + + def unop_test(self, a, res, expr="len(a)", meth="__len__"): + d = {'a': a} + self.assertEqual(eval(expr, d), res) + t = type(a) + m = getattr(t, meth) + + # Find method in parent class + while meth not in t.__dict__: + t = t.__bases__[0] + + self.assertEqual(m, t.__dict__[meth]) + self.assertEqual(m(a), res) + bm = getattr(a, meth) + self.assertEqual(bm(), res) + + def binop_test(self, a, b, res, expr="a+b", meth="__add__"): + d = {'a': a, 'b': b} + + # XXX Hack so this passes before 2.3 when -Qnew is specified. + if meth == "__div__" and 1/2 == 0.5: + meth = "__truediv__" + + if meth == '__divmod__': pass + + self.assertEqual(eval(expr, d), res) + t = type(a) + m = getattr(t, meth) + while meth not in t.__dict__: + t = t.__bases__[0] + self.assertEqual(m, t.__dict__[meth]) + self.assertEqual(m(a, b), res) + bm = getattr(a, meth) + self.assertEqual(bm(b), res) + + def sliceop_test(self, a, b, c, res, expr="a[b:c]", meth="__getitem__"): + d = {'a': a, 'b': b, 'c': c} + self.assertEqual(eval(expr, d), res) + t = type(a) + m = getattr(t, meth) + while meth not in t.__dict__: + t = t.__bases__[0] + self.assertEqual(m, t.__dict__[meth]) + self.assertEqual(m(a, slice(b, c)), res) + bm = getattr(a, meth) + self.assertEqual(bm(slice(b, c)), res) + + def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"): + d = {'a': deepcopy(a), 'b': b} + exec(stmt, d) + self.assertEqual(d['a'], res) + t = type(a) + m = getattr(t, meth) + while meth not in t.__dict__: + t = t.__bases__[0] + self.assertEqual(m, t.__dict__[meth]) + d['a'] = deepcopy(a) + m(d['a'], b) + self.assertEqual(d['a'], res) + d['a'] = deepcopy(a) + bm = getattr(d['a'], meth) + bm(b) + self.assertEqual(d['a'], res) + + def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"): + d = {'a': deepcopy(a), 'b': b, 'c': c} + exec(stmt, d) + self.assertEqual(d['a'], res) + t = type(a) + m = getattr(t, meth) + while meth not in t.__dict__: + t = t.__bases__[0] + self.assertEqual(m, t.__dict__[meth]) + d['a'] = deepcopy(a) + m(d['a'], b, c) + self.assertEqual(d['a'], res) + d['a'] = deepcopy(a) + bm = getattr(d['a'], meth) + bm(b, c) + self.assertEqual(d['a'], res) + + def setsliceop_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setitem__"): + dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d} + exec(stmt, dictionary) + self.assertEqual(dictionary['a'], res) + t = type(a) + while meth not in t.__dict__: + t = t.__bases__[0] + m = getattr(t, meth) + self.assertEqual(m, t.__dict__[meth]) + dictionary['a'] = deepcopy(a) + m(dictionary['a'], slice(b, c), d) + self.assertEqual(dictionary['a'], res) + dictionary['a'] = deepcopy(a) + bm = getattr(dictionary['a'], meth) + bm(slice(b, c), d) + self.assertEqual(dictionary['a'], res) + + def test_lists(self): + # Testing list operations... + # Asserts are within individual test methods + self.binop_test([1], [2], [1,2], "a+b", "__add__") + self.binop_test([1,2,3], 2, 1, "b in a", "__contains__") + self.binop_test([1,2,3], 4, 0, "b in a", "__contains__") + self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__") + self.sliceop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getitem__") + self.setop_test([1], [2], [1,2], "a+=b", "__iadd__") + self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__") + self.unop_test([1,2,3], 3, "len(a)", "__len__") + self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__") + self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__") + self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__") + self.setsliceop_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", + "__setitem__") + + def test_dicts(self): + # Testing dict operations... + ## self.binop_test({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__") + self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__") + self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__") + self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__") + + d = {1:2, 3:4} + l1 = [] + for i in list(d.keys()): + l1.append(i) + l = [] + for i in iter(d): + l.append(i) + self.assertEqual(l, l1) + l = [] + for i in d.__iter__(): + l.append(i) + self.assertEqual(l, l1) + l = [] + for i in dict.__iter__(d): + l.append(i) + self.assertEqual(l, l1) + d = {1:2, 3:4} + self.unop_test(d, 2, "len(a)", "__len__") + self.assertEqual(eval(repr(d), {}), d) + self.assertEqual(eval(d.__repr__(), {}), d) + self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", + "__setitem__") + + # Tests for unary and binary operators + def number_operators(self, a, b, skip=[]): + dict = {'a': a, 'b': b} + + for name, expr in list(self.binops.items()): + if name not in skip: + name = "__%s__" % name + if hasattr(a, name): + res = eval(expr, dict) + self.binop_test(a, b, res, expr, name) + + for name, expr in list(self.unops.items()): + if name not in skip: + name = "__%s__" % name + if hasattr(a, name): + res = eval(expr, dict) + self.unop_test(a, res, expr, name) + + def test_ints(self): + # Testing int operations... + self.number_operators(100, 3) + # The following crashes in Python 2.2 + self.assertEqual((1).__bool__(), 1) + self.assertEqual((0).__bool__(), 0) + # This returns 'NotImplemented' in Python 2.2 + class C(int): + def __add__(self, other): + return NotImplemented + self.assertEqual(C(5), 5) + try: + C() + "" + except TypeError: + pass + else: + self.fail("NotImplemented should have caused TypeError") + + def test_longs(self): + # Testing long operations... + self.number_operators(100, 3) + + def test_floats(self): + # Testing float operations... + self.number_operators(100.0, 3.0) + + def test_complexes(self): + # Testing complex operations... + self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', + 'int', 'long', 'float', + 'divmod', 'mod']) + + class Number(complex): + __slots__ = ['prec'] + def __new__(cls, *args, **kwds): + result = complex.__new__(cls, *args) + result.prec = kwds.get('prec', 12) + return result + def __repr__(self): + prec = self.prec + if self.imag == 0.0: + return "%.*g" % (prec, self.real) + if self.real == 0.0: + return "%.*gj" % (prec, self.imag) + return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag) + __str__ = __repr__ + + a = Number(3.14, prec=6) + self.assertEqual(repr(a), "3.14") + self.assertEqual(a.prec, 6) + + a = Number(a, prec=2) + self.assertEqual(repr(a), "3.1") + self.assertEqual(a.prec, 2) + + a = Number(234.5) + self.assertEqual(repr(a), "234.5") + self.assertEqual(a.prec, 12) + + def test_spam_lists(self): + # Testing spamlist operations... + import copy, xxsubtype as spam + + def spamlist(l, memo=None): + import xxsubtype as spam + return spam.spamlist(l) + + # This is an ugly hack: + copy._deepcopy_dispatch[spam.spamlist] = spamlist + + self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", + "__add__") + self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__") + self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__") + self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__") + self.sliceop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]", + "__getitem__") + self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b", + "__iadd__") + self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", + "__imul__") + self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__") + self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", + "__mul__") + self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", + "__rmul__") + self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", + "__setitem__") + self.setsliceop_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]), + spamlist([1,5,6,4]), "a[b:c]=d", "__setitem__") + # Test subclassing + class C(spam.spamlist): + def foo(self): return 1 + a = C() + self.assertEqual(a, []) + self.assertEqual(a.foo(), 1) + a.append(100) + self.assertEqual(a, [100]) + self.assertEqual(a.getstate(), 0) + a.setstate(42) + self.assertEqual(a.getstate(), 42) + + def test_spam_dicts(self): + # Testing spamdict operations... + import copy, xxsubtype as spam + def spamdict(d, memo=None): + import xxsubtype as spam + sd = spam.spamdict() + for k, v in list(d.items()): + sd[k] = v + return sd + # This is an ugly hack: + copy._deepcopy_dispatch[spam.spamdict] = spamdict + + ## self.binop_test(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", + ## "__cmp__") + self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__") + self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__") + self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__") + d = spamdict({1:2,3:4}) + l1 = [] + for i in list(d.keys()): + l1.append(i) + l = [] + for i in iter(d): + l.append(i) + self.assertEqual(l, l1) + l = [] + for i in d.__iter__(): + l.append(i) + self.assertEqual(l, l1) + l = [] + for i in type(spamdict({})).__iter__(d): + l.append(i) + self.assertEqual(l, l1) + straightd = {1:2, 3:4} + spamd = spamdict(straightd) + self.unop_test(spamd, 2, "len(a)", "__len__") + self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__") + self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}), + "a[b]=c", "__setitem__") + # Test subclassing + class C(spam.spamdict): + def foo(self): return 1 + a = C() + self.assertEqual(list(a.items()), []) + self.assertEqual(a.foo(), 1) + a['foo'] = 'bar' + self.assertEqual(list(a.items()), [('foo', 'bar')]) + self.assertEqual(a.getstate(), 0) + a.setstate(100) + self.assertEqual(a.getstate(), 100) + +class ClassPropertiesAndMethods(unittest.TestCase): + + def test_python_dicts(self): + # Testing Python subclass of dict... + self.assert_(issubclass(dict, dict)) + self.assert_(isinstance({}, dict)) + d = dict() + self.assertEqual(d, {}) + self.assert_(d.__class__ is dict) + self.assert_(isinstance(d, dict)) + class C(dict): + state = -1 + def __init__(self_local, *a, **kw): + if a: + self.assertEqual(len(a), 1) + self_local.state = a[0] + if kw: + for k, v in list(kw.items()): + self_local[v] = k + def __getitem__(self, key): + return self.get(key, 0) + def __setitem__(self_local, key, value): + self.assert_(isinstance(key, type(0))) + dict.__setitem__(self_local, key, value) + def setstate(self, state): + self.state = state + def getstate(self): + return self.state + self.assert_(issubclass(C, dict)) + a1 = C(12) + self.assertEqual(a1.state, 12) + a2 = C(foo=1, bar=2) + self.assertEqual(a2[1] == 'foo' and a2[2], 'bar') + a = C() + self.assertEqual(a.state, -1) + self.assertEqual(a.getstate(), -1) + a.setstate(0) + self.assertEqual(a.state, 0) + self.assertEqual(a.getstate(), 0) + a.setstate(10) + self.assertEqual(a.state, 10) + self.assertEqual(a.getstate(), 10) + self.assertEqual(a[42], 0) + a[42] = 24 + self.assertEqual(a[42], 24) + N = 50 + for i in range(N): + a[i] = C() + for j in range(N): + a[i][j] = i*j + for i in range(N): + for j in range(N): + self.assertEqual(a[i][j], i*j) + + def test_python_lists(self): + # Testing Python subclass of list... + class C(list): + def __getitem__(self, i): + if isinstance(i, slice): + return i.start, i.stop + return list.__getitem__(self, i) + 100 + a = C() + a.extend([0,1,2]) + self.assertEqual(a[0], 100) + self.assertEqual(a[1], 101) + self.assertEqual(a[2], 102) + self.assertEqual(a[100:200], (100,200)) + + def test_metaclass(self): + # Testing __metaclass__... + class C(metaclass=type): + def __init__(self): + self.__state = 0 + def getstate(self): + return self.__state + def setstate(self, state): + self.__state = state + a = C() + self.assertEqual(a.getstate(), 0) + a.setstate(10) + self.assertEqual(a.getstate(), 10) + class _metaclass(type): + def myself(cls): return cls + class D(metaclass=_metaclass): + pass + self.assertEqual(D.myself(), D) + d = D() + self.assertEqual(d.__class__, D) + class M1(type): + def __new__(cls, name, bases, dict): + dict['__spam__'] = 1 + return type.__new__(cls, name, bases, dict) + class C(metaclass=M1): + pass + self.assertEqual(C.__spam__, 1) + c = C() + self.assertEqual(c.__spam__, 1) + + class _instance(object): + pass + class M2(object): + @staticmethod + def __new__(cls, name, bases, dict): + self = object.__new__(cls) + self.name = name + self.bases = bases + self.dict = dict + return self + def __call__(self): + it = _instance() + # Early binding of methods + for key in self.dict: + if key.startswith("__"): + continue + setattr(it, key, self.dict[key].__get__(it, self)) + return it + class C(metaclass=M2): + def spam(self): + return 42 + self.assertEqual(C.name, 'C') + self.assertEqual(C.bases, ()) + self.assert_('spam' in C.dict) + c = C() + self.assertEqual(c.spam(), 42) + + # More metaclass examples + + class autosuper(type): + # Automatically add __super to the class + # This trick only works for dynamic classes + def __new__(metaclass, name, bases, dict): + cls = super(autosuper, metaclass).__new__(metaclass, + name, bases, dict) + # Name mangling for __super removes leading underscores + while name[:1] == "_": + name = name[1:] + if name: + name = "_%s__super" % name + else: + name = "__super" + setattr(cls, name, super(cls)) + return cls + class A(metaclass=autosuper): + def meth(self): + return "A" + class B(A): + def meth(self): + return "B" + self.__super.meth() + class C(A): + def meth(self): + return "C" + self.__super.meth() + class D(C, B): + def meth(self): + return "D" + self.__super.meth() + self.assertEqual(D().meth(), "DCBA") + class E(B, C): + def meth(self): + return "E" + self.__super.meth() + self.assertEqual(E().meth(), "EBCA") + + class autoproperty(type): + # Automatically create property attributes when methods + # named _get_x and/or _set_x are found + def __new__(metaclass, name, bases, dict): + hits = {} + for key, val in dict.items(): + if key.startswith("_get_"): + key = key[5:] + get, set = hits.get(key, (None, None)) + get = val + hits[key] = get, set + elif key.startswith("_set_"): + key = key[5:] + get, set = hits.get(key, (None, None)) + set = val + hits[key] = get, set + for key, (get, set) in hits.items(): + dict[key] = property(get, set) + return super(autoproperty, metaclass).__new__(metaclass, + name, bases, dict) + class A(metaclass=autoproperty): + def _get_x(self): + return -self.__x + def _set_x(self, x): + self.__x = -x + a = A() + self.assert_(not hasattr(a, "x")) + a.x = 12 + self.assertEqual(a.x, 12) + self.assertEqual(a._A__x, -12) + + class multimetaclass(autoproperty, autosuper): + # Merge of multiple cooperating metaclasses + pass + class A(metaclass=multimetaclass): + def _get_x(self): + return "A" + class B(A): + def _get_x(self): + return "B" + self.__super._get_x() + class C(A): + def _get_x(self): + return "C" + self.__super._get_x() + class D(C, B): + def _get_x(self): + return "D" + self.__super._get_x() + self.assertEqual(D().x, "DCBA") + + # Make sure type(x) doesn't call x.__class__.__init__ + class T(type): + counter = 0 + def __init__(self, *args): + T.counter += 1 + class C(metaclass=T): + pass + self.assertEqual(T.counter, 1) + a = C() + self.assertEqual(type(a), C) + self.assertEqual(T.counter, 1) + + class C(object): pass + c = C() + try: c() + except TypeError: pass + else: self.fail("calling object w/o call method should raise " + "TypeError") + + # Testing code to find most derived baseclass + class A(type): + def __new__(*args, **kwargs): + return type.__new__(*args, **kwargs) + + class B(object): + pass + + class C(object, metaclass=A): + pass + + # The most derived metaclass of D is A rather than type. + class D(B, C): + pass + + def test_module_subclasses(self): + # Testing Python subclass of module... + log = [] + import types, sys + MT = type(sys) + class MM(MT): + def __init__(self, name): + MT.__init__(self, name) + def __getattribute__(self, name): + log.append(("getattr", name)) + return MT.__getattribute__(self, name) + def __setattr__(self, name, value): + log.append(("setattr", name, value)) + MT.__setattr__(self, name, value) + def __delattr__(self, name): + log.append(("delattr", name)) + MT.__delattr__(self, name) + a = MM("a") + a.foo = 12 + x = a.foo + del a.foo + self.assertEqual(log, [("setattr", "foo", 12), + ("getattr", "foo"), + ("delattr", "foo")]) -def veris(a, b): - if a is not b: - raise TestFailed("%r is %r" % (a, b)) - -def testunop(a, res, expr="len(a)", meth="__len__"): - if verbose: print("checking", expr) - dict = {'a': a} - vereq(eval(expr, dict), res) - t = type(a) - m = getattr(t, meth) - while meth not in t.__dict__: - t = t.__bases__[0] - vereq(m, t.__dict__[meth]) - vereq(m(a), res) - bm = getattr(a, meth) - vereq(bm(), res) - -def testbinop(a, b, res, expr="a+b", meth="__add__"): - if verbose: print("checking", expr) - dict = {'a': a, 'b': b} - - vereq(eval(expr, dict), res) - t = type(a) - m = getattr(t, meth) - while meth not in t.__dict__: - t = t.__bases__[0] - vereq(m, t.__dict__[meth]) - vereq(m(a, b), res) - bm = getattr(a, meth) - vereq(bm(b), res) - -def testsliceop(a, b, c, res, expr="a[b:c]", meth="__getitem__"): - if verbose: print("checking", expr) - dict = {'a': a, 'b': b, 'c': c} - vereq(eval(expr, dict), res) - t = type(a) - m = getattr(t, meth) - while meth not in t.__dict__: - t = t.__bases__[0] - vereq(m, t.__dict__[meth]) - vereq(m(a, slice(b, c)), res) - bm = getattr(a, meth) - vereq(bm(slice(b, c)), res) - -def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"): - if verbose: print("checking", stmt) - dict = {'a': deepcopy(a), 'b': b} - exec(stmt, dict) - vereq(dict['a'], res) - t = type(a) - m = getattr(t, meth) - while meth not in t.__dict__: - t = t.__bases__[0] - vereq(m, t.__dict__[meth]) - dict['a'] = deepcopy(a) - m(dict['a'], b) - vereq(dict['a'], res) - dict['a'] = deepcopy(a) - bm = getattr(dict['a'], meth) - bm(b) - vereq(dict['a'], res) - -def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"): - if verbose: print("checking", stmt) - dict = {'a': deepcopy(a), 'b': b, 'c': c} - exec(stmt, dict) - vereq(dict['a'], res) - t = type(a) - m = getattr(t, meth) - while meth not in t.__dict__: - t = t.__bases__[0] - vereq(m, t.__dict__[meth]) - dict['a'] = deepcopy(a) - m(dict['a'], b, c) - vereq(dict['a'], res) - dict['a'] = deepcopy(a) - bm = getattr(dict['a'], meth) - bm(b, c) - vereq(dict['a'], res) - -def testsetsliceop(a, b, c, d, res, stmt="a[b:c]=d", meth="__setitem__"): - if verbose: print("checking", stmt) - dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d} - exec(stmt, dict) - vereq(dict['a'], res) - t = type(a) - while meth not in t.__dict__: - t = t.__bases__[0] - m = getattr(t, meth) - vereq(m, t.__dict__[meth]) - dict['a'] = deepcopy(a) - m(dict['a'], slice(b, c), d) - vereq(dict['a'], res) - dict['a'] = deepcopy(a) - bm = getattr(dict['a'], meth) - bm(slice(b, c), d) - vereq(dict['a'], res) - -def class_docstrings(): - class Classic: - "A classic docstring." - vereq(Classic.__doc__, "A classic docstring.") - vereq(Classic.__dict__['__doc__'], "A classic docstring.") - - class Classic2: - pass - verify(Classic2.__doc__ is None) - - class NewStatic(object): - "Another docstring." - vereq(NewStatic.__doc__, "Another docstring.") - vereq(NewStatic.__dict__['__doc__'], "Another docstring.") - - class NewStatic2(object): - pass - verify(NewStatic2.__doc__ is None) - - class NewDynamic(object): - "Another docstring." - vereq(NewDynamic.__doc__, "Another docstring.") - vereq(NewDynamic.__dict__['__doc__'], "Another docstring.") - - class NewDynamic2(object): - pass - verify(NewDynamic2.__doc__ is None) - -def lists(): - if verbose: print("Testing list operations...") - testbinop([1], [2], [1,2], "a+b", "__add__") - testbinop([1,2,3], 2, 1, "b in a", "__contains__") - testbinop([1,2,3], 4, 0, "b in a", "__contains__") - testbinop([1,2,3], 1, 2, "a[b]", "__getitem__") - testsliceop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getitem__") - testsetop([1], [2], [1,2], "a+=b", "__iadd__") - testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__") - testunop([1,2,3], 3, "len(a)", "__len__") - testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__") - testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__") - testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__") - testsetsliceop([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", - "__setitem__") - -def dicts(): - if verbose: print("Testing dict operations...") - ##testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__") - testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__") - testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__") - testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__") - d = {1:2,3:4} - l1 = [] - for i in d.keys(): l1.append(i) - l = [] - for i in iter(d): l.append(i) - vereq(l, l1) - l = [] - for i in d.__iter__(): l.append(i) - vereq(l, l1) - l = [] - for i in dict.__iter__(d): l.append(i) - vereq(l, l1) - d = {1:2, 3:4} - testunop(d, 2, "len(a)", "__len__") - vereq(eval(repr(d), {}), d) - vereq(eval(d.__repr__(), {}), d) - testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__") - -def dict_constructor(): - if verbose: - print("Testing dict constructor ...") - d = dict() - vereq(d, {}) - d = dict({}) - vereq(d, {}) - d = dict({1: 2, 'a': 'b'}) - vereq(d, {1: 2, 'a': 'b'}) - vereq(d, dict(d.items())) - vereq(d, dict(d.items())) - d = dict({'one':1, 'two':2}) - vereq(d, dict(one=1, two=2)) - vereq(d, dict(**d)) - vereq(d, dict({"one": 1}, two=2)) - vereq(d, dict([("two", 2)], one=1)) - vereq(d, dict([("one", 100), ("two", 200)], **d)) - verify(d is not dict(**d)) - for badarg in 0, 0, 0j, "0", [0], (0,): - try: - dict(badarg) - except TypeError: - pass - except ValueError: - if badarg == "0": - # It's a sequence, and its elements are also sequences (gotta - # love strings ), but they aren't of length 2, so this - # one seemed better as a ValueError than a TypeError. + # http://python.org/sf/1174712 + try: + class Module(types.ModuleType, str): pass + except TypeError: + pass + else: + self.fail("inheriting from ModuleType and str at the same time " + "should fail") + + def test_multiple_inheritance(self): + # Testing multiple inheritance... + class C(object): + def __init__(self): + self.__state = 0 + def getstate(self): + return self.__state + def setstate(self, state): + self.__state = state + a = C() + self.assertEqual(a.getstate(), 0) + a.setstate(10) + self.assertEqual(a.getstate(), 10) + class D(dict, C): + def __init__(self): + type({}).__init__(self) + C.__init__(self) + d = D() + self.assertEqual(list(d.keys()), []) + d["hello"] = "world" + self.assertEqual(list(d.items()), [("hello", "world")]) + self.assertEqual(d["hello"], "world") + self.assertEqual(d.getstate(), 0) + d.setstate(10) + self.assertEqual(d.getstate(), 10) + self.assertEqual(D.__mro__, (D, dict, C, object)) + + # SF bug #442833 + class Node(object): + def __int__(self): + return int(self.foo()) + def foo(self): + return "23" + class Frag(Node, list): + def foo(self): + return "42" + self.assertEqual(Node().__int__(), 23) + self.assertEqual(int(Node()), 23) + self.assertEqual(Frag().__int__(), 42) + self.assertEqual(int(Frag()), 42) + + def test_diamond_inheritence(self): + # Testing multiple inheritance special cases... + class A(object): + def spam(self): return "A" + self.assertEqual(A().spam(), "A") + class B(A): + def boo(self): return "B" + def spam(self): return "B" + self.assertEqual(B().spam(), "B") + self.assertEqual(B().boo(), "B") + class C(A): + def boo(self): return "C" + self.assertEqual(C().spam(), "A") + self.assertEqual(C().boo(), "C") + class D(B, C): pass + self.assertEqual(D().spam(), "B") + self.assertEqual(D().boo(), "B") + self.assertEqual(D.__mro__, (D, B, C, A, object)) + class E(C, B): pass + self.assertEqual(E().spam(), "B") + self.assertEqual(E().boo(), "C") + self.assertEqual(E.__mro__, (E, C, B, A, object)) + # MRO order disagreement + try: + class F(D, E): pass + except TypeError: + pass + else: + self.fail("expected MRO order disagreement (F)") + try: + class G(E, D): pass + except TypeError: + pass + else: + self.fail("expected MRO order disagreement (G)") + + # see thread python-dev/2002-October/029035.html + def test_ex5_from_c3_switch(self): + # Testing ex5 from C3 switch discussion... + class A(object): pass + class B(object): pass + class C(object): pass + class X(A): pass + class Y(A): pass + class Z(X,B,Y,C): pass + self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object)) + + # see "A Monotonic Superclass Linearization for Dylan", + # by Kim Barrett et al. (OOPSLA 1996) + def test_monotonicity(self): + # Testing MRO monotonicity... + class Boat(object): pass + class DayBoat(Boat): pass + class WheelBoat(Boat): pass + class EngineLess(DayBoat): pass + class SmallMultihull(DayBoat): pass + class PedalWheelBoat(EngineLess,WheelBoat): pass + class SmallCatamaran(SmallMultihull): pass + class Pedalo(PedalWheelBoat,SmallCatamaran): pass + + self.assertEqual(PedalWheelBoat.__mro__, + (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object)) + self.assertEqual(SmallCatamaran.__mro__, + (SmallCatamaran, SmallMultihull, DayBoat, Boat, object)) + self.assertEqual(Pedalo.__mro__, + (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran, + SmallMultihull, DayBoat, WheelBoat, Boat, object)) + + # see "A Monotonic Superclass Linearization for Dylan", + # by Kim Barrett et al. (OOPSLA 1996) + def test_consistency_with_epg(self): + # Testing consistentcy with EPG... + class Pane(object): pass + class ScrollingMixin(object): pass + class EditingMixin(object): pass + class ScrollablePane(Pane,ScrollingMixin): pass + class EditablePane(Pane,EditingMixin): pass + class EditableScrollablePane(ScrollablePane,EditablePane): pass + + self.assertEqual(EditableScrollablePane.__mro__, + (EditableScrollablePane, ScrollablePane, EditablePane, Pane, + ScrollingMixin, EditingMixin, object)) + + def test_mro_disagreement(self): + # Testing error messages for MRO disagreement... + mro_err_msg = """Cannot create a consistent method resolution +order (MRO) for bases """ + + def raises(exc, expected, callable, *args): + try: + callable(*args) + except exc as msg: + if not str(msg).startswith(expected): + self.fail("Message %r, expected %r" % (str(msg), expected)) else: - raise TestFailed("no TypeError from dict(%r)" % badarg) + self.fail("Expected %s" % exc) + + class A(object): pass + class B(A): pass + class C(object): pass + + # Test some very simple errors + raises(TypeError, "duplicate base class A", + type, "X", (A, A), {}) + raises(TypeError, mro_err_msg, + type, "X", (A, B), {}) + raises(TypeError, mro_err_msg, + type, "X", (A, C, B), {}) + # Test a slightly more complex error + class GridLayout(object): pass + class HorizontalGrid(GridLayout): pass + class VerticalGrid(GridLayout): pass + class HVGrid(HorizontalGrid, VerticalGrid): pass + class VHGrid(VerticalGrid, HorizontalGrid): pass + raises(TypeError, mro_err_msg, + type, "ConfusedGrid", (HVGrid, VHGrid), {}) + + def test_object_class(self): + # Testing object class... + a = object() + self.assertEqual(a.__class__, object) + self.assertEqual(type(a), object) + b = object() + self.assertNotEqual(a, b) + self.assertFalse(hasattr(a, "foo")) + try: + a.foo = 12 + except (AttributeError, TypeError): + pass + else: + self.fail("object() should not allow setting a foo attribute") + self.assertFalse(hasattr(object(), "__dict__")) + + class Cdict(object): + pass + x = Cdict() + self.assertEqual(x.__dict__, {}) + x.foo = 1 + self.assertEqual(x.foo, 1) + self.assertEqual(x.__dict__, {'foo': 1}) + + def test_slots(self): + # Testing __slots__... + class C0(object): + __slots__ = [] + x = C0() + self.assertFalse(hasattr(x, "__dict__")) + self.assertFalse(hasattr(x, "foo")) + + class C1(object): + __slots__ = ['a'] + x = C1() + self.assertFalse(hasattr(x, "__dict__")) + self.assertFalse(hasattr(x, "a")) + x.a = 1 + self.assertEqual(x.a, 1) + x.a = None + self.assertEqual(x.a, None) + del x.a + self.assertFalse(hasattr(x, "a")) + + class C3(object): + __slots__ = ['a', 'b', 'c'] + x = C3() + self.assertFalse(hasattr(x, "__dict__")) + self.assertFalse(hasattr(x, 'a')) + self.assertFalse(hasattr(x, 'b')) + self.assertFalse(hasattr(x, 'c')) + x.a = 1 + x.b = 2 + x.c = 3 + self.assertEqual(x.a, 1) + self.assertEqual(x.b, 2) + self.assertEqual(x.c, 3) + + class C4(object): + """Validate name mangling""" + __slots__ = ['__a'] + def __init__(self, value): + self.__a = value + def get(self): + return self.__a + x = C4(5) + self.assertFalse(hasattr(x, '__dict__')) + self.assertFalse(hasattr(x, '__a')) + self.assertEqual(x.get(), 5) + try: + x.__a = 6 + except AttributeError: + pass + else: + self.fail("Double underscored names not mangled") + + # Make sure slot names are proper identifiers + try: + class C(object): + __slots__ = [None] + except TypeError: + pass + else: + self.fail("[None] slots not caught") + try: + class C(object): + __slots__ = ["foo bar"] + except TypeError: + pass + else: + self.fail("['foo bar'] slots not caught") + try: + class C(object): + __slots__ = ["foo\0bar"] + except TypeError: + pass + else: + self.fail("['foo\\0bar'] slots not caught") + try: + class C(object): + __slots__ = ["1"] + except TypeError: + pass + else: + self.fail("['1'] slots not caught") + try: + class C(object): + __slots__ = [""] + except TypeError: + pass + else: + self.fail("[''] slots not caught") + class C(object): + __slots__ = ["a", "a_b", "_a", "A0123456789Z"] + # XXX(nnorwitz): was there supposed to be something tested + # from the class above? + + # Test a single string is not expanded as a sequence. + class C(object): + __slots__ = "abc" + c = C() + c.abc = 5 + self.assertEqual(c.abc, 5) + + # Test unicode slot names + # Test a single unicode string is not expanded as a sequence. + class C(object): + __slots__ = "abc" + c = C() + c.abc = 5 + self.assertEqual(c.abc, 5) + + # _unicode_to_string used to modify slots in certain circumstances + slots = ("foo", "bar") + class C(object): + __slots__ = slots + x = C() + x.foo = 5 + self.assertEqual(x.foo, 5) + self.assert_(type(slots[0]) is str) + # this used to leak references + try: + class C(object): + __slots__ = [chr(128)] + except (TypeError, UnicodeEncodeError): + pass + else: + raise TestFailed("[chr(128)] slots not caught") + + # Test leaks + class Counted(object): + counter = 0 # counts the number of instances alive + def __init__(self): + Counted.counter += 1 + def __del__(self): + Counted.counter -= 1 + class C(object): + __slots__ = ['a', 'b', 'c'] + x = C() + x.a = Counted() + x.b = Counted() + x.c = Counted() + self.assertEqual(Counted.counter, 3) + del x + self.assertEqual(Counted.counter, 0) + class D(C): + pass + x = D() + x.a = Counted() + x.z = Counted() + self.assertEqual(Counted.counter, 2) + del x + self.assertEqual(Counted.counter, 0) + class E(D): + __slots__ = ['e'] + x = E() + x.a = Counted() + x.z = Counted() + x.e = Counted() + self.assertEqual(Counted.counter, 3) + del x + self.assertEqual(Counted.counter, 0) + + # Test cyclical leaks [SF bug 519621] + class F(object): + __slots__ = ['a', 'b'] + log = [] + s = F() + s.a = [Counted(), s] + self.assertEqual(Counted.counter, 1) + s = None + import gc + gc.collect() + self.assertEqual(Counted.counter, 0) + + # Test lookup leaks [SF bug 572567] + import sys,gc + class G(object): + def __cmp__(self, other): + return 0 + g = G() + orig_objects = len(gc.get_objects()) + for i in range(10): + g==g + new_objects = len(gc.get_objects()) + self.assertEqual(orig_objects, new_objects) + class H(object): + __slots__ = ['a', 'b'] + def __init__(self): + self.a = 1 + self.b = 2 + def __del__(self_): + self.assertEqual(self_.a, 1) + self.assertEqual(self_.b, 2) + + save_stderr = sys.stderr + sys.stderr = sys.stdout + h = H() + try: + del h + finally: + sys.stderr = save_stderr + + def test_slots_special(self): + # Testing __dict__ and __weakref__ in __slots__... + class D(object): + __slots__ = ["__dict__"] + a = D() + self.assert_(hasattr(a, "__dict__")) + self.assertFalse(hasattr(a, "__weakref__")) + a.foo = 42 + self.assertEqual(a.__dict__, {"foo": 42}) + + class W(object): + __slots__ = ["__weakref__"] + a = W() + self.assert_(hasattr(a, "__weakref__")) + self.assertFalse(hasattr(a, "__dict__")) + try: + a.foo = 42 + except AttributeError: + pass + else: + self.fail("shouldn't be allowed to set a.foo") + + class C1(W, D): + __slots__ = [] + a = C1() + self.assert_(hasattr(a, "__dict__")) + self.assert_(hasattr(a, "__weakref__")) + a.foo = 42 + self.assertEqual(a.__dict__, {"foo": 42}) + + class C2(D, W): + __slots__ = [] + a = C2() + self.assert_(hasattr(a, "__dict__")) + self.assert_(hasattr(a, "__weakref__")) + a.foo = 42 + self.assertEqual(a.__dict__, {"foo": 42}) + + def test_slots_descriptor(self): + # Issue2115: slot descriptors did not correctly check + # the type of the given object + import abc + class MyABC(metaclass=abc.ABCMeta): + __slots__ = "a" + + class Unrelated(object): + pass + MyABC.register(Unrelated) + + u = Unrelated() + self.assert_(isinstance(u, MyABC)) + + # This used to crash + self.assertRaises(TypeError, MyABC.a.__set__, u, 3) + + def test_dynamics(self): + # Testing class attribute propagation... + class D(object): + pass + class E(D): + pass + class F(D): + pass + D.foo = 1 + self.assertEqual(D.foo, 1) + # Test that dynamic attributes are inherited + self.assertEqual(E.foo, 1) + self.assertEqual(F.foo, 1) + # Test dynamic instances + class C(object): + pass + a = C() + self.assertFalse(hasattr(a, "foobar")) + C.foobar = 2 + self.assertEqual(a.foobar, 2) + C.method = lambda self: 42 + self.assertEqual(a.method(), 42) + C.__repr__ = lambda self: "C()" + self.assertEqual(repr(a), "C()") + C.__int__ = lambda self: 100 + self.assertEqual(int(a), 100) + self.assertEqual(a.foobar, 2) + self.assertFalse(hasattr(a, "spam")) + def mygetattr(self, name): + if name == "spam": + return "spam" + raise AttributeError + C.__getattr__ = mygetattr + self.assertEqual(a.spam, "spam") + a.new = 12 + self.assertEqual(a.new, 12) + def mysetattr(self, name, value): + if name == "spam": + raise AttributeError + return object.__setattr__(self, name, value) + C.__setattr__ = mysetattr + try: + a.spam = "not spam" + except AttributeError: + pass + else: + self.fail("expected AttributeError") + self.assertEqual(a.spam, "spam") + class D(C): + pass + d = D() + d.foo = 1 + self.assertEqual(d.foo, 1) + + # Test handling of int*seq and seq*int + class I(int): + pass + self.assertEqual("a"*I(2), "aa") + self.assertEqual(I(2)*"a", "aa") + self.assertEqual(2*I(3), 6) + self.assertEqual(I(3)*2, 6) + self.assertEqual(I(3)*I(2), 6) + + # Test handling of long*seq and seq*long + class L(int): + pass + self.assertEqual("a"*L(2), "aa") + self.assertEqual(L(2)*"a", "aa") + self.assertEqual(2*L(3), 6) + self.assertEqual(L(3)*2, 6) + self.assertEqual(L(3)*L(2), 6) + + # Test comparison of classes with dynamic metaclasses + class dynamicmetaclass(type): + pass + class someclass(metaclass=dynamicmetaclass): + pass + self.assertNotEqual(someclass, object) + + def test_errors(self): + # Testing errors... + try: + class C(list, dict): + pass + except TypeError: + pass + else: + self.fail("inheritance from both list and dict should be illegal") + + try: + class C(object, None): + pass + except TypeError: + pass + else: + self.fail("inheritance from non-type should be illegal") + class Classic: + pass + + try: + class C(type(len)): + pass + except TypeError: + pass + else: + self.fail("inheritance from CFunction should be illegal") + + try: + class C(object): + __slots__ = 1 + except TypeError: + pass + else: + self.fail("__slots__ = 1 should be illegal") + + try: + class C(object): + __slots__ = [1] + except TypeError: + pass + else: + self.fail("__slots__ = [1] should be illegal") + + class M1(type): + pass + class M2(type): + pass + class A1(object, metaclass=M1): + pass + class A2(object, metaclass=M2): + pass + try: + class B(A1, A2): + pass + except TypeError: + pass + else: + self.fail("finding the most derived metaclass should have failed") + + def test_classmethods(self): + # Testing class methods... + class C(object): + def foo(*a): return a + goo = classmethod(foo) + c = C() + self.assertEqual(C.goo(1), (C, 1)) + self.assertEqual(c.goo(1), (C, 1)) + self.assertEqual(c.foo(1), (c, 1)) + class D(C): + pass + d = D() + self.assertEqual(D.goo(1), (D, 1)) + self.assertEqual(d.goo(1), (D, 1)) + self.assertEqual(d.foo(1), (d, 1)) + self.assertEqual(D.foo(d, 1), (d, 1)) + # Test for a specific crash (SF bug 528132) + def f(cls, arg): return (cls, arg) + ff = classmethod(f) + self.assertEqual(ff.__get__(0, int)(42), (int, 42)) + self.assertEqual(ff.__get__(0)(42), (int, 42)) + + # Test super() with classmethods (SF bug 535444) + self.assertEqual(C.goo.__self__, C) + self.assertEqual(D.goo.__self__, D) + self.assertEqual(super(D,D).goo.__self__, D) + self.assertEqual(super(D,d).goo.__self__, D) + self.assertEqual(super(D,D).goo(), (D,)) + self.assertEqual(super(D,d).goo(), (D,)) + + # Verify that argument is checked for callability (SF bug 753451) + try: + classmethod(1).__get__(1) + except TypeError: + pass + else: + self.fail("classmethod should check for callability") + + # Verify that classmethod() doesn't allow keyword args + try: + classmethod(f, kw=1) + except TypeError: + pass + else: + self.fail("classmethod shouldn't accept keyword args") + + def test_classmethods_in_c(self): + # Testing C-based class methods... + import xxsubtype as spam + a = (1, 2, 3) + d = {'abc': 123} + x, a1, d1 = spam.spamlist.classmeth(*a, **d) + self.assertEqual(x, spam.spamlist) + self.assertEqual(a, a1) + self.assertEqual(d, d1) + x, a1, d1 = spam.spamlist().classmeth(*a, **d) + self.assertEqual(x, spam.spamlist) + self.assertEqual(a, a1) + self.assertEqual(d, d1) + + def test_staticmethods(self): + # Testing static methods... + class C(object): + def foo(*a): return a + goo = staticmethod(foo) + c = C() + self.assertEqual(C.goo(1), (1,)) + self.assertEqual(c.goo(1), (1,)) + self.assertEqual(c.foo(1), (c, 1,)) + class D(C): + pass + d = D() + self.assertEqual(D.goo(1), (1,)) + self.assertEqual(d.goo(1), (1,)) + self.assertEqual(d.foo(1), (d, 1)) + self.assertEqual(D.foo(d, 1), (d, 1)) + + def test_staticmethods_in_c(self): + # Testing C-based static methods... + import xxsubtype as spam + a = (1, 2, 3) + d = {"abc": 123} + x, a1, d1 = spam.spamlist.staticmeth(*a, **d) + self.assertEqual(x, None) + self.assertEqual(a, a1) + self.assertEqual(d, d1) + x, a1, d2 = spam.spamlist().staticmeth(*a, **d) + self.assertEqual(x, None) + self.assertEqual(a, a1) + self.assertEqual(d, d1) + + def test_classic(self): + # Testing classic classes... + class C: + def foo(*a): return a + goo = classmethod(foo) + c = C() + self.assertEqual(C.goo(1), (C, 1)) + self.assertEqual(c.goo(1), (C, 1)) + self.assertEqual(c.foo(1), (c, 1)) + class D(C): + pass + d = D() + self.assertEqual(D.goo(1), (D, 1)) + self.assertEqual(d.goo(1), (D, 1)) + self.assertEqual(d.foo(1), (d, 1)) + self.assertEqual(D.foo(d, 1), (d, 1)) + class E: # *not* subclassing from C + foo = C.foo + self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound + self.assert_(repr(C.foo.__get__(C())).startswith("= 0) + self.assertEqual(str(c1), repr(c1)) + self.assert_(-1 not in c1) + for i in range(10): + self.assert_(i in c1) + self.assertFalse(10 in c1) + # Test the default behavior for dynamic classes + class D(object): + def __getitem__(self, i): + if 0 <= i < 10: return i + raise IndexError + d1 = D() + d2 = D() + self.assert_(not not d1) + self.assertNotEqual(id(d1), id(d2)) + hash(d1) + hash(d2) + ## self.assertEqual(cmp(d1, d2), cmp(id(d1), id(d2))) + self.assertEqual(d1, d1) + self.assertNotEqual(d1, d2) + self.assert_(not d1 != d1) + self.assert_(not d1 == d2) + # Note that the module name appears in str/repr, and that varies + # depending on whether this test is run standalone or from a framework. + self.assert_(str(d1).find('D object at ') >= 0) + self.assertEqual(str(d1), repr(d1)) + self.assert_(-1 not in d1) + for i in range(10): + self.assert_(i in d1) + self.assertFalse(10 in d1) + # Test overridden behavior for static classes + class Proxy(object): + def __init__(self, x): + self.x = x + def __bool__(self): + return not not self.x + def __hash__(self): + return hash(self.x) + def __eq__(self, other): + return self.x == other + def __ne__(self, other): + return self.x != other + def __cmp__(self, other): + return cmp(self.x, other.x) + def __str__(self): + return "Proxy:%s" % self.x + def __repr__(self): + return "Proxy(%r)" % self.x + def __contains__(self, value): + return value in self.x + p0 = Proxy(0) + p1 = Proxy(1) + p_1 = Proxy(-1) + self.assertFalse(p0) + self.assert_(not not p1) + self.assertEqual(hash(p0), hash(0)) + self.assertEqual(p0, p0) + self.assertNotEqual(p0, p1) + self.assert_(not p0 != p0) + self.assertEqual(not p0, p1) + self.assertEqual(cmp(p0, p1), -1) + self.assertEqual(cmp(p0, p0), 0) + self.assertEqual(cmp(p0, p_1), 1) + self.assertEqual(str(p0), "Proxy:0") + self.assertEqual(repr(p0), "Proxy(0)") + p10 = Proxy(range(10)) + self.assertFalse(-1 in p10) + for i in range(10): + self.assert_(i in p10) + self.assertFalse(10 in p10) + # Test overridden behavior for dynamic classes + class DProxy(object): + def __init__(self, x): + self.x = x + def __bool__(self): + return not not self.x + def __hash__(self): + return hash(self.x) + def __eq__(self, other): + return self.x == other + def __ne__(self, other): + return self.x != other + def __cmp__(self, other): + return cmp(self.x, other.x) + def __str__(self): + return "DProxy:%s" % self.x + def __repr__(self): + return "DProxy(%r)" % self.x + def __contains__(self, value): + return value in self.x + p0 = DProxy(0) + p1 = DProxy(1) + p_1 = DProxy(-1) + self.assertFalse(p0) + self.assert_(not not p1) + self.assertEqual(hash(p0), hash(0)) + self.assertEqual(p0, p0) + self.assertNotEqual(p0, p1) + self.assertNotEqual(not p0, p0) + self.assertEqual(not p0, p1) + self.assertEqual(cmp(p0, p1), -1) + self.assertEqual(cmp(p0, p0), 0) + self.assertEqual(cmp(p0, p_1), 1) + self.assertEqual(str(p0), "DProxy:0") + self.assertEqual(repr(p0), "DProxy(0)") + p10 = DProxy(range(10)) + self.assertFalse(-1 in p10) + for i in range(10): + self.assert_(i in p10) + self.assertFalse(10 in p10) + + ## # Safety test for __cmp__ + ## def unsafecmp(a, b): + ## try: + ## a.__class__.__cmp__(a, b) + ## except TypeError: + ## pass + ## else: + ## self.fail("shouldn't allow %s.__cmp__(%r, %r)" % ( + ## a.__class__, a, b)) + ## + ## unsafecmp("123", "123") + ## unsafecmp("123", "123") + ## unsafecmp(1, 1.0) + ## unsafecmp(1.0, 1) + ## unsafecmp(1, 1) + ## unsafecmp(1, 1) + + def test_weakrefs(self): + # Testing weak references... + import weakref + class C(object): + pass + c = C() + r = weakref.ref(c) + self.assertEqual(r(), c) + del c + self.assertEqual(r(), None) + del r + class NoWeak(object): + __slots__ = ['foo'] + no = NoWeak() + try: + weakref.ref(no) + except TypeError as msg: + self.assert_(str(msg).find("weak reference") >= 0) + else: + self.fail("weakref.ref(no) should be illegal") + class Weak(object): + __slots__ = ['foo', '__weakref__'] + yes = Weak() + r = weakref.ref(yes) + self.assertEqual(r(), yes) + del yes + self.assertEqual(r(), None) + del r + + def test_properties(self): + # Testing property... + class C(object): + def getx(self): + return self.__x + def setx(self, value): + self.__x = value + def delx(self): + del self.__x + x = property(getx, setx, delx, doc="I'm the x property.") + a = C() + self.assertFalse(hasattr(a, "x")) + a.x = 42 + self.assertEqual(a._C__x, 42) + self.assertEqual(a.x, 42) + del a.x + self.assertFalse(hasattr(a, "x")) + self.assertFalse(hasattr(a, "_C__x")) + C.x.__set__(a, 100) + self.assertEqual(C.x.__get__(a), 100) + C.x.__delete__(a) + self.assertFalse(hasattr(a, "x")) + + raw = C.__dict__['x'] + self.assert_(isinstance(raw, property)) + + attrs = dir(raw) + self.assert_("__doc__" in attrs) + self.assert_("fget" in attrs) + self.assert_("fset" in attrs) + self.assert_("fdel" in attrs) + + self.assertEqual(raw.__doc__, "I'm the x property.") + self.assert_(raw.fget is C.__dict__['getx']) + self.assert_(raw.fset is C.__dict__['setx']) + self.assert_(raw.fdel is C.__dict__['delx']) + + for attr in "__doc__", "fget", "fset", "fdel": + try: + setattr(raw, attr, 42) + except AttributeError as msg: + if str(msg).find('readonly') < 0: + self.fail("when setting readonly attr %r on a property, " + "got unexpected AttributeError msg %r" % (attr, str(msg))) + else: + self.fail("expected AttributeError from trying to set readonly %r " + "attr on a property" % attr) + + class D(object): + __getitem__ = property(lambda s: 1/0) + + d = D() + try: + for i in d: + str(i) + except ZeroDivisionError: + pass + else: + self.fail("expected ZeroDivisionError from bad property") + + class E(object): + def getter(self): + "getter method" + return 0 + def setter(self_, value): + "setter method" + pass + prop = property(getter) + self.assertEqual(prop.__doc__, "getter method") + prop2 = property(fset=setter) + self.assertEqual(prop2.__doc__, None) + + # this segfaulted in 2.5b2 + try: + import _testcapi + except ImportError: + pass + else: + class X(object): + p = property(_testcapi.test_with_docstring) + + def test_properties_plus(self): + class C(object): + foo = property(doc="hello") + @foo.getter + def foo(self): + return self._foo + @foo.setter + def foo(self, value): + self._foo = abs(value) + @foo.deleter + def foo(self): + del self._foo + c = C() + self.assertEqual(C.foo.__doc__, "hello") + self.assertFalse(hasattr(c, "foo")) + c.foo = -42 + self.assert_(hasattr(c, '_foo')) + self.assertEqual(c._foo, 42) + self.assertEqual(c.foo, 42) + del c.foo + self.assertFalse(hasattr(c, '_foo')) + self.assertFalse(hasattr(c, "foo")) + + class D(C): + @C.foo.deleter + def foo(self): + try: + del self._foo + except AttributeError: + pass + d = D() + d.foo = 24 + self.assertEqual(d.foo, 24) + del d.foo + del d.foo + + class E(object): + @property + def foo(self): + return self._foo + @foo.setter + def foo(self, value): + raise RuntimeError + @foo.setter + def foo(self, value): + self._foo = abs(value) + @foo.deleter + def foo(self, value=None): + del self._foo + + e = E() + e.foo = -42 + self.assertEqual(e.foo, 42) + del e.foo + + class F(E): + @E.foo.deleter + def foo(self): + del self._foo + @foo.setter + def foo(self, value): + self._foo = max(0, value) + f = F() + f.foo = -10 + self.assertEqual(f.foo, 0) + del f.foo + + def test_dict_constructors(self): + # Testing dict constructor ... + d = dict() + self.assertEqual(d, {}) + d = dict({}) + self.assertEqual(d, {}) + d = dict({1: 2, 'a': 'b'}) + self.assertEqual(d, {1: 2, 'a': 'b'}) + self.assertEqual(d, dict(list(d.items()))) + self.assertEqual(d, dict(iter(d.items()))) + d = dict({'one':1, 'two':2}) + self.assertEqual(d, dict(one=1, two=2)) + self.assertEqual(d, dict(**d)) + self.assertEqual(d, dict({"one": 1}, two=2)) + self.assertEqual(d, dict([("two", 2)], one=1)) + self.assertEqual(d, dict([("one", 100), ("two", 200)], **d)) + self.assertEqual(d, dict(**d)) + + for badarg in 0, 0, 0j, "0", [0], (0,): + try: + dict(badarg) + except TypeError: + pass + except ValueError: + if badarg == "0": + # It's a sequence, and its elements are also sequences (gotta + # love strings ), but they aren't of length 2, so this + # one seemed better as a ValueError than a TypeError. + pass + else: + self.fail("no TypeError from dict(%r)" % badarg) + else: + self.fail("no TypeError from dict(%r)" % badarg) + + try: + dict({}, {}) + except TypeError: + pass + else: + self.fail("no TypeError from dict({}, {})") + + class Mapping: + # Lacks a .keys() method; will be added later. + dict = {1:2, 3:4, 'a':1j} + + try: + dict(Mapping()) + except TypeError: + pass + else: + self.fail("no TypeError from dict(incomplete mapping)") + + Mapping.keys = lambda self: list(self.dict.keys()) + Mapping.__getitem__ = lambda self, i: self.dict[i] + d = dict(Mapping()) + self.assertEqual(d, Mapping.dict) + + # Init from sequence of iterable objects, each producing a 2-sequence. + class AddressBookEntry: + def __init__(self, first, last): + self.first = first + self.last = last + def __iter__(self): + return iter([self.first, self.last]) + + d = dict([AddressBookEntry('Tim', 'Warsaw'), + AddressBookEntry('Barry', 'Peters'), + AddressBookEntry('Tim', 'Peters'), + AddressBookEntry('Barry', 'Warsaw')]) + self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'}) + + d = dict(zip(range(4), range(1, 5))) + self.assertEqual(d, dict([(i, i+1) for i in range(4)])) + + # Bad sequence lengths. + for bad in [('tooshort',)], [('too', 'long', 'by 1')]: + try: + dict(bad) + except ValueError: + pass + else: + self.fail("no ValueError from dict(%r)" % bad) + + def test_dir(self): + # Testing dir() ... + junk = 12 + self.assertEqual(dir(), ['junk', 'self']) + del junk + + # Just make sure these don't blow up! + for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir: + dir(arg) + + # Test dir on new-style classes. Since these have object as a + # base class, a lot more gets sucked in. + def interesting(strings): + return [s for s in strings if not s.startswith('_')] + + class C(object): + Cdata = 1 + def Cmethod(self): pass + + cstuff = ['Cdata', 'Cmethod'] + self.assertEqual(interesting(dir(C)), cstuff) + + c = C() + self.assertEqual(interesting(dir(c)), cstuff) + ## self.assert_('__self__' in dir(C.Cmethod)) + + c.cdata = 2 + c.cmethod = lambda self: 0 + self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod']) + ## self.assert_('__self__' in dir(c.Cmethod)) + + class A(C): + Adata = 1 + def Amethod(self): pass + + astuff = ['Adata', 'Amethod'] + cstuff + self.assertEqual(interesting(dir(A)), astuff) + ## self.assert_('__self__' in dir(A.Amethod)) + a = A() + self.assertEqual(interesting(dir(a)), astuff) + a.adata = 42 + a.amethod = lambda self: 3 + self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod']) + ## self.assert_('__self__' in dir(a.Amethod)) + + # Try a module subclass. + import sys + class M(type(sys)): + pass + minstance = M("m") + minstance.b = 2 + minstance.a = 1 + names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]] + self.assertEqual(names, ['a', 'b']) + + class M2(M): + def getdict(self): + return "Not a dict!" + __dict__ = property(getdict) + + m2instance = M2("m2") + m2instance.b = 2 + m2instance.a = 1 + self.assertEqual(m2instance.__dict__, "Not a dict!") + try: + dir(m2instance) + except TypeError: + pass + + # Two essentially featureless objects, just inheriting stuff from + # object. + self.assertEqual(dir(None), dir(Ellipsis)) + + # Nasty test case for proxied objects + class Wrapper(object): + def __init__(self, obj): + self.__obj = obj + def __repr__(self): + return "Wrapper(%s)" % repr(self.__obj) + def __getitem__(self, key): + return Wrapper(self.__obj[key]) + def __len__(self): + return len(self.__obj) + def __getattr__(self, name): + return Wrapper(getattr(self.__obj, name)) + + class C(object): + def __getclass(self): + return Wrapper(type(self)) + __class__ = property(__getclass) + + dir(C()) # This used to segfault + + def test_supers(self): + # Testing super... + + class A(object): + def meth(self, a): + return "A(%r)" % a + + self.assertEqual(A().meth(1), "A(1)") + + class B(A): + def __init__(self): + self.__super = super(B, self) + def meth(self, a): + return "B(%r)" % a + self.__super.meth(a) + + self.assertEqual(B().meth(2), "B(2)A(2)") + + class C(A): + def meth(self, a): + return "C(%r)" % a + self.__super.meth(a) + C._C__super = super(C) + + self.assertEqual(C().meth(3), "C(3)A(3)") + + class D(C, B): + def meth(self, a): + return "D(%r)" % a + super(D, self).meth(a) + + self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)") + + # Test for subclassing super + + class mysuper(super): + def __init__(self, *args): + return super(mysuper, self).__init__(*args) + + class E(D): + def meth(self, a): + return "E(%r)" % a + mysuper(E, self).meth(a) + + self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)") + + class F(E): + def meth(self, a): + s = self.__super # == mysuper(F, self) + return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a) + F._F__super = mysuper(F) + + self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)") + + # Make sure certain errors are raised + + try: + super(D, 42) + except TypeError: + pass + else: + self.fail("shouldn't allow super(D, 42)") + + try: + super(D, C()) + except TypeError: + pass + else: + self.fail("shouldn't allow super(D, C())") + + try: + super(D).__get__(12) + except TypeError: + pass + else: + self.fail("shouldn't allow super(D).__get__(12)") + + try: + super(D).__get__(C()) + except TypeError: + pass + else: + self.fail("shouldn't allow super(D).__get__(C())") + + # Make sure data descriptors can be overridden and accessed via super + # (new feature in Python 2.3) + + class DDbase(object): + def getx(self): return 42 + x = property(getx) + + class DDsub(DDbase): + def getx(self): return "hello" + x = property(getx) + + dd = DDsub() + self.assertEqual(dd.x, "hello") + self.assertEqual(super(DDsub, dd).x, 42) + + # Ensure that super() lookup of descriptor from classmethod + # works (SF ID# 743627) + + class Base(object): + aProp = property(lambda self: "foo") + + class Sub(Base): + @classmethod + def test(klass): + return super(Sub,klass).aProp + + self.assertEqual(Sub.test(), Base.aProp) + + # Verify that super() doesn't allow keyword args + try: + super(Base, kw=1) + except TypeError: + pass + else: + self.assertEqual("super shouldn't accept keyword args") + + def test_basic_inheritance(self): + # Testing inheritance from basic types... + + class hexint(int): + def __repr__(self): + return hex(self) + def __add__(self, other): + return hexint(int.__add__(self, other)) + # (Note that overriding __radd__ doesn't work, + # because the int type gets first dibs.) + self.assertEqual(repr(hexint(7) + 9), "0x10") + self.assertEqual(repr(hexint(1000) + 7), "0x3ef") + a = hexint(12345) + self.assertEqual(a, 12345) + self.assertEqual(int(a), 12345) + self.assert_(int(a).__class__ is int) + self.assertEqual(hash(a), hash(12345)) + self.assert_((+a).__class__ is int) + self.assert_((a >> 0).__class__ is int) + self.assert_((a << 0).__class__ is int) + self.assert_((hexint(0) << 12).__class__ is int) + self.assert_((hexint(0) >> 12).__class__ is int) + + class octlong(int): + __slots__ = [] + def __str__(self): + s = oct(self) + if s[-1] == 'L': + s = s[:-1] + return s + def __add__(self, other): + return self.__class__(super(octlong, self).__add__(other)) + __radd__ = __add__ + self.assertEqual(str(octlong(3) + 5), "0o10") + # (Note that overriding __radd__ here only seems to work + # because the example uses a short int left argument.) + self.assertEqual(str(5 + octlong(3000)), "0o5675") + a = octlong(12345) + self.assertEqual(a, 12345) + self.assertEqual(int(a), 12345) + self.assertEqual(hash(a), hash(12345)) + self.assert_(int(a).__class__ is int) + self.assert_((+a).__class__ is int) + self.assert_((-a).__class__ is int) + self.assert_((-octlong(0)).__class__ is int) + self.assert_((a >> 0).__class__ is int) + self.assert_((a << 0).__class__ is int) + self.assert_((a - 0).__class__ is int) + self.assert_((a * 1).__class__ is int) + self.assert_((a ** 1).__class__ is int) + self.assert_((a // 1).__class__ is int) + self.assert_((1 * a).__class__ is int) + self.assert_((a | 0).__class__ is int) + self.assert_((a ^ 0).__class__ is int) + self.assert_((a & -1).__class__ is int) + self.assert_((octlong(0) << 12).__class__ is int) + self.assert_((octlong(0) >> 12).__class__ is int) + self.assert_(abs(octlong(0)).__class__ is int) + + # Because octlong overrides __add__, we can't check the absence of +0 + # optimizations using octlong. + class longclone(int): + pass + a = longclone(1) + self.assert_((a + 0).__class__ is int) + self.assert_((0 + a).__class__ is int) + + # Check that negative clones don't segfault + a = longclone(-1) + self.assertEqual(a.__dict__, {}) + self.assertEqual(int(a), -1) # self.assert_ PyNumber_Long() copies the sign bit + + class precfloat(float): + __slots__ = ['prec'] + def __init__(self, value=0.0, prec=12): + self.prec = int(prec) + def __repr__(self): + return "%.*g" % (self.prec, self) + self.assertEqual(repr(precfloat(1.1)), "1.1") + a = precfloat(12345) + self.assertEqual(a, 12345.0) + self.assertEqual(float(a), 12345.0) + self.assert_(float(a).__class__ is float) + self.assertEqual(hash(a), hash(12345.0)) + self.assert_((+a).__class__ is float) + + class madcomplex(complex): + def __repr__(self): + return "%.17gj%+.17g" % (self.imag, self.real) + a = madcomplex(-3, 4) + self.assertEqual(repr(a), "4j-3") + base = complex(-3, 4) + self.assertEqual(base.__class__, complex) + self.assertEqual(a, base) + self.assertEqual(complex(a), base) + self.assertEqual(complex(a).__class__, complex) + a = madcomplex(a) # just trying another form of the constructor + self.assertEqual(repr(a), "4j-3") + self.assertEqual(a, base) + self.assertEqual(complex(a), base) + self.assertEqual(complex(a).__class__, complex) + self.assertEqual(hash(a), hash(base)) + self.assertEqual((+a).__class__, complex) + self.assertEqual((a + 0).__class__, complex) + self.assertEqual(a + 0, base) + self.assertEqual((a - 0).__class__, complex) + self.assertEqual(a - 0, base) + self.assertEqual((a * 1).__class__, complex) + self.assertEqual(a * 1, base) + self.assertEqual((a / 1).__class__, complex) + self.assertEqual(a / 1, base) + + class madtuple(tuple): + _rev = None + def rev(self): + if self._rev is not None: + return self._rev + L = list(self) + L.reverse() + self._rev = self.__class__(L) + return self._rev + a = madtuple((1,2,3,4,5,6,7,8,9,0)) + self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0)) + self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1))) + self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0))) + for i in range(512): + t = madtuple(range(i)) + u = t.rev() + v = u.rev() + self.assertEqual(v, t) + a = madtuple((1,2,3,4,5)) + self.assertEqual(tuple(a), (1,2,3,4,5)) + self.assert_(tuple(a).__class__ is tuple) + self.assertEqual(hash(a), hash((1,2,3,4,5))) + self.assert_(a[:].__class__ is tuple) + self.assert_((a * 1).__class__ is tuple) + self.assert_((a * 0).__class__ is tuple) + self.assert_((a + ()).__class__ is tuple) + a = madtuple(()) + self.assertEqual(tuple(a), ()) + self.assert_(tuple(a).__class__ is tuple) + self.assert_((a + a).__class__ is tuple) + self.assert_((a * 0).__class__ is tuple) + self.assert_((a * 1).__class__ is tuple) + self.assert_((a * 2).__class__ is tuple) + self.assert_(a[:].__class__ is tuple) + + class madstring(str): + _rev = None + def rev(self): + if self._rev is not None: + return self._rev + L = list(self) + L.reverse() + self._rev = self.__class__("".join(L)) + return self._rev + s = madstring("abcdefghijklmnopqrstuvwxyz") + self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz") + self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba")) + self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz")) + for i in range(256): + s = madstring("".join(map(chr, range(i)))) + t = s.rev() + u = t.rev() + self.assertEqual(u, s) + s = madstring("12345") + self.assertEqual(str(s), "12345") + self.assert_(str(s).__class__ is str) + + base = "\x00" * 5 + s = madstring(base) + self.assertEqual(s, base) + self.assertEqual(str(s), base) + self.assert_(str(s).__class__ is str) + self.assertEqual(hash(s), hash(base)) + self.assertEqual({s: 1}[base], 1) + self.assertEqual({base: 1}[s], 1) + self.assert_((s + "").__class__ is str) + self.assertEqual(s + "", base) + self.assert_(("" + s).__class__ is str) + self.assertEqual("" + s, base) + self.assert_((s * 0).__class__ is str) + self.assertEqual(s * 0, "") + self.assert_((s * 1).__class__ is str) + self.assertEqual(s * 1, base) + self.assert_((s * 2).__class__ is str) + self.assertEqual(s * 2, base + base) + self.assert_(s[:].__class__ is str) + self.assertEqual(s[:], base) + self.assert_(s[0:0].__class__ is str) + self.assertEqual(s[0:0], "") + self.assert_(s.strip().__class__ is str) + self.assertEqual(s.strip(), base) + self.assert_(s.lstrip().__class__ is str) + self.assertEqual(s.lstrip(), base) + self.assert_(s.rstrip().__class__ is str) + self.assertEqual(s.rstrip(), base) + identitytab = {} + self.assert_(s.translate(identitytab).__class__ is str) + self.assertEqual(s.translate(identitytab), base) + self.assert_(s.replace("x", "x").__class__ is str) + self.assertEqual(s.replace("x", "x"), base) + self.assert_(s.ljust(len(s)).__class__ is str) + self.assertEqual(s.ljust(len(s)), base) + self.assert_(s.rjust(len(s)).__class__ is str) + self.assertEqual(s.rjust(len(s)), base) + self.assert_(s.center(len(s)).__class__ is str) + self.assertEqual(s.center(len(s)), base) + self.assert_(s.lower().__class__ is str) + self.assertEqual(s.lower(), base) + + class madunicode(str): + _rev = None + def rev(self): + if self._rev is not None: + return self._rev + L = list(self) + L.reverse() + self._rev = self.__class__("".join(L)) + return self._rev + u = madunicode("ABCDEF") + self.assertEqual(u, "ABCDEF") + self.assertEqual(u.rev(), madunicode("FEDCBA")) + self.assertEqual(u.rev().rev(), madunicode("ABCDEF")) + base = "12345" + u = madunicode(base) + self.assertEqual(str(u), base) + self.assert_(str(u).__class__ is str) + self.assertEqual(hash(u), hash(base)) + self.assertEqual({u: 1}[base], 1) + self.assertEqual({base: 1}[u], 1) + self.assert_(u.strip().__class__ is str) + self.assertEqual(u.strip(), base) + self.assert_(u.lstrip().__class__ is str) + self.assertEqual(u.lstrip(), base) + self.assert_(u.rstrip().__class__ is str) + self.assertEqual(u.rstrip(), base) + self.assert_(u.replace("x", "x").__class__ is str) + self.assertEqual(u.replace("x", "x"), base) + self.assert_(u.replace("xy", "xy").__class__ is str) + self.assertEqual(u.replace("xy", "xy"), base) + self.assert_(u.center(len(u)).__class__ is str) + self.assertEqual(u.center(len(u)), base) + self.assert_(u.ljust(len(u)).__class__ is str) + self.assertEqual(u.ljust(len(u)), base) + self.assert_(u.rjust(len(u)).__class__ is str) + self.assertEqual(u.rjust(len(u)), base) + self.assert_(u.lower().__class__ is str) + self.assertEqual(u.lower(), base) + self.assert_(u.upper().__class__ is str) + self.assertEqual(u.upper(), base) + self.assert_(u.capitalize().__class__ is str) + self.assertEqual(u.capitalize(), base) + self.assert_(u.title().__class__ is str) + self.assertEqual(u.title(), base) + self.assert_((u + "").__class__ is str) + self.assertEqual(u + "", base) + self.assert_(("" + u).__class__ is str) + self.assertEqual("" + u, base) + self.assert_((u * 0).__class__ is str) + self.assertEqual(u * 0, "") + self.assert_((u * 1).__class__ is str) + self.assertEqual(u * 1, base) + self.assert_((u * 2).__class__ is str) + self.assertEqual(u * 2, base + base) + self.assert_(u[:].__class__ is str) + self.assertEqual(u[:], base) + self.assert_(u[0:0].__class__ is str) + self.assertEqual(u[0:0], "") + + class sublist(list): + pass + a = sublist(range(5)) + self.assertEqual(a, list(range(5))) + a.append("hello") + self.assertEqual(a, list(range(5)) + ["hello"]) + a[5] = 5 + self.assertEqual(a, list(range(6))) + a.extend(range(6, 20)) + self.assertEqual(a, list(range(20))) + a[-5:] = [] + self.assertEqual(a, list(range(15))) + del a[10:15] + self.assertEqual(len(a), 10) + self.assertEqual(a, list(range(10))) + self.assertEqual(list(a), list(range(10))) + self.assertEqual(a[0], 0) + self.assertEqual(a[9], 9) + self.assertEqual(a[-10], 0) + self.assertEqual(a[-1], 9) + self.assertEqual(a[:5], list(range(5))) + + ## class CountedInput(file): + ## """Counts lines read by self.readline(). + ## + ## self.lineno is the 0-based ordinal of the last line read, up to + ## a maximum of one greater than the number of lines in the file. + ## + ## self.ateof is true if and only if the final "" line has been read, + ## at which point self.lineno stops incrementing, and further calls + ## to readline() continue to return "". + ## """ + ## + ## lineno = 0 + ## ateof = 0 + ## def readline(self): + ## if self.ateof: + ## return "" + ## s = file.readline(self) + ## # Next line works too. + ## # s = super(CountedInput, self).readline() + ## self.lineno += 1 + ## if s == "": + ## self.ateof = 1 + ## return s + ## + ## f = file(name=test_support.TESTFN, mode='w') + ## lines = ['a\n', 'b\n', 'c\n'] + ## try: + ## f.writelines(lines) + ## f.close() + ## f = CountedInput(test_support.TESTFN) + ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]): + ## got = f.readline() + ## self.assertEqual(expected, got) + ## self.assertEqual(f.lineno, i) + ## self.assertEqual(f.ateof, (i > len(lines))) + ## f.close() + ## finally: + ## try: + ## f.close() + ## except: + ## pass + ## test_support.unlink(test_support.TESTFN) + + def test_keywords(self): + # Testing keyword args to basic type constructors ... + self.assertEqual(int(x=1), 1) + self.assertEqual(float(x=2), 2.0) + self.assertEqual(int(x=3), 3) + self.assertEqual(complex(imag=42, real=666), complex(666, 42)) + self.assertEqual(str(object=500), '500') + self.assertEqual(str(object=b'abc', errors='strict'), 'abc') + self.assertEqual(tuple(sequence=range(3)), (0, 1, 2)) + self.assertEqual(list(sequence=(0, 1, 2)), list(range(3))) + # note: as of Python 2.3, dict() no longer has an "items" keyword arg + + for constructor in (int, float, int, complex, str, str, + tuple, list): + try: + constructor(bogus_keyword_arg=1) + except TypeError: + pass + else: + self.fail("expected TypeError from bogus keyword argument to %r" + % constructor) + + def test_str_subclass_as_dict_key(self): + # Testing a str subclass used as dict key .. + + class cistr(str): + """Sublcass of str that computes __eq__ case-insensitively. + + Also computes a hash code of the string in canonical form. + """ + + def __init__(self, value): + self.canonical = value.lower() + self.hashcode = hash(self.canonical) + + def __eq__(self, other): + if not isinstance(other, cistr): + other = cistr(other) + return self.canonical == other.canonical + + def __hash__(self): + return self.hashcode + + self.assertEqual(cistr('ABC'), 'abc') + self.assertEqual('aBc', cistr('ABC')) + self.assertEqual(str(cistr('ABC')), 'ABC') + + d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3} + self.assertEqual(d[cistr('one')], 1) + self.assertEqual(d[cistr('tWo')], 2) + self.assertEqual(d[cistr('THrEE')], 3) + self.assert_(cistr('ONe') in d) + self.assertEqual(d.get(cistr('thrEE')), 3) + + def test_classic_comparisons(self): + # Testing classic comparisons... + class classic: + pass + + for base in (classic, int, object): + class C(base): + def __init__(self, value): + self.value = int(value) + def __eq__(self, other): + if isinstance(other, C): + return self.value == other.value + if isinstance(other, int) or isinstance(other, int): + return self.value == other + return NotImplemented + def __ne__(self, other): + if isinstance(other, C): + return self.value != other.value + if isinstance(other, int) or isinstance(other, int): + return self.value != other + return NotImplemented + def __lt__(self, other): + if isinstance(other, C): + return self.value < other.value + if isinstance(other, int) or isinstance(other, int): + return self.value < other + return NotImplemented + def __le__(self, other): + if isinstance(other, C): + return self.value <= other.value + if isinstance(other, int) or isinstance(other, int): + return self.value <= other + return NotImplemented + def __gt__(self, other): + if isinstance(other, C): + return self.value > other.value + if isinstance(other, int) or isinstance(other, int): + return self.value > other + return NotImplemented + def __ge__(self, other): + if isinstance(other, C): + return self.value >= other.value + if isinstance(other, int) or isinstance(other, int): + return self.value >= other + return NotImplemented + + c1 = C(1) + c2 = C(2) + c3 = C(3) + self.assertEqual(c1, 1) + c = {1: c1, 2: c2, 3: c3} + for x in 1, 2, 3: + for y in 1, 2, 3: + ## self.assert_(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y)) + for op in "<", "<=", "==", "!=", ">", ">=": + self.assert_(eval("c[x] %s c[y]" % op) == eval("x %s y" % op), + "x=%d, y=%d" % (x, y)) + ## self.assert_(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y)) + ## self.assert_(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y)) + + def test_rich_comparisons(self): + # Testing rich comparisons... + class Z(complex): + pass + z = Z(1) + self.assertEqual(z, 1+0j) + self.assertEqual(1+0j, z) + class ZZ(complex): + def __eq__(self, other): + try: + return abs(self - other) <= 1e-6 + except: + return NotImplemented + zz = ZZ(1.0000003) + self.assertEqual(zz, 1+0j) + self.assertEqual(1+0j, zz) + + class classic: + pass + for base in (classic, int, object, list): + class C(base): + def __init__(self, value): + self.value = int(value) + def __cmp__(self_, other): + self.fail("shouldn't call __cmp__") + def __eq__(self, other): + if isinstance(other, C): + return self.value == other.value + if isinstance(other, int) or isinstance(other, int): + return self.value == other + return NotImplemented + def __ne__(self, other): + if isinstance(other, C): + return self.value != other.value + if isinstance(other, int) or isinstance(other, int): + return self.value != other + return NotImplemented + def __lt__(self, other): + if isinstance(other, C): + return self.value < other.value + if isinstance(other, int) or isinstance(other, int): + return self.value < other + return NotImplemented + def __le__(self, other): + if isinstance(other, C): + return self.value <= other.value + if isinstance(other, int) or isinstance(other, int): + return self.value <= other + return NotImplemented + def __gt__(self, other): + if isinstance(other, C): + return self.value > other.value + if isinstance(other, int) or isinstance(other, int): + return self.value > other + return NotImplemented + def __ge__(self, other): + if isinstance(other, C): + return self.value >= other.value + if isinstance(other, int) or isinstance(other, int): + return self.value >= other + return NotImplemented + c1 = C(1) + c2 = C(2) + c3 = C(3) + self.assertEqual(c1, 1) + c = {1: c1, 2: c2, 3: c3} + for x in 1, 2, 3: + for y in 1, 2, 3: + for op in "<", "<=", "==", "!=", ">", ">=": + self.assert_(eval("c[x] %s c[y]" % op) == eval("x %s y" % op), + "x=%d, y=%d" % (x, y)) + self.assert_(eval("c[x] %s y" % op) == eval("x %s y" % op), + "x=%d, y=%d" % (x, y)) + self.assert_(eval("x %s c[y]" % op) == eval("x %s y" % op), + "x=%d, y=%d" % (x, y)) + + def test_descrdoc(self): + # Testing descriptor doc strings... + from _fileio import _FileIO + def check(descr, what): + self.assertEqual(descr.__doc__, what) + check(_FileIO.closed, "True if the file is closed") # getset descriptor + check(complex.real, "the real part of a complex number") # member descriptor + + def test_doc_descriptor(self): + # Testing __doc__ descriptor... + # SF bug 542984 + class DocDescr(object): + def __get__(self, object, otype): + if object: + object = object.__class__.__name__ + ' instance' + if otype: + otype = otype.__name__ + return 'object=%s; type=%s' % (object, otype) + class OldClass: + __doc__ = DocDescr() + class NewClass(object): + __doc__ = DocDescr() + self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass') + self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass') + self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass') + self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass') + + def test_set_class(self): + # Testing __class__ assignment... + class C(object): pass + class D(object): pass + class E(object): pass + class F(D, E): pass + for cls in C, D, E, F: + for cls2 in C, D, E, F: + x = cls() + x.__class__ = cls2 + self.assert_(x.__class__ is cls2) + x.__class__ = cls + self.assert_(x.__class__ is cls) + def cant(x, C): + try: + x.__class__ = C + except TypeError: + pass + else: + self.fail("shouldn't allow %r.__class__ = %r" % (x, C)) + try: + delattr(x, "__class__") + except TypeError: + pass + else: + self.fail("shouldn't allow del %r.__class__" % x) + cant(C(), list) + cant(list(), C) + cant(C(), 1) + cant(C(), object) + cant(object(), list) + cant(list(), object) + class Int(int): __slots__ = [] + cant(2, Int) + cant(Int(), int) + cant(True, int) + cant(2, bool) + o = object() + cant(o, type(1)) + cant(o, type(None)) + del o + class G(object): + __slots__ = ["a", "b"] + class H(object): + __slots__ = ["b", "a"] + class I(object): + __slots__ = ["a", "b"] + class J(object): + __slots__ = ["c", "b"] + class K(object): + __slots__ = ["a", "b", "d"] + class L(H): + __slots__ = ["e"] + class M(I): + __slots__ = ["e"] + class N(J): + __slots__ = ["__weakref__"] + class P(J): + __slots__ = ["__dict__"] + class Q(J): + pass + class R(J): + __slots__ = ["__dict__", "__weakref__"] + + for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)): + x = cls() + x.a = 1 + x.__class__ = cls2 + self.assert_(x.__class__ is cls2, + "assigning %r as __class__ for %r silently failed" % (cls2, x)) + self.assertEqual(x.a, 1) + x.__class__ = cls + self.assert_(x.__class__ is cls, + "assigning %r as __class__ for %r silently failed" % (cls, x)) + self.assertEqual(x.a, 1) + for cls in G, J, K, L, M, N, P, R, list, Int: + for cls2 in G, J, K, L, M, N, P, R, list, Int: + if cls is cls2: + continue + cant(cls(), cls2) + + def test_set_dict(self): + # Testing __dict__ assignment... + class C(object): pass + a = C() + a.__dict__ = {'b': 1} + self.assertEqual(a.b, 1) + def cant(x, dict): + try: + x.__dict__ = dict + except (AttributeError, TypeError): + pass + else: + self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict)) + cant(a, None) + cant(a, []) + cant(a, 1) + del a.__dict__ # Deleting __dict__ is allowed + + class Base(object): + pass + def verify_dict_readonly(x): + """ + x has to be an instance of a class inheriting from Base. + """ + cant(x, {}) + try: + del x.__dict__ + except (AttributeError, TypeError): + pass + else: + self.fail("shouldn't allow del %r.__dict__" % x) + dict_descr = Base.__dict__["__dict__"] + try: + dict_descr.__set__(x, {}) + except (AttributeError, TypeError): + pass + else: + self.fail("dict_descr allowed access to %r's dict" % x) + + # Classes don't allow __dict__ assignment and have readonly dicts + class Meta1(type, Base): + pass + class Meta2(Base, type): + pass + class D(object, metaclass=Meta1): + pass + class E(object, metaclass=Meta2): + pass + for cls in C, D, E: + verify_dict_readonly(cls) + class_dict = cls.__dict__ + try: + class_dict["spam"] = "eggs" + except TypeError: + pass + else: + self.fail("%r's __dict__ can be modified" % cls) + + # Modules also disallow __dict__ assignment + class Module1(types.ModuleType, Base): + pass + class Module2(Base, types.ModuleType): + pass + for ModuleType in Module1, Module2: + mod = ModuleType("spam") + verify_dict_readonly(mod) + mod.__dict__["spam"] = "eggs" + + # Exception's __dict__ can be replaced, but not deleted + class Exception1(Exception, Base): + pass + class Exception2(Base, Exception): + pass + for ExceptionType in Exception, Exception1, Exception2: + e = ExceptionType() + e.__dict__ = {"a": 1} + self.assertEqual(e.a, 1) + try: + del e.__dict__ + except (TypeError, AttributeError): + pass + else: + self.fail("%r's __dict__ can be deleted" % e) + + def test_pickles(self): + # Testing pickling and copying new-style classes and objects... + import pickle + + def sorteditems(d): + L = list(d.items()) + L.sort() + return L + + global C + class C(object): + def __init__(self, a, b): + super(C, self).__init__() + self.a = a + self.b = b + def __repr__(self): + return "C(%r, %r)" % (self.a, self.b) + + global C1 + class C1(list): + def __new__(cls, a, b): + return super(C1, cls).__new__(cls) + def __getnewargs__(self): + return (self.a, self.b) + def __init__(self, a, b): + self.a = a + self.b = b + def __repr__(self): + return "C1(%r, %r)<%r>" % (self.a, self.b, list(self)) + + global C2 + class C2(int): + def __new__(cls, a, b, val=0): + return super(C2, cls).__new__(cls, val) + def __getnewargs__(self): + return (self.a, self.b, int(self)) + def __init__(self, a, b, val=0): + self.a = a + self.b = b + def __repr__(self): + return "C2(%r, %r)<%r>" % (self.a, self.b, int(self)) + + global C3 + class C3(object): + def __init__(self, foo): + self.foo = foo + def __getstate__(self): + return self.foo + def __setstate__(self, foo): + self.foo = foo + + global C4classic, C4 + class C4classic: # classic + pass + class C4(C4classic, object): # mixed inheritance + pass + + for bin in 0, 1: + for cls in C, C1, C2: + s = pickle.dumps(cls, bin) + cls2 = pickle.loads(s) + self.assert_(cls2 is cls) + + a = C1(1, 2); a.append(42); a.append(24) + b = C2("hello", "world", 42) + s = pickle.dumps((a, b), bin) + x, y = pickle.loads(s) + self.assertEqual(x.__class__, a.__class__) + self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__)) + self.assertEqual(y.__class__, b.__class__) + self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__)) + self.assertEqual(repr(x), repr(a)) + self.assertEqual(repr(y), repr(b)) + # Test for __getstate__ and __setstate__ on new style class + u = C3(42) + s = pickle.dumps(u, bin) + v = pickle.loads(s) + self.assertEqual(u.__class__, v.__class__) + self.assertEqual(u.foo, v.foo) + # Test for picklability of hybrid class + u = C4() + u.foo = 42 + s = pickle.dumps(u, bin) + v = pickle.loads(s) + self.assertEqual(u.__class__, v.__class__) + self.assertEqual(u.foo, v.foo) + + # Testing copy.deepcopy() + import copy + for cls in C, C1, C2: + cls2 = copy.deepcopy(cls) + self.assert_(cls2 is cls) + + a = C1(1, 2); a.append(42); a.append(24) + b = C2("hello", "world", 42) + x, y = copy.deepcopy((a, b)) + self.assertEqual(x.__class__, a.__class__) + self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__)) + self.assertEqual(y.__class__, b.__class__) + self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__)) + self.assertEqual(repr(x), repr(a)) + self.assertEqual(repr(y), repr(b)) + + def test_pickle_slots(self): + # Testing pickling of classes with __slots__ ... + import pickle + # Pickling of classes with __slots__ but without __getstate__ should fail + # (if using protocol 0 or 1) + global B, C, D, E + class B(object): + pass + for base in [object, B]: + class C(base): + __slots__ = ['a'] + class D(C): + pass + try: + pickle.dumps(C(), 0) + except TypeError: + pass + else: + self.fail("should fail: pickle C instance - %s" % base) + try: + pickle.dumps(C(), 0) + except TypeError: + pass + else: + self.fail("should fail: pickle D instance - %s" % base) + # Give C a nice generic __getstate__ and __setstate__ + class C(base): + __slots__ = ['a'] + def __getstate__(self): + try: + d = self.__dict__.copy() + except AttributeError: + d = {} + for cls in self.__class__.__mro__: + for sn in cls.__dict__.get('__slots__', ()): + try: + d[sn] = getattr(self, sn) + except AttributeError: + pass + return d + def __setstate__(self, d): + for k, v in list(d.items()): + setattr(self, k, v) + class D(C): + pass + # Now it should work + x = C() + y = pickle.loads(pickle.dumps(x)) + self.assertEqual(hasattr(y, 'a'), 0) + x.a = 42 + y = pickle.loads(pickle.dumps(x)) + self.assertEqual(y.a, 42) + x = D() + x.a = 42 + x.b = 100 + y = pickle.loads(pickle.dumps(x)) + self.assertEqual(y.a + y.b, 142) + # A subclass that adds a slot should also work + class E(C): + __slots__ = ['b'] + x = E() + x.a = 42 + x.b = "foo" + y = pickle.loads(pickle.dumps(x)) + self.assertEqual(y.a, x.a) + self.assertEqual(y.b, x.b) + + def test_binary_operator_override(self): + # Testing overrides of binary operations... + class I(int): + def __repr__(self): + return "I(%r)" % int(self) + def __add__(self, other): + return I(int(self) + int(other)) + __radd__ = __add__ + def __pow__(self, other, mod=None): + if mod is None: + return I(pow(int(self), int(other))) + else: + return I(pow(int(self), int(other), int(mod))) + def __rpow__(self, other, mod=None): + if mod is None: + return I(pow(int(other), int(self), mod)) + else: + return I(pow(int(other), int(self), int(mod))) + + self.assertEqual(repr(I(1) + I(2)), "I(3)") + self.assertEqual(repr(I(1) + 2), "I(3)") + self.assertEqual(repr(1 + I(2)), "I(3)") + self.assertEqual(repr(I(2) ** I(3)), "I(8)") + self.assertEqual(repr(2 ** I(3)), "I(8)") + self.assertEqual(repr(I(2) ** 3), "I(8)") + self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)") + class S(str): + def __eq__(self, other): + return self.lower() == other.lower() + + def test_subclass_propagation(self): + # Testing propagation of slot functions to subclasses... + class A(object): + pass + class B(A): + pass + class C(A): + pass + class D(B, C): + pass + d = D() + orig_hash = hash(d) # related to id(d) in platform-dependent ways + A.__hash__ = lambda self: 42 + self.assertEqual(hash(d), 42) + C.__hash__ = lambda self: 314 + self.assertEqual(hash(d), 314) + B.__hash__ = lambda self: 144 + self.assertEqual(hash(d), 144) + D.__hash__ = lambda self: 100 + self.assertEqual(hash(d), 100) + del D.__hash__ + self.assertEqual(hash(d), 144) + del B.__hash__ + self.assertEqual(hash(d), 314) + del C.__hash__ + self.assertEqual(hash(d), 42) + del A.__hash__ + self.assertEqual(hash(d), orig_hash) + d.foo = 42 + d.bar = 42 + self.assertEqual(d.foo, 42) + self.assertEqual(d.bar, 42) + def __getattribute__(self, name): + if name == "foo": + return 24 + return object.__getattribute__(self, name) + A.__getattribute__ = __getattribute__ + self.assertEqual(d.foo, 24) + self.assertEqual(d.bar, 42) + def __getattr__(self, name): + if name in ("spam", "foo", "bar"): + return "hello" + raise AttributeError(name) + B.__getattr__ = __getattr__ + self.assertEqual(d.spam, "hello") + self.assertEqual(d.foo, 24) + self.assertEqual(d.bar, 42) + del A.__getattribute__ + self.assertEqual(d.foo, 42) + del d.foo + self.assertEqual(d.foo, "hello") + self.assertEqual(d.bar, 42) + del B.__getattr__ + try: + d.foo + except AttributeError: + pass + else: + self.fail("d.foo should be undefined now") + + # Test a nasty bug in recurse_down_subclasses() + import gc + class A(object): + pass + class B(A): + pass + del B + gc.collect() + A.__setitem__ = lambda *a: None # crash + + def test_buffer_inheritance(self): + # Testing that buffer interface is inherited ... + + import binascii + # SF bug [#470040] ParseTuple t# vs subclasses. + + class MyStr(str): + pass + base = 'abc' + m = MyStr(base) + # b2a_hex uses the buffer interface to get its argument's value, via + # PyArg_ParseTuple 't#' code. + self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base)) + + # It's not clear that unicode will continue to support the character + # buffer interface, and this test will fail if that's taken away. + class MyUni(str): + pass + base = 'abc' + m = MyUni(base) + self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base)) + + class MyInt(int): + pass + m = MyInt(42) + try: + binascii.b2a_hex(m) + self.fail('subclass of int should not have a buffer interface') + except TypeError: + pass + + def test_str_of_str_subclass(self): + # Testing __str__ defined in subclass of str ... + import binascii + import io + + class octetstring(str): + def __str__(self): + return binascii.b2a_hex(self).decode("ascii") + def __repr__(self): + return self + " repr" + + o = octetstring('A') + self.assertEqual(type(o), octetstring) + self.assertEqual(type(str(o)), str) + self.assertEqual(type(repr(o)), str) + self.assertEqual(ord(o), 0x41) + self.assertEqual(str(o), '41') + self.assertEqual(repr(o), 'A repr') + self.assertEqual(o.__str__(), '41') + self.assertEqual(o.__repr__(), 'A repr') + + capture = io.StringIO() + # Calling str() or not exercises different internal paths. + print(o, file=capture) + print(str(o), file=capture) + self.assertEqual(capture.getvalue(), '41\n41\n') + capture.close() + + def test_keyword_arguments(self): + # Testing keyword arguments to __init__, __call__... + def f(a): return a + self.assertEqual(f.__call__(a=42), 42) + a = [] + list.__init__(a, sequence=[0, 1, 2]) + self.assertEqual(a, [0, 1, 2]) + + def test_recursive_call(self): + # Testing recursive __call__() by setting to instance of class... + class A(object): + pass + + A.__call__ = A() + try: + A()() + except RuntimeError: + pass else: - raise TestFailed("no TypeError from dict(%r)" % badarg) + self.fail("Recursion limit should have been reached for __call__()") - try: - dict({}, {}) - except TypeError: - pass - else: - raise TestFailed("no TypeError from dict({}, {})") - - class Mapping: - # Lacks a .keys() method; will be added later. - dict = {1:2, 3:4, 'a':1j} - - try: - dict(Mapping()) - except TypeError: - pass - else: - raise TestFailed("no TypeError from dict(incomplete mapping)") - - Mapping.keys = lambda self: self.dict.keys() - Mapping.__getitem__ = lambda self, i: self.dict[i] - d = dict(Mapping()) - vereq(d, Mapping.dict) - - # Init from sequence of iterable objects, each producing a 2-sequence. - class AddressBookEntry: - def __init__(self, first, last): - self.first = first - self.last = last - def __iter__(self): - return iter([self.first, self.last]) - - d = dict([AddressBookEntry('Tim', 'Warsaw'), - AddressBookEntry('Barry', 'Peters'), - AddressBookEntry('Tim', 'Peters'), - AddressBookEntry('Barry', 'Warsaw')]) - vereq(d, {'Barry': 'Warsaw', 'Tim': 'Peters'}) - - d = dict(zip(range(4), range(1, 5))) - vereq(d, dict([(i, i+1) for i in range(4)])) - - # Bad sequence lengths. - for bad in [('tooshort',)], [('too', 'long', 'by 1')]: - try: - dict(bad) - except ValueError: - pass - else: - raise TestFailed("no ValueError from dict(%r)" % bad) - -def test_dir(): - if verbose: - print("Testing dir() ...") - junk = 12 - vereq(dir(), ['junk']) - del junk - - # Just make sure these don't blow up! - for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, test_dir: - dir(arg) - - # Test dir on custom classes. Since these have object as a - # base class, a lot of stuff gets sucked in. - def interesting(strings): - return [s for s in strings if not s.startswith('_')] - - class C(object): - Cdata = 1 - def Cmethod(self): pass - - cstuff = ['Cdata', 'Cmethod'] - vereq(interesting(dir(C)), cstuff) - - c = C() - vereq(interesting(dir(c)), cstuff) - #verify('__self__' in dir(C.Cmethod)) - - c.cdata = 2 - c.cmethod = lambda self: 0 - vereq(interesting(dir(c)), cstuff + ['cdata', 'cmethod']) - #verify('__self__' in dir(c.Cmethod)) - - class A(C): - Adata = 1 - def Amethod(self): pass - - astuff = ['Adata', 'Amethod'] + cstuff - vereq(interesting(dir(A)), astuff) - #verify('__self__' in dir(A.Amethod)) - a = A() - vereq(interesting(dir(a)), astuff) - a.adata = 42 - a.amethod = lambda self: 3 - vereq(interesting(dir(a)), astuff + ['adata', 'amethod']) - #verify('__self__' in dir(a.Amethod)) - - # Try a module subclass. - import sys - class M(type(sys)): - pass - minstance = M("m") - minstance.b = 2 - minstance.a = 1 - names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]] - vereq(names, ['a', 'b']) - - class M2(M): - def getdict(self): - return "Not a dict!" - __dict__ = property(getdict) - - m2instance = M2("m2") - m2instance.b = 2 - m2instance.a = 1 - vereq(m2instance.__dict__, "Not a dict!") - try: - dir(m2instance) - except TypeError: - pass - - # Two essentially featureless objects, just inheriting stuff from - # object. - vereq(dir(None), dir(Ellipsis)) - - # Nasty test case for proxied objects - class Wrapper(object): - def __init__(self, obj): - self.__obj = obj - def __repr__(self): - return "Wrapper(%s)" % repr(self.__obj) - def __getitem__(self, key): - return Wrapper(self.__obj[key]) - def __len__(self): - return len(self.__obj) - def __getattr__(self, name): - return Wrapper(getattr(self.__obj, name)) + def test_delete_hook(self): + # Testing __del__ hook... + log = [] + class C(object): + def __del__(self): + log.append(1) + c = C() + self.assertEqual(log, []) + del c + self.assertEqual(log, [1]) + + class D(object): pass + d = D() + try: del d[0] + except TypeError: pass + else: self.fail("invalid del() didn't raise TypeError") - class C(object): - def __getclass(self): - return Wrapper(type(self)) - __class__ = property(__getclass) - - dir(C()) # This used to segfault - -binops = { - 'add': '+', - 'sub': '-', - 'mul': '*', - 'div': '/', - 'mod': '%', - 'divmod': 'divmod', - 'pow': '**', - 'lshift': '<<', - 'rshift': '>>', - 'and': '&', - 'xor': '^', - 'or': '|', - 'cmp': 'cmp', - 'lt': '<', - 'le': '<=', - 'eq': '==', - 'ne': '!=', - 'gt': '>', - 'ge': '>=', - } - -for name, expr in binops.items(): - if expr.islower(): - expr = expr + "(a, b)" - else: - expr = 'a %s b' % expr - binops[name] = expr - -unops = { - 'pos': '+', - 'neg': '-', - 'abs': 'abs', - 'invert': '~', - 'int': 'int', - 'float': 'float', - 'oct': 'oct', - 'hex': 'hex', - } - -for name, expr in unops.items(): - if expr.islower(): - expr = expr + "(a)" - else: - expr = '%s a' % expr - unops[name] = expr - -def numops(a, b, skip=[]): - dict = {'a': a, 'b': b} - for name, expr in binops.items(): - if name not in skip: - name = "__%s__" % name - if hasattr(a, name): - res = eval(expr, dict) - testbinop(a, b, res, expr, name) - for name, expr in unops.items(): - if name not in skip: - name = "__%s__" % name - if hasattr(a, name): - res = eval(expr, dict) - testunop(a, res, expr, name) - -def ints(): - if verbose: print("Testing int operations...") - numops(100, 3) - # The following crashes in Python 2.2 - vereq((1).__bool__(), True) - vereq((0).__bool__(), False) - # This returns 'NotImplemented' in Python 2.2 - class C(int): - def __add__(self, other): - return NotImplemented - vereq(C(5), 5) - try: - C() + "" - except TypeError: - pass - else: - raise TestFailed("NotImplemented should have caused TypeError") - -def longs(): - if verbose: print("Testing long operations...") - numops(100, 3) - -def floats(): - if verbose: print("Testing float operations...") - numops(100.0, 3.0) - -def complexes(): - if verbose: print("Testing complex operations...") - numops(100.0j, 3.0j, - skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float', - 'divmod', 'mod']) - class Number(complex): - __slots__ = ['prec'] - def __new__(cls, *args, **kwds): - result = complex.__new__(cls, *args) - result.prec = kwds.get('prec', 12) - return result - def __repr__(self): - prec = self.prec - if self.imag == 0.0: - return "%.*g" % (prec, self.real) - if self.real == 0.0: - return "%.*gj" % (prec, self.imag) - return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag) - __str__ = __repr__ - - a = Number(3.14, prec=6) - vereq(repr(a), "3.14") - vereq(a.prec, 6) - - a = Number(a, prec=2) - vereq(repr(a), "3.1") - vereq(a.prec, 2) - - a = Number(234.5) - vereq(repr(a), "234.5") - vereq(a.prec, 12) - -def spamlists(): - if verbose: print("Testing spamlist operations...") - import copy, xxsubtype as spam - def spamlist(l, memo=None): - import xxsubtype as spam - return spam.spamlist(l) - # This is an ugly hack: - copy._deepcopy_dispatch[spam.spamlist] = spamlist - - testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__") - testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__") - testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__") - testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__") - testsliceop(spamlist([1,2,3]), 0, 2, spamlist([1,2]), - "a[b:c]", "__getitem__") - testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]), - "a+=b", "__iadd__") - testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__") - testunop(spamlist([1,2,3]), 3, "len(a)", "__len__") - testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__") - testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__") - testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__") - testsetsliceop(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]), - spamlist([1,5,6,4]), "a[b:c]=d", "__setitem__") - # Test subclassing - class C(spam.spamlist): - def foo(self): return 1 - a = C() - vereq(a, []) - vereq(a.foo(), 1) - a.append(100) - vereq(a, [100]) - vereq(a.getstate(), 0) - a.setstate(42) - vereq(a.getstate(), 42) - -def spamdicts(): - if verbose: print("Testing spamdict operations...") - import copy, xxsubtype as spam - def spamdict(d, memo=None): - import xxsubtype as spam - sd = spam.spamdict() - for k, v in d.items(): sd[k] = v - return sd - # This is an ugly hack: - copy._deepcopy_dispatch[spam.spamdict] = spamdict - - ##testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__") - testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__") - testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__") - testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__") - d = spamdict({1:2,3:4}) - l1 = [] - for i in d.keys(): l1.append(i) - l = [] - for i in iter(d): l.append(i) - vereq(l, l1) - l = [] - for i in d.__iter__(): l.append(i) - vereq(l, l1) - l = [] - for i in type(spamdict({})).__iter__(d): l.append(i) - vereq(l, l1) - straightd = {1:2, 3:4} - spamd = spamdict(straightd) - testunop(spamd, 2, "len(a)", "__len__") - testunop(spamd, repr(straightd), "repr(a)", "__repr__") - testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}), - "a[b]=c", "__setitem__") - # Test subclassing - class C(spam.spamdict): - def foo(self): return 1 - a = C() - vereq(list(a.items()), []) - vereq(a.foo(), 1) - a['foo'] = 'bar' - vereq(list(a.items()), [('foo', 'bar')]) - vereq(a.getstate(), 0) - a.setstate(100) - vereq(a.getstate(), 100) - -def pydicts(): - if verbose: print("Testing Python subclass of dict...") - verify(issubclass(dict, dict)) - verify(isinstance({}, dict)) - d = dict() - vereq(d, {}) - verify(d.__class__ is dict) - verify(isinstance(d, dict)) - class C(dict): - state = -1 - def __init__(self, *a, **kw): - if a: - vereq(len(a), 1) - self.state = a[0] - if kw: - for k, v in kw.items(): self[v] = k - def __getitem__(self, key): - return self.get(key, 0) - def __setitem__(self, key, value): - verify(isinstance(key, type(0))) - dict.__setitem__(self, key, value) - def setstate(self, state): - self.state = state - def getstate(self): - return self.state - verify(issubclass(C, dict)) - a1 = C(12) - vereq(a1.state, 12) - a2 = C(foo=1, bar=2) - vereq(a2[1] == 'foo' and a2[2], 'bar') - a = C() - vereq(a.state, -1) - vereq(a.getstate(), -1) - a.setstate(0) - vereq(a.state, 0) - vereq(a.getstate(), 0) - a.setstate(10) - vereq(a.state, 10) - vereq(a.getstate(), 10) - vereq(a[42], 0) - a[42] = 24 - vereq(a[42], 24) - if verbose: print("pydict stress test ...") - N = 50 - for i in range(N): - a[i] = C() - for j in range(N): - a[i][j] = i*j - for i in range(N): - for j in range(N): - vereq(a[i][j], i*j) - -def pylists(): - if verbose: print("Testing Python subclass of list...") - class C(list): - def __getitem__(self, i): - if isinstance(i, slice): - return (i.start, i.stop) - return list.__getitem__(self, i) + 100 - a = C() - a.extend([0,1,2]) - vereq(a[0], 100) - vereq(a[1], 101) - vereq(a[2], 102) - vereq(a[100:200], (100,200)) - -def metaclass(): - if verbose: print("Testing metaclass...") - class C(metaclass=type): - def __init__(self): - self.__state = 0 - def getstate(self): - return self.__state - def setstate(self, state): - self.__state = state - a = C() - vereq(a.getstate(), 0) - a.setstate(10) - vereq(a.getstate(), 10) - class _metaclass(type): - def myself(cls): return cls - class D(metaclass=_metaclass): - pass - vereq(D.myself(), D) - d = D() - verify(d.__class__ is D) - class M1(type): - def __new__(cls, name, bases, dict): - dict['__spam__'] = 1 - return type.__new__(cls, name, bases, dict) - class C(metaclass=M1): - pass - vereq(C.__spam__, 1) - c = C() - vereq(c.__spam__, 1) - - class _instance(object): - pass - class M2(object): - @staticmethod - def __new__(cls, name, bases, dict): - self = object.__new__(cls) - self.name = name - self.bases = bases - self.dict = dict - return self - def __call__(self): - it = _instance() - # Early binding of methods - for key in self.dict: - if key.startswith("__"): - continue - setattr(it, key, self.dict[key].__get__(it, self)) - return it - class C(metaclass=M2): - def spam(self): - return 42 - vereq(C.name, 'C') - vereq(C.bases, ()) - verify('spam' in C.dict) - c = C() - vereq(c.spam(), 42) - - # More metaclass examples - - class autosuper(type): - # Automatically add __super to the class - # This trick only works for dynamic classes - def __new__(metaclass, name, bases, dict): - cls = super(autosuper, metaclass).__new__(metaclass, - name, bases, dict) - # Name mangling for __super removes leading underscores - while name[:1] == "_": - name = name[1:] - if name: - name = "_%s__super" % name - else: - name = "__super" - setattr(cls, name, super(cls)) - return cls - class A(metaclass=autosuper): - def meth(self): - return "A" - class B(A): - def meth(self): - return "B" + self.__super.meth() - class C(A): - def meth(self): - return "C" + self.__super.meth() - class D(C, B): - def meth(self): - return "D" + self.__super.meth() - vereq(D().meth(), "DCBA") - class E(B, C): - def meth(self): - return "E" + self.__super.meth() - vereq(E().meth(), "EBCA") - - class autoproperty(type): - # Automatically create property attributes when methods - # named _get_x and/or _set_x are found - def __new__(metaclass, name, bases, dict): - hits = {} - for key, val in dict.items(): - if key.startswith("_get_"): - key = key[5:] - get, set = hits.get(key, (None, None)) - get = val - hits[key] = get, set - elif key.startswith("_set_"): - key = key[5:] - get, set = hits.get(key, (None, None)) - set = val - hits[key] = get, set - for key, (get, set) in hits.items(): - dict[key] = property(get, set) - return super(autoproperty, metaclass).__new__(metaclass, - name, bases, dict) - class A(metaclass=autoproperty): - def _get_x(self): - return -self.__x - def _set_x(self, x): - self.__x = -x - a = A() - verify(not hasattr(a, "x")) - a.x = 12 - vereq(a.x, 12) - vereq(a._A__x, -12) - - class multimetaclass(autoproperty, autosuper): - # Merge of multiple cooperating metaclasses - pass - class A(metaclass=multimetaclass): - def _get_x(self): - return "A" - class B(A): - def _get_x(self): - return "B" + self.__super._get_x() - class C(A): - def _get_x(self): - return "C" + self.__super._get_x() - class D(C, B): - def _get_x(self): - return "D" + self.__super._get_x() - vereq(D().x, "DCBA") - - # Make sure type(x) doesn't call x.__class__.__init__ - class T(type): - counter = 0 - def __init__(self, *args): - T.counter += 1 - class C(metaclass=T): - pass - vereq(T.counter, 1) - a = C() - vereq(type(a), C) - vereq(T.counter, 1) - - class C(object): pass - c = C() - try: c() - except TypeError: pass - else: raise TestFailed("calling object w/o call method should raise TypeError") - - # Testing code to find most derived baseclass - class A(type): - def __new__(*args, **kwargs): - return type.__new__(*args, **kwargs) - - class B(object): - pass - - class C(object, metaclass=A): - pass - - # The most derived metaclass of D is A rather than type. - class D(B, C): - pass - - -def pymods(): - if verbose: print("Testing Python subclass of module...") - log = [] - import sys - MT = type(sys) - class MM(MT): - def __init__(self, name): - MT.__init__(self, name) - def __getattribute__(self, name): - log.append(("getattr", name)) - return MT.__getattribute__(self, name) - def __setattr__(self, name, value): - log.append(("setattr", name, value)) - MT.__setattr__(self, name, value) - def __delattr__(self, name): - log.append(("delattr", name)) - MT.__delattr__(self, name) - a = MM("a") - a.foo = 12 - x = a.foo - del a.foo - vereq(log, [("setattr", "foo", 12), - ("getattr", "foo"), - ("delattr", "foo")]) - - # http://python.org/sf/1174712 - try: - class Module(types.ModuleType, str): - pass - except TypeError: - pass - else: - raise TestFailed("inheriting from ModuleType and str at the " - "same time should fail") - -def multi(): - if verbose: print("Testing multiple inheritance...") - class C(object): - def __init__(self): - self.__state = 0 - def getstate(self): - return self.__state - def setstate(self, state): - self.__state = state - a = C() - vereq(a.getstate(), 0) - a.setstate(10) - vereq(a.getstate(), 10) - class D(dict, C): - def __init__(self): - type({}).__init__(self) - C.__init__(self) - d = D() - vereq(list(d.keys()), []) - d["hello"] = "world" - vereq(list(d.items()), [("hello", "world")]) - vereq(d["hello"], "world") - vereq(d.getstate(), 0) - d.setstate(10) - vereq(d.getstate(), 10) - vereq(D.__mro__, (D, dict, C, object)) - - # SF bug #442833 - class Node(object): - def __int__(self): - return int(self.foo()) - def foo(self): - return "23" - class Frag(Node, list): - def foo(self): - return "42" - vereq(Node().__int__(), 23) - vereq(int(Node()), 23) - vereq(Frag().__int__(), 42) - vereq(int(Frag()), 42) - -def diamond(): - if verbose: print("Testing multiple inheritance special cases...") - class A(object): - def spam(self): return "A" - vereq(A().spam(), "A") - class B(A): - def boo(self): return "B" - def spam(self): return "B" - vereq(B().spam(), "B") - vereq(B().boo(), "B") - class C(A): - def boo(self): return "C" - vereq(C().spam(), "A") - vereq(C().boo(), "C") - class D(B, C): pass - vereq(D().spam(), "B") - vereq(D().boo(), "B") - vereq(D.__mro__, (D, B, C, A, object)) - class E(C, B): pass - vereq(E().spam(), "B") - vereq(E().boo(), "C") - vereq(E.__mro__, (E, C, B, A, object)) - # MRO order disagreement - try: - class F(D, E): pass - except TypeError: - pass - else: - raise TestFailed("expected MRO order disagreement (F)") - try: - class G(E, D): pass - except TypeError: - pass - else: - raise TestFailed("expected MRO order disagreement (G)") - - -# see thread python-dev/2002-October/029035.html -def ex5(): - if verbose: print("Testing ex5 from C3 switch discussion...") - class A(object): pass - class B(object): pass - class C(object): pass - class X(A): pass - class Y(A): pass - class Z(X,B,Y,C): pass - vereq(Z.__mro__, (Z, X, B, Y, A, C, object)) - -# see "A Monotonic Superclass Linearization for Dylan", -# by Kim Barrett et al. (OOPSLA 1996) -def monotonicity(): - if verbose: print("Testing MRO monotonicity...") - class Boat(object): pass - class DayBoat(Boat): pass - class WheelBoat(Boat): pass - class EngineLess(DayBoat): pass - class SmallMultihull(DayBoat): pass - class PedalWheelBoat(EngineLess,WheelBoat): pass - class SmallCatamaran(SmallMultihull): pass - class Pedalo(PedalWheelBoat,SmallCatamaran): pass - - vereq(PedalWheelBoat.__mro__, - (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, - object)) - vereq(SmallCatamaran.__mro__, - (SmallCatamaran, SmallMultihull, DayBoat, Boat, object)) - - vereq(Pedalo.__mro__, - (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran, - SmallMultihull, DayBoat, WheelBoat, Boat, object)) - -# see "A Monotonic Superclass Linearization for Dylan", -# by Kim Barrett et al. (OOPSLA 1996) -def consistency_with_epg(): - if verbose: print("Testing consistentcy with EPG...") - class Pane(object): pass - class ScrollingMixin(object): pass - class EditingMixin(object): pass - class ScrollablePane(Pane,ScrollingMixin): pass - class EditablePane(Pane,EditingMixin): pass - class EditableScrollablePane(ScrollablePane,EditablePane): pass - - vereq(EditableScrollablePane.__mro__, - (EditableScrollablePane, ScrollablePane, EditablePane, - Pane, ScrollingMixin, EditingMixin, object)) + def test_hash_inheritance(self): + # Testing hash of mutable subclasses... -mro_err_msg = """Cannot create a consistent method resolution -order (MRO) for bases """ + class mydict(dict): + pass + d = mydict() + try: + hash(d) + except TypeError: + pass + else: + self.fail("hash() of dict subclass should fail") -def mro_disagreement(): - if verbose: print("Testing error messages for MRO disagreement...") - def raises(exc, expected, callable, *args): - try: - callable(*args) - except exc as msg: - if not str(msg).startswith(expected): - raise TestFailed("Message %r, expected %r" % (str(msg), - expected)) - else: - raise TestFailed("Expected %s" % exc) - class A(object): pass - class B(A): pass - class C(object): pass - # Test some very simple errors - raises(TypeError, "duplicate base class A", - type, "X", (A, A), {}) - raises(TypeError, mro_err_msg, - type, "X", (A, B), {}) - raises(TypeError, mro_err_msg, - type, "X", (A, C, B), {}) - # Test a slightly more complex error - class GridLayout(object): pass - class HorizontalGrid(GridLayout): pass - class VerticalGrid(GridLayout): pass - class HVGrid(HorizontalGrid, VerticalGrid): pass - class VHGrid(VerticalGrid, HorizontalGrid): pass - raises(TypeError, mro_err_msg, - type, "ConfusedGrid", (HVGrid, VHGrid), {}) - -def objects(): - if verbose: print("Testing object class...") - a = object() - vereq(a.__class__, object) - vereq(type(a), object) - b = object() - verify(a is not b) - verify(not hasattr(a, "foo")) - try: - a.foo = 12 - except (AttributeError, TypeError): - pass - else: - verify(0, "object() should not allow setting a foo attribute") - verify(not hasattr(object(), "__dict__")) - - class Cdict(object): - pass - x = Cdict() - vereq(x.__dict__, {}) - x.foo = 1 - vereq(x.foo, 1) - vereq(x.__dict__, {'foo': 1}) - -def slots(): - if verbose: print("Testing __slots__...") - class C0(object): - __slots__ = [] - x = C0() - verify(not hasattr(x, "__dict__")) - verify(not hasattr(x, "foo")) - - class C1(object): - __slots__ = ['a'] - x = C1() - verify(not hasattr(x, "__dict__")) - verify(not hasattr(x, "a")) - x.a = 1 - vereq(x.a, 1) - x.a = None - veris(x.a, None) - del x.a - verify(not hasattr(x, "a")) - - class C3(object): - __slots__ = ['a', 'b', 'c'] - x = C3() - verify(not hasattr(x, "__dict__")) - verify(not hasattr(x, 'a')) - verify(not hasattr(x, 'b')) - verify(not hasattr(x, 'c')) - x.a = 1 - x.b = 2 - x.c = 3 - vereq(x.a, 1) - vereq(x.b, 2) - vereq(x.c, 3) - - class C4(object): - """Validate name mangling""" - __slots__ = ['__a'] - def __init__(self, value): - self.__a = value - def get(self): - return self.__a - x = C4(5) - verify(not hasattr(x, '__dict__')) - verify(not hasattr(x, '__a')) - vereq(x.get(), 5) - try: - x.__a = 6 - except AttributeError: - pass - else: - raise TestFailed("Double underscored names not mangled") + class mylist(list): + pass + d = mylist() + try: + hash(d) + except TypeError: + pass + else: + self.fail("hash() of list subclass should fail") - # Make sure slot names are proper identifiers - try: - class C(object): - __slots__ = [None] - except TypeError: - pass - else: - raise TestFailed("[None] slots not caught") - try: - class C(object): - __slots__ = ["foo bar"] - except TypeError: - pass - else: - raise TestFailed("['foo bar'] slots not caught") - try: - class C(object): - __slots__ = ["foo\0bar"] - except TypeError: - pass - else: - raise TestFailed("['foo\\0bar'] slots not caught") - try: + def test_str_operations(self): + try: 'a' + 5 + except TypeError: pass + else: self.fail("'' + 5 doesn't raise TypeError") + + try: ''.split('') + except ValueError: pass + else: self.fail("''.split('') doesn't raise ValueError") + + try: ''.join([0]) + except TypeError: pass + else: self.fail("''.join([0]) doesn't raise TypeError") + + try: ''.rindex('5') + except ValueError: pass + else: self.fail("''.rindex('5') doesn't raise ValueError") + + try: '%(n)s' % None + except TypeError: pass + else: self.fail("'%(n)s' % None doesn't raise TypeError") + + try: '%(n' % {} + except ValueError: pass + else: self.fail("'%(n' % {} '' doesn't raise ValueError") + + try: '%*s' % ('abc') + except TypeError: pass + else: self.fail("'%*s' % ('abc') doesn't raise TypeError") + + try: '%*.*s' % ('abc', 5) + except TypeError: pass + else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError") + + try: '%s' % (1, 2) + except TypeError: pass + else: self.fail("'%s' % (1, 2) doesn't raise TypeError") + + try: '%' % None + except ValueError: pass + else: self.fail("'%' % None doesn't raise ValueError") + + self.assertEqual('534253'.isdigit(), 1) + self.assertEqual('534253x'.isdigit(), 0) + self.assertEqual('%c' % 5, '\x05') + self.assertEqual('%c' % '5', '5') + + def test_deepcopy_recursive(self): + # Testing deepcopy of recursive objects... + class Node: + pass + a = Node() + b = Node() + a.b = b + b.a = a + z = deepcopy(a) # This blew up before + + def test_unintialized_modules(self): + # Testing uninitialized module objects... + from types import ModuleType as M + m = M.__new__(M) + str(m) + self.assertEqual(hasattr(m, "__name__"), 0) + self.assertEqual(hasattr(m, "__file__"), 0) + self.assertEqual(hasattr(m, "foo"), 0) + self.assertEqual(m.__dict__, None) + m.foo = 1 + self.assertEqual(m.__dict__, {"foo": 1}) + + def test_funny_new(self): + # Testing __new__ returning something unexpected... class C(object): - __slots__ = ["1"] - except TypeError: - pass - else: - raise TestFailed("['1'] slots not caught") - try: + def __new__(cls, arg): + if isinstance(arg, str): return [1, 2, 3] + elif isinstance(arg, int): return object.__new__(D) + else: return object.__new__(cls) + class D(C): + def __init__(self, arg): + self.foo = arg + self.assertEqual(C("1"), [1, 2, 3]) + self.assertEqual(D("1"), [1, 2, 3]) + d = D(None) + self.assertEqual(d.foo, None) + d = C(1) + self.assertEqual(isinstance(d, D), True) + self.assertEqual(d.foo, 1) + d = D(1) + self.assertEqual(isinstance(d, D), True) + self.assertEqual(d.foo, 1) + + def test_imul_bug(self): + # Testing for __imul__ problems... + # SF bug 544647 class C(object): - __slots__ = [""] - except TypeError: - pass - else: - raise TestFailed("[''] slots not caught") - class C(object): - __slots__ = ["a", "a_b", "_a", "A0123456789Z"] - # XXX(nnorwitz): was there supposed to be something tested - # from the class above? - - # Test a single string is not expanded as a sequence. - class C(object): - __slots__ = "abc" - c = C() - c.abc = 5 - vereq(c.abc, 5) - - # Test unicode slot names - # Test a single unicode string is not expanded as a sequence. - class C(object): - __slots__ = "abc" - c = C() - c.abc = 5 - vereq(c.abc, 5) - - # _unicode_to_string used to modify slots in certain circumstances - slots = ("foo", "bar") - class C(object): - __slots__ = slots - x = C() - x.foo = 5 - vereq(x.foo, 5) - veris(type(slots[0]), str) - # this used to leak references - try: + def __imul__(self, other): + return (self, other) + x = C() + y = x + y *= 1.0 + self.assertEqual(y, (x, 1.0)) + y = x + y *= 2 + self.assertEqual(y, (x, 2)) + y = x + y *= 3 + self.assertEqual(y, (x, 3)) + y = x + y *= 1<<100 + self.assertEqual(y, (x, 1<<100)) + y = x + y *= None + self.assertEqual(y, (x, None)) + y = x + y *= "foo" + self.assertEqual(y, (x, "foo")) + + def test_copy_setstate(self): + # Testing that copy.*copy() correctly uses __setstate__... + import copy class C(object): - __slots__ = [chr(128)] - except (TypeError, UnicodeEncodeError): - pass - else: - raise TestFailed("[unichr(128)] slots not caught") - - # Test leaks - class Counted(object): - counter = 0 # counts the number of instances alive - def __init__(self): - Counted.counter += 1 - def __del__(self): - Counted.counter -= 1 - class C(object): - __slots__ = ['a', 'b', 'c'] - x = C() - x.a = Counted() - x.b = Counted() - x.c = Counted() - vereq(Counted.counter, 3) - del x - vereq(Counted.counter, 0) - class D(C): - pass - x = D() - x.a = Counted() - x.z = Counted() - vereq(Counted.counter, 2) - del x - vereq(Counted.counter, 0) - class E(D): - __slots__ = ['e'] - x = E() - x.a = Counted() - x.z = Counted() - x.e = Counted() - vereq(Counted.counter, 3) - del x - vereq(Counted.counter, 0) - - # Test cyclical leaks [SF bug 519621] - class F(object): - __slots__ = ['a', 'b'] - log = [] - s = F() - s.a = [Counted(), s] - vereq(Counted.counter, 1) - s = None - import gc - gc.collect() - vereq(Counted.counter, 0) - - # Test lookup leaks [SF bug 572567] - import sys,gc - class G(object): - def __cmp__(self, other): - return 0 - g = G() - orig_objects = len(gc.get_objects()) - for i in range(10): - g==g - new_objects = len(gc.get_objects()) - vereq(orig_objects, new_objects) - class H(object): - __slots__ = ['a', 'b'] - def __init__(self): - self.a = 1 - self.b = 2 - def __del__(self): - assert self.a == 1 - assert self.b == 2 - - save_stderr = sys.stderr - sys.stderr = sys.stdout - h = H() - try: - del h - finally: - sys.stderr = save_stderr - -def slotspecials(): - if verbose: print("Testing __dict__ and __weakref__ in __slots__...") - - class D(object): - __slots__ = ["__dict__"] - a = D() - verify(hasattr(a, "__dict__")) - verify(not hasattr(a, "__weakref__")) - a.foo = 42 - vereq(a.__dict__, {"foo": 42}) - - class W(object): - __slots__ = ["__weakref__"] - a = W() - verify(hasattr(a, "__weakref__")) - verify(not hasattr(a, "__dict__")) - try: - a.foo = 42 - except AttributeError: - pass - else: - raise TestFailed("shouldn't be allowed to set a.foo") - - class C1(W, D): - __slots__ = [] - a = C1() - verify(hasattr(a, "__dict__")) - verify(hasattr(a, "__weakref__")) - a.foo = 42 - vereq(a.__dict__, {"foo": 42}) - - class C2(D, W): - __slots__ = [] - a = C2() - verify(hasattr(a, "__dict__")) - verify(hasattr(a, "__weakref__")) - a.foo = 42 - vereq(a.__dict__, {"foo": 42}) - -# MRO order disagreement -# -# class C3(C1, C2): -# __slots__ = [] -# -# class C4(C2, C1): -# __slots__ = [] - -def dynamics(): - if verbose: print("Testing class attribute propagation...") - class D(object): - pass - class E(D): - pass - class F(D): - pass - D.foo = 1 - vereq(D.foo, 1) - # Test that dynamic attributes are inherited - vereq(E.foo, 1) - vereq(F.foo, 1) - # Test dynamic instances - class C(object): - pass - a = C() - verify(not hasattr(a, "foobar")) - C.foobar = 2 - vereq(a.foobar, 2) - C.method = lambda self: 42 - vereq(a.method(), 42) - C.__repr__ = lambda self: "C()" - vereq(repr(a), "C()") - C.__int__ = lambda self: 100 - vereq(int(a), 100) - vereq(a.foobar, 2) - verify(not hasattr(a, "spam")) - def mygetattr(self, name): - if name == "spam": - return "spam" - raise AttributeError - C.__getattr__ = mygetattr - vereq(a.spam, "spam") - a.new = 12 - vereq(a.new, 12) - def mysetattr(self, name, value): - if name == "spam": - raise AttributeError - return object.__setattr__(self, name, value) - C.__setattr__ = mysetattr - try: - a.spam = "not spam" - except AttributeError: - pass - else: - verify(0, "expected AttributeError") - vereq(a.spam, "spam") - class D(C): - pass - d = D() - d.foo = 1 - vereq(d.foo, 1) - - # Test handling of int*seq and seq*int - class I(int): - pass - vereq("a"*I(2), "aa") - vereq(I(2)*"a", "aa") - vereq(2*I(3), 6) - vereq(I(3)*2, 6) - vereq(I(3)*I(2), 6) - - # Test handling of long*seq and seq*long - class L(int): - pass - vereq("a"*L(2), "aa") - vereq(L(2)*"a", "aa") - vereq(2*L(3), 6) - vereq(L(3)*2, 6) - vereq(L(3)*L(2), 6) - - # Test comparison of classes with dynamic metaclasses - class dynamicmetaclass(type): - pass - class someclass(metaclass=dynamicmetaclass): - pass - verify(someclass != object) - -def errors(): - if verbose: print("Testing errors...") - - try: - class C(list, dict): - pass - except TypeError: - pass - else: - verify(0, "inheritance from both list and dict should be illegal") - - try: - class C(object, None): - pass - except TypeError: - pass - else: - verify(0, "inheritance from non-type should be illegal") - class Classic: - pass - - try: - class C(type(len)): - pass - except TypeError: - pass - else: - verify(0, "inheritance from CFunction should be illegal") + def __init__(self, foo=None): + self.foo = foo + self.__foo = foo + def setfoo(self, foo=None): + self.foo = foo + def getfoo(self): + return self.__foo + def __getstate__(self): + return [self.foo] + def __setstate__(self_, lst): + self.assertEqual(len(lst), 1) + self_.__foo = self_.foo = lst[0] + a = C(42) + a.setfoo(24) + self.assertEqual(a.foo, 24) + self.assertEqual(a.getfoo(), 42) + b = copy.copy(a) + self.assertEqual(b.foo, 24) + self.assertEqual(b.getfoo(), 24) + b = copy.deepcopy(a) + self.assertEqual(b.foo, 24) + self.assertEqual(b.getfoo(), 24) + + def test_slices(self): + # Testing cases with slices and overridden __getitem__ ... + + # Strings + self.assertEqual("hello"[:4], "hell") + self.assertEqual("hello"[slice(4)], "hell") + self.assertEqual(str.__getitem__("hello", slice(4)), "hell") + class S(str): + def __getitem__(self, x): + return str.__getitem__(self, x) + self.assertEqual(S("hello")[:4], "hell") + self.assertEqual(S("hello")[slice(4)], "hell") + self.assertEqual(S("hello").__getitem__(slice(4)), "hell") + # Tuples + self.assertEqual((1,2,3)[:2], (1,2)) + self.assertEqual((1,2,3)[slice(2)], (1,2)) + self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2)) + class T(tuple): + def __getitem__(self, x): + return tuple.__getitem__(self, x) + self.assertEqual(T((1,2,3))[:2], (1,2)) + self.assertEqual(T((1,2,3))[slice(2)], (1,2)) + self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2)) + # Lists + self.assertEqual([1,2,3][:2], [1,2]) + self.assertEqual([1,2,3][slice(2)], [1,2]) + self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2]) + class L(list): + def __getitem__(self, x): + return list.__getitem__(self, x) + self.assertEqual(L([1,2,3])[:2], [1,2]) + self.assertEqual(L([1,2,3])[slice(2)], [1,2]) + self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2]) + # Now do lists and __setitem__ + a = L([1,2,3]) + a[slice(1, 3)] = [3,2] + self.assertEqual(a, [1,3,2]) + a[slice(0, 2, 1)] = [3,1] + self.assertEqual(a, [3,1,2]) + a.__setitem__(slice(1, 3), [2,1]) + self.assertEqual(a, [3,2,1]) + a.__setitem__(slice(0, 2, 1), [2,3]) + self.assertEqual(a, [2,3,1]) - try: - class C(object): - __slots__ = 1 - except TypeError: - pass - else: - verify(0, "__slots__ = 1 should be illegal") + def test_subtype_resurrection(self): + # Testing resurrection of new-style instance... - try: class C(object): - __slots__ = [1] - except TypeError: - pass - else: - verify(0, "__slots__ = [1] should be illegal") - - class M1(type): - pass - class M2(type): - pass - class A1(object, metaclass=M1): - pass - class A2(object, metaclass=M2): - pass - try: - class B(A1, A2): - pass - except TypeError: - pass - else: - verify(0, "finding the most derived metaclass should have failed") - -def classmethods(): - if verbose: print("Testing class methods...") - class C(object): - def foo(*a): return a - goo = classmethod(foo) - c = C() - vereq(C.goo(1), (C, 1)) - vereq(c.goo(1), (C, 1)) - vereq(c.foo(1), (c, 1)) - class D(C): - pass - d = D() - vereq(D.goo(1), (D, 1)) - vereq(d.goo(1), (D, 1)) - vereq(d.foo(1), (d, 1)) - vereq(D.foo(d, 1), (d, 1)) - # Test for a specific crash (SF bug 528132) - def f(cls, arg): return (cls, arg) - ff = classmethod(f) - vereq(ff.__get__(0, int)(42), (int, 42)) - vereq(ff.__get__(0)(42), (int, 42)) - - # Test super() with classmethods (SF bug 535444) - veris(C.goo.__self__, C) - veris(D.goo.__self__, D) - veris(super(D,D).goo.__self__, D) - veris(super(D,d).goo.__self__, D) - vereq(super(D,D).goo(), (D,)) - vereq(super(D,d).goo(), (D,)) - - # Verify that argument is checked for callability (SF bug 753451) - try: - classmethod(1).__get__(1) - except TypeError: - pass - else: - raise TestFailed("classmethod should check for callability") - - # Verify that classmethod() doesn't allow keyword args - try: - classmethod(f, kw=1) - except TypeError: - pass - else: - raise TestFailed("classmethod shouldn't accept keyword args") - -def classmethods_in_c(): - if verbose: print("Testing C-based class methods...") - import xxsubtype as spam - a = (1, 2, 3) - d = {'abc': 123} - x, a1, d1 = spam.spamlist.classmeth(*a, **d) - veris(x, spam.spamlist) - vereq(a, a1) - vereq(d, d1) - x, a1, d1 = spam.spamlist().classmeth(*a, **d) - veris(x, spam.spamlist) - vereq(a, a1) - vereq(d, d1) - -def staticmethods(): - if verbose: print("Testing static methods...") - class C(object): - def foo(*a): return a - goo = staticmethod(foo) - c = C() - vereq(C.goo(1), (1,)) - vereq(c.goo(1), (1,)) - vereq(c.foo(1), (c, 1,)) - class D(C): - pass - d = D() - vereq(D.goo(1), (1,)) - vereq(d.goo(1), (1,)) - vereq(d.foo(1), (d, 1)) - vereq(D.foo(d, 1), (d, 1)) - -def staticmethods_in_c(): - if verbose: print("Testing C-based static methods...") - import xxsubtype as spam - a = (1, 2, 3) - d = {"abc": 123} - x, a1, d1 = spam.spamlist.staticmeth(*a, **d) - veris(x, None) - vereq(a, a1) - vereq(d, d1) - x, a1, d2 = spam.spamlist().staticmeth(*a, **d) - veris(x, None) - vereq(a, a1) - vereq(d, d1) - -def classic(): - if verbose: print("Testing classic classes...") - class C: - def foo(*a): return a - goo = classmethod(foo) - c = C() - vereq(C.goo(1), (C, 1)) - vereq(c.goo(1), (C, 1)) - vereq(c.foo(1), (c, 1)) - class D(C): - pass - d = D() - vereq(D.goo(1), (D, 1)) - vereq(d.goo(1), (D, 1)) - vereq(d.foo(1), (d, 1)) - vereq(D.foo(d, 1), (d, 1)) - class E: # *not* subclassing from C - foo = C.foo - r = repr(E().foo) - verify(r.startswith("= 0) - vereq(str(c1), repr(c1)) - verify(-1 not in c1) - for i in range(10): - verify(i in c1) - verify(10 not in c1) - # Test the default behavior for dynamic classes - class D(object): - def __getitem__(self, i): - if 0 <= i < 10: return i - raise IndexError - d1 = D() - d2 = D() - verify(not not d1) - verify(id(d1) != id(d2)) - hash(d1) - hash(d2) - ##vereq(cmp(d1, d2), cmp(id(d1), id(d2))) - vereq(d1, d1) - verify(d1 != d2) - verify(not d1 != d1) - verify(not d1 == d2) - # Note that the module name appears in str/repr, and that varies - # depending on whether this test is run standalone or from a framework. - verify(str(d1).find('D object at ') >= 0) - vereq(str(d1), repr(d1)) - verify(-1 not in d1) - for i in range(10): - verify(i in d1) - verify(10 not in d1) - # Test overridden behavior for static classes - class Proxy(object): - def __init__(self, x): - self.x = x - def __bool__(self): - return not not self.x - def __hash__(self): - return hash(self.x) - def __eq__(self, other): - return self.x == other - def __ne__(self, other): - return self.x != other - def __cmp__(self, other): - return cmp(self.x, other.x) - def __str__(self): - return "Proxy:%s" % self.x - def __repr__(self): - return "Proxy(%r)" % self.x - def __contains__(self, value): - return value in self.x - p0 = Proxy(0) - p1 = Proxy(1) - p_1 = Proxy(-1) - verify(not p0) - verify(not not p1) - vereq(hash(p0), hash(0)) - vereq(p0, p0) - verify(p0 != p1) - verify(not p0 != p0) - vereq(not p0, p1) - vereq(cmp(p0, p1), -1) - vereq(cmp(p0, p0), 0) - vereq(cmp(p0, p_1), 1) - vereq(str(p0), "Proxy:0") - vereq(repr(p0), "Proxy(0)") - p10 = Proxy(range(10)) - verify(-1 not in p10) - for i in range(10): - verify(i in p10) - verify(10 not in p10) - # Test overridden behavior for dynamic classes - class DProxy(object): - def __init__(self, x): - self.x = x - def __bool__(self): - return not not self.x - def __hash__(self): - return hash(self.x) - def __eq__(self, other): - return self.x == other - def __ne__(self, other): - return self.x != other - def __cmp__(self, other): - return cmp(self.x, other.x) - def __str__(self): - return "DProxy:%s" % self.x - def __repr__(self): - return "DProxy(%r)" % self.x - def __contains__(self, value): - return value in self.x - p0 = DProxy(0) - p1 = DProxy(1) - p_1 = DProxy(-1) - verify(not p0) - verify(not not p1) - vereq(hash(p0), hash(0)) - vereq(p0, p0) - verify(p0 != p1) - verify(not p0 != p0) - vereq(not p0, p1) - vereq(cmp(p0, p1), -1) - vereq(cmp(p0, p0), 0) - vereq(cmp(p0, p_1), 1) - vereq(str(p0), "DProxy:0") - vereq(repr(p0), "DProxy(0)") - p10 = DProxy(range(10)) - verify(-1 not in p10) - for i in range(10): - verify(i in p10) - verify(10 not in p10) -## # Safety test for __cmp__ -## def unsafecmp(a, b): -## try: -## a.__class__.__cmp__(a, b) -## except TypeError: -## pass -## else: -## raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % ( -## a.__class__, a, b) -## unsafecmp(u"123", "123") -## unsafecmp("123", u"123") -## unsafecmp(1, 1.0) -## unsafecmp(1.0, 1) -## unsafecmp(1, 1L) -## unsafecmp(1L, 1) - -def recursions(): - if verbose: - print("Testing recursion checks ...") - -## class Letter(str): -## def __new__(cls, letter): -## if letter == 'EPS': -## return str.__new__(cls) -## return str.__new__(cls, letter) -## def __str__(self): -## if not self: -## return 'EPS' -## return self -## # sys.stdout needs to be the original to trigger the recursion bug -## import sys -## test_stdout = sys.stdout -## sys.stdout = get_original_stdout() -## try: -## # nothing should actually be printed, this should raise an exception -## print(Letter('w')) -## except RuntimeError: -## pass -## else: -## raise TestFailed, "expected a RuntimeError for print recursion" -## sys.stdout = test_stdout - -def weakrefs(): - if verbose: print("Testing weak references...") - import weakref - class C(object): - pass - c = C() - r = weakref.ref(c) - verify(r() is c) - del c - verify(r() is None) - del r - class NoWeak(object): - __slots__ = ['foo'] - no = NoWeak() - try: - weakref.ref(no) - except TypeError as msg: - verify(str(msg).find("weak reference") >= 0) - else: - verify(0, "weakref.ref(no) should be illegal") - class Weak(object): - __slots__ = ['foo', '__weakref__'] - yes = Weak() - r = weakref.ref(yes) - verify(r() is yes) - del yes - verify(r() is None) - del r - -def properties(): - if verbose: print("Testing property...") - class C(object): - def getx(self): - return self.__x - def setx(self, value): - self.__x = value - def delx(self): - del self.__x - x = property(getx, setx, delx, doc="I'm the x property.") - a = C() - verify(not hasattr(a, "x")) - a.x = 42 - vereq(a._C__x, 42) - vereq(a.x, 42) - del a.x - verify(not hasattr(a, "x")) - verify(not hasattr(a, "_C__x")) - C.x.__set__(a, 100) - vereq(C.x.__get__(a), 100) - C.x.__delete__(a) - verify(not hasattr(a, "x")) - - raw = C.__dict__['x'] - verify(isinstance(raw, property)) - - attrs = dir(raw) - verify("__doc__" in attrs) - verify("fget" in attrs) - verify("fset" in attrs) - verify("fdel" in attrs) - - vereq(raw.__doc__, "I'm the x property.") - verify(raw.fget is C.__dict__['getx']) - verify(raw.fset is C.__dict__['setx']) - verify(raw.fdel is C.__dict__['delx']) - - for attr in "__doc__", "fget", "fset", "fdel": - try: - setattr(raw, attr, 42) - except AttributeError as msg: - if str(msg).find('readonly') < 0: - raise TestFailed("when setting readonly attr %r on a " - "property, got unexpected AttributeError " - "msg %r" % (attr, str(msg))) - else: - raise TestFailed("expected AttributeError from trying to set " - "readonly %r attr on a property" % attr) - - class D(object): - __getitem__ = property(lambda s: 1/0) - - d = D() - try: - for i in d: - str(i) - except ZeroDivisionError: - pass - else: - raise TestFailed("expected ZeroDivisionError from bad property") - - class E(object): - def getter(self): - "getter method" - return 0 - def setter(self, value): - "setter method" - pass - prop = property(getter) - vereq(prop.__doc__, "getter method") - prop2 = property(fset=setter) - vereq(prop2.__doc__, None) - - # this segfaulted in 2.5b2 - try: - import _testcapi - except ImportError: - pass - else: - class X(object): - p = property(_testcapi.test_with_docstring) - - -def properties_plus(): - class C(object): - foo = property(doc="hello") - @foo.getter - def foo(self): - return self._foo - @foo.setter - def foo(self, value): - self._foo = abs(value) - @foo.deleter - def foo(self): - del self._foo - c = C() - assert C.foo.__doc__ == "hello" - assert not hasattr(c, "foo") - c.foo = -42 - assert hasattr(c, '_foo') - assert c._foo == 42 - assert c.foo == 42 - del c.foo - assert not hasattr(c, '_foo') - assert not hasattr(c, "foo") - - class D(C): - @C.foo.deleter - def foo(self): - try: - del self._foo - except AttributeError: - pass - d = D() - d.foo = 24 - assert d.foo == 24 - del d.foo - del d.foo - - class E(object): - @property - def foo(self): - return self._foo - @foo.setter - def foo(self, value): - raise RuntimeError - @foo.setter - def foo(self, value): - self._foo = abs(value) - @foo.deleter - def foo(self, value=None): - del self._foo - - e = E() - e.foo = -42 - assert e.foo == 42 - del e.foo - - class F(E): - @E.foo.deleter - def foo(self): - del self._foo - @foo.setter - def foo(self, value): - self._foo = max(0, value) - f = F() - f.foo = -10 - assert f.foo == 0 - del f.foo - - -def supers(): - if verbose: print("Testing super...") - - class A(object): - def meth(self, a): - return "A(%r)" % a - - vereq(A().meth(1), "A(1)") - - class B(A): - def __init__(self): - self.__super = super(B, self) - def meth(self, a): - return "B(%r)" % a + self.__super.meth(a) - - vereq(B().meth(2), "B(2)A(2)") - - class C(A): - def meth(self, a): - return "C(%r)" % a + self.__super.meth(a) - C._C__super = super(C) - - vereq(C().meth(3), "C(3)A(3)") - - class D(C, B): - def meth(self, a): - return "D(%r)" % a + super(D, self).meth(a) - - vereq(D().meth(4), "D(4)C(4)B(4)A(4)") - - # Test for subclassing super - - class mysuper(super): - def __init__(self, *args): - return super(mysuper, self).__init__(*args) - - class E(D): - def meth(self, a): - return "E(%r)" % a + mysuper(E, self).meth(a) - - vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)") - - class F(E): - def meth(self, a): - s = self.__super # == mysuper(F, self) - return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a) - F._F__super = mysuper(F) - - vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)") - - # Make sure certain errors are raised - - try: - super(D, 42) - except TypeError: - pass - else: - raise TestFailed("shouldn't allow super(D, 42)") - - try: - super(D, C()) - except TypeError: - pass - else: - raise TestFailed("shouldn't allow super(D, C())") - - try: - super(D).__get__(12) - except TypeError: - pass - else: - raise TestFailed("shouldn't allow super(D).__get__(12)") - - try: - super(D).__get__(C()) - except TypeError: - pass - else: - raise TestFailed("shouldn't allow super(D).__get__(C())") - - # Make sure data descriptors can be overridden and accessed via super - # (new feature in Python 2.3) - - class DDbase(object): - def getx(self): return 42 - x = property(getx) - - class DDsub(DDbase): - def getx(self): return "hello" - x = property(getx) - - dd = DDsub() - vereq(dd.x, "hello") - vereq(super(DDsub, dd).x, 42) - - # Ensure that super() lookup of descriptor from classmethod - # works (SF ID# 743627) - - class Base(object): - aProp = property(lambda self: "foo") - - class Sub(Base): - @classmethod - def test(klass): - return super(Sub,klass).aProp - - veris(Sub.test(), Base.aProp) - - # Verify that super() doesn't allow keyword args - try: - super(Base, kw=1) - except TypeError: - pass - else: - raise TestFailed("super shouldn't accept keyword args") - -def inherits(): - if verbose: print("Testing inheritance from basic types...") - - class hexint(int): - def __repr__(self): - return hex(self) - def __add__(self, other): - return hexint(int.__add__(self, other)) - # (Note that overriding __radd__ doesn't work, - # because the int type gets first dibs.) - vereq(repr(hexint(7) + 9), "0x10") - vereq(repr(hexint(1000) + 7), "0x3ef") - a = hexint(12345) - vereq(a, 12345) - vereq(int(a), 12345) - verify(int(a).__class__ is int) - vereq(hash(a), hash(12345)) - verify((+a).__class__ is int) - verify((a >> 0).__class__ is int) - verify((a << 0).__class__ is int) - verify((hexint(0) << 12).__class__ is int) - verify((hexint(0) >> 12).__class__ is int) - - class octlong(int): - __slots__ = [] - def __str__(self): - return oct(self) - def __add__(self, other): - return self.__class__(super(octlong, self).__add__(other)) - __radd__ = __add__ - vereq(str(octlong(3) + 5), "0o10") - # (Note that overriding __radd__ here only seems to work - # because the example uses a short int left argument.) - vereq(str(5 + octlong(3000)), "0o5675") - a = octlong(12345) - vereq(a, 12345) - vereq(int(a), 12345) - vereq(hash(a), hash(12345)) - verify(int(a).__class__ is int) - verify((+a).__class__ is int) - verify((-a).__class__ is int) - verify((-octlong(0)).__class__ is int) - verify((a >> 0).__class__ is int) - verify((a << 0).__class__ is int) - verify((a - 0).__class__ is int) - verify((a * 1).__class__ is int) - verify((a ** 1).__class__ is int) - verify((a // 1).__class__ is int) - verify((1 * a).__class__ is int) - verify((a | 0).__class__ is int) - verify((a ^ 0).__class__ is int) - verify((a & -1).__class__ is int) - verify((octlong(0) << 12).__class__ is int) - verify((octlong(0) >> 12).__class__ is int) - verify(abs(octlong(0)).__class__ is int) - - # Because octlong overrides __add__, we can't check the absence of +0 - # optimizations using octlong. - class longclone(int): - pass - a = longclone(1) - verify((a + 0).__class__ is int) - verify((0 + a).__class__ is int) - - # Check that negative clones don't segfault - a = longclone(-1) - vereq(a.__dict__, {}) - vereq(int(a), -1) # verify PyNumber_Long() copies the sign bit - - class precfloat(float): - __slots__ = ['prec'] - def __init__(self, value=0.0, prec=12): - self.prec = int(prec) - def __repr__(self): - return "%.*g" % (self.prec, self) - vereq(repr(precfloat(1.1)), "1.1") - a = precfloat(12345) - vereq(a, 12345.0) - vereq(float(a), 12345.0) - verify(float(a).__class__ is float) - vereq(hash(a), hash(12345.0)) - verify((+a).__class__ is float) - - class madcomplex(complex): - def __repr__(self): - return "%.17gj%+.17g" % (self.imag, self.real) - a = madcomplex(-3, 4) - vereq(repr(a), "4j-3") - base = complex(-3, 4) - veris(base.__class__, complex) - vereq(a, base) - vereq(complex(a), base) - veris(complex(a).__class__, complex) - a = madcomplex(a) # just trying another form of the constructor - vereq(repr(a), "4j-3") - vereq(a, base) - vereq(complex(a), base) - veris(complex(a).__class__, complex) - vereq(hash(a), hash(base)) - veris((+a).__class__, complex) - veris((a + 0).__class__, complex) - vereq(a + 0, base) - veris((a - 0).__class__, complex) - vereq(a - 0, base) - veris((a * 1).__class__, complex) - vereq(a * 1, base) - veris((a / 1).__class__, complex) - vereq(a / 1, base) - - class madtuple(tuple): - _rev = None - def rev(self): - if self._rev is not None: - return self._rev - L = list(self) - L.reverse() - self._rev = self.__class__(L) - return self._rev - a = madtuple((1,2,3,4,5,6,7,8,9,0)) - vereq(a, (1,2,3,4,5,6,7,8,9,0)) - vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1))) - vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0))) - for i in range(512): - t = madtuple(range(i)) - u = t.rev() - v = u.rev() - vereq(v, t) - a = madtuple((1,2,3,4,5)) - vereq(tuple(a), (1,2,3,4,5)) - verify(tuple(a).__class__ is tuple) - vereq(hash(a), hash((1,2,3,4,5))) - verify(a[:].__class__ is tuple) - verify((a * 1).__class__ is tuple) - verify((a * 0).__class__ is tuple) - verify((a + ()).__class__ is tuple) - a = madtuple(()) - vereq(tuple(a), ()) - verify(tuple(a).__class__ is tuple) - verify((a + a).__class__ is tuple) - verify((a * 0).__class__ is tuple) - verify((a * 1).__class__ is tuple) - verify((a * 2).__class__ is tuple) - verify(a[:].__class__ is tuple) - - class madstring(str): - _rev = None - def rev(self): - if self._rev is not None: - return self._rev - L = list(self) - L.reverse() - self._rev = self.__class__("".join(L)) - return self._rev - s = madstring("abcdefghijklmnopqrstuvwxyz") - vereq(s, "abcdefghijklmnopqrstuvwxyz") - vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba")) - vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz")) - for i in range(256): - s = madstring("".join(map(chr, range(i)))) - t = s.rev() - u = t.rev() - vereq(u, s) - s = madstring("12345") - vereq(str(s), "12345") - verify(str(s).__class__ is str) - - base = "\x00" * 5 - s = madstring(base) - vereq(s, base) - vereq(str(s), base) - verify(str(s).__class__ is str) - vereq(hash(s), hash(base)) - vereq({s: 1}[base], 1) - vereq({base: 1}[s], 1) - verify((s + "").__class__ is str) - vereq(s + "", base) - verify(("" + s).__class__ is str) - vereq("" + s, base) - verify((s * 0).__class__ is str) - vereq(s * 0, "") - verify((s * 1).__class__ is str) - vereq(s * 1, base) - verify((s * 2).__class__ is str) - vereq(s * 2, base + base) - verify(s[:].__class__ is str) - vereq(s[:], base) - verify(s[0:0].__class__ is str) - vereq(s[0:0], "") - verify(s.strip().__class__ is str) - vereq(s.strip(), base) - verify(s.lstrip().__class__ is str) - vereq(s.lstrip(), base) - verify(s.rstrip().__class__ is str) - vereq(s.rstrip(), base) - identitytab = {} - verify(s.translate(identitytab).__class__ is str) - vereq(s.translate(identitytab), base) - verify(s.replace("x", "x").__class__ is str) - vereq(s.replace("x", "x"), base) - verify(s.ljust(len(s)).__class__ is str) - vereq(s.ljust(len(s)), base) - verify(s.rjust(len(s)).__class__ is str) - vereq(s.rjust(len(s)), base) - verify(s.center(len(s)).__class__ is str) - vereq(s.center(len(s)), base) - verify(s.lower().__class__ is str) - vereq(s.lower(), base) - - class madunicode(str): - _rev = None - def rev(self): - if self._rev is not None: - return self._rev - L = list(self) - L.reverse() - self._rev = self.__class__("".join(L)) - return self._rev - u = madunicode("ABCDEF") - vereq(u, "ABCDEF") - vereq(u.rev(), madunicode("FEDCBA")) - vereq(u.rev().rev(), madunicode("ABCDEF")) - base = "12345" - u = madunicode(base) - vereq(str(u), base) - verify(str(u).__class__ is str) - vereq(hash(u), hash(base)) - vereq({u: 1}[base], 1) - vereq({base: 1}[u], 1) - verify(u.strip().__class__ is str) - vereq(u.strip(), base) - verify(u.lstrip().__class__ is str) - vereq(u.lstrip(), base) - verify(u.rstrip().__class__ is str) - vereq(u.rstrip(), base) - verify(u.replace("x", "x").__class__ is str) - vereq(u.replace("x", "x"), base) - verify(u.replace("xy", "xy").__class__ is str) - vereq(u.replace("xy", "xy"), base) - verify(u.center(len(u)).__class__ is str) - vereq(u.center(len(u)), base) - verify(u.ljust(len(u)).__class__ is str) - vereq(u.ljust(len(u)), base) - verify(u.rjust(len(u)).__class__ is str) - vereq(u.rjust(len(u)), base) - verify(u.lower().__class__ is str) - vereq(u.lower(), base) - verify(u.upper().__class__ is str) - vereq(u.upper(), base) - verify(u.capitalize().__class__ is str) - vereq(u.capitalize(), base) - verify(u.title().__class__ is str) - vereq(u.title(), base) - verify((u + "").__class__ is str) - vereq(u + "", base) - verify(("" + u).__class__ is str) - vereq("" + u, base) - verify((u * 0).__class__ is str) - vereq(u * 0, "") - verify((u * 1).__class__ is str) - vereq(u * 1, base) - verify((u * 2).__class__ is str) - vereq(u * 2, base + base) - verify(u[:].__class__ is str) - vereq(u[:], base) - verify(u[0:0].__class__ is str) - vereq(u[0:0], "") - - class sublist(list): - pass - a = sublist(range(5)) - vereq(a, list(range(5))) - a.append("hello") - vereq(a, list(range(5)) + ["hello"]) - a[5] = 5 - vereq(a, list(range(6))) - a.extend(range(6, 20)) - vereq(a, list(range(20))) - a[-5:] = [] - vereq(a, list(range(15))) - del a[10:15] - vereq(len(a), 10) - vereq(a, list(range(10))) - vereq(list(a), list(range(10))) - vereq(a[0], 0) - vereq(a[9], 9) - vereq(a[-10], 0) - vereq(a[-1], 9) - vereq(a[:5], list(range(5))) - -## class CountedInput(file): -## """Counts lines read by self.readline(). - -## self.lineno is the 0-based ordinal of the last line read, up to -## a maximum of one greater than the number of lines in the file. - -## self.ateof is true if and only if the final "" line has been read, -## at which point self.lineno stops incrementing, and further calls -## to readline() continue to return "". -## """ - -## lineno = 0 -## ateof = 0 -## def readline(self): -## if self.ateof: -## return "" -## s = file.readline(self) -## # Next line works too. -## # s = super(CountedInput, self).readline() -## self.lineno += 1 -## if s == "": -## self.ateof = 1 -## return s - -## f = open(name=TESTFN, mode='w') -## lines = ['a\n', 'b\n', 'c\n'] -## try: -## f.writelines(lines) -## f.close() -## f = CountedInput(TESTFN) -## for (i, expected) in zip(list(range(1, 5)) + [4], lines + 2 * [""]): -## got = f.readline() -## vereq(expected, got) -## vereq(f.lineno, i) -## vereq(f.ateof, (i > len(lines))) -## f.close() -## finally: -## try: -## f.close() -## except: -## pass -## try: -## import os -## os.unlink(TESTFN) -## except: -## pass - -def keywords(): - if verbose: - print("Testing keyword args to basic type constructors ...") - vereq(int(x=1), 1) - vereq(float(x=2), 2.0) - vereq(int(x=3), 3) - vereq(complex(imag=42, real=666), complex(666, 42)) - vereq(str(object=500), '500') - vereq(str(object=b'abc', errors='strict'), 'abc') - vereq(tuple(sequence=range(3)), (0, 1, 2)) - vereq(list(sequence=(0, 1, 2)), list(range(3))) - # note: as of Python 2.3, dict() no longer has an "items" keyword arg - - for constructor in (int, float, int, complex, str, str, tuple, list): - try: - constructor(bogus_keyword_arg=1) - except TypeError: - pass - else: - raise TestFailed("expected TypeError from bogus keyword " - "argument to %r" % constructor) - -def str_subclass_as_dict_key(): - if verbose: - print("Testing a str subclass used as dict key ..") - - class cistr(str): - """Sublcass of str that computes __eq__ case-insensitively. - - Also computes a hash code of the string in canonical form. - """ - - def __init__(self, value): - self.canonical = value.lower() - self.hashcode = hash(self.canonical) - - def __eq__(self, other): - if not isinstance(other, cistr): - other = cistr(other) - return self.canonical == other.canonical - - def __hash__(self): - return self.hashcode - - vereq(cistr('ABC'), 'abc') - vereq('aBc', cistr('ABC')) - vereq(str(cistr('ABC')), 'ABC') - - d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3} - vereq(d[cistr('one')], 1) - vereq(d[cistr('tWo')], 2) - vereq(d[cistr('THrEE')], 3) - verify(cistr('ONe') in d) - vereq(d.get(cistr('thrEE')), 3) - -def classic_comparisons(): - if verbose: print("Testing classic comparisons...") - class classic: - pass - for base in (classic, int, object): - if verbose: print(" (base = %s)" % base) - class C(base): - def __init__(self, value): - self.value = int(value) - def __eq__(self, other): - if isinstance(other, C): - return self.value == other.value - if isinstance(other, int) or isinstance(other, int): - return self.value == other - return NotImplemented - def __ne__(self, other): - if isinstance(other, C): - return self.value != other.value - if isinstance(other, int) or isinstance(other, int): - return self.value != other - return NotImplemented - def __lt__(self, other): - if isinstance(other, C): - return self.value < other.value - if isinstance(other, int) or isinstance(other, int): - return self.value < other - return NotImplemented - def __le__(self, other): - if isinstance(other, C): - return self.value <= other.value - if isinstance(other, int) or isinstance(other, int): - return self.value <= other - return NotImplemented - def __gt__(self, other): - if isinstance(other, C): - return self.value > other.value - if isinstance(other, int) or isinstance(other, int): - return self.value > other - return NotImplemented - def __ge__(self, other): - if isinstance(other, C): - return self.value >= other.value - if isinstance(other, int) or isinstance(other, int): - return self.value >= other - return NotImplemented + try: + D.__bases__ = () + except TypeError as msg: + if str(msg) == "a new-style class can't have only classic bases": + self.fail("wrong error message for .__bases__ = ()") + else: + self.fail("shouldn't be able to set .__bases__ to ()") - c1 = C(1) - c2 = C(2) - c3 = C(3) - vereq(c1, 1) - c = {1: c1, 2: c2, 3: c3} - for x in 1, 2, 3: - for y in 1, 2, 3: - ##verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y)) - for op in "<", "<=", "==", "!=", ">", ">=": - verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op), - "x=%d, y=%d" % (x, y)) - ##verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y)) - ##verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y)) - -def rich_comparisons(): - if verbose: - print("Testing rich comparisons...") - class Z(complex): - pass - z = Z(1) - vereq(z, 1+0j) - vereq(1+0j, z) - class ZZ(complex): - def __eq__(self, other): - try: - return abs(self - other) <= 1e-6 - except: - return NotImplemented - zz = ZZ(1.0000003) - vereq(zz, 1+0j) - vereq(1+0j, zz) - - class classic: - pass - for base in (classic, int, object, list): - if verbose: print(" (base = %s)" % base) - class C(base): - def __init__(self, value): - self.value = int(value) - def __cmp__(self, other): - raise TestFailed("shouldn't call __cmp__") - def __eq__(self, other): - if isinstance(other, C): - return self.value == other.value - if isinstance(other, int) or isinstance(other, int): - return self.value == other - return NotImplemented - def __ne__(self, other): - if isinstance(other, C): - return self.value != other.value - if isinstance(other, int) or isinstance(other, int): - return self.value != other - return NotImplemented - def __lt__(self, other): - if isinstance(other, C): - return self.value < other.value - if isinstance(other, int) or isinstance(other, int): - return self.value < other - return NotImplemented - def __le__(self, other): - if isinstance(other, C): - return self.value <= other.value - if isinstance(other, int) or isinstance(other, int): - return self.value <= other - return NotImplemented - def __gt__(self, other): - if isinstance(other, C): - return self.value > other.value - if isinstance(other, int) or isinstance(other, int): - return self.value > other - return NotImplemented - def __ge__(self, other): - if isinstance(other, C): - return self.value >= other.value - if isinstance(other, int) or isinstance(other, int): - return self.value >= other - return NotImplemented - c1 = C(1) - c2 = C(2) - c3 = C(3) - vereq(c1, 1) - c = {1: c1, 2: c2, 3: c3} - for x in 1, 2, 3: - for y in 1, 2, 3: - for op in "<", "<=", "==", "!=", ">", ">=": - verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op), - "x=%d, y=%d" % (x, y)) - verify(eval("c[x] %s y" % op) == eval("x %s y" % op), - "x=%d, y=%d" % (x, y)) - verify(eval("x %s c[y]" % op) == eval("x %s y" % op), - "x=%d, y=%d" % (x, y)) - -def descrdoc(): - if verbose: print("Testing descriptor doc strings...") - from _fileio import _FileIO - def check(descr, what): - vereq(descr.__doc__, what) - check(_FileIO.closed, "True if the file is closed") # getset descriptor - check(complex.real, "the real part of a complex number") # member descriptor - -def setclass(): - if verbose: print("Testing __class__ assignment...") - class C(object): pass - class D(object): pass - class E(object): pass - class F(D, E): pass - for cls in C, D, E, F: - for cls2 in C, D, E, F: - x = cls() - x.__class__ = cls2 - verify(x.__class__ is cls2) - x.__class__ = cls - verify(x.__class__ is cls) - def cant(x, C): try: - x.__class__ = C + D.__bases__ = (D,) except TypeError: pass else: - raise TestFailed("shouldn't allow %r.__class__ = %r" % (x, C)) + # actually, we'll have crashed by here... + self.fail("shouldn't be able to create inheritance cycles") + try: - delattr(x, "__class__") + D.__bases__ = (C, C) except TypeError: pass else: - raise TestFailed("shouldn't allow del %r.__class__" % x) - cant(C(), list) - cant(list(), C) - cant(C(), 1) - cant(C(), object) - cant(object(), list) - cant(list(), object) - class Int(int): __slots__ = [] - cant(2, Int) - cant(Int(), int) - cant(True, int) - cant(2, bool) - o = object() - cant(o, type(1)) - cant(o, type(None)) - del o - class G(object): - __slots__ = ["a", "b"] - class H(object): - __slots__ = ["b", "a"] - class I(object): - __slots__ = ["a", "b"] - class J(object): - __slots__ = ["c", "b"] - class K(object): - __slots__ = ["a", "b", "d"] - class L(H): - __slots__ = ["e"] - class M(I): - __slots__ = ["e"] - class N(J): - __slots__ = ["__weakref__"] - class P(J): - __slots__ = ["__dict__"] - class Q(J): - pass - class R(J): - __slots__ = ["__dict__", "__weakref__"] + self.fail("didn't detect repeated base classes") - for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)): - x = cls() - x.a = 1 - x.__class__ = cls2 - verify(x.__class__ is cls2, - "assigning %r as __class__ for %r silently failed" % (cls2, x)) - vereq(x.a, 1) - x.__class__ = cls - verify(x.__class__ is cls, - "assigning %r as __class__ for %r silently failed" % (cls, x)) - vereq(x.a, 1) - for cls in G, J, K, L, M, N, P, R, list, Int: - for cls2 in G, J, K, L, M, N, P, R, list, Int: - if cls is cls2: - continue - cant(cls(), cls2) - -def setdict(): - if verbose: print("Testing __dict__ assignment...") - class C(object): pass - a = C() - a.__dict__ = {'b': 1} - vereq(a.b, 1) - def cant(x, dict): try: - x.__dict__ = dict - except (AttributeError, TypeError): + D.__bases__ = (E,) + except TypeError: pass else: - raise TestFailed("shouldn't allow %r.__dict__ = %r" % (x, dict)) - cant(a, None) - cant(a, []) - cant(a, 1) - del a.__dict__ # Deleting __dict__ is allowed - - class Base(object): - pass - def verify_dict_readonly(x): - """ - x has to be an instance of a class inheriting from Base. - """ - cant(x, {}) - try: - del x.__dict__ - except (AttributeError, TypeError): + self.fail("shouldn't be able to create inheritance cycles") + + def test_mutable_bases_with_failing_mro(self): + # Testing mutable bases with failing mro... + class WorkOnce(type): + def __new__(self, name, bases, ns): + self.flag = 0 + return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns) + def mro(self): + if self.flag > 0: + raise RuntimeError("bozo") + else: + self.flag += 1 + return type.mro(self) + + class WorkAlways(type): + def mro(self): + # this is here to make sure that .mro()s aren't called + # with an exception set (which was possible at one point). + # An error message will be printed in a debug build. + # What's a good way to test for this? + return type.mro(self) + + class C(object): + pass + + class C2(object): + pass + + class D(C): + pass + + class E(D): + pass + + class F(D, metaclass=WorkOnce): + pass + + class G(D, metaclass=WorkAlways): pass + + # Immediate subclasses have their mro's adjusted in alphabetical + # order, so E's will get adjusted before adjusting F's fails. We + # check here that E's gets restored. + + E_mro_before = E.__mro__ + D_mro_before = D.__mro__ + + try: + D.__bases__ = (C2,) + except RuntimeError: + self.assertEqual(E.__mro__, E_mro_before) + self.assertEqual(D.__mro__, D_mro_before) else: - raise TestFailed("shouldn't allow del %r.__dict__" % x) - dict_descr = Base.__dict__["__dict__"] + self.fail("exception not propagated") + + def test_mutable_bases_catch_mro_conflict(self): + # Testing mutable bases catch mro conflict... + class A(object): + pass + + class B(object): + pass + + class C(A, B): + pass + + class D(A, B): + pass + + class E(C, D): + pass + try: - dict_descr.__set__(x, {}) - except (AttributeError, TypeError): + C.__bases__ = (B, A) + except TypeError: pass else: - raise TestFailed("dict_descr allowed access to %r's dict" % x) + self.fail("didn't catch MRO conflict") - # Classes don't allow __dict__ assignment and have readonly dicts - class Meta1(type, Base): - pass - class Meta2(Base, type): - pass - class D(object): - __metaclass__ = Meta1 - class E(object): - __metaclass__ = Meta2 - for cls in C, D, E: - verify_dict_readonly(cls) - class_dict = cls.__dict__ - try: - class_dict["spam"] = "eggs" - except TypeError: - pass - else: - raise TestFailed("%r's __dict__ can be modified" % cls) - - # Modules also disallow __dict__ assignment - class Module1(types.ModuleType, Base): - pass - class Module2(Base, types.ModuleType): - pass - for ModuleType in Module1, Module2: - mod = ModuleType("spam") - verify_dict_readonly(mod) - mod.__dict__["spam"] = "eggs" - - # Exception's __dict__ can be replaced, but not deleted - class Exception1(Exception, Base): - pass - class Exception2(Base, Exception): - pass - for ExceptionType in Exception, Exception1, Exception2: - e = ExceptionType() - e.__dict__ = {"a": 1} - vereq(e.a, 1) - try: - del e.__dict__ - except (TypeError, AttributeError): - pass - else: - raise TestFaied("%r's __dict__ can be deleted" % e) - - -def pickles(): - if verbose: - print("Testing pickling and copying new-style classes and objects...") - import pickle - - def sorteditems(d): - return sorted(d.items()) - - global C - class C(object): - def __init__(self, a, b): - super(C, self).__init__() - self.a = a - self.b = b - def __repr__(self): - return "C(%r, %r)" % (self.a, self.b) - - global C1 - class C1(list): - def __new__(cls, a, b): - return super(C1, cls).__new__(cls) - def __getnewargs__(self): - return (self.a, self.b) - def __init__(self, a, b): - self.a = a - self.b = b - def __repr__(self): - return "C1(%r, %r)<%r>" % (self.a, self.b, list(self)) - - global C2 - class C2(int): - def __new__(cls, a, b, val=0): - return super(C2, cls).__new__(cls, val) - def __getnewargs__(self): - return (self.a, self.b, int(self)) - def __init__(self, a, b, val=0): - self.a = a - self.b = b - def __repr__(self): - return "C2(%r, %r)<%r>" % (self.a, self.b, int(self)) - - global C3 - class C3(object): - def __init__(self, foo): - self.foo = foo - def __getstate__(self): - return self.foo - def __setstate__(self, foo): - self.foo = foo - - global C4classic, C4 - class C4classic: # classic - pass - class C4(C4classic, object): # mixed inheritance - pass + def test_mutable_names(self): + # Testing mutable names... + class C(object): + pass - for p in [pickle]: - for bin in 0, 1: - if verbose: - print(p.__name__, ["text", "binary"][bin]) + # C.__module__ could be 'test_descr' or '__main__' + mod = C.__module__ - for cls in C, C1, C2: - s = p.dumps(cls, bin) - cls2 = p.loads(s) - verify(cls2 is cls) + C.__name__ = 'D' + self.assertEqual((C.__module__, C.__name__), (mod, 'D')) + + C.__name__ = 'D.E' + self.assertEqual((C.__module__, C.__name__), (mod, 'D.E')) + + def test_subclass_right_op(self): + # Testing correct dispatch of subclass overloading __r__... + + # This code tests various cases where right-dispatch of a subclass + # should be preferred over left-dispatch of a base class. + + # Case 1: subclass of int; this tests code in abstract.c::binary_op1() + + class B(int): + def __floordiv__(self, other): + return "B.__floordiv__" + def __rfloordiv__(self, other): + return "B.__rfloordiv__" + + self.assertEqual(B(1) // 1, "B.__floordiv__") + self.assertEqual(1 // B(1), "B.__rfloordiv__") + + # Case 2: subclass of object; this is just the baseline for case 3 + + class C(object): + def __floordiv__(self, other): + return "C.__floordiv__" + def __rfloordiv__(self, other): + return "C.__rfloordiv__" + + self.assertEqual(C() // 1, "C.__floordiv__") + self.assertEqual(1 // C(), "C.__rfloordiv__") + + # Case 3: subclass of new-style class; here it gets interesting - a = C1(1, 2); a.append(42); a.append(24) - b = C2("hello", "world", 42) - s = p.dumps((a, b), bin) - x, y = p.loads(s) - vereq(x.__class__, a.__class__) - vereq(sorteditems(x.__dict__), sorteditems(a.__dict__)) - vereq(y.__class__, b.__class__) - vereq(sorteditems(y.__dict__), sorteditems(b.__dict__)) - vereq(repr(x), repr(a)) - vereq(repr(y), repr(b)) - if verbose: - print("a = x =", a) - print("b = y =", b) - # Test for __getstate__ and __setstate__ on new style class - u = C3(42) - s = p.dumps(u, bin) - v = p.loads(s) - veris(u.__class__, v.__class__) - vereq(u.foo, v.foo) - # Test for picklability of hybrid class - u = C4() - u.foo = 42 - s = p.dumps(u, bin) - v = p.loads(s) - veris(u.__class__, v.__class__) - vereq(u.foo, v.foo) - - # Testing copy.deepcopy() - if verbose: - print("deepcopy") - import copy - for cls in C, C1, C2: - cls2 = copy.deepcopy(cls) - verify(cls2 is cls) - - a = C1(1, 2); a.append(42); a.append(24) - b = C2("hello", "world", 42) - x, y = copy.deepcopy((a, b)) - vereq(x.__class__, a.__class__) - vereq(sorteditems(x.__dict__), sorteditems(a.__dict__)) - vereq(y.__class__, b.__class__) - vereq(sorteditems(y.__dict__), sorteditems(b.__dict__)) - vereq(repr(x), repr(a)) - vereq(repr(y), repr(b)) - if verbose: - print("a = x =", a) - print("b = y =", b) - -def pickleslots(): - if verbose: print("Testing pickling of classes with __slots__ ...") - import pickle - # Pickling of classes with __slots__ but without __getstate__ should fail - # (when using protocols 0 or 1) - global B, C, D, E - class B(object): - pass - for base in [object, B]: - class C(base): - __slots__ = ['a'] class D(C): + def __floordiv__(self, other): + return "D.__floordiv__" + def __rfloordiv__(self, other): + return "D.__rfloordiv__" + + self.assertEqual(D() // C(), "D.__floordiv__") + self.assertEqual(C() // D(), "D.__rfloordiv__") + + # Case 4: this didn't work right in 2.2.2 and 2.3a1 + + class E(C): + pass + + self.assertEqual(E.__rfloordiv__, C.__rfloordiv__) + + self.assertEqual(E() // 1, "C.__floordiv__") + self.assertEqual(1 // E(), "C.__rfloordiv__") + self.assertEqual(E() // C(), "C.__floordiv__") + self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail + + def test_meth_class_get(self): + # Testing __get__ method of METH_CLASS C methods... + # Full coverage of descrobject.c::classmethod_get() + + # Baseline + arg = [1, 2, 3] + res = {1: None, 2: None, 3: None} + self.assertEqual(dict.fromkeys(arg), res) + self.assertEqual({}.fromkeys(arg), res) + + # Now get the descriptor + descr = dict.__dict__["fromkeys"] + + # More baseline using the descriptor directly + self.assertEqual(descr.__get__(None, dict)(arg), res) + self.assertEqual(descr.__get__({})(arg), res) + + # Now check various error cases + try: + descr.__get__(None, None) + except TypeError: pass + else: + self.fail("shouldn't have allowed descr.__get__(None, None)") try: - pickle.dumps(C(), 0) + descr.__get__(42) except TypeError: pass else: - raise TestFailed("should fail: pickle C instance - %s" % base) + self.fail("shouldn't have allowed descr.__get__(42)") try: - pickle.dumps(C(), 0) + descr.__get__(None, 42) except TypeError: pass else: - raise TestFailed("should fail: pickle D instance - %s" % base) - # Give C a nice generic __getstate__ and __setstate__ - class C(base): - __slots__ = ['a'] - def __getstate__(self): - try: - d = self.__dict__.copy() - except AttributeError: - d = {} - for cls in self.__class__.__mro__: - for sn in cls.__dict__.get('__slots__', ()): - try: - d[sn] = getattr(self, sn) - except AttributeError: - pass - return d - def __setstate__(self, d): - for k, v in d.items(): - setattr(self, k, v) + self.fail("shouldn't have allowed descr.__get__(None, 42)") + try: + descr.__get__(None, int) + except TypeError: + pass + else: + self.fail("shouldn't have allowed descr.__get__(None, int)") + + def test_isinst_isclass(self): + # Testing proxy isinstance() and isclass()... + class Proxy(object): + def __init__(self, obj): + self.__obj = obj + def __getattribute__(self, name): + if name.startswith("_Proxy__"): + return object.__getattribute__(self, name) + else: + return getattr(self.__obj, name) + # Test with a classic class + class C: + pass + a = C() + pa = Proxy(a) + self.assert_(isinstance(a, C)) # Baseline + self.assert_(isinstance(pa, C)) # Test + # Test with a classic subclass class D(C): pass - # Now it should work - x = C() - y = pickle.loads(pickle.dumps(x)) - vereq(hasattr(y, 'a'), 0) - x.a = 42 - y = pickle.loads(pickle.dumps(x)) - vereq(y.a, 42) - x = D() - x.a = 42 - x.b = 100 - y = pickle.loads(pickle.dumps(x)) - vereq(y.a + y.b, 142) - # A subclass that adds a slot should also work - class E(C): - __slots__ = ['b'] - x = E() - x.a = 42 - x.b = "foo" - y = pickle.loads(pickle.dumps(x)) - vereq(y.a, x.a) - vereq(y.b, x.b) - -def copies(): - if verbose: print("Testing copy.copy() and copy.deepcopy()...") - import copy - class C(object): - pass - - a = C() - a.foo = 12 - b = copy.copy(a) - vereq(b.__dict__, a.__dict__) - - a.bar = [1,2,3] - c = copy.copy(a) - vereq(c.bar, a.bar) - verify(c.bar is a.bar) - - d = copy.deepcopy(a) - vereq(d.__dict__, a.__dict__) - a.bar.append(4) - vereq(d.bar, [1,2,3]) - -def binopoverride(): - if verbose: print("Testing overrides of binary operations...") - class I(int): - def __repr__(self): - return "I(%r)" % int(self) - def __add__(self, other): - return I(int(self) + int(other)) - __radd__ = __add__ - def __pow__(self, other, mod=None): - if mod is None: - return I(pow(int(self), int(other))) - else: - return I(pow(int(self), int(other), int(mod))) - def __rpow__(self, other, mod=None): - if mod is None: - return I(pow(int(other), int(self), mod)) - else: - return I(pow(int(other), int(self), int(mod))) + a = D() + pa = Proxy(a) + self.assert_(isinstance(a, C)) # Baseline + self.assert_(isinstance(pa, C)) # Test + # Test with a new-style class + class C(object): + pass + a = C() + pa = Proxy(a) + self.assert_(isinstance(a, C)) # Baseline + self.assert_(isinstance(pa, C)) # Test + # Test with a new-style subclass + class D(C): + pass + a = D() + pa = Proxy(a) + self.assert_(isinstance(a, C)) # Baseline + self.assert_(isinstance(pa, C)) # Test + + def test_proxy_super(self): + # Testing super() for a proxy object... + class Proxy(object): + def __init__(self, obj): + self.__obj = obj + def __getattribute__(self, name): + if name.startswith("_Proxy__"): + return object.__getattribute__(self, name) + else: + return getattr(self.__obj, name) + + class B(object): + def f(self): + return "B.f" + + class C(B): + def f(self): + return super(C, self).f() + "->C.f" + + obj = C() + p = Proxy(obj) + self.assertEqual(C.__dict__["f"](p), "B.f->C.f") - vereq(repr(I(1) + I(2)), "I(3)") - vereq(repr(I(1) + 2), "I(3)") - vereq(repr(1 + I(2)), "I(3)") - vereq(repr(I(2) ** I(3)), "I(8)") - vereq(repr(2 ** I(3)), "I(8)") - vereq(repr(I(2) ** 3), "I(8)") - vereq(repr(pow(I(2), I(3), I(5))), "I(3)") - class S(str): - def __eq__(self, other): - return self.lower() == other.lower() - -def subclasspropagation(): - if verbose: print("Testing propagation of slot functions to subclasses...") - class A(object): - pass - class B(A): - pass - class C(A): - pass - class D(B, C): - pass - d = D() - orig_hash = hash(d) # related to id(d) in platform-dependent ways - A.__hash__ = lambda self: 42 - vereq(hash(d), 42) - C.__hash__ = lambda self: 314 - vereq(hash(d), 314) - B.__hash__ = lambda self: 144 - vereq(hash(d), 144) - D.__hash__ = lambda self: 100 - vereq(hash(d), 100) - del D.__hash__ - vereq(hash(d), 144) - del B.__hash__ - vereq(hash(d), 314) - del C.__hash__ - vereq(hash(d), 42) - del A.__hash__ - vereq(hash(d), orig_hash) - d.foo = 42 - d.bar = 42 - vereq(d.foo, 42) - vereq(d.bar, 42) - def __getattribute__(self, name): - if name == "foo": - return 24 - return object.__getattribute__(self, name) - A.__getattribute__ = __getattribute__ - vereq(d.foo, 24) - vereq(d.bar, 42) - def __getattr__(self, name): - if name in ("spam", "foo", "bar"): - return "hello" - raise AttributeError(name) - B.__getattr__ = __getattr__ - vereq(d.spam, "hello") - vereq(d.foo, 24) - vereq(d.bar, 42) - del A.__getattribute__ - vereq(d.foo, 42) - del d.foo - vereq(d.foo, "hello") - vereq(d.bar, 42) - del B.__getattr__ - try: - d.foo - except AttributeError: - pass - else: - raise TestFailed("d.foo should be undefined now") - - # Test a nasty bug in recurse_down_subclasses() - import gc - class A(object): - pass - class B(A): - pass - del B - gc.collect() - A.__setitem__ = lambda *a: None # crash - -def buffer_inherit(): - import binascii - # SF bug [#470040] ParseTuple t# vs subclasses. - if verbose: - print("Testing that buffer interface is inherited ...") - - class MyStr(str): - pass - base = 'abc' - m = MyStr(base) - # b2a_hex uses the buffer interface to get its argument's value, via - # PyArg_ParseTuple 't#' code. - vereq(binascii.b2a_hex(m), binascii.b2a_hex(base)) - - # It's not clear that unicode will continue to support the character - # buffer interface, and this test will fail if that's taken away. - class MyUni(str): - pass - base = 'abc' - m = MyUni(base) - vereq(binascii.b2a_hex(m), binascii.b2a_hex(base)) - - class MyInt(int): - pass - m = MyInt(42) - try: - binascii.b2a_hex(m) - raise TestFailed('subclass of int should not have a buffer interface') - except TypeError: - pass - -def str_of_str_subclass(): - import binascii - import io - - if verbose: - print("Testing __str__ defined in subclass of str ...") - - class octetstring(str): - def __str__(self): - return binascii.b2a_hex(self).decode("ascii") - def __repr__(self): - return self + " repr" - - o = octetstring('A') - vereq(type(o), octetstring) - vereq(type(str(o)), str) - vereq(type(repr(o)), str) - vereq(ord(o), 0x41) - vereq(str(o), '41') - vereq(repr(o), 'A repr') - vereq(o.__str__(), '41') - vereq(o.__repr__(), 'A repr') - - capture = io.StringIO() - # Calling str() or not exercises different internal paths. - print(o, file=capture) - print(str(o), file=capture) - vereq(capture.getvalue(), '41\n41\n') - capture.close() - -def kwdargs(): - if verbose: print("Testing keyword arguments to __init__, __call__...") - def f(a): return a - vereq(f.__call__(a=42), 42) - a = [] - list.__init__(a, sequence=[0, 1, 2]) - vereq(a, [0, 1, 2]) - -def recursive__call__(): - if verbose: print(("Testing recursive __call__() by setting to instance of " - "class ...")) - class A(object): - pass - - A.__call__ = A() - try: - A()() - except RuntimeError: - pass - else: - raise TestFailed("Recursion limit should have been reached for " - "__call__()") - -def delhook(): - if verbose: print("Testing __del__ hook...") - log = [] - class C(object): - def __del__(self): - log.append(1) - c = C() - vereq(log, []) - del c - vereq(log, [1]) - - class D(object): pass - d = D() - try: del d[0] - except TypeError: pass - else: raise TestFailed("invalid del() didn't raise TypeError") - -def hashinherit(): - if verbose: print("Testing hash of mutable subclasses...") - - class mydict(dict): - pass - d = mydict() - try: - hash(d) - except TypeError: - pass - else: - raise TestFailed("hash() of dict subclass should fail") - - class mylist(list): - pass - d = mylist() - try: - hash(d) - except TypeError: - pass - else: - raise TestFailed("hash() of list subclass should fail") - -def strops(): - try: 'a' + 5 - except TypeError: pass - else: raise TestFailed("'' + 5 doesn't raise TypeError") - - try: ''.split('') - except ValueError: pass - else: raise TestFailed("''.split('') doesn't raise ValueError") - - try: ''.rindex('5') - except ValueError: pass - else: raise TestFailed("''.rindex('5') doesn't raise ValueError") - - try: '%(n)s' % None - except TypeError: pass - else: raise TestFailed("'%(n)s' % None doesn't raise TypeError") - - try: '%(n' % {} - except ValueError: pass - else: raise TestFailed("'%(n' % {} '' doesn't raise ValueError") - - try: '%*s' % ('abc') - except TypeError: pass - else: raise TestFailed("'%*s' % ('abc') doesn't raise TypeError") - - try: '%*.*s' % ('abc', 5) - except TypeError: pass - else: raise TestFailed("'%*.*s' % ('abc', 5) doesn't raise TypeError") - - try: '%s' % (1, 2) - except TypeError: pass - else: raise TestFailed("'%s' % (1, 2) doesn't raise TypeError") - - try: '%' % None - except ValueError: pass - else: raise TestFailed("'%' % None doesn't raise ValueError") - - vereq('534253'.isdigit(), 1) - vereq('534253x'.isdigit(), 0) - vereq('%c' % 5, '\x05') - vereq('%c' % '5', '5') - -def deepcopyrecursive(): - if verbose: print("Testing deepcopy of recursive objects...") - class Node: - pass - a = Node() - b = Node() - a.b = b - b.a = a - z = deepcopy(a) # This blew up before - -def modules(): - if verbose: print("Testing uninitialized module objects...") - from types import ModuleType as M - m = M.__new__(M) - str(m) - vereq(hasattr(m, "__name__"), 0) - vereq(hasattr(m, "__file__"), 0) - vereq(hasattr(m, "foo"), 0) - vereq(m.__dict__, None) - m.foo = 1 - vereq(m.__dict__, {"foo": 1}) - -def dictproxyiterkeys(): - class C(object): - def meth(self): - pass - if verbose: print("Testing dict-proxy iterkeys...") - keys = [ key for key in C.__dict__.keys() ] - keys.sort() - vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth']) - -def dictproxyitervalues(): - class C(object): - def meth(self): - pass - if verbose: print("Testing dict-proxy itervalues...") - values = [ values for values in C.__dict__.values() ] - vereq(len(values), 5) - -def dictproxyiteritems(): - class C(object): - def meth(self): - pass - if verbose: print("Testing dict-proxy iteritems...") - keys = [ key for (key, value) in C.__dict__.items() ] - keys.sort() - vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth']) - -def funnynew(): - if verbose: print("Testing __new__ returning something unexpected...") - class C(object): - def __new__(cls, arg): - if isinstance(arg, str): return [1, 2, 3] - elif isinstance(arg, int): return object.__new__(D) - else: return object.__new__(cls) - class D(C): - def __init__(self, arg): - self.foo = arg - vereq(C("1"), [1, 2, 3]) - vereq(D("1"), [1, 2, 3]) - d = D(None) - veris(d.foo, None) - d = C(1) - vereq(isinstance(d, D), True) - vereq(d.foo, 1) - d = D(1) - vereq(isinstance(d, D), True) - vereq(d.foo, 1) - -def imulbug(): - # SF bug 544647 - if verbose: print("Testing for __imul__ problems...") - class C(object): - def __imul__(self, other): - return (self, other) - x = C() - y = x - y *= 1.0 - vereq(y, (x, 1.0)) - y = x - y *= 2 - vereq(y, (x, 2)) - y = x - y *= 3 - vereq(y, (x, 3)) - y = x - y *= 1<<100 - vereq(y, (x, 1<<100)) - y = x - y *= None - vereq(y, (x, None)) - y = x - y *= "foo" - vereq(y, (x, "foo")) - -def docdescriptor(): - # SF bug 542984 - if verbose: print("Testing __doc__ descriptor...") - class DocDescr(object): - def __get__(self, object, otype): - if object: - object = object.__class__.__name__ + ' instance' - if otype: - otype = otype.__name__ - return 'object=%s; type=%s' % (object, otype) - class OldClass: - __doc__ = DocDescr() - class NewClass(object): - __doc__ = DocDescr() - vereq(OldClass.__doc__, 'object=None; type=OldClass') - vereq(OldClass().__doc__, 'object=OldClass instance; type=OldClass') - vereq(NewClass.__doc__, 'object=None; type=NewClass') - vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass') - -def copy_setstate(): - if verbose: - print("Testing that copy.*copy() correctly uses __setstate__...") - import copy - class C(object): - def __init__(self, foo=None): - self.foo = foo - self.__foo = foo - def setfoo(self, foo=None): - self.foo = foo - def getfoo(self): - return self.__foo - def __getstate__(self): - return [self.foo] - def __setstate__(self, lst): - assert len(lst) == 1 - self.__foo = self.foo = lst[0] - a = C(42) - a.setfoo(24) - vereq(a.foo, 24) - vereq(a.getfoo(), 42) - b = copy.copy(a) - vereq(b.foo, 24) - vereq(b.getfoo(), 24) - b = copy.deepcopy(a) - vereq(b.foo, 24) - vereq(b.getfoo(), 24) - -def slices(): - if verbose: - print("Testing cases with slices and overridden __getitem__ ...") - # Strings - vereq("hello"[:4], "hell") - vereq("hello"[slice(4)], "hell") - vereq(str.__getitem__("hello", slice(4)), "hell") - class S(str): - def __getitem__(self, x): - return str.__getitem__(self, x) - vereq(S("hello")[:4], "hell") - vereq(S("hello")[slice(4)], "hell") - vereq(S("hello").__getitem__(slice(4)), "hell") - # Tuples - vereq((1,2,3)[:2], (1,2)) - vereq((1,2,3)[slice(2)], (1,2)) - vereq(tuple.__getitem__((1,2,3), slice(2)), (1,2)) - class T(tuple): - def __getitem__(self, x): - return tuple.__getitem__(self, x) - vereq(T((1,2,3))[:2], (1,2)) - vereq(T((1,2,3))[slice(2)], (1,2)) - vereq(T((1,2,3)).__getitem__(slice(2)), (1,2)) - # Lists - vereq([1,2,3][:2], [1,2]) - vereq([1,2,3][slice(2)], [1,2]) - vereq(list.__getitem__([1,2,3], slice(2)), [1,2]) - class L(list): - def __getitem__(self, x): - return list.__getitem__(self, x) - vereq(L([1,2,3])[:2], [1,2]) - vereq(L([1,2,3])[slice(2)], [1,2]) - vereq(L([1,2,3]).__getitem__(slice(2)), [1,2]) - # Now do lists and __setitem__ - a = L([1,2,3]) - a[slice(1, 3)] = [3,2] - vereq(a, [1,3,2]) - a[slice(0, 2, 1)] = [3,1] - vereq(a, [3,1,2]) - a.__setitem__(slice(1, 3), [2,1]) - vereq(a, [3,2,1]) - a.__setitem__(slice(0, 2, 1), [2,3]) - vereq(a, [2,3,1]) - -def subtype_resurrection(): - if verbose: - print("Testing resurrection of new-style instance...") - - class C(object): - container = [] - - def __del__(self): - # resurrect the instance - C.container.append(self) - - c = C() - c.attr = 42 - # The most interesting thing here is whether this blows up, due to flawed - # GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug). - del c - - # If that didn't blow up, it's also interesting to see whether clearing - # the last container slot works: that will attempt to delete c again, - # which will cause c to get appended back to the container again "during" - # the del. - del C.container[-1] - vereq(len(C.container), 1) - vereq(C.container[-1].attr, 42) - - # Make c mortal again, so that the test framework with -l doesn't report - # it as a leak. - del C.__del__ - -def slottrash(): - # Deallocating deeply nested slotted trash caused stack overflows - if verbose: - print("Testing slot trash...") - class trash(object): - __slots__ = ['x'] - def __init__(self, x): - self.x = x - o = None - for i in range(50000): - o = trash(o) - del o - -def slotmultipleinheritance(): - # SF bug 575229, multiple inheritance w/ slots dumps core - class A(object): - __slots__=() - class B(object): - pass - class C(A,B) : - __slots__=() - vereq(C.__basicsize__, B.__basicsize__) - verify(hasattr(C, '__dict__')) - verify(hasattr(C, '__weakref__')) - C().x = 2 - -def testrmul(): - # SF patch 592646 - if verbose: - print("Testing correct invocation of __rmul__...") - class C(object): - def __mul__(self, other): - return "mul" - def __rmul__(self, other): - return "rmul" - a = C() - vereq(a*2, "mul") - vereq(a*2.2, "mul") - vereq(2*a, "rmul") - vereq(2.2*a, "rmul") - -def testipow(): - # [SF bug 620179] - if verbose: - print("Testing correct invocation of __ipow__...") - class C(object): - def __ipow__(self, other): - pass - a = C() - a **= 2 - -def do_this_first(): - if verbose: - print("Testing SF bug 551412 ...") - # This dumps core when SF bug 551412 isn't fixed -- - # but only when test_descr.py is run separately. - # (That can't be helped -- as soon as PyType_Ready() - # is called for PyLong_Type, the bug is gone.) - class UserLong(object): - def __pow__(self, *args): - pass - try: - pow(0, UserLong(), 0) - except: - pass - - if verbose: - print("Testing SF bug 570483...") - # Another segfault only when run early - # (before PyType_Ready(tuple) is called) - type.mro(tuple) - -def test_mutable_bases(): - if verbose: - print("Testing mutable bases...") - # stuff that should work: - class C(object): - pass - class C2(object): - def __getattribute__(self, attr): - if attr == 'a': - return 2 - else: - return super(C2, self).__getattribute__(attr) - def meth(self): - return 1 - class D(C): - pass - class E(D): - pass - d = D() - e = E() - D.__bases__ = (C,) - D.__bases__ = (C2,) - vereq(d.meth(), 1) - vereq(e.meth(), 1) - vereq(d.a, 2) - vereq(e.a, 2) - vereq(C2.__subclasses__(), [D]) - - # stuff that shouldn't: - class L(list): - pass - - try: - L.__bases__ = (dict,) - except TypeError: - pass - else: - raise TestFailed("shouldn't turn list subclass into dict subclass") - - try: - list.__bases__ = (dict,) - except TypeError: - pass - else: - raise TestFailed("shouldn't be able to assign to list.__bases__") - - try: - D.__bases__ = (C2, list) - except TypeError: - pass - else: - assert 0, "best_base calculation found wanting" - - try: - del D.__bases__ - except TypeError: - pass - else: - raise TestFailed("shouldn't be able to delete .__bases__") - - try: - D.__bases__ = () - except TypeError as msg: - if str(msg) == "a new-style class can't have only classic bases": - raise TestFailed("wrong error message for .__bases__ = ()") - else: - raise TestFailed("shouldn't be able to set .__bases__ to ()") - - try: - D.__bases__ = (D,) - except TypeError: - pass - else: - # actually, we'll have crashed by here... - raise TestFailed("shouldn't be able to create inheritance cycles") - - try: - D.__bases__ = (C, C) - except TypeError: - pass - else: - raise TestFailed("didn't detect repeated base classes") - - try: - D.__bases__ = (E,) - except TypeError: - pass - else: - raise TestFailed("shouldn't be able to create inheritance cycles") - -def test_mutable_bases_with_failing_mro(): - if verbose: - print("Testing mutable bases with failing mro...") - class WorkOnce(type): - def __new__(self, name, bases, ns): - self.flag = 0 - return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns) - def mro(self): - if self.flag > 0: - raise RuntimeError("bozo") - else: - self.flag += 1 - return type.mro(self) + def test_carloverre(self): + # Testing prohibition of Carlo Verre's hack... + try: + object.__setattr__(str, "foo", 42) + except TypeError: + pass + else: + self.fail("Carlo Verre __setattr__ suceeded!") + try: + object.__delattr__(str, "lower") + except TypeError: + pass + else: + self.fail("Carlo Verre __delattr__ succeeded!") + + def test_weakref_segfault(self): + # Testing weakref segfault... + # SF 742911 + import weakref - class WorkAlways(type): - def mro(self): - # this is here to make sure that .mro()s aren't called - # with an exception set (which was possible at one point). - # An error message will be printed in a debug build. - # What's a good way to test for this? - return type.mro(self) + class Provoker: + def __init__(self, referrent): + self.ref = weakref.ref(referrent) - class C(object): - pass + def __del__(self): + x = self.ref() - class C2(object): - pass + class Oops(object): + pass - class D(C): - pass + o = Oops() + o.whatever = Provoker(o) + del o + + def test_wrapper_segfault(self): + # SF 927248: deeply nested wrappers could cause stack overflow + f = lambda:None + for i in range(1000000): + f = f.__call__ + f = None + + def test_file_fault(self): + # Testing sys.stdout is changed in getattr... + import sys + class StdoutGuard: + def __getattr__(self, attr): + sys.stdout = sys.__stdout__ + raise RuntimeError("Premature access to sys.stdout.%s" % attr) + sys.stdout = StdoutGuard() + try: + print("Oops!") + except RuntimeError: + pass - class E(D): - pass + def test_vicious_descriptor_nonsense(self): + # Testing vicious_descriptor_nonsense... - class F(D, metaclass=WorkOnce): - pass + # A potential segfault spotted by Thomas Wouters in mail to + # python-dev 2003-04-17, turned into an example & fixed by Michael + # Hudson just less than four months later... + + class Evil(object): + def __hash__(self): + return hash('attr') + def __eq__(self, other): + del C.attr + return 0 - class G(D, metaclass=WorkAlways): - pass + class Descr(object): + def __get__(self, ob, type=None): + return 1 - # Immediate subclasses have their mro's adjusted in alphabetical - # order, so E's will get adjusted before adjusting F's fails. We - # check here that E's gets restored. + class C(object): + attr = Descr() - E_mro_before = E.__mro__ - D_mro_before = D.__mro__ + c = C() + c.__dict__[Evil()] = 0 - try: - D.__bases__ = (C2,) - except RuntimeError: - vereq(E.__mro__, E_mro_before) - vereq(D.__mro__, D_mro_before) - else: - raise TestFailed("exception not propagated") - -def test_mutable_bases_catch_mro_conflict(): - if verbose: - print("Testing mutable bases catch mro conflict...") - class A(object): - pass - - class B(object): - pass - - class C(A, B): - pass - - class D(A, B): - pass - - class E(C, D): - pass - - try: - C.__bases__ = (B, A) - except TypeError: - pass - else: - raise TestFailed("didn't catch MRO conflict") - -def mutable_names(): - if verbose: - print("Testing mutable names...") - class C(object): - pass - - # C.__module__ could be 'test_descr' or '__main__' - mod = C.__module__ - - C.__name__ = 'D' - vereq((C.__module__, C.__name__), (mod, 'D')) - - C.__name__ = 'D.E' - vereq((C.__module__, C.__name__), (mod, 'D.E')) - -def subclass_right_op(): - if verbose: - print("Testing correct dispatch of subclass overloading __r__...") - - # This code tests various cases where right-dispatch of a subclass - # should be preferred over left-dispatch of a base class. - - # Case 1: subclass of int; this tests code in abstract.c::binary_op1() - - class B(int): - def __floordiv__(self, other): - return "B.__floordiv__" - def __rfloordiv__(self, other): - return "B.__rfloordiv__" - - vereq(B(1) // 1, "B.__floordiv__") - vereq(1 // B(1), "B.__rfloordiv__") - - # Case 2: subclass of object; this is just the baseline for case 3 - - class C(object): - def __floordiv__(self, other): - return "C.__floordiv__" - def __rfloordiv__(self, other): - return "C.__rfloordiv__" - - vereq(C() // 1, "C.__floordiv__") - vereq(1 // C(), "C.__rfloordiv__") - - # Case 3: subclass of new-style class; here it gets interesting - - class D(C): - def __floordiv__(self, other): - return "D.__floordiv__" - def __rfloordiv__(self, other): - return "D.__rfloordiv__" - - vereq(D() // C(), "D.__floordiv__") - vereq(C() // D(), "D.__rfloordiv__") - - # Case 4: this didn't work right in 2.2.2 and 2.3a1 - - class E(C): - pass - - vereq(E.__rfloordiv__, C.__rfloordiv__) - - vereq(E() // 1, "C.__floordiv__") - vereq(1 // E(), "C.__rfloordiv__") - vereq(E() // C(), "C.__floordiv__") - vereq(C() // E(), "C.__floordiv__") # This one would fail - -def dict_type_with_metaclass(): - if verbose: - print("Testing type of __dict__ when metaclass set...") - - class B(object): - pass - class M(type): - pass - class C(metaclass=M): - # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy - pass - veris(type(C.__dict__), type(B.__dict__)) - -def meth_class_get(): - # Full coverage of descrobject.c::classmethod_get() - if verbose: - print("Testing __get__ method of METH_CLASS C methods...") - # Baseline - arg = [1, 2, 3] - res = {1: None, 2: None, 3: None} - vereq(dict.fromkeys(arg), res) - vereq({}.fromkeys(arg), res) - # Now get the descriptor - descr = dict.__dict__["fromkeys"] - # More baseline using the descriptor directly - vereq(descr.__get__(None, dict)(arg), res) - vereq(descr.__get__({})(arg), res) - # Now check various error cases - try: - descr.__get__(None, None) - except TypeError: - pass - else: - raise TestFailed("shouldn't have allowed descr.__get__(None, None)") - try: - descr.__get__(42) - except TypeError: - pass - else: - raise TestFailed("shouldn't have allowed descr.__get__(42)") - try: - descr.__get__(None, 42) - except TypeError: - pass - else: - raise TestFailed("shouldn't have allowed descr.__get__(None, 42)") - try: - descr.__get__(None, int) - except TypeError: - pass - else: - raise TestFailed("shouldn't have allowed descr.__get__(None, int)") - -def isinst_isclass(): - if verbose: - print("Testing proxy isinstance() and isclass()...") - class Proxy(object): - def __init__(self, obj): - self.__obj = obj - def __getattribute__(self, name): - if name.startswith("_Proxy__"): - return object.__getattribute__(self, name) - else: - return getattr(self.__obj, name) - # Test with a classic class - class C: - pass - a = C() - pa = Proxy(a) - verify(isinstance(a, C)) # Baseline - verify(isinstance(pa, C)) # Test - # Test with a classic subclass - class D(C): - pass - a = D() - pa = Proxy(a) - verify(isinstance(a, C)) # Baseline - verify(isinstance(pa, C)) # Test - # Test with a new-style class - class C(object): - pass - a = C() - pa = Proxy(a) - verify(isinstance(a, C)) # Baseline - verify(isinstance(pa, C)) # Test - # Test with a new-style subclass - class D(C): - pass - a = D() - pa = Proxy(a) - verify(isinstance(a, C)) # Baseline - verify(isinstance(pa, C)) # Test - -def proxysuper(): - if verbose: - print("Testing super() for a proxy object...") - class Proxy(object): - def __init__(self, obj): - self.__obj = obj - def __getattribute__(self, name): - if name.startswith("_Proxy__"): - return object.__getattribute__(self, name) + self.assertEqual(c.attr, 1) + # this makes a crash more likely: + import gc; gc.collect() + self.assertEqual(hasattr(c, 'attr'), False) + + def test_init(self): + # SF 1155938 + class Foo(object): + def __init__(self): + return 10 + try: + Foo() + except TypeError: + pass + else: + self.fail("did not test __init__() for None return") + + def test_method_wrapper(self): + # Testing method-wrapper objects... + # did not support any reflection before 2.5 + + return # XXX should methods really support __eq__? + + l = [] + self.assertEqual(l.__add__, l.__add__) + self.assertEqual(l.__add__, [].__add__) + self.assert_(l.__add__ != [5].__add__) + self.assert_(l.__add__ != l.__mul__) + self.assert_(l.__add__.__name__ == '__add__') + self.assert_(l.__add__.__self__ is l) + self.assert_(l.__add__.__objclass__ is list) + self.assertEqual(l.__add__.__doc__, list.__add__.__doc__) + try: + hash(l.__add__) + except TypeError: + pass + else: + self.fail("no TypeError from hash([].__add__)") + + t = () + t += (7,) + self.assertEqual(t.__add__, (7,).__add__) + self.assertEqual(hash(t.__add__), hash((7,).__add__)) + + def test_not_implemented(self): + # Testing NotImplemented... + # all binary methods should be able to return a NotImplemented + import sys + import types + import operator + + def specialmethod(self, other): + return NotImplemented + + def check(expr, x, y): + try: + exec(expr, {'x': x, 'y': y, 'operator': operator}) + except TypeError: + pass else: - return getattr(self.__obj, name) + self.fail("no TypeError from %r" % (expr,)) - class B(object): - def f(self): - return "B.f" - - class C(B): - def f(self): - return super(C, self).f() + "->C.f" - - obj = C() - p = Proxy(obj) - vereq(C.__dict__["f"](p), "B.f->C.f") - -def carloverre(): - if verbose: - print("Testing prohibition of Carlo Verre's hack...") - try: - object.__setattr__(str, "foo", 42) - except TypeError: - pass - else: - raise TestFailed("Carlo Verre __setattr__ suceeded!") - try: - object.__delattr__(str, "lower") - except TypeError: - pass - else: - raise TestFailed("Carlo Verre __delattr__ succeeded!") - -def weakref_segfault(): - # SF 742911 - if verbose: - print("Testing weakref segfault...") - - import weakref - - class Provoker: - def __init__(self, referrent): - self.ref = weakref.ref(referrent) - - def __del__(self): - x = self.ref() - - class Oops(object): - pass - - o = Oops() - o.whatever = Provoker(o) - del o - -def wrapper_segfault(): - # SF 927248: deeply nested wrappers could cause stack overflow - if verbose: - print("Testing wrapper segfault...") - f = lambda:None - for i in range(1000000): - f = f.__call__ - f = None - -# Fix SF #762455, segfault when sys.stdout is changed in getattr -def filefault(): - if verbose: - print("Testing sys.stdout is changed in getattr...") - import sys - class StdoutGuard: - def __getattr__(self, attr): - sys.stdout = sys.__stdout__ - raise RuntimeError("Premature access to sys.stdout.%s" % attr) - sys.stdout = StdoutGuard() - try: - print("Oops!") - except RuntimeError: - pass - -def vicious_descriptor_nonsense(): - # A potential segfault spotted by Thomas Wouters in mail to - # python-dev 2003-04-17, turned into an example & fixed by Michael - # Hudson just less than four months later... - if verbose: - print("Testing vicious_descriptor_nonsense...") - - class Evil(object): - def __hash__(self): - return hash('attr') - def __eq__(self, other): - del C.attr - return 0 - - class Descr(object): - def __get__(self, ob, type=None): - return 1 - - class C(object): - attr = Descr() - - c = C() - c.__dict__[Evil()] = 0 - - vereq(c.attr, 1) - # this makes a crash more likely: - import gc; gc.collect() - vereq(hasattr(c, 'attr'), False) - -def test_init(): - # SF 1155938 - class Foo(object): - def __init__(self): - return 10 - try: - Foo() - except TypeError: - pass - else: - raise TestFailed("did not test __init__() for None return") - -def methodwrapper(): - # did not support any reflection before 2.5 - if verbose: - print("Testing method-wrapper objects...") - - return # XXX should methods really support __eq__? - - l = [] - vereq(l.__add__, l.__add__) - vereq(l.__add__, [].__add__) - verify(l.__add__ != [5].__add__) - verify(l.__add__ != l.__mul__) - verify(l.__add__.__name__ == '__add__') - verify(l.__add__.__self__ is l) - verify(l.__add__.__objclass__ is list) - vereq(l.__add__.__doc__, list.__add__.__doc__) - try: - hash(l.__add__) - except TypeError: - pass - else: - raise TestFailed("no TypeError from hash([].__add__)") - - t = () - t += (7,) - vereq(t.__add__, (7,).__add__) - vereq(hash(t.__add__), hash((7,).__add__)) - -def notimplemented(): - # all binary methods should be able to return a NotImplemented - if verbose: - print("Testing NotImplemented...") - - import sys - import types - import operator - - def specialmethod(self, other): - return NotImplemented - - def check(expr, x, y): - try: - exec(expr, {'x': x, 'y': y, 'operator': operator}) - except TypeError: - pass - else: - raise TestFailed("no TypeError from %r" % (expr,)) - - N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of TypeErrors - N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger - # ValueErrors instead of TypeErrors - if 1: - metaclass = type + N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of + # TypeErrors + N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger + # ValueErrors instead of TypeErrors for name, expr, iexpr in [ ('__add__', 'x + y', 'x += y'), ('__sub__', 'x - y', 'x -= y'), ('__mul__', 'x * y', 'x *= y'), - ('__truediv__', 'x / y', None), - ('__floordiv__', 'x // y', None), + ('__truediv__', 'operator.truediv(x, y)', None), + ('__floordiv__', 'operator.floordiv(x, y)', None), + ('__div__', 'x / y', 'x /= y'), ('__mod__', 'x % y', 'x %= y'), ('__divmod__', 'divmod(x, y)', None), ('__pow__', 'x ** y', 'x **= y'), @@ -4139,241 +3999,102 @@ ('__rshift__', 'x >> y', 'x >>= y'), ('__and__', 'x & y', 'x &= y'), ('__or__', 'x | y', 'x |= y'), - ('__xor__', 'x ^ y', 'x ^= y'), - ]: + ('__xor__', 'x ^ y', 'x ^= y')]: rname = '__r' + name[2:] - A = metaclass('A', (), {name: specialmethod}) - B = metaclass('B', (), {rname: specialmethod}) + A = type('A', (), {name: specialmethod}) a = A() - b = B() check(expr, a, a) - check(expr, a, b) - check(expr, b, a) - check(expr, b, b) check(expr, a, N1) check(expr, a, N2) - check(expr, N1, b) - check(expr, N2, b) if iexpr: check(iexpr, a, a) - check(iexpr, a, b) - check(iexpr, b, a) - check(iexpr, b, b) check(iexpr, a, N1) check(iexpr, a, N2) iname = '__i' + name[2:] - C = metaclass('C', (), {iname: specialmethod}) + C = type('C', (), {iname: specialmethod}) c = C() check(iexpr, c, a) - check(iexpr, c, b) check(iexpr, c, N1) check(iexpr, c, N2) -def test_assign_slice(): - # ceval.c's assign_slice used to check for - # tp->tp_as_sequence->sq_slice instead of - # tp->tp_as_sequence->sq_ass_slice - if verbose: - print("Testing assign_slice...") - - class C(object): - def __setitem__(self, idx, value): - self.value = value - - c = C() - c[1:2] = 3 - vereq(c.value, 3) - -def test_weakref_in_del_segfault(): - # This used to segfault until r60057 - if verbose: - print("Testing weakref in del segfault...") - - import weakref - global ref - - class Target(): - def __del__(self): - global ref - ref = weakref.ref(self) - - w = Target() - del w - del ref - -def test_borrowed_ref_3_segfault(): - # This used to segfault until r60224 - if verbose: - print("Testing borrowed ref 3 segfault...") - - class KeyFunc(object): - def __call__(self, n): - del d['key'] - return 1 - - d = {'key': KeyFunc()} - try: - min(range(10), **d) - except: - pass - -def test_borrowed_ref_4_segfault(): - # This used to segfault until r60224 - if verbose: - print("Testing borrowed ref 4 segfault...") + def test_assign_slice(self): + # ceval.c's assign_slice used to check for + # tp->tp_as_sequence->sq_slice instead of + # tp->tp_as_sequence->sq_ass_slice + + class C(object): + def __setitem__(self, idx, value): + self.value = value - import types - import builtins + c = C() + c[1:2] = 3 + self.assertEqual(c.value, 3) - class X(object): - def __getattr__(self, name): - # this is called with name == '__bases__' by PyObject_IsInstance() - # during the unbound method call -- it frees the unbound method - # itself before it invokes its im_func. - del builtins.__import__ - return () - - pseudoclass = X() - - class Y(object): - def __call__(self, *args): - # 'self' was freed already - return (self, args) - - # make an unbound method - orig_import = __import__ - try: - builtins.__import__ = types.MethodType(Y(), (pseudoclass, str)) - import spam - finally: - builtins.__import__ = orig_import - -def test_losing_dict_ref_segfault(): - # This used to segfault; - # derived from issue #1303614, test67.py - if verbose: - print("Testing losing dict ref segfault...") - - class Strange(object): - def __hash__(self): - return hash('hello') - - def __eq__(self, other): - x.__dict__ = {} # the old x.__dict__ is deallocated - return False - - class X(object): - pass - - v = 123 - x = X() - x.__dict__ = {Strange(): 42, 'hello': v+456} - x.hello +class DictProxyTests(unittest.TestCase): + def setUp(self): + class C(object): + def meth(self): + pass + self.C = C -def test_main(): - weakref_segfault() # Must be first, somehow - wrapper_segfault() # NB This one is slow - do_this_first() - class_docstrings() - lists() - dicts() - dict_constructor() - test_dir() - ints() - longs() - floats() - complexes() - spamlists() - spamdicts() - pydicts() - pylists() - metaclass() - pymods() - multi() - mro_disagreement() - diamond() - ex5() - monotonicity() - consistency_with_epg() - objects() - slots() - slotspecials() - dynamics() - errors() - classmethods() - classmethods_in_c() - staticmethods() - staticmethods_in_c() - classic() - compattr() - newslot() - altmro() - overloading() - methods() - specials() - recursions() - weakrefs() - properties() - properties_plus() - supers() - inherits() - keywords() - str_subclass_as_dict_key() - classic_comparisons() - rich_comparisons() - descrdoc() - setclass() - setdict() - pickles() - copies() - binopoverride() - subclasspropagation() - buffer_inherit() - str_of_str_subclass() - kwdargs() - recursive__call__() - delhook() - hashinherit() - strops() - deepcopyrecursive() - modules() - dictproxyiterkeys() - dictproxyitervalues() - dictproxyiteritems() - pickleslots() - funnynew() - imulbug() - docdescriptor() - copy_setstate() - slices() - subtype_resurrection() - slottrash() - slotmultipleinheritance() - testrmul() - testipow() - test_mutable_bases() - test_mutable_bases_with_failing_mro() - test_mutable_bases_catch_mro_conflict() - mutable_names() - subclass_right_op() - dict_type_with_metaclass() - meth_class_get() - isinst_isclass() - proxysuper() - carloverre() - filefault() - vicious_descriptor_nonsense() - test_init() - methodwrapper() - notimplemented() - test_assign_slice() - test_weakref_in_del_segfault() - test_borrowed_ref_3_segfault() - test_borrowed_ref_4_segfault() - test_losing_dict_ref_segfault() + def test_iter_keys(self): + # Testing dict-proxy iterkeys... + keys = [ key for key in self.C.__dict__.keys() ] + keys.sort() + self.assertEquals(keys, ['__dict__', '__doc__', '__module__', + '__weakref__', 'meth']) + + def test_iter_values(self): + # Testing dict-proxy itervalues... + values = [ values for values in self.C.__dict__.values() ] + self.assertEqual(len(values), 5) + + def test_iter_items(self): + # Testing dict-proxy iteritems... + keys = [ key for (key, value) in self.C.__dict__.items() ] + keys.sort() + self.assertEqual(keys, ['__dict__', '__doc__', '__module__', + '__weakref__', 'meth']) + + def test_dict_type_with_metaclass(self): + # Testing type of __dict__ when metaclass set... + class B(object): + pass + class M(type): + pass + class C(metaclass=M): + # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy + pass + self.assertEqual(type(C.__dict__), type(B.__dict__)) - if verbose: print("All OK") + +class PTypesLongInitTest(unittest.TestCase): + # This is in its own TestCase so that it can be run before any other tests. + def test_pytype_long_ready(self): + # Testing SF bug 551412 ... + + # This dumps core when SF bug 551412 isn't fixed -- + # but only when test_descr.py is run separately. + # (That can't be helped -- as soon as PyType_Ready() + # is called for PyLong_Type, the bug is gone.) + class UserLong(object): + def __pow__(self, *args): + pass + try: + pow(0, UserLong(), 0) + except: + pass + + # Another segfault only when run early + # (before PyType_Ready(tuple) is called) + type.mro(tuple) + + +def test_main(): + # Run all local test cases, with PTypesLongInitTest first. + test_support.run_unittest(PTypesLongInitTest, OperatorsTest, + ClassPropertiesAndMethods, DictProxyTests) if __name__ == "__main__": test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_descrtut.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_descrtut.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_descrtut.py Wed Apr 30 15:57:13 2008 @@ -39,7 +39,7 @@ >>> print(defaultdict) # show our type >>> print(type(defaultdict)) # its metatype - + >>> a = defaultdict(default=0.0) # create an instance >>> print(a) # show the instance {} @@ -149,11 +149,11 @@ For instance of built-in types, x.__class__ is now the same as type(x): >>> type([]) - + >>> [].__class__ - + >>> list - + >>> isinstance([], list) True >>> isinstance([], dict) @@ -196,6 +196,7 @@ '__setattr__', '__setitem__', '__str__', + '__subclasshook__', 'append', 'count', 'extend', @@ -345,7 +346,7 @@ >>> del property # unmask the builtin >>> property - + >>> class C(object): ... def __init__(self): Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_dict.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_dict.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_dict.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,7 @@ import unittest from test import test_support -import sys, UserDict, random, string +import sys, collections, random, string class DictTest(unittest.TestCase): @@ -13,12 +13,14 @@ def test_literal_constructor(self): # check literal constructor for different sized dicts (to exercise the BUILD_MAP oparg - items = [] - for n in range(400): + for n in (0, 1, 6, 256, 400): + items = [(''.join([random.choice(string.ascii_letters) + for j in range(8)]), + i) + for i in range(n)] + random.shuffle(items) dictliteral = '{' + ', '.join('%r: %d' % item for item in items) + '}' self.assertEqual(eval(dictliteral), dict(items)) - items.append((''.join([random.choice(string.ascii_letters) for j in range(8)]), n)) - random.shuffle(items) def test_bool(self): self.assert_(not {}) @@ -191,14 +193,6 @@ self.assertRaises(ValueError, {}.update, [(1, 2, 3)]) - # SF #1615701: make d.update(m) honor __getitem__() and keys() in dict subclasses - class KeyUpperDict(dict): - def __getitem__(self, key): - return key.upper() - d.clear() - d.update(KeyUpperDict.fromkeys('abc')) - self.assertEqual(d, {'a':'A', 'b':'B', 'c':'C'}) - def test_fromkeys(self): self.assertEqual(dict.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) d = {} @@ -217,10 +211,10 @@ self.assert_(type(dictlike().fromkeys('a')) is dictlike) class mydict(dict): def __new__(cls): - return UserDict.UserDict() + return collections.UserDict() ud = mydict.fromkeys('ab') self.assertEqual(ud, {'a':None, 'b':None}) - self.assert_(isinstance(ud, UserDict.UserDict)) + self.assert_(isinstance(ud, collections.UserDict)) self.assertRaises(TypeError, dict.fromkeys) class Exc(Exception): pass Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_dis.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_dis.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_dis.py Wed Apr 30 15:57:13 2008 @@ -1,6 +1,6 @@ # Minimal tests for dis module -from test.test_support import verbose, run_unittest +from test.test_support import run_unittest import unittest import sys import dis Deleted: python/branches/py3k-ctypes-pep3118/Lib/test/test_dl.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_dl.py Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,34 +0,0 @@ -#! /usr/bin/env python -"""Test dlmodule.c - Roger E. Masse revised strategy by Barry Warsaw -""" - -import dl -from test.test_support import verbose,TestSkipped - -sharedlibs = [ - ('/usr/lib/libc.so', 'getpid'), - ('/lib/libc.so.6', 'getpid'), - ('/usr/bin/cygwin1.dll', 'getpid'), - ('/usr/lib/libc.dylib', 'getpid'), - ] - -for s, func in sharedlibs: - try: - if verbose: - print('trying to open:', s, end=' ') - l = dl.open(s) - except dl.error as err: - if verbose: - print('failed', repr(str(err))) - pass - else: - if verbose: - print('succeeded...', end=' ') - l.call(func) - l.close() - if verbose: - print('worked!') - break -else: - raise TestSkipped('Could not open any shared libraries') Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_doctest3.txt ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_doctest3.txt (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_doctest3.txt Wed Apr 30 15:57:13 2008 @@ -2,4 +2,4 @@ Here we check that `__file__` is provided: >>> type(__file__) - + Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_docxmlrpc.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_docxmlrpc.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_docxmlrpc.py Wed Apr 30 15:57:13 2008 @@ -117,11 +117,11 @@ The documentation for the "add" method contains the test material. """ self.client.request("GET", "/") - response = self.client.getresponse() + response = self.client.getresponse().read() self.assert_( # This is ugly ... how can it be made better? -b"""
add(x, y)
Add two instances together. This follows PEP008, but has nothing
\nto do with RFC1952. Case should matter: pEp008 and rFC1952.  Things
\nthat start with http and ftp should be auto-linked, too:
\nhttp://google.com.
""" - in response.read()) +b"""
add(x, y)
Add two instances together. This follows PEP008, but has nothing
\nto do with RFC1952. Case should matter: pEp008 and rFC1952.  Things
\nthat start with http and ftp should be auto-linked, too:
\nhttp://google.com.
""" + in response, response) def test_system_methods(self): """Test the precense of three consecutive system.* methods. Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_dummy_threading.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_dummy_threading.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_dummy_threading.py Wed Apr 30 15:57:13 2008 @@ -1,72 +1,63 @@ -# Very rudimentary test of threading module - -# Create a bunch of threads, let each do some work, wait until all are done - -from test.test_support import verbose -import random +from test import test_support +import unittest import dummy_threading as _threading import time +class DummyThreadingTestCase(unittest.TestCase): -class TestThread(_threading.Thread): + class TestThread(_threading.Thread): - def run(self): + def run(self): + global running + global sema + global mutex + # Uncomment if testing another module, such as the real 'threading' + # module. + #delay = random.random() * 2 + delay = 0 + if test_support.verbose: + print('task', self.getName(), 'will run for', delay, 'sec') + sema.acquire() + mutex.acquire() + running += 1 + if test_support.verbose: + print(running, 'tasks are running') + mutex.release() + time.sleep(delay) + if test_support.verbose: + print('task', self.getName(), 'done') + mutex.acquire() + running -= 1 + if test_support.verbose: + print(self.getName(), 'is finished.', running, 'tasks are running') + mutex.release() + sema.release() + + def setUp(self): + self.numtasks = 10 + global sema + sema = _threading.BoundedSemaphore(value=3) + global mutex + mutex = _threading.RLock() global running - # Uncomment if testing another module, such as the real 'threading' - # module. - #delay = random.random() * 2 - delay = 0 - if verbose: - print('task', self.getName(), 'will run for', delay, 'sec') - sema.acquire() - mutex.acquire() - running = running + 1 - if verbose: - print(running, 'tasks are running') - mutex.release() - time.sleep(delay) - if verbose: - print('task', self.getName(), 'done') - mutex.acquire() - running = running - 1 - if verbose: - print(self.getName(), 'is finished.', running, 'tasks are running') - mutex.release() - sema.release() - -def starttasks(): - for i in range(numtasks): - t = TestThread(name=""%i) - threads.append(t) - t.start() + running = 0 + self.threads = [] + def test_tasks(self): + for i in range(self.numtasks): + t = self.TestThread(name=""%i) + self.threads.append(t) + t.start() + + if test_support.verbose: + print('waiting for all tasks to complete') + for t in self.threads: + t.join() + if test_support.verbose: + print('all tasks done') def test_main(): - # This takes about n/3 seconds to run (about n/3 clumps of tasks, times - # about 1 second per clump). - global numtasks - numtasks = 10 - - # no more than 3 of the 10 can run at once - global sema - sema = _threading.BoundedSemaphore(value=3) - global mutex - mutex = _threading.RLock() - global running - running = 0 - - global threads - threads = [] - - starttasks() - - if verbose: - print('waiting for all tasks to complete') - for t in threads: - t.join() - if verbose: - print('all tasks done') - + test_support.run_unittest(DummyThreadingTestCase) if __name__ == '__main__': Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_email.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_email.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_email.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,6 @@ # Copyright (C) 2001-2007 Python Software Foundation # email package unit tests -import unittest # The specific tests now live in Lib/email/test from email.test.test_email import suite from test import test_support Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_eof.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_eof.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_eof.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,6 @@ #! /usr/bin/env python """test script for a few new invalid token catches""" -import os import unittest from test import test_support Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_errno.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_errno.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_errno.py Wed Apr 30 15:57:13 2008 @@ -4,46 +4,37 @@ """ import errno -from test.test_support import verbose +from test import test_support +import unittest -errors = ['E2BIG', 'EACCES', 'EADDRINUSE', 'EADDRNOTAVAIL', 'EADV', - 'EAFNOSUPPORT', 'EAGAIN', 'EALREADY', 'EBADE', 'EBADF', - 'EBADFD', 'EBADMSG', 'EBADR', 'EBADRQC', 'EBADSLT', - 'EBFONT', 'EBUSY', 'ECHILD', 'ECHRNG', 'ECOMM', - 'ECONNABORTED', 'ECONNREFUSED', 'ECONNRESET', - 'EDEADLK', 'EDEADLOCK', 'EDESTADDRREQ', 'EDOM', - 'EDQUOT', 'EEXIST', 'EFAULT', 'EFBIG', 'EHOSTDOWN', - 'EHOSTUNREACH', 'EIDRM', 'EILSEQ', 'EINPROGRESS', - 'EINTR', 'EINVAL', 'EIO', 'EISCONN', 'EISDIR', - 'EL2HLT', 'EL2NSYNC', 'EL3HLT', 'EL3RST', 'ELIBACC', - 'ELIBBAD', 'ELIBEXEC', 'ELIBMAX', 'ELIBSCN', 'ELNRNG', - 'ELOOP', 'EMFILE', 'EMLINK', 'EMSGSIZE', 'EMULTIHOP', - 'ENAMETOOLONG', 'ENETDOWN', 'ENETRESET', 'ENETUNREACH', - 'ENFILE', 'ENOANO', 'ENOBUFS', 'ENOCSI', 'ENODATA', - 'ENODEV', 'ENOENT', 'ENOEXEC', 'ENOLCK', 'ENOLINK', - 'ENOMEM', 'ENOMSG', 'ENONET', 'ENOPKG', 'ENOPROTOOPT', - 'ENOSPC', 'ENOSR', 'ENOSTR', 'ENOSYS', 'ENOTBLK', - 'ENOTCONN', 'ENOTDIR', 'ENOTEMPTY', 'ENOTOBACCO', 'ENOTSOCK', - 'ENOTTY', 'ENOTUNIQ', 'ENXIO', 'EOPNOTSUPP', - 'EOVERFLOW', 'EPERM', 'EPFNOSUPPORT', 'EPIPE', - 'EPROTO', 'EPROTONOSUPPORT', 'EPROTOTYPE', - 'ERANGE', 'EREMCHG', 'EREMOTE', 'ERESTART', - 'EROFS', 'ESHUTDOWN', 'ESOCKTNOSUPPORT', 'ESPIPE', - 'ESRCH', 'ESRMNT', 'ESTALE', 'ESTRPIPE', 'ETIME', - 'ETIMEDOUT', 'ETOOMANYREFS', 'ETXTBSY', 'EUNATCH', - 'EUSERS', 'EWOULDBLOCK', 'EXDEV', 'EXFULL'] - -# -# This is a wee bit bogus since the module only conditionally adds -# errno constants if they have been defined by errno.h However, this -# test seems to work on SGI, Sparc & intel Solaris, and linux. -# -for error in errors: - try: - a = getattr(errno, error) - except AttributeError: - if verbose: - print('%s: not found' % error) - else: - if verbose: - print('%s: %d' % (error, a)) +std_c_errors = frozenset(['EDOM', 'ERANGE']) + +class ErrnoAttributeTests(unittest.TestCase): + + def test_for_improper_attributes(self): + # No unexpected attributes should be on the module. + for error_code in std_c_errors: + self.assert_(hasattr(errno, error_code), + "errno is missing %s" % error_code) + + def test_using_errorcode(self): + # Every key value in errno.errorcode should be on the module. + for value in errno.errorcode.values(): + self.assert_(hasattr(errno, value), 'no %s attr in errno' % value) + + +class ErrorcodeTests(unittest.TestCase): + + def test_attributes_in_errorcode(self): + for attribute in errno.__dict__.keys(): + if attribute.isupper(): + self.assert_(getattr(errno, attribute) in errno.errorcode, + 'no %s attr in errno.errorcode' % attribute) + + +def test_main(): + test_support.run_unittest(ErrnoAttributeTests, ErrorcodeTests) + + +if __name__ == '__main__': + test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_extcall.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_extcall.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_extcall.py Wed Apr 30 15:57:13 2008 @@ -1,275 +1,255 @@ -from test.test_support import verify, verbose, TestFailed, sortdict -from UserList import UserList -from UserDict import UserDict - -def e(a, b): - print(a, b) - -def f(*a, **k): - print(a, sortdict(k)) - -def g(x, *y, **z): - print(x, y, sortdict(z)) - -def h(j=1, a=2, h=3): - print(j, a, h) - -f() -f(1) -f(1, 2) -f(1, 2, 3) - -f(1, 2, 3, *(4, 5)) -f(1, 2, 3, *[4, 5]) -f(1, 2, 3, *UserList([4, 5])) -f(1, 2, 3, **{'a':4, 'b':5}) -f(1, 2, 3, *(4, 5), **{'a':6, 'b':7}) -f(1, 2, 3, x=4, y=5, *(6, 7), **{'a':8, 'b':9}) - - -f(1, 2, 3, **UserDict(a=4, b=5)) -f(1, 2, 3, *(4, 5), **UserDict(a=6, b=7)) -f(1, 2, 3, x=4, y=5, *(6, 7), **UserDict(a=8, b=9)) - - -# Verify clearing of SF bug #733667 -try: - e(c=3) -except TypeError: - pass -else: - print("should raise TypeError: e() got an unexpected keyword argument 'c'") - -try: - g() -except TypeError as err: - print("TypeError:", err) -else: - print("should raise TypeError: not enough arguments; expected 1, got 0") - -try: - g(*()) -except TypeError as err: - print("TypeError:", err) -else: - print("should raise TypeError: not enough arguments; expected 1, got 0") - -try: - g(*(), **{}) -except TypeError as err: - print("TypeError:", err) -else: - print("should raise TypeError: not enough arguments; expected 1, got 0") - -g(1) -g(1, 2) -g(1, 2, 3) -g(1, 2, 3, *(4, 5)) -class Nothing: pass -try: - g(*Nothing()) -except TypeError as attr: - pass -else: - print("should raise TypeError") - -class Nothing: - def __len__(self): - return 5 -try: - g(*Nothing()) -except TypeError as attr: - pass -else: - print("should raise TypeError") - -class Nothing: - def __len__(self): - return 5 - def __getitem__(self, i): - if i < 3: - return i - else: - raise IndexError(i) -g(*Nothing()) - -class Nothing: - def __init__(self): - self.c = 0 - def __iter__(self): - return self -try: - g(*Nothing()) -except TypeError as attr: - pass -else: - print("should raise TypeError") - -class Nothing: - def __init__(self): - self.c = 0 - def __iter__(self): - return self - def __next__(self): - if self.c == 4: - raise StopIteration - c = self.c - self.c += 1 - return c -g(*Nothing()) - -# make sure the function call doesn't stomp on the dictionary? -d = {'a': 1, 'b': 2, 'c': 3} -d2 = d.copy() -verify(d == d2) -g(1, d=4, **d) -print(sortdict(d)) -print(sortdict(d2)) -verify(d == d2, "function call modified dictionary") - -# what about willful misconduct? -def saboteur(**kw): - kw['x'] = locals() # yields a cyclic kw - return kw -d = {} -kw = saboteur(a=1, **d) -verify(d == {}) -# break the cycle -del kw['x'] - -try: - g(1, 2, 3, **{'x':4, 'y':5}) -except TypeError as err: - print(err) -else: - print("should raise TypeError: keyword parameter redefined") - -try: - g(1, 2, 3, a=4, b=5, *(6, 7), **{'a':8, 'b':9}) -except TypeError as err: - print(err) -else: - print("should raise TypeError: keyword parameter redefined") - -try: - f(**{1:2}) -except TypeError as err: - print(err) -else: - print("should raise TypeError: keywords must be strings") - -try: - h(**{'e': 2}) -except TypeError as err: - print(err) -else: - print("should raise TypeError: unexpected keyword argument: e") - -try: - h(*h) -except TypeError as err: - print(err) -else: - print("should raise TypeError: * argument must be a tuple") - -try: - dir(*h) -except TypeError as err: - print(err) -else: - print("should raise TypeError: * argument must be a tuple") - -try: - None(*h) -except TypeError as err: - print(err) -else: - print("should raise TypeError: * argument must be a tuple") - -try: - h(**h) -except TypeError as err: - print(err) -else: - print("should raise TypeError: ** argument must be a dictionary") - -try: - dir(**h) -except TypeError as err: - print(err) -else: - print("should raise TypeError: ** argument must be a dictionary") - -try: - None(**h) -except TypeError as err: - print(err) -else: - print("should raise TypeError: ** argument must be a dictionary") - -try: - dir(b=1,**{'b':1}) -except TypeError as err: - print(err) -else: - print("should raise TypeError: dir() got multiple values for keyword argument 'b'") - -def f2(*a, **b): - return a, b - -d = {} -for i in range(512): - key = 'k%d' % i - d[key] = i -a, b = f2(1, *(2, 3), **d) -print(len(a), len(b), b == d) - -class Foo: - def method(self, arg1, arg2): - return arg1 + arg2 - -x = Foo() -print(Foo.method(*(x, 1, 2))) -print(Foo.method(x, *(1, 2))) -print(Foo.method(*(1, 2, 3))) -print(Foo.method(1, *(2, 3))) - -# A PyCFunction that takes only positional parameters should allow an -# empty keyword dictionary to pass without a complaint, but raise a -# TypeError if the dictionary is non-empty. -id(1, **{}) -try: - id(1, **{"foo": 1}) -except TypeError: - pass -else: - raise TestFailed('expected TypeError; no exception raised') - -a, b, d, e, v, k = 'A', 'B', 'D', 'E', 'V', 'K' -funcs = [] -maxargs = {} -for args in ['', 'a', 'ab']: - for defargs in ['', 'd', 'de']: - for vararg in ['', 'v']: - for kwarg in ['', 'k']: - name = 'z' + args + defargs + vararg + kwarg - arglist = list(args) + ['%s="%s"' % (x, x) for x in defargs] - if vararg: arglist.append('*' + vararg) - if kwarg: arglist.append('**' + kwarg) - decl = (('def %s(%s): print("ok %s", a, b, d, e, v, ' + - 'type(k) is type ("") and k or sortdict(k))') - % (name, ', '.join(arglist), name)) - exec(decl) - func = eval(name) - funcs.append(func) - maxargs[func] = len(args + defargs) - -for name in ['za', 'zade', 'zabk', 'zabdv', 'zabdevk']: - func = eval(name) - for args in [(), (1, 2), (1, 2, 3, 4, 5)]: - for kwargs in ['', 'a', 'd', 'ad', 'abde']: - kwdict = {} - for k in kwargs: kwdict[k] = k + k - print(func.__name__, args, sortdict(kwdict), '->', end=' ') - try: func(*args, **kwdict) - except TypeError as err: print(err) +"""Doctest for method/function calls. + +We're going the use these types for extra testing + + >>> from collections import UserList + >>> from collections import UserDict + +We're defining four helper functions + + >>> def e(a,b): + ... print(a, b) + + >>> def f(*a, **k): + ... print(a, test_support.sortdict(k)) + + >>> def g(x, *y, **z): + ... print(x, y, test_support.sortdict(z)) + + >>> def h(j=1, a=2, h=3): + ... print(j, a, h) + +Argument list examples + + >>> f() + () {} + >>> f(1) + (1,) {} + >>> f(1, 2) + (1, 2) {} + >>> f(1, 2, 3) + (1, 2, 3) {} + >>> f(1, 2, 3, *(4, 5)) + (1, 2, 3, 4, 5) {} + >>> f(1, 2, 3, *[4, 5]) + (1, 2, 3, 4, 5) {} + >>> f(1, 2, 3, *UserList([4, 5])) + (1, 2, 3, 4, 5) {} + +Here we add keyword arguments + + >>> f(1, 2, 3, **{'a':4, 'b':5}) + (1, 2, 3) {'a': 4, 'b': 5} + >>> f(1, 2, 3, *[4, 5], **{'a':6, 'b':7}) + (1, 2, 3, 4, 5) {'a': 6, 'b': 7} + >>> f(1, 2, 3, x=4, y=5, *(6, 7), **{'a':8, 'b': 9}) + (1, 2, 3, 6, 7) {'a': 8, 'b': 9, 'x': 4, 'y': 5} + + >>> f(1, 2, 3, **UserDict(a=4, b=5)) + (1, 2, 3) {'a': 4, 'b': 5} + >>> f(1, 2, 3, *(4, 5), **UserDict(a=6, b=7)) + (1, 2, 3, 4, 5) {'a': 6, 'b': 7} + >>> f(1, 2, 3, x=4, y=5, *(6, 7), **UserDict(a=8, b=9)) + (1, 2, 3, 6, 7) {'a': 8, 'b': 9, 'x': 4, 'y': 5} + +Examples with invalid arguments (TypeErrors). We're also testing the function +names in the exception messages. + +Verify clearing of SF bug #733667 + + >>> e(c=4) + Traceback (most recent call last): + ... + TypeError: e() got an unexpected keyword argument 'c' + + >>> g() + Traceback (most recent call last): + ... + TypeError: g() takes at least 1 positional argument (0 given) + + >>> g(*()) + Traceback (most recent call last): + ... + TypeError: g() takes at least 1 positional argument (0 given) + + >>> g(*(), **{}) + Traceback (most recent call last): + ... + TypeError: g() takes at least 1 positional argument (0 given) + + >>> g(1) + 1 () {} + >>> g(1, 2) + 1 (2,) {} + >>> g(1, 2, 3) + 1 (2, 3) {} + >>> g(1, 2, 3, *(4, 5)) + 1 (2, 3, 4, 5) {} + + >>> class Nothing: pass + ... + >>> g(*Nothing()) + Traceback (most recent call last): + ... + TypeError: g() argument after * must be a sequence, not Nothing + + >>> class Nothing: + ... def __len__(self): return 5 + ... + + >>> g(*Nothing()) + Traceback (most recent call last): + ... + TypeError: g() argument after * must be a sequence, not Nothing + + >>> class Nothing(): + ... def __len__(self): return 5 + ... def __getitem__(self, i): + ... if i<3: return i + ... else: raise IndexError(i) + ... + + >>> g(*Nothing()) + 0 (1, 2) {} + + >>> class Nothing: + ... def __init__(self): self.c = 0 + ... def __iter__(self): return self + ... def __next__(self): + ... if self.c == 4: + ... raise StopIteration + ... c = self.c + ... self.c += 1 + ... return c + ... + + >>> g(*Nothing()) + 0 (1, 2, 3) {} + +Make sure that the function doesn't stomp the dictionary + + >>> d = {'a': 1, 'b': 2, 'c': 3} + >>> d2 = d.copy() + >>> g(1, d=4, **d) + 1 () {'a': 1, 'b': 2, 'c': 3, 'd': 4} + >>> d == d2 + True + +What about willful misconduct? + + >>> def saboteur(**kw): + ... kw['x'] = 'm' + ... return kw + + >>> d = {} + >>> kw = saboteur(a=1, **d) + >>> d + {} + + + >>> g(1, 2, 3, **{'x': 4, 'y': 5}) + Traceback (most recent call last): + ... + TypeError: g() got multiple values for keyword argument 'x' + + >>> f(**{1:2}) + Traceback (most recent call last): + ... + TypeError: f() keywords must be strings + + >>> h(**{'e': 2}) + Traceback (most recent call last): + ... + TypeError: h() got an unexpected keyword argument 'e' + + >>> h(*h) + Traceback (most recent call last): + ... + TypeError: h() argument after * must be a sequence, not function + + >>> dir(*h) + Traceback (most recent call last): + ... + TypeError: dir() argument after * must be a sequence, not function + + >>> None(*h) + Traceback (most recent call last): + ... + TypeError: NoneType object argument after * must be a sequence, \ +not function + + >>> h(**h) + Traceback (most recent call last): + ... + TypeError: h() argument after ** must be a mapping, not function + + >>> dir(**h) + Traceback (most recent call last): + ... + TypeError: dir() argument after ** must be a mapping, not function + + >>> None(**h) + Traceback (most recent call last): + ... + TypeError: NoneType object argument after ** must be a mapping, \ +not function + + >>> dir(b=1, **{'b': 1}) + Traceback (most recent call last): + ... + TypeError: dir() got multiple values for keyword argument 'b' + +Another helper function + + >>> def f2(*a, **b): + ... return a, b + + + >>> d = {} + >>> for i in range(512): + ... key = 'k%d' % i + ... d[key] = i + >>> a, b = f2(1, *(2,3), **d) + >>> len(a), len(b), b == d + (3, 512, True) + + >>> class Foo: + ... def method(self, arg1, arg2): + ... return arg1+arg2 + + >>> x = Foo() + >>> Foo.method(*(x, 1, 2)) + 3 + >>> Foo.method(x, *(1, 2)) + 3 + >>> Foo.method(*(1, 2, 3)) + 5 + >>> Foo.method(1, *[2, 3]) + 5 + +A PyCFunction that takes only positional parameters shoud allow an +empty keyword dictionary to pass without a complaint, but raise a +TypeError if te dictionary is not empty + + >>> try: + ... silence = id(1, *{}) + ... True + ... except: + ... False + True + + >>> id(1, **{'foo': 1}) + Traceback (most recent call last): + ... + TypeError: id() takes no keyword arguments + +""" + +from test import test_support + +def test_main(): + from test import test_extcall # self import + test_support.run_doctest(test_extcall, True) + +if __name__ == '__main__': + test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_fcntl.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_fcntl.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_fcntl.py Wed Apr 30 15:57:13 2008 @@ -1,69 +1,88 @@ -#! /usr/bin/env python """Test program for the fcntl C module. - OS/2+EMX doesn't support the file locking operations. - Roger E. Masse -""" -import struct -import fcntl -import os, sys -from test.test_support import verbose, TESTFN -filename = TESTFN +OS/2+EMX doesn't support the file locking operations. -try: - os.O_LARGEFILE -except AttributeError: - start_len = "ll" -else: - start_len = "qq" - -if sys.platform.startswith('atheos'): - start_len = "qq" - -if sys.platform in ('netbsd1', 'netbsd2', 'netbsd3', - 'Darwin1.2', 'darwin', - 'freebsd2', 'freebsd3', 'freebsd4', 'freebsd5', - 'freebsd6', 'freebsd7', 'freebsd8', - 'bsdos2', 'bsdos3', 'bsdos4', - 'openbsd', 'openbsd2', 'openbsd3', 'openbsd4'): - if struct.calcsize('l') == 8: - off_t = 'l' - pid_t = 'i' +""" +import fcntl +import os +import struct +import sys +import unittest +from test.test_support import verbose, TESTFN, unlink, run_unittest + +# TODO - Write tests for flock() and lockf(). + +def get_lockdata(): + if sys.platform.startswith('atheos'): + start_len = "qq" else: - off_t = 'lxxxx' - pid_t = 'l' - lockdata = struct.pack(off_t+off_t+pid_t+'hh', 0, 0, 0, fcntl.F_WRLCK, 0) -elif sys.platform in ['aix3', 'aix4', 'hp-uxB', 'unixware7']: - lockdata = struct.pack('hhlllii', fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0) -elif sys.platform in ['os2emx']: - lockdata = None -else: - lockdata = struct.pack('hh'+start_len+'hh', fcntl.F_WRLCK, 0, 0, 0, 0, 0) -if lockdata: - if verbose: - print('struct.pack: ', repr(lockdata)) - -# the example from the library docs -f = open(filename, 'w') -rv = fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) -if verbose: - print('Status from fcntl with O_NONBLOCK: ', rv) - -if sys.platform not in ['os2emx']: - rv = fcntl.fcntl(f.fileno(), fcntl.F_SETLKW, lockdata) - if verbose: - print('String from fcntl with F_SETLKW: ', repr(rv)) - -f.close() -os.unlink(filename) - - -# Again, but pass the file rather than numeric descriptor: -f = open(filename, 'w') -rv = fcntl.fcntl(f, fcntl.F_SETFL, os.O_NONBLOCK) + try: + os.O_LARGEFILE + except AttributeError: + start_len = "ll" + else: + start_len = "qq" + + if sys.platform in ('netbsd1', 'netbsd2', 'netbsd3', + 'Darwin1.2', 'darwin', + 'freebsd2', 'freebsd3', 'freebsd4', 'freebsd5', + 'freebsd6', 'freebsd7', 'freebsd8', + 'bsdos2', 'bsdos3', 'bsdos4', + 'openbsd', 'openbsd2', 'openbsd3', 'openbsd4'): + if struct.calcsize('l') == 8: + off_t = 'l' + pid_t = 'i' + else: + off_t = 'lxxxx' + pid_t = 'l' + lockdata = struct.pack(off_t + off_t + pid_t + 'hh', 0, 0, 0, + fcntl.F_WRLCK, 0) + elif sys.platform in ['aix3', 'aix4', 'hp-uxB', 'unixware7']: + lockdata = struct.pack('hhlllii', fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0) + elif sys.platform in ['os2emx']: + lockdata = None + else: + lockdata = struct.pack('hh'+start_len+'hh', fcntl.F_WRLCK, 0, 0, 0, 0, 0) + if lockdata: + if verbose: + print('struct.pack: ', repr(lockdata)) + return lockdata + +lockdata = get_lockdata() + +class TestFcntl(unittest.TestCase): + + def setUp(self): + self.f = None + + def tearDown(self): + if not self.f.closed: + self.f.close() + unlink(TESTFN) + + def test_fcntl_fileno(self): + # the example from the library docs + self.f = open(TESTFN, 'w') + rv = fcntl.fcntl(self.f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) + if verbose: + print('Status from fcntl with O_NONBLOCK: ', rv) + if sys.platform not in ['os2emx']: + rv = fcntl.fcntl(self.f.fileno(), fcntl.F_SETLKW, lockdata) + if verbose: + print('String from fcntl with F_SETLKW: ', repr(rv)) + self.f.close() + + def test_fcntl_file_descriptor(self): + # again, but pass the file rather than numeric descriptor + self.f = open(TESTFN, 'w') + rv = fcntl.fcntl(self.f, fcntl.F_SETFL, os.O_NONBLOCK) + if sys.platform not in ['os2emx']: + rv = fcntl.fcntl(self.f, fcntl.F_SETLKW, lockdata) + self.f.close() + -if sys.platform not in ['os2emx']: - rv = fcntl.fcntl(f, fcntl.F_SETLKW, lockdata) +def test_main(): + run_unittest(TestFcntl) -f.close() -os.unlink(filename) +if __name__ == '__main__': + test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_file.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_file.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_file.py Wed Apr 30 15:57:13 2008 @@ -5,7 +5,7 @@ from weakref import proxy from test.test_support import TESTFN, findfile, run_unittest -from UserList import UserList +from collections import UserList class AutoFileTests(unittest.TestCase): # file tests for which a test file is automatically set up Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_fileinput.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_fileinput.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_fileinput.py Wed Apr 30 15:57:13 2008 @@ -6,7 +6,7 @@ import unittest from test.test_support import verbose, TESTFN, run_unittest from test.test_support import unlink as safe_unlink -import sys, os, re +import sys, re from io import StringIO from fileinput import FileInput, hook_encoded @@ -34,6 +34,7 @@ def test_buffer_sizes(self): # First, run the tests with default and teeny buffer size. for round, bs in (0, 0), (1, 30): + t1 = t2 = t3 = t4 = None try: t1 = writeTmp(1, ["Line %s of file 1\n" % (i+1) for i in range(15)]) t2 = writeTmp(2, ["Line %s of file 2\n" % (i+1) for i in range(10)]) @@ -122,6 +123,7 @@ class FileInputTests(unittest.TestCase): def test_zero_byte_files(self): + t1 = t2 = t3 = t4 = None try: t1 = writeTmp(1, [""]) t2 = writeTmp(2, [""]) @@ -145,6 +147,7 @@ remove_tempfiles(t1, t2, t3, t4) def test_files_that_dont_end_with_newline(self): + t1 = t2 = None try: t1 = writeTmp(1, ["A\nB\nC"]) t2 = writeTmp(2, ["D\nE\nF"]) @@ -171,6 +174,7 @@ ## remove_tempfiles(t1) def test_fileno(self): + t1 = t2 = None try: t1 = writeTmp(1, ["A\nB"]) t2 = writeTmp(2, ["C\nD"]) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_fileio.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_fileio.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_fileio.py Wed Apr 30 15:57:13 2008 @@ -7,7 +7,7 @@ from weakref import proxy from test.test_support import TESTFN, findfile, run_unittest -from UserList import UserList +from collections import UserList import _fileio Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_float.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_float.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_float.py Wed Apr 30 15:57:13 2008 @@ -2,12 +2,12 @@ import unittest, struct import os from test import test_support +import math +from math import isinf, isnan +import operator -def isinf(x): - return x * 0.5 == x - -def isnan(x): - return x != x +INF = float("inf") +NAN = float("nan") class FormatFunctionsTestCase(unittest.TestCase): @@ -133,13 +133,10 @@ self.assertEqual(format(0.01, ''), '0.01') self.assertEqual(format(0.01, 'g'), '0.01') - self.assertEqual(format(0, 'f'), '0.000000') self.assertEqual(format(1.0, 'f'), '1.000000') - self.assertEqual(format(1, 'f'), '1.000000') self.assertEqual(format(-1.0, 'f'), '-1.000000') - self.assertEqual(format(-1, 'f'), '-1.000000') self.assertEqual(format( 1.0, ' f'), ' 1.000000') self.assertEqual(format(-1.0, ' f'), '-1.000000') @@ -152,6 +149,18 @@ # conversion to string should fail self.assertRaises(ValueError, format, 3.0, "s") + # other format specifiers shouldn't work on floats, + # in particular int specifiers + for format_spec in ([chr(x) for x in range(ord('a'), ord('z')+1)] + + [chr(x) for x in range(ord('A'), ord('Z')+1)]): + if not format_spec in 'eEfFgGn%': + self.assertRaises(ValueError, format, 0.0, format_spec) + self.assertRaises(ValueError, format, 1.0, format_spec) + self.assertRaises(ValueError, format, -1.0, format_spec) + self.assertRaises(ValueError, format, 1e100, format_spec) + self.assertRaises(ValueError, format, -1e100, format_spec) + self.assertRaises(ValueError, format, 1e-100, format_spec) + self.assertRaises(ValueError, format, -1e-100, format_spec) class ReprTestCase(unittest.TestCase): def test_repr(self): @@ -230,6 +239,17 @@ self.assertEqual(str(1e300 * 1e300 * 0), "nan") self.assertEqual(str(-1e300 * 1e300 * 0), "nan") + def notest_float_nan(self): + self.assert_(NAN.is_nan()) + self.failIf(INF.is_nan()) + self.failIf((0.).is_nan()) + + def notest_float_inf(self): + self.assert_(INF.is_inf()) + self.failIf(NAN.is_inf()) + self.failIf((0.).is_inf()) + + def test_main(): test_support.run_unittest( FormatFunctionsTestCase, Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_format.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_format.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_format.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,9 @@ from test.test_support import verbose, TestFailed import sys -from test.test_support import MAX_Py_ssize_t -maxsize = MAX_Py_ssize_t +import test.test_support as test_support +import unittest + +maxsize = test_support.MAX_Py_ssize_t # test string formatting operator (I am not sure if this is being tested # elsewhere but, surely, some of the given cases are *not* tested because @@ -11,7 +13,7 @@ overflowok = 1 overflowrequired = 0 -def testformat(formatstr, args, output=None): +def testformat(formatstr, args, output=None, limit=None): if verbose: if output: print("%r %% %r =? %r ..." %\ @@ -30,210 +32,232 @@ if verbose: print('no') print("overflow expected on %r %% %r" % (formatstr, args)) - elif output and result != output: + elif output and limit is None and result != output: + if verbose: + print('no') + #print("%r %% %r == %r != %r" %\ + # (formatstr, args, result, output)) + raise AssertionError("%r %% %r == %r != %r" % + (formatstr, args, result, output)) + # when 'limit' is specified, it determines how many characters + # must match exactly; lengths must always match. + # ex: limit=5, '12345678' matches '12345___' + # (mainly for floating point format tests for which an exact match + # can't be guaranteed due to rounding and representation errors) + elif output and limit is not None and ( + len(result)!=len(output) or result[:limit]!=output[:limit]): if verbose: print('no') - print("%r %% %r == %r != %r" %\ - (formatstr, args, result, output)) + print("%s %% %s == %s != %s" % \ + (repr(formatstr), repr(args), repr(result), repr(output))) else: if verbose: print('yes') -testformat("%.1d", (1,), "1") -testformat("%.*d", (sys.maxsize,1)) # expect overflow -testformat("%.100d", (1,), '0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001') -testformat("%#.117x", (1,), '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001') -testformat("%#.118x", (1,), '0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001') - -testformat("%f", (1.0,), "1.000000") -# these are trying to test the limits of the internal magic-number-length -# formatting buffer, if that number changes then these tests are less -# effective -testformat("%#.*g", (109, -1.e+49/3.)) -testformat("%#.*g", (110, -1.e+49/3.)) -testformat("%#.*g", (110, -1.e+100/3.)) - -# test some ridiculously large precision, expect overflow -testformat('%12.*f', (123456, 1.0)) - -# check for internal overflow validation on length of precision -overflowrequired = 1 -testformat("%#.*g", (110, -1.e+100/3.)) -testformat("%#.*G", (110, -1.e+100/3.)) -testformat("%#.*f", (110, -1.e+100/3.)) -testformat("%#.*F", (110, -1.e+100/3.)) -overflowrequired = 0 -# Formatting of long integers. Overflow is not ok -overflowok = 0 -testformat("%x", 10, "a") -testformat("%x", 100000000000, "174876e800") -testformat("%o", 10, "12") -testformat("%o", 100000000000, "1351035564000") -testformat("%d", 10, "10") -testformat("%d", 100000000000, "100000000000") - -big = 123456789012345678901234567890 -testformat("%d", big, "123456789012345678901234567890") -testformat("%d", -big, "-123456789012345678901234567890") -testformat("%5d", -big, "-123456789012345678901234567890") -testformat("%31d", -big, "-123456789012345678901234567890") -testformat("%32d", -big, " -123456789012345678901234567890") -testformat("%-32d", -big, "-123456789012345678901234567890 ") -testformat("%032d", -big, "-0123456789012345678901234567890") -testformat("%-032d", -big, "-123456789012345678901234567890 ") -testformat("%034d", -big, "-000123456789012345678901234567890") -testformat("%034d", big, "0000123456789012345678901234567890") -testformat("%0+34d", big, "+000123456789012345678901234567890") -testformat("%+34d", big, " +123456789012345678901234567890") -testformat("%34d", big, " 123456789012345678901234567890") -testformat("%.2d", big, "123456789012345678901234567890") -testformat("%.30d", big, "123456789012345678901234567890") -testformat("%.31d", big, "0123456789012345678901234567890") -testformat("%32.31d", big, " 0123456789012345678901234567890") - -big = 0x1234567890abcdef12345 # 21 hex digits -testformat("%x", big, "1234567890abcdef12345") -testformat("%x", -big, "-1234567890abcdef12345") -testformat("%5x", -big, "-1234567890abcdef12345") -testformat("%22x", -big, "-1234567890abcdef12345") -testformat("%23x", -big, " -1234567890abcdef12345") -testformat("%-23x", -big, "-1234567890abcdef12345 ") -testformat("%023x", -big, "-01234567890abcdef12345") -testformat("%-023x", -big, "-1234567890abcdef12345 ") -testformat("%025x", -big, "-0001234567890abcdef12345") -testformat("%025x", big, "00001234567890abcdef12345") -testformat("%0+25x", big, "+0001234567890abcdef12345") -testformat("%+25x", big, " +1234567890abcdef12345") -testformat("%25x", big, " 1234567890abcdef12345") -testformat("%.2x", big, "1234567890abcdef12345") -testformat("%.21x", big, "1234567890abcdef12345") -testformat("%.22x", big, "01234567890abcdef12345") -testformat("%23.22x", big, " 01234567890abcdef12345") -testformat("%-23.22x", big, "01234567890abcdef12345 ") -testformat("%X", big, "1234567890ABCDEF12345") -testformat("%#X", big, "0X1234567890ABCDEF12345") -testformat("%#x", big, "0x1234567890abcdef12345") -testformat("%#x", -big, "-0x1234567890abcdef12345") -testformat("%#.23x", -big, "-0x001234567890abcdef12345") -testformat("%#+.23x", big, "+0x001234567890abcdef12345") -testformat("%# .23x", big, " 0x001234567890abcdef12345") -testformat("%#+.23X", big, "+0X001234567890ABCDEF12345") -testformat("%#-+.23X", big, "+0X001234567890ABCDEF12345") -testformat("%#-+26.23X", big, "+0X001234567890ABCDEF12345") -testformat("%#-+27.23X", big, "+0X001234567890ABCDEF12345 ") -testformat("%#+27.23X", big, " +0X001234567890ABCDEF12345") -# next one gets two leading zeroes from precision, and another from the -# 0 flag and the width -testformat("%#+027.23X", big, "+0X0001234567890ABCDEF12345") -# same, except no 0 flag -testformat("%#+27.23X", big, " +0X001234567890ABCDEF12345") - -big = 0o12345670123456701234567012345670 # 32 octal digits -testformat("%o", big, "12345670123456701234567012345670") -testformat("%o", -big, "-12345670123456701234567012345670") -testformat("%5o", -big, "-12345670123456701234567012345670") -testformat("%33o", -big, "-12345670123456701234567012345670") -testformat("%34o", -big, " -12345670123456701234567012345670") -testformat("%-34o", -big, "-12345670123456701234567012345670 ") -testformat("%034o", -big, "-012345670123456701234567012345670") -testformat("%-034o", -big, "-12345670123456701234567012345670 ") -testformat("%036o", -big, "-00012345670123456701234567012345670") -testformat("%036o", big, "000012345670123456701234567012345670") -testformat("%0+36o", big, "+00012345670123456701234567012345670") -testformat("%+36o", big, " +12345670123456701234567012345670") -testformat("%36o", big, " 12345670123456701234567012345670") -testformat("%.2o", big, "12345670123456701234567012345670") -testformat("%.32o", big, "12345670123456701234567012345670") -testformat("%.33o", big, "012345670123456701234567012345670") -testformat("%34.33o", big, " 012345670123456701234567012345670") -testformat("%-34.33o", big, "012345670123456701234567012345670 ") -testformat("%o", big, "12345670123456701234567012345670") -testformat("%#o", big, "0o12345670123456701234567012345670") -testformat("%#o", -big, "-0o12345670123456701234567012345670") -testformat("%#.34o", -big, "-0o0012345670123456701234567012345670") -testformat("%#+.34o", big, "+0o0012345670123456701234567012345670") -testformat("%# .34o", big, " 0o0012345670123456701234567012345670") -testformat("%#-+.34o", big, "+0o0012345670123456701234567012345670") -testformat("%#-+39.34o", big, "+0o0012345670123456701234567012345670 ") -testformat("%#+39.34o", big, " +0o0012345670123456701234567012345670") -# next one gets one leading zero from precision -testformat("%.33o", big, "012345670123456701234567012345670") -# one leading zero from precision -testformat("%#.33o", big, "0o012345670123456701234567012345670") -# leading zero vanishes -testformat("%#.32o", big, "0o12345670123456701234567012345670") -# one leading zero from precision, and another from '0' flag & width -testformat("%034.33o", big, "0012345670123456701234567012345670") -# max width includes base marker; padding zeroes come after marker -testformat("%0#38.33o", big, "0o000012345670123456701234567012345670") -# padding spaces come before marker -testformat("%#36.33o", big, " 0o012345670123456701234567012345670") - -# Some small ints, in both Python int and long flavors). -testformat("%d", 42, "42") -testformat("%d", -42, "-42") -testformat("%#x", 1, "0x1") -testformat("%#X", 1, "0X1") -testformat("%#o", 1, "0o1") -testformat("%#o", 1, "0o1") -testformat("%#o", 0, "0o0") -testformat("%#o", 0, "0o0") -testformat("%o", 0, "0") -testformat("%d", 0, "0") -testformat("%#x", 0, "0x0") -testformat("%#X", 0, "0X0") - -testformat("%x", 0x42, "42") -testformat("%x", -0x42, "-42") - -testformat("%o", 0o42, "42") -testformat("%o", -0o42, "-42") -testformat("%o", 0o42, "42") -testformat("%o", -0o42, "-42") - -# Test exception for unknown format characters -if verbose: - print('Testing exceptions') +class FormatTest(unittest.TestCase): + def test_format(self): + testformat("%.1d", (1,), "1") + testformat("%.*d", (sys.maxsize,1)) # expect overflow + testformat("%.100d", (1,), '0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001') + testformat("%#.117x", (1,), '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001') + testformat("%#.118x", (1,), '0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001') + + testformat("%f", (1.0,), "1.000000") + # these are trying to test the limits of the internal magic-number-length + # formatting buffer, if that number changes then these tests are less + # effective + testformat("%#.*g", (109, -1.e+49/3.)) + testformat("%#.*g", (110, -1.e+49/3.)) + testformat("%#.*g", (110, -1.e+100/3.)) + # test some ridiculously large precision, expect overflow + testformat('%12.*f', (123456, 1.0)) + # check for internal overflow validation on length of precision + overflowrequired = 1 + testformat("%#.*g", (110, -1.e+100/3.)) + testformat("%#.*G", (110, -1.e+100/3.)) + testformat("%#.*f", (110, -1.e+100/3.)) + testformat("%#.*F", (110, -1.e+100/3.)) + overflowrequired = 0 + # Formatting of integers. Overflow is not ok + overflowok = 0 + testformat("%x", 10, "a") + testformat("%x", 100000000000, "174876e800") + testformat("%o", 10, "12") + testformat("%o", 100000000000, "1351035564000") + testformat("%d", 10, "10") + testformat("%d", 100000000000, "100000000000") + big = 123456789012345678901234567890 + testformat("%d", big, "123456789012345678901234567890") + testformat("%d", -big, "-123456789012345678901234567890") + testformat("%5d", -big, "-123456789012345678901234567890") + testformat("%31d", -big, "-123456789012345678901234567890") + testformat("%32d", -big, " -123456789012345678901234567890") + testformat("%-32d", -big, "-123456789012345678901234567890 ") + testformat("%032d", -big, "-0123456789012345678901234567890") + testformat("%-032d", -big, "-123456789012345678901234567890 ") + testformat("%034d", -big, "-000123456789012345678901234567890") + testformat("%034d", big, "0000123456789012345678901234567890") + testformat("%0+34d", big, "+000123456789012345678901234567890") + testformat("%+34d", big, " +123456789012345678901234567890") + testformat("%34d", big, " 123456789012345678901234567890") + testformat("%.2d", big, "123456789012345678901234567890") + testformat("%.30d", big, "123456789012345678901234567890") + testformat("%.31d", big, "0123456789012345678901234567890") + testformat("%32.31d", big, " 0123456789012345678901234567890") + testformat("%d", float(big), "123456________________________", 6) + big = 0x1234567890abcdef12345 # 21 hex digits + testformat("%x", big, "1234567890abcdef12345") + testformat("%x", -big, "-1234567890abcdef12345") + testformat("%5x", -big, "-1234567890abcdef12345") + testformat("%22x", -big, "-1234567890abcdef12345") + testformat("%23x", -big, " -1234567890abcdef12345") + testformat("%-23x", -big, "-1234567890abcdef12345 ") + testformat("%023x", -big, "-01234567890abcdef12345") + testformat("%-023x", -big, "-1234567890abcdef12345 ") + testformat("%025x", -big, "-0001234567890abcdef12345") + testformat("%025x", big, "00001234567890abcdef12345") + testformat("%0+25x", big, "+0001234567890abcdef12345") + testformat("%+25x", big, " +1234567890abcdef12345") + testformat("%25x", big, " 1234567890abcdef12345") + testformat("%.2x", big, "1234567890abcdef12345") + testformat("%.21x", big, "1234567890abcdef12345") + testformat("%.22x", big, "01234567890abcdef12345") + testformat("%23.22x", big, " 01234567890abcdef12345") + testformat("%-23.22x", big, "01234567890abcdef12345 ") + testformat("%X", big, "1234567890ABCDEF12345") + testformat("%#X", big, "0X1234567890ABCDEF12345") + testformat("%#x", big, "0x1234567890abcdef12345") + testformat("%#x", -big, "-0x1234567890abcdef12345") + testformat("%#.23x", -big, "-0x001234567890abcdef12345") + testformat("%#+.23x", big, "+0x001234567890abcdef12345") + testformat("%# .23x", big, " 0x001234567890abcdef12345") + testformat("%#+.23X", big, "+0X001234567890ABCDEF12345") + testformat("%#-+.23X", big, "+0X001234567890ABCDEF12345") + testformat("%#-+26.23X", big, "+0X001234567890ABCDEF12345") + testformat("%#-+27.23X", big, "+0X001234567890ABCDEF12345 ") + testformat("%#+27.23X", big, " +0X001234567890ABCDEF12345") + # next one gets two leading zeroes from precision, and another from the + # 0 flag and the width + testformat("%#+027.23X", big, "+0X0001234567890ABCDEF12345") + # same, except no 0 flag + testformat("%#+27.23X", big, " +0X001234567890ABCDEF12345") + testformat("%x", float(big), "123456_______________", 6) + big = 0o12345670123456701234567012345670 # 32 octal digits + testformat("%o", big, "12345670123456701234567012345670") + testformat("%o", -big, "-12345670123456701234567012345670") + testformat("%5o", -big, "-12345670123456701234567012345670") + testformat("%33o", -big, "-12345670123456701234567012345670") + testformat("%34o", -big, " -12345670123456701234567012345670") + testformat("%-34o", -big, "-12345670123456701234567012345670 ") + testformat("%034o", -big, "-012345670123456701234567012345670") + testformat("%-034o", -big, "-12345670123456701234567012345670 ") + testformat("%036o", -big, "-00012345670123456701234567012345670") + testformat("%036o", big, "000012345670123456701234567012345670") + testformat("%0+36o", big, "+00012345670123456701234567012345670") + testformat("%+36o", big, " +12345670123456701234567012345670") + testformat("%36o", big, " 12345670123456701234567012345670") + testformat("%.2o", big, "12345670123456701234567012345670") + testformat("%.32o", big, "12345670123456701234567012345670") + testformat("%.33o", big, "012345670123456701234567012345670") + testformat("%34.33o", big, " 012345670123456701234567012345670") + testformat("%-34.33o", big, "012345670123456701234567012345670 ") + testformat("%o", big, "12345670123456701234567012345670") + testformat("%#o", big, "0o12345670123456701234567012345670") + testformat("%#o", -big, "-0o12345670123456701234567012345670") + testformat("%#.34o", -big, "-0o0012345670123456701234567012345670") + testformat("%#+.34o", big, "+0o0012345670123456701234567012345670") + testformat("%# .34o", big, " 0o0012345670123456701234567012345670") + testformat("%#+.34o", big, "+0o0012345670123456701234567012345670") + testformat("%#-+.34o", big, "+0o0012345670123456701234567012345670") + testformat("%#-+37.34o", big, "+0o0012345670123456701234567012345670") + testformat("%#+37.34o", big, "+0o0012345670123456701234567012345670") + # next one gets one leading zero from precision + testformat("%.33o", big, "012345670123456701234567012345670") + # base marker shouldn't change that, since "0" is redundant + testformat("%#.33o", big, "0o012345670123456701234567012345670") + # but reduce precision, and base marker should add a zero + testformat("%#.32o", big, "0o12345670123456701234567012345670") + # one leading zero from precision, and another from "0" flag & width + testformat("%034.33o", big, "0012345670123456701234567012345670") + # base marker shouldn't change that + testformat("%0#34.33o", big, "0o012345670123456701234567012345670") + testformat("%o", float(big), "123456__________________________", 6) + # Some small ints, in both Python int and flavors). + testformat("%d", 42, "42") + testformat("%d", -42, "-42") + testformat("%d", 42, "42") + testformat("%d", -42, "-42") + testformat("%d", 42.0, "42") + testformat("%#x", 1, "0x1") + testformat("%#x", 1, "0x1") + testformat("%#X", 1, "0X1") + testformat("%#X", 1, "0X1") + testformat("%#x", 1.0, "0x1") + testformat("%#o", 1, "0o1") + testformat("%#o", 1, "0o1") + testformat("%#o", 0, "0o0") + testformat("%#o", 0, "0o0") + testformat("%o", 0, "0") + testformat("%o", 0, "0") + testformat("%d", 0, "0") + testformat("%d", 0, "0") + testformat("%#x", 0, "0x0") + testformat("%#x", 0, "0x0") + testformat("%#X", 0, "0X0") + testformat("%#X", 0, "0X0") + testformat("%x", 0x42, "42") + testformat("%x", -0x42, "-42") + testformat("%x", 0x42, "42") + testformat("%x", -0x42, "-42") + testformat("%x", float(0x42), "42") + testformat("%o", 0o42, "42") + testformat("%o", -0o42, "-42") + testformat("%o", 0o42, "42") + testformat("%o", -0o42, "-42") + testformat("%o", float(0o42), "42") + # Test exception for unknown format characters + if verbose: + print('Testing exceptions') + def test_exc(formatstr, args, exception, excmsg): + try: + testformat(formatstr, args) + except exception as exc: + if str(exc) == excmsg: + if verbose: + print("yes") + else: + if verbose: print('no') + print('Unexpected ', exception, ':', repr(str(exc))) + except: + if verbose: print('no') + print('Unexpected exception') + raise + else: + raise TestFailed('did not get expected exception: %s' % excmsg) + test_exc('abc %a', 1, ValueError, + "unsupported format character 'a' (0x61) at index 5") + #test_exc(unicode('abc %\u3000','raw-unicode-escape'), 1, ValueError, + # "unsupported format character '?' (0x3000) at index 5") + test_exc('%d', '1', TypeError, "%d format: a number is required, not str") + test_exc('%g', '1', TypeError, "a float is required") + test_exc('no format', '1', TypeError, + "not all arguments converted during string formatting") + test_exc('no format', '1', TypeError, + "not all arguments converted during string formatting") + + if maxsize == 2**31-1: + # crashes 2.2.1 and earlier: + try: + "%*d"%(maxsize, -127) + except MemoryError: + pass + else: + raise TestFailed('"%*d"%(maxsize, -127) should fail') -def test_exc(formatstr, args, exception, excmsg): - try: - testformat(formatstr, args) - except exception as exc: - if str(exc) == excmsg: - if verbose: - print("yes") - else: - if verbose: print('no') - print('Unexpected ', exception, ':', repr(str(exc))) - except: - if verbose: print('no') - print('Unexpected exception') - raise - else: - raise TestFailed('did not get expected exception: %s' % excmsg) +def test_main(): + test_support.run_unittest(FormatTest) -test_exc('abc %a', 1, ValueError, - "unsupported format character 'a' (0x61) at index 5") -test_exc(str(b'abc %\u3000', 'raw-unicode-escape'), 1, ValueError, - "unsupported format character '?' (0x3000) at index 5") - -test_exc('%d', '1', TypeError, "an integer is required") -test_exc('%g', '1', TypeError, "a float is required") -test_exc('no format', '1', TypeError, - "not all arguments converted during string formatting") -test_exc('no format', '1', TypeError, - "not all arguments converted during string formatting") -test_exc('no format', '1', TypeError, - "not all arguments converted during string formatting") -test_exc('no format', '1', TypeError, - "not all arguments converted during string formatting") -if maxsize == 2**31-1: - # crashes 2.2.1 and earlier: - try: - "%*d"%(maxsize, -127) - except MemoryError: - pass - else: - raise TestFailed('"%*d"%(maxsize, -127) should fail') +if __name__ == "__main__": + unittest.main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_frozen.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_frozen.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_frozen.py Wed Apr 30 15:57:13 2008 @@ -39,6 +39,18 @@ else: self.fail("import __phello__.foo should have failed") + if sys.platform != "mac": # On the Mac this import does succeed. + try: + import __phello__.foo + except ImportError: + pass + else: + self.fail("import __phello__.foo should have failed") + + del sys.modules['__hello__'] + del sys.modules['__phello__'] + del sys.modules['__phello__.spam'] + def test_main(): run_unittest(FrozenTests) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_ftplib.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_ftplib.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_ftplib.py Wed Apr 30 15:57:13 2008 @@ -6,32 +6,43 @@ from unittest import TestCase from test import test_support -def server(evt, ready): - serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - serv.settimeout(3) - serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - serv.bind(("", 9091)) +HOST = test_support.HOST + +# This function sets the evt 3 times: +# 1) when the connection is ready to be accepted. +# 2) when it is safe for the caller to close the connection +# 3) when we have closed the socket +def server(evt, serv): serv.listen(5) - ready.set() + + # (1) Signal the caller that we are ready to accept the connection. + evt.set() try: conn, addr = serv.accept() except socket.timeout: pass else: conn.send(b"1 Hola mundo\n") + # (2) Signal the caller that it is safe to close the socket. + evt.set() conn.close() finally: serv.close() + # (3) Signal the caller that we are done. evt.set() class GeneralTests(TestCase): def setUp(self): - ftplib.FTP.port = 9091 self.evt = threading.Event() - ready = threading.Event() - threading.Thread(target=server, args=(self.evt, ready)).start() - ready.wait() + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.sock.settimeout(3) + self.port = test_support.bind_port(self.sock) + threading.Thread(target=server, args=(self.evt,self.sock)).start() + # Wait for the server to be ready. + self.evt.wait() + self.evt.clear() + ftplib.FTP.port = self.port def tearDown(self): self.evt.wait() @@ -41,38 +52,44 @@ ftplib.FTP() # connects - ftp = ftplib.FTP("localhost") + ftp = ftplib.FTP(HOST) + self.evt.wait() ftp.sock.close() def testTimeoutDefault(self): # default - ftp = ftplib.FTP("localhost") + ftp = ftplib.FTP(HOST) self.assertTrue(ftp.sock.gettimeout() is None) + self.evt.wait() ftp.sock.close() def testTimeoutValue(self): # a value - ftp = ftplib.FTP("localhost", timeout=30) + ftp = ftplib.FTP(HOST, timeout=30) self.assertEqual(ftp.sock.gettimeout(), 30) + self.evt.wait() ftp.sock.close() def testTimeoutConnect(self): ftp = ftplib.FTP() - ftp.connect("localhost", timeout=30) + ftp.connect(HOST, timeout=30) self.assertEqual(ftp.sock.gettimeout(), 30) + self.evt.wait() ftp.sock.close() def testTimeoutDifferentOrder(self): ftp = ftplib.FTP(timeout=30) - ftp.connect("localhost") + ftp.connect(HOST) self.assertEqual(ftp.sock.gettimeout(), 30) + self.evt.wait() ftp.sock.close() def testTimeoutDirectAccess(self): ftp = ftplib.FTP() ftp.timeout = 30 - ftp.connect("localhost") + ftp.connect(HOST) self.assertEqual(ftp.sock.gettimeout(), 30) + self.evt.wait() ftp.sock.close() def testTimeoutNone(self): @@ -80,14 +97,14 @@ previous = socket.getdefaulttimeout() socket.setdefaulttimeout(30) try: - ftp = ftplib.FTP("localhost", timeout=None) + ftp = ftplib.FTP(HOST, timeout=None) finally: socket.setdefaulttimeout(previous) self.assertEqual(ftp.sock.gettimeout(), 30) + self.evt.wait() ftp.close() - def test_main(verbose=None): test_support.run_unittest(GeneralTests) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_funcattrs.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_funcattrs.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_funcattrs.py Wed Apr 30 15:57:13 2008 @@ -1,369 +1,233 @@ -from test.test_support import verbose, TestFailed, verify +from test import test_support import types +import unittest -class F: - def a(self): - pass - -def b(): - 'my docstring' - pass - -# __module__ is a special attribute -verify(b.__module__ == __name__) -verify(verify.__module__ == "test.test_support") - -# setting attributes on functions -try: - b.publish -except AttributeError: pass -else: raise TestFailed('expected AttributeError') - -if b.__dict__ != {}: - raise TestFailed('expected unassigned func.__dict__ to be {}') - -b.publish = 1 -if b.publish != 1: - raise TestFailed('function attribute not set to expected value') - -docstring = 'its docstring' -b.__doc__ = docstring -if b.__doc__ != docstring: - raise TestFailed('problem with setting __doc__ attribute') - -if 'publish' not in dir(b): - raise TestFailed('attribute not in dir()') - -try: - del b.__dict__ -except TypeError: pass -else: raise TestFailed('del func.__dict__ expected TypeError') - -b.publish = 1 -try: - b.__dict__ = None -except TypeError: pass -else: raise TestFailed('func.__dict__ = None expected TypeError') - -d = {'hello': 'world'} -b.__dict__ = d -if b.__dict__ is not d: - raise TestFailed('func.__dict__ assignment to dictionary failed') -if b.hello != 'world': - raise TestFailed('attribute after func.__dict__ assignment failed') - -f1 = F() -f2 = F() - -try: - F.a.publish -except AttributeError: pass -else: raise TestFailed('expected AttributeError') - -try: - f1.a.publish -except AttributeError: pass -else: raise TestFailed('expected AttributeError') - -# In Python 2.1 beta 1, we disallowed setting attributes on unbound methods -# (it was already disallowed on bound methods). See the PEP for details. -# In Python 3.0 unbound methods are gone. -F.a.publish = 1 - -if F.a.publish != 1: - raise TestFailed('unbound method attribute not set to expected value') - -if f1.a.publish != 1: - raise TestFailed('bound method attribute access did not work') - -if f2.a.publish != 1: - raise TestFailed('bound method attribute access did not work') - -if 'publish' not in dir(F.a): - raise TestFailed('attribute not in dir()') - -try: - f1.a.publish = 0 -except (AttributeError, TypeError): pass -else: raise TestFailed('expected AttributeError or TypeError') - -# try setting __dict__ -F.a.__dict__ = {'one': 11, 'two': 22, 'three': 33} - -if f1.a.two != 22: - raise TestFailed('setting __dict__') - -from UserDict import UserDict -d = UserDict({'four': 44, 'five': 55}) - -try: - F.a.__dict__ = d -except (AttributeError, TypeError): pass -else: raise TestFailed +class FuncAttrsTest(unittest.TestCase): + def setUp(self): + class F: + def a(self): + pass + def b(): + return 3 + self.fi = F() + self.F = F + self.b = b + + def cannot_set_attr(self, obj, name, value, exceptions): + try: + setattr(obj, name, value) + except exceptions: + pass + else: + self.fail("shouldn't be able to set %s to %r" % (name, value)) + try: + delattr(obj, name) + except exceptions: + pass + else: + self.fail("shouldn't be able to del %s" % name) + + +class FunctionPropertiesTest(FuncAttrsTest): + # Include the external setUp method that is common to all tests + def test_module(self): + self.assertEqual(self.b.__module__, __name__) + + def test_dir_includes_correct_attrs(self): + self.b.known_attr = 7 + self.assert_('known_attr' in dir(self.b), + "set attributes not in dir listing of method") + # Test on underlying function object of method + self.F.a.known_attr = 7 + self.assert_('known_attr' in dir(self.fi.a), "set attribute on function " + "implementations, should show up in next dir") + + def test_duplicate_function_equality(self): + # Body of `duplicate' is the exact same as self.b + def duplicate(): + 'my docstring' + return 3 + self.assertNotEqual(self.b, duplicate) + + def test_copying___code__(self): + def test(): pass + self.assertEqual(test(), None) + test.__code__ = self.b.__code__ + self.assertEqual(test(), 3) # self.b always returns 3, arbitrarily + + def test___globals__(self): + self.assertEqual(self.b.__globals__, globals()) + self.cannot_set_attr(self.b, '__globals__', 2, (AttributeError, TypeError)) + + def test___name__(self): + self.assertEqual(self.b.__name__, 'b') + self.b.__name__ = 'c' + self.assertEqual(self.b.__name__, 'c') + self.b.__name__ = 'd' + self.assertEqual(self.b.__name__, 'd') + # __name__ and __name__ must be a string + self.cannot_set_attr(self.b, '__name__', 7, TypeError) + # __name__ must be available when in restricted mode. Exec will raise + # AttributeError if __name__ is not available on f. + s = """def f(): pass\nf.__name__""" + exec(s, {'__builtins__': {}}) + # Test on methods, too + self.assertEqual(self.fi.a.__name__, 'a') + self.cannot_set_attr(self.fi.a, "__name__", 'a', AttributeError) + + def test___code__(self): + num_one, num_two = 7, 8 + def a(): pass + def b(): return 12 + def c(): return num_one + def d(): return num_two + def e(): return num_one, num_two + for func in [a, b, c, d, e]: + self.assertEqual(type(func.__code__), types.CodeType) + self.assertEqual(c(), 7) + self.assertEqual(d(), 8) + d.__code__ = c.__code__ + self.assertEqual(c.__code__, d.__code__) + self.assertEqual(c(), 7) + # self.assertEqual(d(), 7) + try: b.__code__ = c.__code__ + except ValueError: pass + else: self.fail( + "__code__ with different numbers of free vars should not be " + "possible") + try: e.__code__ = d.__code__ + except ValueError: pass + else: self.fail( + "__code__ with different numbers of free vars should not be " + "possible") + + def test_blank_func_defaults(self): + self.assertEqual(self.b.__defaults__, None) + del self.b.__defaults__ + self.assertEqual(self.b.__defaults__, None) + + def test_func_default_args(self): + def first_func(a, b): + return a+b + def second_func(a=1, b=2): + return a+b + self.assertEqual(first_func.__defaults__, None) + self.assertEqual(second_func.__defaults__, (1, 2)) + first_func.__defaults__ = (1, 2) + self.assertEqual(first_func.__defaults__, (1, 2)) + self.assertEqual(first_func(), 3) + self.assertEqual(first_func(3), 5) + self.assertEqual(first_func(3, 5), 8) + del second_func.__defaults__ + self.assertEqual(second_func.__defaults__, None) + try: second_func() + except TypeError: pass + else: self.fail( + "func_defaults does not update; deleting it does not remove " + "requirement") + +class ImplicitReferencesTest(FuncAttrsTest): + + def test___class__(self): + self.assertEqual(self.fi.a.__self__.__class__, self.F) + self.cannot_set_attr(self.fi.a, "__class__", self.F, TypeError) + + def test___func__(self): + self.assertEqual(self.fi.a.__func__, self.F.a) + self.cannot_set_attr(self.fi.a, "__func__", self.F.a, AttributeError) + + def test___self__(self): + self.assertEqual(self.fi.a.__self__, self.fi) + self.cannot_set_attr(self.fi.a, "__self__", self.fi, AttributeError) + + def test___func___non_method(self): + # Behavior should be the same when a method is added via an attr + # assignment + self.fi.id = types.MethodType(id, self.fi) + self.assertEqual(self.fi.id(), id(self.fi)) + # Test usage + try: self.fi.id.unknown_attr + except AttributeError: pass + else: self.fail("using unknown attributes should raise AttributeError") + # Test assignment and deletion + self.cannot_set_attr(self.fi.id, 'unknown_attr', 2, AttributeError) + +class ArbitraryFunctionAttrTest(FuncAttrsTest): + def test_set_attr(self): + self.b.known_attr = 7 + self.assertEqual(self.b.known_attr, 7) + try: self.fi.a.known_attr = 7 + except AttributeError: pass + else: self.fail("setting attributes on methods should raise error") + + def test_delete_unknown_attr(self): + try: del self.b.unknown_attr + except AttributeError: pass + else: self.fail("deleting unknown attribute should raise TypeError") + + def test_unset_attr(self): + for func in [self.b, self.fi.a]: + try: func.non_existant_attr + except AttributeError: pass + else: self.fail("using unknown attributes should raise " + "AttributeError") + +class FunctionDictsTest(FuncAttrsTest): + def test_setting_dict_to_invalid(self): + self.cannot_set_attr(self.b, '__dict__', None, TypeError) + from collections import UserDict + d = UserDict({'known_attr': 7}) + self.cannot_set_attr(self.fi.a.__func__, '__dict__', d, TypeError) + + def test_setting_dict_to_valid(self): + d = {'known_attr': 7} + self.b.__dict__ = d + # Test assignment + self.assertEqual(d, self.b.__dict__) + # ... and on all the different ways of referencing the method's func + self.F.a.__dict__ = d + self.assertEqual(d, self.fi.a.__func__.__dict__) + self.assertEqual(d, self.fi.a.__dict__) + # Test value + self.assertEqual(self.b.known_attr, 7) + self.assertEqual(self.b.__dict__['known_attr'], 7) + # ... and again, on all the different method's names + self.assertEqual(self.fi.a.__func__.known_attr, 7) + self.assertEqual(self.fi.a.known_attr, 7) + + def test_delete___dict__(self): + try: del self.b.__dict__ + except TypeError: pass + else: self.fail("deleting function dictionary should raise TypeError") + + def test_unassigned_dict(self): + self.assertEqual(self.b.__dict__, {}) + + def test_func_as_dict_key(self): + value = "Some string" + d = {} + d[self.b] = value + self.assertEqual(d[self.b], value) + +class FunctionDocstringTest(FuncAttrsTest): + def test_set_docstring_attr(self): + self.assertEqual(self.b.__doc__, None) + docstr = "A test method that does nothing" + self.b.__doc__ = docstr + self.F.a.__doc__ = docstr + self.assertEqual(self.b.__doc__, docstr) + self.assertEqual(self.fi.a.__doc__, docstr) + self.cannot_set_attr(self.fi.a, "__doc__", docstr, AttributeError) + + def test_delete_docstring(self): + self.b.__doc__ = "The docstring" + del self.b.__doc__ + self.assertEqual(self.b.__doc__, None) + +def test_main(): + test_support.run_unittest(FunctionPropertiesTest, ImplicitReferencesTest, + ArbitraryFunctionAttrTest, FunctionDictsTest, + FunctionDocstringTest) -if f2.a.one != f1.a.one != F.a.one != 11: - raise TestFailed - -# __func__ may not be a Python method! -import types -F.id = id - -eff = F() -eff.id = types.MethodType(id, eff) -if eff.id() != id(eff): - raise TestFailed - -try: - F.id.foo -except AttributeError: pass -else: raise TestFailed - -try: - F.id.foo = 12 -except (AttributeError, TypeError): pass -else: raise TestFailed - -try: - F.id.foo -except AttributeError: pass -else: raise TestFailed - -try: - eff.id.foo -except AttributeError: pass -else: raise TestFailed - -try: - eff.id.foo = 12 -except (AttributeError, TypeError): pass -else: raise TestFailed - -try: - eff.id.foo -except AttributeError: pass -else: raise TestFailed - -# Regression test for a crash in pre-2.1a1 -def another(): - pass - -try: - del another.__dict__ -except TypeError: pass -else: raise TestFailed - -try: - del another.__dict__ -except TypeError: pass -else: raise TestFailed - -try: - another.__dict__ = None -except TypeError: pass -else: raise TestFailed - -try: - del another.bar -except AttributeError: pass -else: raise TestFailed - -# This isn't specifically related to function attributes, but it does test a -# core dump regression in funcobject.c -del another.__defaults__ - -def foo(): - pass - -def bar(): - pass - -def temp(): - print(1) - -if foo==bar: - raise TestFailed - -d={} -d[foo] = 1 - -foo.__code__ = temp.__code__ - -d[foo] - -# Test all predefined function attributes systematically - -def cantset(obj, name, value, exception=(AttributeError, TypeError)): - verify(hasattr(obj, name)) # Otherwise it's probably a typo - try: - setattr(obj, name, value) - except exception: - pass - else: - raise TestFailed("shouldn't be able to set %s to %r" % (name, value)) - try: - delattr(obj, name) - except (AttributeError, TypeError): - pass - else: - raise TestFailed("shouldn't be able to del %s" % name) - -def test_func_closure(): - a = 12 - def f(): print(a) - c = f.__closure__ - verify(isinstance(c, tuple)) - verify(len(c) == 1) - verify(c[0].__class__.__name__ == "cell") # don't have a type object handy - cantset(f, "__closure__", c) - -def test_empty_cell(): - def f(): print(a) - try: - f.__closure__[0].cell_contents - except ValueError: - pass - else: - raise TestFailed("shouldn't be able to read an empty cell") - - a = 12 - -def test_func_doc(): - def f(): pass - verify(f.__doc__ is None) - f.__doc__ = "hello" - verify(f.__doc__ == "hello") - del f.__doc__ - verify(f.__doc__ is None) - -def test_func_globals(): - def f(): pass - verify(f.__globals__ is globals()) - cantset(f, "__globals__", globals()) - -def test_func_name(): - def f(): pass - verify(f.__name__ == "f") - f.__name__ = "g" - verify(f.__name__ == "g") - cantset(f, "__globals__", 1) - cantset(f, "__name__", 1) - # test that you can access func.__name__ in restricted mode - s = """def f(): pass\nf.__name__""" - exec(s, {'__builtins__':{}}) - - -def test_func_code(): - a = b = 24 - def f(): pass - def g(): print(12) - def f1(): print(a) - def g1(): print(b) - def f2(): print(a, b) - verify(type(f.__code__) is types.CodeType) - f.__code__ = g.__code__ - cantset(f, "__code__", None) - # can't change the number of free vars - cantset(f, "__code__", f1.__code__, exception=ValueError) - cantset(f1, "__code__", f.__code__, exception=ValueError) - cantset(f1, "__code__", f2.__code__, exception=ValueError) - f1.__code__ = g1.__code__ - -def test_func_defaults(): - def f(a, b): return (a, b) - verify(f.__defaults__ is None) - f.__defaults__ = (1, 2) - verify(f.__defaults__ == (1, 2)) - verify(f(10) == (10, 2)) - def g(a=1, b=2): return (a, b) - verify(g.__defaults__ == (1, 2)) - del g.__defaults__ - verify(g.__defaults__ is None) - try: - g() - except TypeError: - pass - else: - raise TestFailed("shouldn't be allowed to call g() w/o defaults") - -def test_func_dict(): - def f(): pass - a = f.__dict__ - verify(a == {}) - f.hello = 'world' - verify(a == {'hello': 'world'}) - verify(a is f.__dict__) - f.__dict__ = {'world': 'hello'} - verify(f.world == "hello") - verify(f.__dict__ == {'world': 'hello'}) - cantset(f, "__dict__", None) - -def test___self__(): - class C: - def foo(self): pass - #verify(C.foo.__self__.__class__ is C) - verify(C().foo.__self__.__class__ is C) - #cantset(C.foo, "__self__.__class__", C) - cantset(C().foo, "__self__.__class__", C) - -def test___func__(): - def foo(self): pass - class C: - pass - C.foo = foo - #verify(C.foo.__func__ is foo) - verify(C().foo.__func__ is foo) - #cantset(C.foo, "__func__", foo) - cantset(C().foo, "__func__", foo) - -def test___self__(): - class C: - def foo(self): pass - #verify(C.foo.__self__ is None) - c = C() - #verify(c.foo.__self__ is c) - #cantset(C.foo, "__self__", None) - #cantset(c.foo, "__self__", c) - -def test_im_dict(): - class C: - def foo(self): pass - foo.bar = 42 - verify(C.foo.__dict__ == {'bar': 42}) - verify(C().foo.__dict__ == {'bar': 42}) - #cantset(C.foo, "__dict__", C.foo.__dict__) - #cantset(C().foo, "__dict__", C.foo.__dict__) - -def test_im_doc(): - class C: - def foo(self): "hello" - verify(C.foo.__doc__ == "hello") - verify(C().foo.__doc__ == "hello") - #cantset(C.foo, "__doc__", "hello") - #cantset(C().foo, "__doc__", "hello") - -def test_im_name(): - class C: - def foo(self): pass - verify(C.foo.__name__ == "foo") - verify(C().foo.__name__ == "foo") - #cantset(C.foo, "__name__", "foo") - #cantset(C().foo, "__name__", "foo") - -def testmore(): - test_func_closure() - test_empty_cell() - test_func_doc() - test_func_globals() - test_func_name() - test_func_code() - test_func_defaults() - test_func_dict() - # Tests for instance method attributes - test___self__() - test___func__() - test___self__() - test_im_dict() - test_im_doc() - test_im_name() - -testmore() +if __name__ == "__main__": + test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_gc.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_gc.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_gc.py Wed Apr 30 15:57:13 2008 @@ -236,21 +236,33 @@ gc.disable() gc.set_threshold(*thresholds) + # The following two tests are fragile: + # They precisely count the number of allocations, + # which is highly implementation-dependent. + # For example: + # - disposed tuples are not freed, but reused + # - the call to assertEqual somehow avoids building its args tuple def test_get_count(self): + # Avoid future allocation of method object + assertEqual = self.assertEqual gc.collect() - self.assertEqual(gc.get_count(), (0, 0, 0)) + assertEqual(gc.get_count(), (0, 0, 0)) a = dict() - self.assertEqual(gc.get_count(), (1, 0, 0)) + # since gc.collect(), we created two objects: + # the dict, and the tuple returned by get_count() + assertEqual(gc.get_count(), (2, 0, 0)) def test_collect_generations(self): + # Avoid future allocation of method object + assertEqual = self.assertEqual gc.collect() a = dict() gc.collect(0) - self.assertEqual(gc.get_count(), (0, 1, 0)) + assertEqual(gc.get_count(), (0, 1, 0)) gc.collect(1) - self.assertEqual(gc.get_count(), (0, 0, 1)) + assertEqual(gc.get_count(), (0, 0, 1)) gc.collect(2) - self.assertEqual(gc.get_count(), (0, 0, 0)) + assertEqual(gc.get_count(), (0, 0, 0)) def test_trashcan(self): class Ouch: Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_gdbm.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_gdbm.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_gdbm.py Wed Apr 30 15:57:13 2008 @@ -1,46 +1,81 @@ -#! /usr/bin/env python -"""Test script for the gdbm module - Roger E. Masse -""" - import gdbm -from gdbm import error -from test.test_support import verbose, verify, TestFailed, TESTFN +import unittest +import os +from test.test_support import verbose, TESTFN, run_unittest, unlink + filename = TESTFN -g = gdbm.open(filename, 'c') -verify(g.keys() == []) -g[b'a'] = b'b' -g[b'12345678910'] = b'019237410982340912840198242' -a = g.keys() -if verbose: - print('Test gdbm file keys: ', a) - -b'a' in g -g.close() -try: - g['a'] -except error: - pass -else: - raise TestFailed("expected gdbm.error accessing closed database") -g = gdbm.open(filename, 'r') -g.close() -g = gdbm.open(filename, 'w') -g.close() -g = gdbm.open(filename, 'n') -g.close() -try: - g = gdbm.open(filename, 'rx') - g.close() -except error: - pass -else: - raise TestFailed("expected gdbm.error when passing invalid open flags") - -try: - import os - os.unlink(filename) -except: - pass +class TestGdbm(unittest.TestCase): + def setUp(self): + self.g = None + + def tearDown(self): + if self.g is not None: + self.g.close() + unlink(filename) + + def test_key_methods(self): + self.g = gdbm.open(filename, 'c') + self.assertEqual(self.g.keys(), []) + self.g['a'] = 'b' + self.g['12345678910'] = '019237410982340912840198242' + key_set = set(self.g.keys()) + self.assertEqual(key_set, set([b'a', b'12345678910'])) + self.assert_(b'a' in self.g) + key = self.g.firstkey() + while key: + self.assert_(key in key_set) + key_set.remove(key) + key = self.g.nextkey(key) + self.assertRaises(KeyError, lambda: self.g['xxx']) + + def test_error_conditions(self): + # Try to open a non-existent database. + unlink(filename) + self.assertRaises(gdbm.error, gdbm.open, filename, 'r') + # Try to access a closed database. + self.g = gdbm.open(filename, 'c') + self.g.close() + self.assertRaises(gdbm.error, lambda: self.g['a']) + # try pass an invalid open flag + self.assertRaises(gdbm.error, lambda: gdbm.open(filename, 'rx').close()) + + def test_flags(self): + # Test the flag parameter open() by trying all supported flag modes. + all = set(gdbm.open_flags) + # Test standard flags (presumably "crwn"). + modes = all - set('fsu') + for mode in modes: + self.g = gdbm.open(filename, mode) + self.g.close() + + # Test additional flags (presumably "fsu"). + flags = all - set('crwn') + for mode in modes: + for flag in flags: + self.g = gdbm.open(filename, mode + flag) + self.g.close() + + def test_reorganize(self): + self.g = gdbm.open(filename, 'c') + size0 = os.path.getsize(filename) + + self.g['x'] = 'x' * 10000 + size1 = os.path.getsize(filename) + self.assert_(size0 < size1) + + del self.g['x'] + # 'size' is supposed to be the same even after deleting an entry. + self.assertEqual(os.path.getsize(filename), size1) + + self.g.reorganize() + size2 = os.path.getsize(filename) + self.assert_(size1 > size2 >= size0) + + +def test_main(): + run_unittest(TestGdbm) + +if __name__ == '__main__': + test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_generators.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_generators.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_generators.py Wed Apr 30 15:57:13 2008 @@ -377,12 +377,12 @@ ... yield 1 ... >>> type(g) - + >>> i = g() >>> type(i) - + >>> [s for s in dir(i) if not s.startswith('_')] -['close', 'gi_frame', 'gi_running', 'send', 'throw'] +['close', 'gi_code', 'gi_frame', 'gi_running', 'send', 'throw'] >>> print(i.__next__.__doc__) x.__next__() <==> next(x) >>> iter(i) is i @@ -396,7 +396,7 @@ >>> i.gi_running 0 >>> type(i.gi_frame) - + >>> i.gi_running = 42 Traceback (most recent call last): ... @@ -794,27 +794,27 @@ >>> def f(): ... yield >>> type(f()) - + >>> def f(): ... if 0: ... yield >>> type(f()) - + >>> def f(): ... if 0: ... yield 1 >>> type(f()) - + >>> def f(): ... if "": ... yield None >>> type(f()) - + >>> def f(): ... return @@ -838,7 +838,7 @@ ... x = 1 ... return >>> type(f()) - + >>> def f(): ... if 0: @@ -846,7 +846,7 @@ ... yield 1 ... >>> type(f()) - + >>> def f(): ... if 0: @@ -856,7 +856,7 @@ ... def f(self): ... yield 2 >>> type(f()) - + >>> def f(): ... if 0: @@ -864,7 +864,7 @@ ... if 0: ... yield 2 >>> type(f()) - + >>> def f(): @@ -899,6 +899,24 @@ >>> print(next(g)) Traceback (most recent call last): StopIteration + + +Test the gi_code attribute + +>>> def f(): +... yield 5 +... +>>> g = f() +>>> g.gi_code is f.__code__ +True +>>> next(g) +5 +>>> next(g) +Traceback (most recent call last): +StopIteration +>>> g.gi_code is f.__code__ +True + """ # conjoin is a simple backtracking generator, named in honor of Icon's @@ -1494,7 +1512,7 @@ >>> def f(): list(i for i in [(yield 26)]) >>> type(f()) - + A yield expression with augmented assignment. @@ -1731,25 +1749,25 @@ >>> def f(): x += yield >>> type(f()) - + >>> def f(): x = yield >>> type(f()) - + >>> def f(): lambda x=(yield): 1 >>> type(f()) - + >>> def f(): x=(i for i in (yield) if (yield)) >>> type(f()) - + >>> def f(d): d[(yield "a")] = d[(yield "b")] = 27 >>> data = [1,2] >>> g = f(data) >>> type(g) - + >>> g.send(None) 'a' >>> data Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_genexps.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_genexps.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_genexps.py Wed Apr 30 15:57:13 2008 @@ -27,7 +27,7 @@ >>> g = (i*i for i in range(4)) >>> type(g) - + >>> list(g) [0, 1, 4, 9] Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_getargs2.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_getargs2.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_getargs2.py Wed Apr 30 15:57:13 2008 @@ -1,8 +1,8 @@ import unittest from test import test_support -import sys +from _testcapi import getargs_keywords -import warnings, re +import warnings warnings.filterwarnings("ignore", category=DeprecationWarning, message=".*integer argument expected, got float", @@ -187,8 +187,8 @@ # n returns 'Py_ssize_t', and does range checking # (PY_SSIZE_T_MIN ... PY_SSIZE_T_MAX) self.assertRaises(TypeError, getargs_n, 3.14) - self.failUnlessEqual(99, getargs_n(Long())) - self.failUnlessEqual(99, getargs_n(Int())) + self.assertRaises(TypeError, getargs_n, Long()) + self.assertRaises(TypeError, getargs_n, Int()) self.assertRaises(OverflowError, getargs_n, PY_SSIZE_T_MIN-1) self.failUnlessEqual(PY_SSIZE_T_MIN, getargs_n(PY_SSIZE_T_MIN)) @@ -249,9 +249,57 @@ raise ValueError self.assertRaises(TypeError, getargs_tuple, 1, seq()) +class Keywords_TestCase(unittest.TestCase): + def test_positional_args(self): + # using all positional args + self.assertEquals( + getargs_keywords((1,2), 3, (4,(5,6)), (7,8,9), 10), + (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + ) + def test_mixed_args(self): + # positional and keyword args + self.assertEquals( + getargs_keywords((1,2), 3, (4,(5,6)), arg4=(7,8,9), arg5=10), + (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + ) + def test_keyword_args(self): + # all keywords + self.assertEquals( + getargs_keywords(arg1=(1,2), arg2=3, arg3=(4,(5,6)), arg4=(7,8,9), arg5=10), + (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + ) + def test_optional_args(self): + # missing optional keyword args, skipping tuples + self.assertEquals( + getargs_keywords(arg1=(1,2), arg2=3, arg5=10), + (1, 2, 3, -1, -1, -1, -1, -1, -1, 10) + ) + def test_required_args(self): + # required arg missing + try: + getargs_keywords(arg1=(1,2)) + except TypeError as err: + self.assertEquals(str(err), "Required argument 'arg2' (pos 2) not found") + else: + self.fail('TypeError should have been raised') + def test_too_many_args(self): + try: + getargs_keywords((1,2),3,(4,(5,6)),(7,8,9),10,111) + except TypeError as err: + self.assertEquals(str(err), "function takes at most 5 arguments (6 given)") + else: + self.fail('TypeError should have been raised') + def test_invalid_keyword(self): + # extraneous keyword arg + try: + getargs_keywords((1,2),3,arg5=10,arg666=666) + except TypeError as err: + self.assertEquals(str(err), "'arg666' is an invalid keyword argument for this function") + else: + self.fail('TypeError should have been raised') def test_main(): - tests = [Signed_TestCase, Unsigned_TestCase, Tuple_TestCase] + tests = [Signed_TestCase, Unsigned_TestCase, Tuple_TestCase, Keywords_TestCase] try: from _testcapi import getargs_L, getargs_K except ImportError: Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_grammar.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_grammar.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_grammar.py Wed Apr 30 15:57:13 2008 @@ -310,6 +310,10 @@ def f(*, k=1): return closure def f() -> int: return closure + # Check ast errors in *args and *kwargs + check_syntax_error(self, "f(*g(1=2))") + check_syntax_error(self, "f(**g(1=2))") + def testLambdef(self): ### lambdef: 'lambda' [varargslist] ':' test l1 = lambda : 0 Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_gzip.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_gzip.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_gzip.py Wed Apr 30 15:57:13 2008 @@ -4,7 +4,7 @@ import unittest from test import test_support -import sys, os +import os import gzip @@ -25,13 +25,10 @@ filename = test_support.TESTFN def setUp (self): - pass + test_support.unlink(self.filename) def tearDown (self): - try: - os.unlink(self.filename) - except os.error: - pass + test_support.unlink(self.filename) def test_write (self): Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_heapq.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_heapq.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_heapq.py Wed Apr 30 15:57:13 2008 @@ -1,21 +1,32 @@ """Unittests for heapq.""" -from heapq import heappush, heappop, heapify, heapreplace, merge, nlargest, nsmallest import random import unittest from test import test_support import sys +# We do a bit of trickery here to be able to test both the C implementation +# and the Python implementation of the module. + +# Make it impossible to import the C implementation anymore. +sys.modules['_heapq'] = 0 +# We must also handle the case that heapq was imported before. +if 'heapq' in sys.modules: + del sys.modules['heapq'] + +# Now we can import the module and get the pure Python implementation. +import heapq as py_heapq + +# Restore everything to normal. +del sys.modules['_heapq'] +del sys.modules['heapq'] + +# This is now the module with the C implementation. +import heapq as c_heapq -def heapiter(heap): - # An iterator returning a heap's elements, smallest-first. - try: - while 1: - yield heappop(heap) - except IndexError: - pass class TestHeap(unittest.TestCase): + module = None def test_push_pop(self): # 1) Push 256 random numbers and pop them off, verifying all's OK. @@ -25,11 +36,11 @@ for i in range(256): item = random.random() data.append(item) - heappush(heap, item) + self.module.heappush(heap, item) self.check_invariant(heap) results = [] while heap: - item = heappop(heap) + item = self.module.heappop(heap) self.check_invariant(heap) results.append(item) data_sorted = data[:] @@ -38,10 +49,10 @@ # 2) Check that the invariant holds for a sorted array self.check_invariant(results) - self.assertRaises(TypeError, heappush, []) + self.assertRaises(TypeError, self.module.heappush, []) try: - self.assertRaises(TypeError, heappush, None, None) - self.assertRaises(TypeError, heappop, None) + self.assertRaises(TypeError, self.module.heappush, None, None) + self.assertRaises(TypeError, self.module.heappop, None) except AttributeError: pass @@ -55,21 +66,29 @@ def test_heapify(self): for size in range(30): heap = [random.random() for dummy in range(size)] - heapify(heap) + self.module.heapify(heap) self.check_invariant(heap) - self.assertRaises(TypeError, heapify, None) + self.assertRaises(TypeError, self.module.heapify, None) def test_naive_nbest(self): data = [random.randrange(2000) for i in range(1000)] heap = [] for item in data: - heappush(heap, item) + self.module.heappush(heap, item) if len(heap) > 10: - heappop(heap) + self.module.heappop(heap) heap.sort() self.assertEqual(heap, sorted(data)[-10:]) + def heapiter(self, heap): + # An iterator returning a heap's elements, smallest-first. + try: + while 1: + yield self.module.heappop(heap) + except IndexError: + pass + def test_nbest(self): # Less-naive "N-best" algorithm, much faster (if len(data) is big # enough ) than sorting all of data. However, if we had a max @@ -78,15 +97,43 @@ # (10 log-time steps). data = [random.randrange(2000) for i in range(1000)] heap = data[:10] - heapify(heap) + self.module.heapify(heap) for item in data[10:]: if item > heap[0]: # this gets rarer the longer we run - heapreplace(heap, item) - self.assertEqual(list(heapiter(heap)), sorted(data)[-10:]) + self.module.heapreplace(heap, item) + self.assertEqual(list(self.heapiter(heap)), sorted(data)[-10:]) - self.assertRaises(TypeError, heapreplace, None) - self.assertRaises(TypeError, heapreplace, None, None) - self.assertRaises(IndexError, heapreplace, [], None) + self.assertRaises(TypeError, self.module.heapreplace, None) + self.assertRaises(TypeError, self.module.heapreplace, None, None) + self.assertRaises(IndexError, self.module.heapreplace, [], None) + + def test_nbest_with_pushpop(self): + data = [random.randrange(2000) for i in range(1000)] + heap = data[:10] + self.module.heapify(heap) + for item in data[10:]: + self.module.heappushpop(heap, item) + self.assertEqual(list(self.heapiter(heap)), sorted(data)[-10:]) + self.assertEqual(self.module.heappushpop([], 'x'), 'x') + + def test_heappushpop(self): + h = [] + x = self.module.heappushpop(h, 10) + self.assertEqual((h, x), ([], 10)) + + h = [10] + x = self.module.heappushpop(h, 10.0) + self.assertEqual((h, x), ([10], 10.0)) + self.assertEqual(type(h[0]), int) + self.assertEqual(type(x), float) + + h = [10]; + x = self.module.heappushpop(h, 9) + self.assertEqual((h, x), ([10], 9)) + + h = [10]; + x = self.module.heappushpop(h, 11) + self.assertEqual((h, x), ([11], 10)) def test_heapsort(self): # Exercise everything with repeated heapsort checks @@ -95,12 +142,12 @@ data = [random.randrange(25) for i in range(size)] if trial & 1: # Half of the time, use heapify heap = data[:] - heapify(heap) + self.module.heapify(heap) else: # The rest of the time, use heappush heap = [] for item in data: - heappush(heap, item) - heap_sorted = [heappop(heap) for i in range(size)] + self.module.heappush(heap, item) + heap_sorted = [self.module.heappop(heap) for i in range(size)] self.assertEqual(heap_sorted, sorted(data)) def test_merge(self): @@ -108,8 +155,8 @@ for i in range(random.randrange(5)): row = sorted(random.randrange(1000) for j in range(random.randrange(10))) inputs.append(row) - self.assertEqual(sorted(chain(*inputs)), list(merge(*inputs))) - self.assertEqual(list(merge()), []) + self.assertEqual(sorted(chain(*inputs)), list(self.module.merge(*inputs))) + self.assertEqual(list(self.module.merge()), []) def test_merge_stability(self): class Int(int): @@ -123,26 +170,33 @@ inputs[stream].append(obj) for stream in inputs: stream.sort() - result = [i.pair for i in merge(*inputs)] + result = [i.pair for i in self.module.merge(*inputs)] self.assertEqual(result, sorted(result)) def test_nsmallest(self): data = [(random.randrange(2000), i) for i in range(1000)] for f in (None, lambda x: x[0] * 547 % 2000): for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): - self.assertEqual(list(nsmallest(n, data)), sorted(data)[:n]) - self.assertEqual(list(nsmallest(n, data, key=f)), + self.assertEqual(list(self.module.nsmallest(n, data)), + sorted(data)[:n]) + self.assertEqual(list(self.module.nsmallest(n, data, key=f)), sorted(data, key=f)[:n]) def test_nlargest(self): data = [(random.randrange(2000), i) for i in range(1000)] for f in (None, lambda x: x[0] * 547 % 2000): for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): - self.assertEqual(list(nlargest(n, data)), + self.assertEqual(list(self.module.nlargest(n, data)), sorted(data, reverse=True)[:n]) - self.assertEqual(list(nlargest(n, data, key=f)), + self.assertEqual(list(self.module.nlargest(n, data, key=f)), sorted(data, key=f, reverse=True)[:n]) +class TestHeapPython(TestHeap): + module = py_heapq + +class TestHeapC(TestHeap): + module = c_heapq + #============================================================================== @@ -234,50 +288,55 @@ def __next__(self): raise StopIteration -from itertools import chain, imap +from itertools import chain def L(seqn): 'Test multiple tiers of iterators' - return chain(imap(lambda x:x, R(Ig(G(seqn))))) + return chain(map(lambda x:x, R(Ig(G(seqn))))) class TestErrorHandling(unittest.TestCase): + # only for C implementation + module = c_heapq def test_non_sequence(self): - for f in (heapify, heappop): + for f in (self.module.heapify, self.module.heappop): self.assertRaises(TypeError, f, 10) - for f in (heappush, heapreplace, nlargest, nsmallest): + for f in (self.module.heappush, self.module.heapreplace, + self.module.nlargest, self.module.nsmallest): self.assertRaises(TypeError, f, 10, 10) def test_len_only(self): - for f in (heapify, heappop): + for f in (self.module.heapify, self.module.heappop): self.assertRaises(TypeError, f, LenOnly()) - for f in (heappush, heapreplace): + for f in (self.module.heappush, self.module.heapreplace): self.assertRaises(TypeError, f, LenOnly(), 10) - for f in (nlargest, nsmallest): + for f in (self.module.nlargest, self.module.nsmallest): self.assertRaises(TypeError, f, 2, LenOnly()) def test_get_only(self): - for f in (heapify, heappop): + for f in (self.module.heapify, self.module.heappop): self.assertRaises(TypeError, f, GetOnly()) - for f in (heappush, heapreplace): + for f in (self.module.heappush, self.module.heapreplace): self.assertRaises(TypeError, f, GetOnly(), 10) - for f in (nlargest, nsmallest): + for f in (self.module.nlargest, self.module.nsmallest): self.assertRaises(TypeError, f, 2, GetOnly()) def test_get_only(self): seq = [CmpErr(), CmpErr(), CmpErr()] - for f in (heapify, heappop): + for f in (self.module.heapify, self.module.heappop): self.assertRaises(ZeroDivisionError, f, seq) - for f in (heappush, heapreplace): + for f in (self.module.heappush, self.module.heapreplace): self.assertRaises(ZeroDivisionError, f, seq, 10) - for f in (nlargest, nsmallest): + for f in (self.module.nlargest, self.module.nsmallest): self.assertRaises(ZeroDivisionError, f, 2, seq) def test_arg_parsing(self): - for f in (heapify, heappop, heappush, heapreplace, nlargest, nsmallest): + for f in (self.module.heapify, self.module.heappop, + self.module.heappush, self.module.heapreplace, + self.module.nlargest, self.module.nsmallest): self.assertRaises(TypeError, f, 10) def test_iterable_args(self): - for f in (nlargest, nsmallest): + for f in (self.module.nlargest, self.module.nsmallest): for s in ("123", "", range(1000), (1, 1.2), range(2000,2200,5)): for g in (G, I, Ig, L, R): self.assertEqual(list(f(2, g(s))), list(f(2,s))) @@ -286,15 +345,14 @@ self.assertRaises(TypeError, f, 2, N(s)) self.assertRaises(ZeroDivisionError, f, 2, E(s)) + #============================================================================== def test_main(verbose=None): from types import BuiltinFunctionType - test_classes = [TestHeap] - if isinstance(heapify, BuiltinFunctionType): - test_classes.append(TestErrorHandling) + test_classes = [TestHeapPython, TestHeapC, TestErrorHandling] test_support.run_unittest(*test_classes) # verify reference counting Deleted: python/branches/py3k-ctypes-pep3118/Lib/test/test_hexoct.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_hexoct.py Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,116 +0,0 @@ -"""Test correct treatment of hex/oct constants. - -This is complex because of changes due to PEP 237. -""" - -import sys -platform_long_is_32_bits = sys.maxsize == 2147483647 - -import unittest -from test import test_support - -import warnings -warnings.filterwarnings("ignore", "hex/oct constants", FutureWarning, - "") - -class TextHexOct(unittest.TestCase): - - def test_hex_baseline(self): - # Baseline tests - self.assertEqual(0x0, 0) - self.assertEqual(0x10, 16) - if platform_long_is_32_bits: - self.assertEqual(0x7fffffff, 2147483647) - else: - self.assertEqual(0x7fffffffffffffff, 9223372036854775807) - # Ditto with a minus sign and parentheses - self.assertEqual(-(0x0), 0) - self.assertEqual(-(0x10), -16) - if platform_long_is_32_bits: - self.assertEqual(-(0x7fffffff), -2147483647) - else: - self.assertEqual(-(0x7fffffffffffffff), -9223372036854775807) - # Ditto with a minus sign and NO parentheses - self.assertEqual(-0x0, 0) - self.assertEqual(-0x10, -16) - if platform_long_is_32_bits: - self.assertEqual(-0x7fffffff, -2147483647) - else: - self.assertEqual(-0x7fffffffffffffff, -9223372036854775807) - - def test_hex_unsigned(self): - if platform_long_is_32_bits: - # Positive constants - self.assertEqual(0x80000000, 2147483648) - self.assertEqual(0xffffffff, 4294967295) - # Ditto with a minus sign and parentheses - self.assertEqual(-(0x80000000), -2147483648) - self.assertEqual(-(0xffffffff), -4294967295) - # Ditto with a minus sign and NO parentheses - # This failed in Python 2.2 through 2.2.2 and in 2.3a1 - self.assertEqual(-0x80000000, -2147483648) - self.assertEqual(-0xffffffff, -4294967295) - else: - # Positive constants - self.assertEqual(0x8000000000000000, 9223372036854775808) - self.assertEqual(0xffffffffffffffff, 18446744073709551615) - # Ditto with a minus sign and parentheses - self.assertEqual(-(0x8000000000000000), -9223372036854775808) - self.assertEqual(-(0xffffffffffffffff), -18446744073709551615) - # Ditto with a minus sign and NO parentheses - # This failed in Python 2.2 through 2.2.2 and in 2.3a1 - self.assertEqual(-0x8000000000000000, -9223372036854775808) - self.assertEqual(-0xffffffffffffffff, -18446744073709551615) - - def test_oct_baseline(self): - # Baseline tests - self.assertEqual(00, 0) - self.assertEqual(0o20, 16) - if platform_long_is_32_bits: - self.assertEqual(0o17777777777, 2147483647) - else: - self.assertEqual(0o777777777777777777777, 9223372036854775807) - # Ditto with a minus sign and parentheses - self.assertEqual(-(00), 0) - self.assertEqual(-(0o20), -16) - if platform_long_is_32_bits: - self.assertEqual(-(0o17777777777), -2147483647) - else: - self.assertEqual(-(0o777777777777777777777), -9223372036854775807) - # Ditto with a minus sign and NO parentheses - self.assertEqual(-00, 0) - self.assertEqual(-0o20, -16) - if platform_long_is_32_bits: - self.assertEqual(-0o17777777777, -2147483647) - else: - self.assertEqual(-0o777777777777777777777, -9223372036854775807) - - def test_oct_unsigned(self): - if platform_long_is_32_bits: - # Positive constants - self.assertEqual(0o20000000000, 2147483648) - self.assertEqual(0o37777777777, 4294967295) - # Ditto with a minus sign and parentheses - self.assertEqual(-(0o20000000000), -2147483648) - self.assertEqual(-(0o37777777777), -4294967295) - # Ditto with a minus sign and NO parentheses - # This failed in Python 2.2 through 2.2.2 and in 2.3a1 - self.assertEqual(-0o20000000000, -2147483648) - self.assertEqual(-0o37777777777, -4294967295) - else: - # Positive constants - self.assertEqual(0o1000000000000000000000, 9223372036854775808) - self.assertEqual(0o1777777777777777777777, 18446744073709551615) - # Ditto with a minus sign and parentheses - self.assertEqual(-(0o1000000000000000000000), -9223372036854775808) - self.assertEqual(-(0o1777777777777777777777), -18446744073709551615) - # Ditto with a minus sign and NO parentheses - # This failed in Python 2.2 through 2.2.2 and in 2.3a1 - self.assertEqual(-0o1000000000000000000000, -9223372036854775808) - self.assertEqual(-0o1777777777777777777777, -18446744073709551615) - -def test_main(): - test_support.run_unittest(TextHexOct) - -if __name__ == "__main__": - test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_hmac.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_hmac.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_hmac.py Wed Apr 30 15:57:13 2008 @@ -211,8 +211,8 @@ def digest(self): return self._x.digest() - warnings.simplefilter('error', RuntimeWarning) - try: + with test_support.catch_warning(): + warnings.simplefilter('error', RuntimeWarning) try: hmac.HMAC(b'a', b'b', digestmod=MockCrazyHash) except RuntimeWarning: @@ -227,8 +227,6 @@ pass else: self.fail('Expected warning about small block_size') - finally: - warnings.resetwarnings() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_htmlparser.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_htmlparser.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_htmlparser.py Wed Apr 30 15:57:13 2008 @@ -2,7 +2,6 @@ import HTMLParser import pprint -import sys import unittest from test import test_support Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_httplib.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_httplib.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_httplib.py Wed Apr 30 15:57:13 2008 @@ -1,12 +1,13 @@ import httplib import io -import sys import socket from unittest import TestCase from test import test_support +HOST = test_support.HOST + class FakeSocket: def __init__(self, text, fileclass=io.BytesIO): if isinstance(text, str): @@ -160,20 +161,52 @@ self.assertTrue(sock.data.startswith(expected), '%r != %r' % (sock.data[:len(expected)], expected)) + def test_chunked(self): + chunked_start = ( + 'HTTP/1.1 200 OK\r\n' + 'Transfer-Encoding: chunked\r\n\r\n' + 'a\r\n' + 'hello worl\r\n' + '1\r\n' + 'd\r\n' + ) + sock = FakeSocket(chunked_start + '0\r\n') + resp = httplib.HTTPResponse(sock, method="GET") + resp.begin() + self.assertEquals(resp.read(), b'hello world') + resp.close() + + for x in ('', 'foo\r\n'): + sock = FakeSocket(chunked_start + x) + resp = httplib.HTTPResponse(sock, method="GET") + resp.begin() + try: + resp.read() + except httplib.IncompleteRead as i: + self.assertEquals(i.partial, b'hello world') + else: + self.fail('IncompleteRead expected') + finally: + resp.close() + + def test_negative_content_length(self): + sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n') + resp = httplib.HTTPResponse(sock, method="GET") + resp.begin() + self.assertEquals(resp.read(), b'Hello\r\n') + resp.close() + + class OfflineTest(TestCase): def test_responses(self): self.assertEquals(httplib.responses[httplib.NOT_FOUND], "Not Found") -PORT = 50003 -HOST = "localhost" - class TimeoutTest(TestCase): + PORT = None def setUp(self): self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - global PORT - PORT = test_support.bind_port(self.serv, HOST, PORT) + TimeoutTest.PORT = test_support.bind_port(self.serv) self.serv.listen(5) def tearDown(self): @@ -185,13 +218,13 @@ # and into the socket. # default - httpConn = httplib.HTTPConnection(HOST, PORT) + httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT) httpConn.connect() self.assertTrue(httpConn.sock.gettimeout() is None) httpConn.close() # a value - httpConn = httplib.HTTPConnection(HOST, PORT, timeout=30) + httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30) httpConn.connect() self.assertEqual(httpConn.sock.gettimeout(), 30) httpConn.close() @@ -200,7 +233,8 @@ previous = socket.getdefaulttimeout() socket.setdefaulttimeout(30) try: - httpConn = httplib.HTTPConnection(HOST, PORT, timeout=None) + httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT, + timeout=None) httpConn.connect() finally: socket.setdefaulttimeout(previous) @@ -214,11 +248,12 @@ def test_attributes(self): # simple test to check it's storing it if hasattr(httplib, 'HTTPSConnection'): - h = httplib.HTTPSConnection(HOST, PORT, timeout=30) + h = httplib.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30) self.assertEqual(h.timeout, 30) def test_main(verbose=None): - test_support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest, HTTPSTimeoutTest) + test_support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest, + HTTPSTimeoutTest) if __name__ == '__main__': test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_imaplib.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_imaplib.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_imaplib.py Wed Apr 30 15:57:13 2008 @@ -1,12 +1,25 @@ import imaplib import time -# We can check only that it successfully produces a result, -# not the correctness of the result itself, since the result -# depends on the timezone the machine is in. +from test import test_support +import unittest -timevalues = [2000000000, 2000000000.0, time.localtime(2000000000), - '"18-May-2033 05:33:20 +0200"'] -for t in timevalues: - imaplib.Time2Internaldate(t) +class TestImaplib(unittest.TestCase): + def test_that_Time2Internaldate_returns_a_result(self): + # We can check only that it successfully produces a result, + # not the correctness of the result itself, since the result + # depends on the timezone the machine is in. + timevalues = [2000000000, 2000000000.0, time.localtime(2000000000), + '"18-May-2033 05:33:20 +0200"'] + + for t in timevalues: + imaplib.Time2Internaldate(t) + + +def test_main(): + test_support.run_unittest(TestImaplib) + + +if __name__ == "__main__": + unittest.main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_imp.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_imp.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_imp.py Wed Apr 30 15:57:13 2008 @@ -1,5 +1,4 @@ import imp -import thread import unittest from test import test_support Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_import.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_import.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_import.py Wed Apr 30 15:57:13 2008 @@ -255,8 +255,20 @@ self.assertEqual(mod.testdata, 'test_trailing_slash') unload("test_trailing_slash") +class RelativeImport(unittest.TestCase): + def tearDown(self): + try: + del sys.modules["test.relimport"] + except: + pass + + def test_relimport_star(self): + # This will import * from .test_import. + from . import relimport + self.assertTrue(hasattr(relimport, "RelativeImport")) + def test_main(verbose=None): - run_unittest(ImportTest, PathsTests) + run_unittest(ImportTest, PathsTests, RelativeImport) if __name__ == '__main__': test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_index.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_index.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_index.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,6 @@ import unittest from test import test_support import operator -import sys maxsize = test_support.MAX_Py_ssize_t minsize = -maxsize-1 Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_inspect.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_inspect.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_inspect.py Wed Apr 30 15:57:13 2008 @@ -13,10 +13,10 @@ # Functions tested in this suite: # ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode, -# isbuiltin, isroutine, getmembers, getdoc, getfile, getmodule, -# getsourcefile, getcomments, getsource, getclasstree, getargspec, -# getargvalues, formatargspec, formatargvalues, currentframe, stack, trace -# isdatadescriptor +# isbuiltin, isroutine, isgenerator, isgeneratorfunction, getmembers, +# getdoc, getfile, getmodule, getsourcefile, getcomments, getsource, +# getclasstree, getargspec, getargvalues, formatargspec, formatargvalues, +# currentframe, stack, trace, isdatadescriptor modfile = mod.__file__ if modfile.endswith(('c', 'o')): @@ -41,23 +41,33 @@ class IsTestBase(unittest.TestCase): predicates = set([inspect.isbuiltin, inspect.isclass, inspect.iscode, inspect.isframe, inspect.isfunction, inspect.ismethod, - inspect.ismodule, inspect.istraceback]) + inspect.ismodule, inspect.istraceback, + inspect.isgenerator, inspect.isgeneratorfunction]) def istest(self, predicate, exp): obj = eval(exp) self.failUnless(predicate(obj), '%s(%s)' % (predicate.__name__, exp)) for other in self.predicates - set([predicate]): + if predicate == inspect.isgeneratorfunction and\ + other == inspect.isfunction: + continue self.failIf(other(obj), 'not %s(%s)' % (other.__name__, exp)) +def generator_function_example(self): + for i in range(2): + yield i + class TestPredicates(IsTestBase): - def test_thirteen(self): + def test_sixteen(self): count = len([x for x in dir(inspect) if x.startswith('is')]) - # Doc/lib/libinspect.tex claims there are 13 such functions - expected = 13 + # This test is here for remember you to update Doc/library/inspect.rst + # which claims there are 16 such functions + expected = 16 err_msg = "There are %d (not %d) is* functions" % (count, expected) self.assertEqual(count, expected, err_msg) + def test_excluding_predicates(self): self.istest(inspect.isbuiltin, 'sys.exit') self.istest(inspect.isbuiltin, '[].append') @@ -70,6 +80,8 @@ self.istest(inspect.ismodule, 'mod') self.istest(inspect.istraceback, 'tb') self.istest(inspect.isdatadescriptor, 'collections.defaultdict.default_factory') + self.istest(inspect.isgenerator, '(x for x in range(2))') + self.istest(inspect.isgeneratorfunction, 'generator_function_example') if hasattr(types, 'GetSetDescriptorType'): self.istest(inspect.isgetsetdescriptor, 'type(tb.tb_frame).f_locals') @@ -227,7 +239,7 @@ fodderFile = mod2 def test_wrapped_decorator(self): - self.assertSourceEqual(mod2.wrapped, 16, 17) + self.assertSourceEqual(mod2.wrapped, 14, 17) def test_replacing_decorator(self): self.assertSourceEqual(mod2.gone, 9, 10) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_io.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_io.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_io.py Wed Apr 30 15:57:13 2008 @@ -8,6 +8,7 @@ from itertools import chain from test import test_support +import codecs import io # The module under test @@ -78,6 +79,9 @@ class IOTest(unittest.TestCase): + def setUp(self): + test_support.unlink(test_support.TESTFN) + def tearDown(self): test_support.unlink(test_support.TESTFN) @@ -486,12 +490,155 @@ self.assertEquals(b"fl", rw.read(11)) self.assertRaises(TypeError, rw.seek, 0.0) +# To fully exercise seek/tell, the StatefulIncrementalDecoder has these +# properties: +# - A single output character can correspond to many bytes of input. +# - The number of input bytes to complete the character can be +# undetermined until the last input byte is received. +# - The number of input bytes can vary depending on previous input. +# - A single input byte can correspond to many characters of output. +# - The number of output characters can be undetermined until the +# last input byte is received. +# - The number of output characters can vary depending on previous input. + +class StatefulIncrementalDecoder(codecs.IncrementalDecoder): + """ + For testing seek/tell behavior with a stateful, buffering decoder. + + Input is a sequence of words. Words may be fixed-length (length set + by input) or variable-length (period-terminated). In variable-length + mode, extra periods are ignored. Possible words are: + - 'i' followed by a number sets the input length, I (maximum 99). + When I is set to 0, words are space-terminated. + - 'o' followed by a number sets the output length, O (maximum 99). + - Any other word is converted into a word followed by a period on + the output. The output word consists of the input word truncated + or padded out with hyphens to make its length equal to O. If O + is 0, the word is output verbatim without truncating or padding. + I and O are initially set to 1. When I changes, any buffered input is + re-scanned according to the new I. EOF also terminates the last word. + """ + + def __init__(self, errors='strict'): + codecs.IncrementalDecoder.__init__(self, errors) + self.reset() + + def __repr__(self): + return '' % id(self) + + def reset(self): + self.i = 1 + self.o = 1 + self.buffer = bytearray() + + def getstate(self): + i, o = self.i ^ 1, self.o ^ 1 # so that flags = 0 after reset() + return bytes(self.buffer), i*100 + o + + def setstate(self, state): + buffer, io = state + self.buffer = bytearray(buffer) + i, o = divmod(io, 100) + self.i, self.o = i ^ 1, o ^ 1 + + def decode(self, input, final=False): + output = '' + for b in input: + if self.i == 0: # variable-length, terminated with period + if b == ord('.'): + if self.buffer: + output += self.process_word() + else: + self.buffer.append(b) + else: # fixed-length, terminate after self.i bytes + self.buffer.append(b) + if len(self.buffer) == self.i: + output += self.process_word() + if final and self.buffer: # EOF terminates the last word + output += self.process_word() + return output + + def process_word(self): + output = '' + if self.buffer[0] == ord('i'): + self.i = min(99, int(self.buffer[1:] or 0)) # set input length + elif self.buffer[0] == ord('o'): + self.o = min(99, int(self.buffer[1:] or 0)) # set output length + else: + output = self.buffer.decode('ascii') + if len(output) < self.o: + output += '-'*self.o # pad out with hyphens + if self.o: + output = output[:self.o] # truncate to output length + output += '.' + self.buffer = bytearray() + return output + + codecEnabled = False + + @classmethod + def lookupTestDecoder(cls, name): + if cls.codecEnabled and name == 'test_decoder': + return codecs.CodecInfo( + name='test_decoder', encode=None, decode=None, + incrementalencoder=None, + streamreader=None, streamwriter=None, + incrementaldecoder=cls) + +# Register the previous decoder for testing. +# Disabled by default, tests will enable it. +codecs.register(StatefulIncrementalDecoder.lookupTestDecoder) + + +class StatefulIncrementalDecoderTest(unittest.TestCase): + """ + Make sure the StatefulIncrementalDecoder actually works. + """ + + test_cases = [ + # I=1, O=1 (fixed-length input == fixed-length output) + (b'abcd', False, 'a.b.c.d.'), + # I=0, O=0 (variable-length input, variable-length output) + (b'oiabcd', True, 'abcd.'), + # I=0, O=0 (should ignore extra periods) + (b'oi...abcd...', True, 'abcd.'), + # I=0, O=6 (variable-length input, fixed-length output) + (b'i.o6.x.xyz.toolongtofit.', False, 'x-----.xyz---.toolon.'), + # I=2, O=6 (fixed-length input < fixed-length output) + (b'i.i2.o6xyz', True, 'xy----.z-----.'), + # I=6, O=3 (fixed-length input > fixed-length output) + (b'i.o3.i6.abcdefghijklmnop', True, 'abc.ghi.mno.'), + # I=0, then 3; O=29, then 15 (with longer output) + (b'i.o29.a.b.cde.o15.abcdefghijabcdefghij.i3.a.b.c.d.ei00k.l.m', True, + 'a----------------------------.' + + 'b----------------------------.' + + 'cde--------------------------.' + + 'abcdefghijabcde.' + + 'a.b------------.' + + '.c.------------.' + + 'd.e------------.' + + 'k--------------.' + + 'l--------------.' + + 'm--------------.') + ] + + def testDecoder(self): + # Try a few one-shot test cases. + for input, eof, output in self.test_cases: + d = StatefulIncrementalDecoder() + self.assertEquals(d.decode(input, eof), output) + + # Also test an unfinished decode, followed by forcing EOF. + d = StatefulIncrementalDecoder() + self.assertEquals(d.decode(b'oiabcd'), '') + self.assertEquals(d.decode(b'', 1), 'abcd.') class TextIOWrapperTest(unittest.TestCase): def setUp(self): self.testdata = b"AAA\r\nBBB\rCCC\r\nDDD\nEEE\r\n" self.normalized = b"AAA\nBBB\nCCC\nDDD\nEEE\n".decode("ascii") + test_support.unlink(test_support.TESTFN) def tearDown(self): test_support.unlink(test_support.TESTFN) @@ -765,6 +912,51 @@ f.readline() f.tell() + def testSeekAndTell(self): + """Test seek/tell using the StatefulIncrementalDecoder.""" + + def testSeekAndTellWithData(data, min_pos=0): + """Tell/seek to various points within a data stream and ensure + that the decoded data returned by read() is consistent.""" + f = io.open(test_support.TESTFN, 'wb') + f.write(data) + f.close() + f = io.open(test_support.TESTFN, encoding='test_decoder') + decoded = f.read() + f.close() + + for i in range(min_pos, len(decoded) + 1): # seek positions + for j in [1, 5, len(decoded) - i]: # read lengths + f = io.open(test_support.TESTFN, encoding='test_decoder') + self.assertEquals(f.read(i), decoded[:i]) + cookie = f.tell() + self.assertEquals(f.read(j), decoded[i:i + j]) + f.seek(cookie) + self.assertEquals(f.read(), decoded[i:]) + f.close() + + # Enable the test decoder. + StatefulIncrementalDecoder.codecEnabled = 1 + + # Run the tests. + try: + # Try each test case. + for input, _, _ in StatefulIncrementalDecoderTest.test_cases: + testSeekAndTellWithData(input) + + # Position each test case so that it crosses a chunk boundary. + CHUNK_SIZE = io.TextIOWrapper._CHUNK_SIZE + for input, _, _ in StatefulIncrementalDecoderTest.test_cases: + offset = CHUNK_SIZE - len(input)//2 + prefix = b'.'*offset + # Don't bother seeking into the prefix (takes too long). + min_pos = offset*2 + testSeekAndTellWithData(prefix + input, min_pos) + + # Ensure our test decoder won't interfere with subsequent tests. + finally: + StatefulIncrementalDecoder.codecEnabled = 0 + def testEncodedWrites(self): data = "1234567890" tests = ("utf-16", @@ -895,6 +1087,12 @@ txt.seek(pos) self.assertEquals(txt.read(4), "BBB\n") + def test_issue2282(self): + buffer = io.BytesIO(self.testdata) + txt = io.TextIOWrapper(buffer, encoding="ascii") + + self.assertEqual(buffer.seekable(), txt.seekable()) + def test_newline_decoder(self): import codecs decoder = codecs.getincrementaldecoder("utf-8")() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_ioctl.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_ioctl.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_ioctl.py Wed Apr 30 15:57:13 2008 @@ -14,6 +14,11 @@ except IOError: raise TestSkipped("Unable to open /dev/tty") +try: + import pty +except ImportError: + pty = None + class IoctlTests(unittest.TestCase): def test_ioctl(self): # If this process has been put into the background, TIOCGPGRP returns @@ -34,6 +39,30 @@ self.assertEquals(r, 0) self.assert_(rpgrp in ids, "%s not in %s" % (rpgrp, ids)) + def test_ioctl_signed_unsigned_code_param(self): + if not pty: + raise TestSkipped('pty module required') + mfd, sfd = pty.openpty() + try: + if termios.TIOCSWINSZ < 0: + set_winsz_opcode_maybe_neg = termios.TIOCSWINSZ + set_winsz_opcode_pos = termios.TIOCSWINSZ & 0xffffffff + else: + set_winsz_opcode_pos = termios.TIOCSWINSZ + set_winsz_opcode_maybe_neg, = struct.unpack("i", + struct.pack("I", termios.TIOCSWINSZ)) + + # We're just testing that these calls do not raise exceptions. + saved_winsz = fcntl.ioctl(mfd, termios.TIOCGWINSZ, "\0"*8) + our_winsz = struct.pack("HHHH",80,25,0,0) + # test both with a positive and potentially negative ioctl code + new_winsz = fcntl.ioctl(mfd, set_winsz_opcode_pos, our_winsz) + new_winsz = fcntl.ioctl(mfd, set_winsz_opcode_maybe_neg, our_winsz) + fcntl.ioctl(mfd, set_winsz_opcode_maybe_neg, saved_winsz) + finally: + os.close(mfd) + os.close(sfd) + def test_main(): run_unittest(IoctlTests) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_iterlen.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_iterlen.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_iterlen.py Wed Apr 30 15:57:13 2008 @@ -45,7 +45,6 @@ from test import test_support from itertools import repeat from collections import deque -from UserList import UserList from builtins import len as _len n = 10 @@ -196,44 +195,6 @@ d.extend(range(20)) self.assertEqual(len(it), 0) -class TestSeqIter(TestInvariantWithoutMutations): - - def setUp(self): - self.it = iter(UserList(range(n))) - - def test_mutation(self): - d = UserList(range(n)) - it = iter(d) - next(it) - next(it) - self.assertEqual(len(it), n-2) - d.append(n) - self.assertEqual(len(it), n-1) # grow with append - d[1:] = [] - self.assertEqual(len(it), 0) - self.assertEqual(list(it), []) - d.extend(range(20)) - self.assertEqual(len(it), 0) - -class TestSeqIterReversed(TestInvariantWithoutMutations): - - def setUp(self): - self.it = reversed(UserList(range(n))) - - def test_mutation(self): - d = UserList(range(n)) - it = reversed(d) - next(it) - next(it) - self.assertEqual(len(it), n-2) - d.append(n) - self.assertEqual(len(it), n-2) # ignore append - d[1:] = [] - self.assertEqual(len(it), 0) - self.assertEqual(list(it), []) # confirm invariant - d.extend(range(20)) - self.assertEqual(len(it), 0) - def test_main(): unittests = [ @@ -249,8 +210,6 @@ TestSet, TestList, TestListReversed, - TestSeqIter, - TestSeqIterReversed, ] test_support.run_unittest(*unittests) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_itertools.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_itertools.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_itertools.py Wed Apr 30 15:57:13 2008 @@ -5,6 +5,7 @@ import sys import operator import random +from functools import reduce maxsize = test_support.MAX_Py_ssize_t minsize = -maxsize-1 @@ -43,13 +44,152 @@ 'Convenience function for partially consuming a long of infinite iterable' return list(islice(seq, n)) +def prod(iterable): + return reduce(operator.mul, iterable, 1) + +def fact(n): + 'Factorial' + return prod(range(1, n+1)) + class TestBasicOps(unittest.TestCase): def test_chain(self): - self.assertEqual(list(chain('abc', 'def')), list('abcdef')) - self.assertEqual(list(chain('abc')), list('abc')) - self.assertEqual(list(chain('')), []) - self.assertEqual(take(4, chain('abc', 'def')), list('abcd')) - self.assertRaises(TypeError, chain, 2, 3) + + def chain2(*iterables): + 'Pure python version in the docs' + for it in iterables: + for element in it: + yield element + + for c in (chain, chain2): + self.assertEqual(list(c('abc', 'def')), list('abcdef')) + self.assertEqual(list(c('abc')), list('abc')) + self.assertEqual(list(c('')), []) + self.assertEqual(take(4, c('abc', 'def')), list('abcd')) + self.assertRaises(TypeError, list,c(2, 3)) + + def test_chain_from_iterable(self): + self.assertEqual(list(chain.from_iterable(['abc', 'def'])), list('abcdef')) + self.assertEqual(list(chain.from_iterable(['abc'])), list('abc')) + self.assertEqual(list(chain.from_iterable([''])), []) + self.assertEqual(take(4, chain.from_iterable(['abc', 'def'])), list('abcd')) + self.assertRaises(TypeError, list, chain.from_iterable([2, 3])) + + def test_combinations(self): + self.assertRaises(TypeError, combinations, 'abc') # missing r argument + self.assertRaises(TypeError, combinations, 'abc', 2, 1) # too many arguments + self.assertRaises(TypeError, combinations, None) # pool is not iterable + self.assertRaises(ValueError, combinations, 'abc', -2) # r is negative + self.assertRaises(ValueError, combinations, 'abc', 32) # r is too big + self.assertEqual(list(combinations(range(4), 3)), + [(0,1,2), (0,1,3), (0,2,3), (1,2,3)]) + + def combinations1(iterable, r): + 'Pure python version shown in the docs' + pool = tuple(iterable) + n = len(pool) + indices = list(range(r)) + yield tuple(pool[i] for i in indices) + while 1: + for i in reversed(range(r)): + if indices[i] != i + n - r: + break + else: + return + indices[i] += 1 + for j in range(i+1, r): + indices[j] = indices[j-1] + 1 + yield tuple(pool[i] for i in indices) + + def combinations2(iterable, r): + 'Pure python version shown in the docs' + pool = tuple(iterable) + n = len(pool) + for indices in permutations(range(n), r): + if sorted(indices) == list(indices): + yield tuple(pool[i] for i in indices) + + for n in range(7): + values = [5*x-12 for x in range(n)] + for r in range(n+1): + result = list(combinations(values, r)) + self.assertEqual(len(result), fact(n) / fact(r) / fact(n-r)) # right number of combs + self.assertEqual(len(result), len(set(result))) # no repeats + self.assertEqual(result, sorted(result)) # lexicographic order + for c in result: + self.assertEqual(len(c), r) # r-length combinations + self.assertEqual(len(set(c)), r) # no duplicate elements + self.assertEqual(list(c), sorted(c)) # keep original ordering + self.assert_(all(e in values for e in c)) # elements taken from input iterable + self.assertEqual(list(c), + [e for e in values if e in c]) # comb is a subsequence of the input iterable + self.assertEqual(result, list(combinations1(values, r))) # matches first pure python version + self.assertEqual(result, list(combinations2(values, r))) # matches first pure python version + + # Test implementation detail: tuple re-use + self.assertEqual(len(set(map(id, combinations('abcde', 3)))), 1) + self.assertNotEqual(len(set(map(id, list(combinations('abcde', 3))))), 1) + + def test_permutations(self): + self.assertRaises(TypeError, permutations) # too few arguments + self.assertRaises(TypeError, permutations, 'abc', 2, 1) # too many arguments + self.assertRaises(TypeError, permutations, None) # pool is not iterable + self.assertRaises(ValueError, permutations, 'abc', -2) # r is negative + self.assertRaises(ValueError, permutations, 'abc', 32) # r is too big + self.assertRaises(TypeError, permutations, 'abc', 's') # r is not an int or None + self.assertEqual(list(permutations(range(3), 2)), + [(0,1), (0,2), (1,0), (1,2), (2,0), (2,1)]) + + def permutations1(iterable, r=None): + 'Pure python version shown in the docs' + pool = tuple(iterable) + n = len(pool) + r = n if r is None else r + indices = list(range(n)) + cycles = list(range(n-r+1, n+1))[::-1] + yield tuple(pool[i] for i in indices[:r]) + while n: + for i in reversed(range(r)): + cycles[i] -= 1 + if cycles[i] == 0: + indices[i:] = indices[i+1:] + indices[i:i+1] + cycles[i] = n - i + else: + j = cycles[i] + indices[i], indices[-j] = indices[-j], indices[i] + yield tuple(pool[i] for i in indices[:r]) + break + else: + return + + def permutations2(iterable, r=None): + 'Pure python version shown in the docs' + pool = tuple(iterable) + n = len(pool) + r = n if r is None else r + for indices in product(range(n), repeat=r): + if len(set(indices)) == r: + yield tuple(pool[i] for i in indices) + + for n in range(7): + values = [5*x-12 for x in range(n)] + for r in range(n+1): + result = list(permutations(values, r)) + self.assertEqual(len(result), fact(n) / fact(n-r)) # right number of perms + self.assertEqual(len(result), len(set(result))) # no repeats + self.assertEqual(result, sorted(result)) # lexicographic order + for p in result: + self.assertEqual(len(p), r) # r-length permutations + self.assertEqual(len(set(p)), r) # no duplicate elements + self.assert_(all(e in values for e in p)) # elements taken from input iterable + self.assertEqual(result, list(permutations1(values, r))) # matches first pure python version + self.assertEqual(result, list(permutations2(values, r))) # matches first pure python version + if r == n: + self.assertEqual(result, list(permutations(values, None))) # test r as None + self.assertEqual(result, list(permutations(values))) # test default r + + # Test implementation detail: tuple re-use + self.assertEqual(len(set(map(id, permutations('abcde', 3)))), 1) + self.assertNotEqual(len(set(map(id, list(permutations('abcde', 3))))), 1) def test_count(self): self.assertEqual(lzip('abc',count()), [('a', 0), ('b', 1), ('c', 2)]) @@ -173,48 +313,50 @@ keyfunc.skip = 1 self.assertRaises(ExpectedError, gulp, [None, None], keyfunc) - def test_ifilter(self): - self.assertEqual(list(ifilter(isEven, range(6))), [0,2,4]) - self.assertEqual(list(ifilter(None, [0,1,0,2,0])), [1,2]) - self.assertEqual(take(4, ifilter(isEven, count())), [0,2,4,6]) - self.assertRaises(TypeError, ifilter) - self.assertRaises(TypeError, ifilter, lambda x:x) - self.assertRaises(TypeError, ifilter, lambda x:x, range(6), 7) - self.assertRaises(TypeError, ifilter, isEven, 3) - self.assertRaises(TypeError, next, ifilter(range(6), range(6))) - - def test_ifilterfalse(self): - self.assertEqual(list(ifilterfalse(isEven, range(6))), [1,3,5]) - self.assertEqual(list(ifilterfalse(None, [0,1,0,2,0])), [0,0,0]) - self.assertEqual(take(4, ifilterfalse(isEven, count())), [1,3,5,7]) - self.assertRaises(TypeError, ifilterfalse) - self.assertRaises(TypeError, ifilterfalse, lambda x:x) - self.assertRaises(TypeError, ifilterfalse, lambda x:x, range(6), 7) - self.assertRaises(TypeError, ifilterfalse, isEven, 3) - self.assertRaises(TypeError, next, ifilterfalse(range(6), range(6))) - - def test_izip(self): - # XXX This is rather silly now that builtin zip() calls izip()... - ans = [(x,y) for x, y in izip('abc',count())] + def test_filter(self): + self.assertEqual(list(filter(isEven, range(6))), [0,2,4]) + self.assertEqual(list(filter(None, [0,1,0,2,0])), [1,2]) + self.assertEqual(list(filter(bool, [0,1,0,2,0])), [1,2]) + self.assertEqual(take(4, filter(isEven, count())), [0,2,4,6]) + self.assertRaises(TypeError, filter) + self.assertRaises(TypeError, filter, lambda x:x) + self.assertRaises(TypeError, filter, lambda x:x, range(6), 7) + self.assertRaises(TypeError, filter, isEven, 3) + self.assertRaises(TypeError, next, filter(range(6), range(6))) + + def test_filterfalse(self): + self.assertEqual(list(filterfalse(isEven, range(6))), [1,3,5]) + self.assertEqual(list(filterfalse(None, [0,1,0,2,0])), [0,0,0]) + self.assertEqual(list(filterfalse(bool, [0,1,0,2,0])), [0,0,0]) + self.assertEqual(take(4, filterfalse(isEven, count())), [1,3,5,7]) + self.assertRaises(TypeError, filterfalse) + self.assertRaises(TypeError, filterfalse, lambda x:x) + self.assertRaises(TypeError, filterfalse, lambda x:x, range(6), 7) + self.assertRaises(TypeError, filterfalse, isEven, 3) + self.assertRaises(TypeError, next, filterfalse(range(6), range(6))) + + def test_zip(self): + # XXX This is rather silly now that builtin zip() calls zip()... + ans = [(x,y) for x, y in zip('abc',count())] self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)]) - self.assertEqual(list(izip('abc', range(6))), lzip('abc', range(6))) - self.assertEqual(list(izip('abcdef', range(3))), lzip('abcdef', range(3))) - self.assertEqual(take(3,izip('abcdef', count())), lzip('abcdef', range(3))) - self.assertEqual(list(izip('abcdef')), lzip('abcdef')) - self.assertEqual(list(izip()), lzip()) - self.assertRaises(TypeError, izip, 3) - self.assertRaises(TypeError, izip, range(3), 3) + self.assertEqual(list(zip('abc', range(6))), lzip('abc', range(6))) + self.assertEqual(list(zip('abcdef', range(3))), lzip('abcdef', range(3))) + self.assertEqual(take(3,zip('abcdef', count())), lzip('abcdef', range(3))) + self.assertEqual(list(zip('abcdef')), lzip('abcdef')) + self.assertEqual(list(zip()), lzip()) + self.assertRaises(TypeError, zip, 3) + self.assertRaises(TypeError, zip, range(3), 3) # Check tuple re-use (implementation detail) - self.assertEqual([tuple(list(pair)) for pair in izip('abc', 'def')], + self.assertEqual([tuple(list(pair)) for pair in zip('abc', 'def')], lzip('abc', 'def')) - self.assertEqual([pair for pair in izip('abc', 'def')], + self.assertEqual([pair for pair in zip('abc', 'def')], lzip('abc', 'def')) - ids = list(map(id, izip('abc', 'def'))) + ids = list(map(id, zip('abc', 'def'))) self.assertEqual(min(ids), max(ids)) - ids = list(map(id, list(izip('abc', 'def')))) + ids = list(map(id, list(zip('abc', 'def')))) self.assertEqual(len(dict.fromkeys(ids)), len(ids)) - def test_iziplongest(self): + def test_ziplongest(self): for args in [ ['abc', range(6)], [range(6), 'abc'], @@ -224,25 +366,25 @@ ]: target = [tuple([arg[i] if i < len(arg) else None for arg in args]) for i in range(max(map(len, args)))] - self.assertEqual(list(izip_longest(*args)), target) - self.assertEqual(list(izip_longest(*args, **{})), target) + self.assertEqual(list(zip_longest(*args)), target) + self.assertEqual(list(zip_longest(*args, **{})), target) target = [tuple((e is None and 'X' or e) for e in t) for t in target] # Replace None fills with 'X' - self.assertEqual(list(izip_longest(*args, **dict(fillvalue='X'))), target) + self.assertEqual(list(zip_longest(*args, **dict(fillvalue='X'))), target) - self.assertEqual(take(3,izip_longest('abcdef', count())), list(zip('abcdef', range(3)))) # take 3 from infinite input + self.assertEqual(take(3,zip_longest('abcdef', count())), list(zip('abcdef', range(3)))) # take 3 from infinite input - self.assertEqual(list(izip_longest()), list(zip())) - self.assertEqual(list(izip_longest([])), list(zip([]))) - self.assertEqual(list(izip_longest('abcdef')), list(zip('abcdef'))) - - self.assertEqual(list(izip_longest('abc', 'defg', **{})), - list(izip(list('abc')+[None], 'defg'))) # empty keyword dict - self.assertRaises(TypeError, izip_longest, 3) - self.assertRaises(TypeError, izip_longest, range(3), 3) + self.assertEqual(list(zip_longest()), list(zip())) + self.assertEqual(list(zip_longest([])), list(zip([]))) + self.assertEqual(list(zip_longest('abcdef')), list(zip('abcdef'))) + + self.assertEqual(list(zip_longest('abc', 'defg', **{})), + list(zip(list('abc')+[None], 'defg'))) # empty keyword dict + self.assertRaises(TypeError, zip_longest, 3) + self.assertRaises(TypeError, zip_longest, range(3), 3) for stmt in [ - "izip_longest('abc', fv=1)", - "izip_longest('abc', fillvalue=1, bogus_keyword=None)", + "zip_longest('abc', fv=1)", + "zip_longest('abc', fillvalue=1, bogus_keyword=None)", ]: try: eval(stmt, globals(), locals()) @@ -252,15 +394,77 @@ self.fail('Did not raise Type in: ' + stmt) # Check tuple re-use (implementation detail) - self.assertEqual([tuple(list(pair)) for pair in izip_longest('abc', 'def')], + self.assertEqual([tuple(list(pair)) for pair in zip_longest('abc', 'def')], list(zip('abc', 'def'))) - self.assertEqual([pair for pair in izip_longest('abc', 'def')], + self.assertEqual([pair for pair in zip_longest('abc', 'def')], list(zip('abc', 'def'))) - ids = list(map(id, izip_longest('abc', 'def'))) + ids = list(map(id, zip_longest('abc', 'def'))) self.assertEqual(min(ids), max(ids)) - ids = list(map(id, list(izip_longest('abc', 'def')))) + ids = list(map(id, list(zip_longest('abc', 'def')))) self.assertEqual(len(dict.fromkeys(ids)), len(ids)) + def test_product(self): + for args, result in [ + ([], [()]), # zero iterables + (['ab'], [('a',), ('b',)]), # one iterable + ([range(2), range(3)], [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2)]), # two iterables + ([range(0), range(2), range(3)], []), # first iterable with zero length + ([range(2), range(0), range(3)], []), # middle iterable with zero length + ([range(2), range(3), range(0)], []), # last iterable with zero length + ]: + self.assertEqual(list(product(*args)), result) + for r in range(4): + self.assertEqual(list(product(*(args*r))), + list(product(*args, **dict(repeat=r)))) + self.assertEqual(len(list(product(*[range(7)]*6))), 7**6) + self.assertRaises(TypeError, product, range(6), None) + + def product1(*args, **kwds): + pools = list(map(tuple, args)) * kwds.get('repeat', 1) + n = len(pools) + if n == 0: + yield () + return + if any(len(pool) == 0 for pool in pools): + return + indices = [0] * n + yield tuple(pool[i] for pool, i in zip(pools, indices)) + while 1: + for i in reversed(range(n)): # right to left + if indices[i] == len(pools[i]) - 1: + continue + indices[i] += 1 + for j in range(i+1, n): + indices[j] = 0 + yield tuple(pool[i] for pool, i in zip(pools, indices)) + break + else: + return + + def product2(*args, **kwds): + 'Pure python version used in docs' + pools = list(map(tuple, args)) * kwds.get('repeat', 1) + result = [[]] + for pool in pools: + result = [x+[y] for x in result for y in pool] + for prod in result: + yield tuple(prod) + + argtypes = ['', 'abc', '', range(0), range(4), dict(a=1, b=2, c=3), + set('abcdefg'), range(11), tuple(range(13))] + for i in range(100): + args = [random.choice(argtypes) for j in range(random.randrange(5))] + expected_len = prod(map(len, args)) + self.assertEqual(len(list(product(*args))), expected_len) + self.assertEqual(list(product(*args)), list(product1(*args))) + self.assertEqual(list(product(*args)), list(product2(*args))) + args = map(iter, args) + self.assertEqual(len(list(product(*args))), expected_len) + + # Test implementation detail: tuple re-use + self.assertEqual(len(set(map(id, product('abc', 'def')))), 1) + self.assertNotEqual(len(set(map(id, list(product('abc', 'def'))))), 1) + def test_repeat(self): self.assertEqual(lzip(range(3),repeat('a')), [(0, 'a'), (1, 'a'), (2, 'a')]) @@ -278,29 +482,29 @@ list(r) self.assertEqual(repr(r), 'repeat((1+0j), 0)') - def test_imap(self): - self.assertEqual(list(imap(operator.pow, range(3), range(1,7))), + def test_map(self): + self.assertEqual(list(map(operator.pow, range(3), range(1,7))), [0**1, 1**2, 2**3]) def tupleize(*args): return args - self.assertEqual(list(imap(tupleize, 'abc', range(5))), + self.assertEqual(list(map(tupleize, 'abc', range(5))), [('a',0),('b',1),('c',2)]) - self.assertEqual(list(imap(tupleize, 'abc', count())), + self.assertEqual(list(map(tupleize, 'abc', count())), [('a',0),('b',1),('c',2)]) - self.assertEqual(take(2,imap(tupleize, 'abc', count())), + self.assertEqual(take(2,map(tupleize, 'abc', count())), [('a',0),('b',1)]) - self.assertEqual(list(imap(operator.pow, [])), []) - self.assertRaises(TypeError, imap) - self.assertRaises(TypeError, list, imap(None, range(3), range(3))) - self.assertRaises(TypeError, imap, operator.neg) - self.assertRaises(TypeError, next, imap(10, range(5))) - self.assertRaises(ValueError, next, imap(errfunc, [4], [5])) - self.assertRaises(TypeError, next, imap(onearg, [4], [5])) + self.assertEqual(list(map(operator.pow, [])), []) + self.assertRaises(TypeError, map) + self.assertRaises(TypeError, list, map(None, range(3), range(3))) + self.assertRaises(TypeError, map, operator.neg) + self.assertRaises(TypeError, next, map(10, range(5))) + self.assertRaises(ValueError, next, map(errfunc, [4], [5])) + self.assertRaises(TypeError, next, map(onearg, [4], [5])) def test_starmap(self): self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))), [0**1, 1**2, 2**3]) - self.assertEqual(take(3, starmap(operator.pow, izip(count(), count(1)))), + self.assertEqual(take(3, starmap(operator.pow, zip(count(), count(1)))), [0**1, 1**2, 2**3]) self.assertEqual(list(starmap(operator.pow, [])), []) self.assertEqual(list(starmap(operator.pow, [iter([4,5])])), [4**5]) @@ -471,9 +675,9 @@ self.assertRaises(ReferenceError, getattr, p, '__class__') def test_StopIteration(self): - self.assertRaises(StopIteration, next, izip()) + self.assertRaises(StopIteration, next, zip()) - for f in (chain, cycle, izip, groupby): + for f in (chain, cycle, zip, groupby): self.assertRaises(StopIteration, next, f([])) self.assertRaises(StopIteration, next, f(StopNow())) @@ -489,10 +693,85 @@ self.assertRaises(StopIteration, next, repeat(None, 0)) - for f in (ifilter, ifilterfalse, imap, takewhile, dropwhile, starmap): + for f in (filter, filterfalse, map, takewhile, dropwhile, starmap): self.assertRaises(StopIteration, next, f(lambda x:x, [])) self.assertRaises(StopIteration, next, f(lambda x:x, StopNow())) +class TestExamples(unittest.TestCase): + + def test_chain(self): + self.assertEqual(''.join(chain('ABC', 'DEF')), 'ABCDEF') + + def test_chain_from_iterable(self): + self.assertEqual(''.join(chain.from_iterable(['ABC', 'DEF'])), 'ABCDEF') + + def test_combinations(self): + self.assertEqual(list(combinations('ABCD', 2)), + [('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')]) + self.assertEqual(list(combinations(range(4), 3)), + [(0,1,2), (0,1,3), (0,2,3), (1,2,3)]) + + def test_count(self): + self.assertEqual(list(islice(count(10), 5)), [10, 11, 12, 13, 14]) + + def test_cycle(self): + self.assertEqual(list(islice(cycle('ABCD'), 12)), list('ABCDABCDABCD')) + + def test_dropwhile(self): + self.assertEqual(list(dropwhile(lambda x: x<5, [1,4,6,4,1])), [6,4,1]) + + def test_groupby(self): + self.assertEqual([k for k, g in groupby('AAAABBBCCDAABBB')], + list('ABCDAB')) + self.assertEqual([(list(g)) for k, g in groupby('AAAABBBCCD')], + [list('AAAA'), list('BBB'), list('CC'), list('D')]) + + def test_filter(self): + self.assertEqual(list(filter(lambda x: x%2, range(10))), [1,3,5,7,9]) + + def test_filterfalse(self): + self.assertEqual(list(filterfalse(lambda x: x%2, range(10))), [0,2,4,6,8]) + + def test_map(self): + self.assertEqual(list(map(pow, (2,3,10), (5,2,3))), [32, 9, 1000]) + + def test_islice(self): + self.assertEqual(list(islice('ABCDEFG', 2)), list('AB')) + self.assertEqual(list(islice('ABCDEFG', 2, 4)), list('CD')) + self.assertEqual(list(islice('ABCDEFG', 2, None)), list('CDEFG')) + self.assertEqual(list(islice('ABCDEFG', 0, None, 2)), list('ACEG')) + + def test_zip(self): + self.assertEqual(list(zip('ABCD', 'xy')), [('A', 'x'), ('B', 'y')]) + + def test_zip_longest(self): + self.assertEqual(list(zip_longest('ABCD', 'xy', fillvalue='-')), + [('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-')]) + + def test_permutations(self): + self.assertEqual(list(permutations('ABCD', 2)), + list(map(tuple, 'AB AC AD BA BC BD CA CB CD DA DB DC'.split()))) + self.assertEqual(list(permutations(range(3))), + [(0,1,2), (0,2,1), (1,0,2), (1,2,0), (2,0,1), (2,1,0)]) + + def test_product(self): + self.assertEqual(list(product('ABCD', 'xy')), + list(map(tuple, 'Ax Ay Bx By Cx Cy Dx Dy'.split()))) + self.assertEqual(list(product(range(2), repeat=3)), + [(0,0,0), (0,0,1), (0,1,0), (0,1,1), + (1,0,0), (1,0,1), (1,1,0), (1,1,1)]) + + def test_repeat(self): + self.assertEqual(list(repeat(10, 3)), [10, 10, 10]) + + def test_stapmap(self): + self.assertEqual(list(starmap(pow, [(2,5), (3,2), (10,3)])), + [32, 9, 1000]) + + def test_takewhile(self): + self.assertEqual(list(takewhile(lambda x: x<5, [1,4,6,4,1])), [1,4]) + + class TestGC(unittest.TestCase): def makecycle(self, iterator, container): @@ -504,6 +783,14 @@ a = [] self.makecycle(chain(a), a) + def test_chain_from_iterable(self): + a = [] + self.makecycle(chain.from_iterable([a]), a) + + def test_combinations(self): + a = [] + self.makecycle(combinations([1,2,a,3], 3), a) + def test_cycle(self): a = [] self.makecycle(cycle([a]*2), a) @@ -516,26 +803,47 @@ a = [] self.makecycle(groupby([a]*2, lambda x:x), a) - def test_ifilter(self): + def test_issue2246(self): + # Issue 2246 -- the _grouper iterator was not included in GC + n = 10 + keyfunc = lambda x: x + for i, j in groupby(range(n), key=keyfunc): + keyfunc.__dict__.setdefault('x',[]).append(j) + + def test_filter(self): + a = [] + self.makecycle(filter(lambda x:True, [a]*2), a) + + def test_filterfalse(self): a = [] - self.makecycle(ifilter(lambda x:True, [a]*2), a) + self.makecycle(filterfalse(lambda x:False, a), a) - def test_ifilterfalse(self): + def test_zip(self): a = [] - self.makecycle(ifilterfalse(lambda x:False, a), a) + self.makecycle(zip([a]*2, [a]*3), a) - def test_izip(self): + def test_zip_longest(self): a = [] - self.makecycle(izip([a]*2, [a]*3), a) + self.makecycle(zip_longest([a]*2, [a]*3), a) + b = [a, None] + self.makecycle(zip_longest([a]*2, [a]*3, fillvalue=b), a) - def test_imap(self): + def test_map(self): a = [] - self.makecycle(imap(lambda x:x, [a]*2), a) + self.makecycle(map(lambda x:x, [a]*2), a) def test_islice(self): a = [] self.makecycle(islice([a]*2, None), a) + def test_permutations(self): + a = [] + self.makecycle(permutations([1,2,a,3], 3), a) + + def test_product(self): + a = [] + self.makecycle(product([1,2,a,3], repeat=3), a) + def test_repeat(self): a = [] self.makecycle(repeat(a), a) @@ -622,7 +930,7 @@ def L(seqn): 'Test multiple tiers of iterators' - return chain(imap(lambda x:x, R(Ig(G(seqn))))) + return chain(map(lambda x:x, R(Ig(G(seqn))))) class TestVariousIteratorArgs(unittest.TestCase): @@ -632,10 +940,16 @@ for g in (G, I, Ig, S, L, R): self.assertEqual(list(chain(g(s))), list(g(s))) self.assertEqual(list(chain(g(s), g(s))), list(g(s))+list(g(s))) - self.assertRaises(TypeError, chain, X(s)) - self.assertRaises(TypeError, chain, N(s)) + self.assertRaises(TypeError, list, chain(X(s))) + self.assertRaises(TypeError, list, chain(N(s))) self.assertRaises(ZeroDivisionError, list, chain(E(s))) + def test_product(self): + for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)): + self.assertRaises(TypeError, product, X(s)) + self.assertRaises(TypeError, product, N(s)) + self.assertRaises(ZeroDivisionError, product, E(s)) + def test_cycle(self): for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)): for g in (G, I, Ig, S, L, R): @@ -655,52 +969,52 @@ self.assertRaises(TypeError, groupby, N(s)) self.assertRaises(ZeroDivisionError, list, groupby(E(s))) - def test_ifilter(self): + def test_filter(self): for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)): for g in (G, I, Ig, S, L, R): - self.assertEqual(list(ifilter(isEven, g(s))), + self.assertEqual(list(filter(isEven, g(s))), [x for x in g(s) if isEven(x)]) - self.assertRaises(TypeError, ifilter, isEven, X(s)) - self.assertRaises(TypeError, ifilter, isEven, N(s)) - self.assertRaises(ZeroDivisionError, list, ifilter(isEven, E(s))) + self.assertRaises(TypeError, filter, isEven, X(s)) + self.assertRaises(TypeError, filter, isEven, N(s)) + self.assertRaises(ZeroDivisionError, list, filter(isEven, E(s))) - def test_ifilterfalse(self): + def test_filterfalse(self): for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)): for g in (G, I, Ig, S, L, R): - self.assertEqual(list(ifilterfalse(isEven, g(s))), + self.assertEqual(list(filterfalse(isEven, g(s))), [x for x in g(s) if isOdd(x)]) - self.assertRaises(TypeError, ifilterfalse, isEven, X(s)) - self.assertRaises(TypeError, ifilterfalse, isEven, N(s)) - self.assertRaises(ZeroDivisionError, list, ifilterfalse(isEven, E(s))) + self.assertRaises(TypeError, filterfalse, isEven, X(s)) + self.assertRaises(TypeError, filterfalse, isEven, N(s)) + self.assertRaises(ZeroDivisionError, list, filterfalse(isEven, E(s))) - def test_izip(self): + def test_zip(self): for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)): for g in (G, I, Ig, S, L, R): - self.assertEqual(list(izip(g(s))), lzip(g(s))) - self.assertEqual(list(izip(g(s), g(s))), lzip(g(s), g(s))) - self.assertRaises(TypeError, izip, X(s)) - self.assertRaises(TypeError, izip, N(s)) - self.assertRaises(ZeroDivisionError, list, izip(E(s))) + self.assertEqual(list(zip(g(s))), lzip(g(s))) + self.assertEqual(list(zip(g(s), g(s))), lzip(g(s), g(s))) + self.assertRaises(TypeError, zip, X(s)) + self.assertRaises(TypeError, zip, N(s)) + self.assertRaises(ZeroDivisionError, list, zip(E(s))) - def test_iziplongest(self): + def test_ziplongest(self): for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)): for g in (G, I, Ig, S, L, R): - self.assertEqual(list(izip_longest(g(s))), list(zip(g(s)))) - self.assertEqual(list(izip_longest(g(s), g(s))), list(zip(g(s), g(s)))) - self.assertRaises(TypeError, izip_longest, X(s)) - self.assertRaises(TypeError, izip_longest, N(s)) - self.assertRaises(ZeroDivisionError, list, izip_longest(E(s))) + self.assertEqual(list(zip_longest(g(s))), list(zip(g(s)))) + self.assertEqual(list(zip_longest(g(s), g(s))), list(zip(g(s), g(s)))) + self.assertRaises(TypeError, zip_longest, X(s)) + self.assertRaises(TypeError, zip_longest, N(s)) + self.assertRaises(ZeroDivisionError, list, zip_longest(E(s))) - def test_imap(self): + def test_map(self): for s in (range(10), range(0), range(100), (7,11), range(20,50,5)): for g in (G, I, Ig, S, L, R): - self.assertEqual(list(imap(onearg, g(s))), + self.assertEqual(list(map(onearg, g(s))), [onearg(x) for x in g(s)]) - self.assertEqual(list(imap(operator.pow, g(s), g(s))), + self.assertEqual(list(map(operator.pow, g(s), g(s))), [x**x for x in g(s)]) - self.assertRaises(TypeError, imap, onearg, X(s)) - self.assertRaises(TypeError, imap, onearg, N(s)) - self.assertRaises(ZeroDivisionError, list, imap(onearg, E(s))) + self.assertRaises(TypeError, map, onearg, X(s)) + self.assertRaises(TypeError, map, onearg, N(s)) + self.assertRaises(ZeroDivisionError, list, map(onearg, E(s))) def test_islice(self): for s in ("12345", "", range(1000), ('do', 1.2), range(2000,2200,5)): @@ -777,8 +1091,8 @@ return value items = list(tuple2) items[1:1] = list(tuple1) - gen = imap(g, items) - z = izip(*[gen]*len(tuple1)) + gen = map(g, items) + z = zip(*[gen]*len(tuple1)) next(z) def f(t): @@ -825,7 +1139,7 @@ class SubclassWithKwargsTest(unittest.TestCase): def test_keywords_in_subclass(self): # count is not subclassable... - for cls in (repeat, izip, ifilter, ifilterfalse, chain, imap, + for cls in (repeat, zip, filter, filterfalse, chain, map, starmap, islice, takewhile, dropwhile, cycle): class Subclass(cls): def __init__(self, newarg=None, *args): @@ -841,7 +1155,7 @@ >>> amounts = [120.15, 764.05, 823.14] ->>> for checknum, amount in izip(count(1200), amounts): +>>> for checknum, amount in zip(count(1200), amounts): ... print('Check %d is for $%.2f' % (checknum, amount)) ... Check 1200 is for $120.15 @@ -849,7 +1163,7 @@ Check 1202 is for $823.14 >>> import operator ->>> for cube in imap(operator.pow, range(1,4), repeat(3)): +>>> for cube in map(operator.pow, range(1,4), repeat(3)): ... print(cube) ... 1 @@ -894,14 +1208,14 @@ ... return list(islice(seq, n)) >>> def enumerate(iterable): -... return izip(count(), iterable) +... return zip(count(), iterable) >>> def tabulate(function): ... "Return function(0), function(1), ..." -... return imap(function, count()) +... return map(function, count()) >>> def iteritems(mapping): -... return izip(mapping.keys(), mapping.values()) +... return zip(mapping.keys(), mapping.values()) >>> def nth(iterable, n): ... "Returns the nth item" @@ -909,25 +1223,25 @@ >>> def all(seq, pred=None): ... "Returns True if pred(x) is true for every element in the iterable" -... for elem in ifilterfalse(pred, seq): +... for elem in filterfalse(pred, seq): ... return False ... return True >>> def any(seq, pred=None): ... "Returns True if pred(x) is true for at least one element in the iterable" -... for elem in ifilter(pred, seq): +... for elem in filter(pred, seq): ... return True ... return False >>> def no(seq, pred=None): ... "Returns True if pred(x) is false for every element in the iterable" -... for elem in ifilter(pred, seq): +... for elem in filter(pred, seq): ... return False ... return True >>> def quantify(seq, pred=None): ... "Count how many times the predicate is true in the sequence" -... return sum(imap(pred, seq)) +... return sum(map(pred, seq)) >>> def padnone(seq): ... "Returns the sequence elements and then returns None indefinitely" @@ -938,10 +1252,10 @@ ... return chain(*repeat(seq, n)) >>> def dotproduct(vec1, vec2): -... return sum(imap(operator.mul, vec1, vec2)) +... return sum(map(operator.mul, vec1, vec2)) >>> def flatten(listOfLists): -... return list(chain(*listOfLists)) +... return list(chain.from_iterable(listOfLists)) >>> def repeatfunc(func, times=None, *args): ... "Repeat calls to func with specified arguments." @@ -958,7 +1272,39 @@ ... next(b) ... except StopIteration: ... pass -... return izip(a, b) +... return zip(a, b) + +>>> def grouper(n, iterable, fillvalue=None): +... "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')" +... args = [iter(iterable)] * n +... kwds = dict(fillvalue=fillvalue) +... return zip_longest(*args, **kwds) + +>>> def roundrobin(*iterables): +... "roundrobin('abc', 'd', 'ef') --> 'a', 'd', 'e', 'b', 'f', 'c'" +... # Recipe credited to George Sakkis +... pending = len(iterables) +... nexts = cycle(iter(it).__next__ for it in iterables) +... while pending: +... try: +... for next in nexts: +... yield next() +... except StopIteration: +... pending -= 1 +... nexts = cycle(islice(nexts, pending)) + +>>> def powerset(iterable): +... "powerset('ab') --> set([]), set(['a']), set(['b']), set(['a', 'b'])" +... # Recipe credited to Eric Raymond +... pairs = [(2**i, x) for i, x in enumerate(iterable)] +... for n in range(2**len(pairs)): +... yield set(x for m, x in pairs if m&n) + +>>> def compress(data, selectors): +... "compress('abcdef', [1,0,1,0,1,1]) --> a c e f" +... for d, s in zip(data, selectors): +... if s: +... yield d This is not part of the examples but it tests to make sure the definitions perform as purported. @@ -1004,7 +1350,7 @@ [8, 8, 8, 8, 8] >>> import random ->>> take(5, imap(int, repeatfunc(random.random))) +>>> take(5, map(int, repeatfunc(random.random))) [0, 0, 0, 0, 0] >>> list(pairwise('abcd')) @@ -1025,6 +1371,18 @@ >>> dotproduct([1,2,3], [4,5,6]) 32 +>>> list(grouper(3, 'abcdefg', 'x')) +[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'x', 'x')] + +>>> list(roundrobin('abc', 'd', 'ef')) +['a', 'd', 'e', 'b', 'f', 'c'] + +>>> list(map(sorted, powerset('ab'))) +[[], ['a'], ['b'], ['a', 'b']] + +>>> list(compress('abcdef', [1,0,1,0,1,1])) +['a', 'c', 'e', 'f'] + """ __test__ = {'libreftest' : libreftest} @@ -1032,7 +1390,7 @@ def test_main(verbose=None): test_classes = (TestBasicOps, TestVariousIteratorArgs, TestGC, RegressionTests, LengthTransparency, - SubclassWithKwargsTest) + SubclassWithKwargsTest, TestExamples) test_support.run_unittest(*test_classes) # verify reference counting Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_largefile.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_largefile.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_largefile.py Wed Apr 30 15:57:13 2008 @@ -1,12 +1,12 @@ -#!python +"""Test largefile support on system where this makes sense. +""" -#---------------------------------------------------------------------- -# test largefile support on system where this makes sense -# -#---------------------------------------------------------------------- - -from test import test_support -import os, stat, sys +import os +import stat +import sys +import unittest +from test.test_support import run_unittest, TESTFN, verbose, requires, \ + TestSkipped, unlink try: import signal @@ -17,154 +17,158 @@ except (ImportError, AttributeError): pass - # create >2GB file (2GB = 2147483648 bytes) size = 2500000000 -name = test_support.TESTFN -# On Windows and Mac OSX this test comsumes large resources; It takes -# a long time to build the >2GB file and takes >2GB of disk space -# therefore the resource must be enabled to run this test. If not, -# nothing after this line stanza will be executed. -if sys.platform[:3] == 'win' or sys.platform == 'darwin': - test_support.requires( - 'largefile', - 'test requires %s bytes and a long time to run' % str(size)) -else: - # Only run if the current filesystem supports large files. - # (Skip this test on Windows, since we now always support large files.) - f = open(test_support.TESTFN, 'wb') - try: - # 2**31 == 2147483648 - f.seek(2147483649) - # Seeking is not enough of a test: you must write and flush, too! - f.write(b"x") - f.flush() - except (IOError, OverflowError): - f.close() - os.unlink(test_support.TESTFN) - raise test_support.TestSkipped( - "filesystem does not have largefile support") +class TestCase(unittest.TestCase): + """Test that each file function works as expected for a large + (i.e. > 2GB, do we have to check > 4GB) files. + + NOTE: the order of execution of the test methods is important! test_seek + must run first to create the test file. File cleanup must also be handled + outside the test instances because of this. + + """ + + def test_seek(self): + if verbose: + print('create large file via seek (may be sparse file) ...') + with open(TESTFN, 'wb') as f: + f.write(b'z') + f.seek(0) + f.seek(size) + f.write(b'a') + f.flush() + if verbose: + print('check file size with os.fstat') + self.assertEqual(os.fstat(f.fileno())[stat.ST_SIZE], size+1) + + def test_osstat(self): + if verbose: + print('check file size with os.stat') + self.assertEqual(os.stat(TESTFN)[stat.ST_SIZE], size+1) + + def test_seek_read(self): + if verbose: + print('play around with seek() and read() with the built largefile') + with open(TESTFN, 'rb') as f: + self.assertEqual(f.tell(), 0) + self.assertEqual(f.read(1), b'z') + self.assertEqual(f.tell(), 1) + f.seek(0) + self.assertEqual(f.tell(), 0) + f.seek(0, 0) + self.assertEqual(f.tell(), 0) + f.seek(42) + self.assertEqual(f.tell(), 42) + f.seek(42, 0) + self.assertEqual(f.tell(), 42) + f.seek(42, 1) + self.assertEqual(f.tell(), 84) + f.seek(0, 1) + self.assertEqual(f.tell(), 84) + f.seek(0, 2) # seek from the end + self.assertEqual(f.tell(), size + 1 + 0) + f.seek(-10, 2) + self.assertEqual(f.tell(), size + 1 - 10) + f.seek(-size-1, 2) + self.assertEqual(f.tell(), 0) + f.seek(size) + self.assertEqual(f.tell(), size) + # the 'a' that was written at the end of file above + self.assertEqual(f.read(1), b'a') + f.seek(-size-1, 1) + self.assertEqual(f.read(1), b'z') + self.assertEqual(f.tell(), 1) + + def test_lseek(self): + if verbose: + print('play around with os.lseek() with the built largefile') + with open(TESTFN, 'rb') as f: + self.assertEqual(os.lseek(f.fileno(), 0, 0), 0) + self.assertEqual(os.lseek(f.fileno(), 42, 0), 42) + self.assertEqual(os.lseek(f.fileno(), 42, 1), 84) + self.assertEqual(os.lseek(f.fileno(), 0, 1), 84) + self.assertEqual(os.lseek(f.fileno(), 0, 2), size+1+0) + self.assertEqual(os.lseek(f.fileno(), -10, 2), size+1-10) + self.assertEqual(os.lseek(f.fileno(), -size-1, 2), 0) + self.assertEqual(os.lseek(f.fileno(), size, 0), size) + # the 'a' that was written at the end of file above + self.assertEqual(f.read(1), b'a') + + def test_truncate(self): + if verbose: + print('try truncate') + with open(TESTFN, 'r+b') as f: + # this is already decided before start running the test suite + # but we do it anyway for extra protection + if not hasattr(f, 'truncate'): + raise TestSkipped("open().truncate() not available on this system") + f.seek(0, 2) + # else we've lost track of the true size + self.assertEqual(f.tell(), size+1) + # Cut it back via seek + truncate with no argument. + newsize = size - 10 + f.seek(newsize) + f.truncate() + self.assertEqual(f.tell(), newsize) # else pointer moved + f.seek(0, 2) + self.assertEqual(f.tell(), newsize) # else wasn't truncated + # Ensure that truncate(smaller than true size) shrinks + # the file. + newsize -= 1 + f.seek(42) + f.truncate(newsize) + self.assertEqual(f.tell(), 42) # else pointer moved + f.seek(0, 2) + self.assertEqual(f.tell(), newsize) # else wasn't truncated + # XXX truncate(larger than true size) is ill-defined + # across platform; cut it waaaaay back + f.seek(0) + f.truncate(1) + self.assertEqual(f.tell(), 0) # else pointer moved + self.assertEqual(len(f.read()), 1) # else wasn't truncated + +def test_main(): + # On Windows and Mac OSX this test comsumes large resources; It + # takes a long time to build the >2GB file and takes >2GB of disk + # space therefore the resource must be enabled to run this test. + # If not, nothing after this line stanza will be executed. + if sys.platform[:3] == 'win' or sys.platform == 'darwin': + requires('largefile', + 'test requires %s bytes and a long time to run' % str(size)) else: - f.close() - - -def expect(got_this, expect_this): - if test_support.verbose: - print('%r =?= %r ...' % (got_this, expect_this), end=' ') - if got_this != expect_this: - if test_support.verbose: - print('no') - raise test_support.TestFailed('got %r, but expected %r' - % (got_this, expect_this)) - else: - if test_support.verbose: - print('yes') - - -# test that each file function works as expected for a large (i.e. >2GB, do -# we have to check >4GB) files - -if test_support.verbose: - print('create large file via seek (may be sparse file) ...') -f = open(name, 'wb') -try: - f.write(b'z') - f.seek(0) - f.seek(size) - f.write(b'a') - f.flush() - if test_support.verbose: - print('check file size with os.fstat') - expect(os.fstat(f.fileno())[stat.ST_SIZE], size+1) -finally: - f.close() -if test_support.verbose: - print('check file size with os.stat') -expect(os.stat(name)[stat.ST_SIZE], size+1) - -if test_support.verbose: - print('play around with seek() and read() with the built largefile') -f = open(name, 'rb') -try: - expect(f.tell(), 0) - expect(f.read(1), b'z') - expect(f.tell(), 1) - f.seek(0) - expect(f.tell(), 0) - f.seek(0, 0) - expect(f.tell(), 0) - f.seek(42) - expect(f.tell(), 42) - f.seek(42, 0) - expect(f.tell(), 42) - f.seek(42, 1) - expect(f.tell(), 84) - f.seek(0, 1) - expect(f.tell(), 84) - f.seek(0, 2) # seek from the end - expect(f.tell(), size + 1 + 0) - f.seek(-10, 2) - expect(f.tell(), size + 1 - 10) - f.seek(-size-1, 2) - expect(f.tell(), 0) - f.seek(size) - expect(f.tell(), size) - expect(f.read(1), b'a') # the 'a' that was written at the end of file above - f.seek(-size-1, 1) - expect(f.read(1), b'z') - expect(f.tell(), 1) -finally: - f.close() - -if test_support.verbose: - print('play around with os.lseek() with the built largefile') -f = open(name, 'rb') -try: - expect(os.lseek(f.fileno(), 0, 0), 0) - expect(os.lseek(f.fileno(), 42, 0), 42) - expect(os.lseek(f.fileno(), 42, 1), 84) - expect(os.lseek(f.fileno(), 0, 1), 84) - expect(os.lseek(f.fileno(), 0, 2), size+1+0) - expect(os.lseek(f.fileno(), -10, 2), size+1-10) - expect(os.lseek(f.fileno(), -size-1, 2), 0) - expect(os.lseek(f.fileno(), size, 0), size) - expect(f.read(1), b'a') # the 'a' that was written at the end of file above -finally: - f.close() - -if hasattr(f, 'truncate'): - if test_support.verbose: - print('try truncate') - f = open(name, 'r+b') + # Only run if the current filesystem supports large files. + # (Skip this test on Windows, since we now always support + # large files.) + f = open(TESTFN, 'wb') + try: + # 2**31 == 2147483648 + f.seek(2147483649) + # Seeking is not enough of a test: you must write and + # flush, too! + f.write(b'x') + f.flush() + except (IOError, OverflowError): + f.close() + unlink(TESTFN) + raise TestSkipped("filesystem does not have largefile support") + else: + f.close() + suite = unittest.TestSuite() + suite.addTest(TestCase('test_seek')) + suite.addTest(TestCase('test_osstat')) + suite.addTest(TestCase('test_seek_read')) + suite.addTest(TestCase('test_lseek')) + with open(TESTFN, 'w') as f: + if hasattr(f, 'truncate'): + suite.addTest(TestCase('test_truncate')) + unlink(TESTFN) try: - f.seek(0, 2) - expect(f.tell(), size+1) # else we've lost track of the true size - # Cut it back via seek + truncate with no argument. - newsize = size - 10 - f.seek(newsize) - f.truncate() - expect(f.tell(), newsize) # else pointer moved - f.seek(0, 2) - expect(f.tell(), newsize) # else wasn't truncated - # Ensure that truncate(smaller than true size) shrinks the file. - newsize -= 1 - f.seek(42) - f.truncate(newsize) - expect(f.tell(), 42) # else pointer moved - f.seek(0, 2) - expect(f.tell(), newsize) # else wasn't truncated - - # XXX truncate(larger than true size) is ill-defined across platforms - - # cut it waaaaay back - f.seek(0) - f.truncate(1) - expect(f.tell(), 0) # else pointer moved - expect(len(f.read()), 1) # else wasn't truncated - + run_unittest(suite) finally: - f.close() + unlink(TESTFN) -os.unlink(name) +if __name__ == '__main__': + test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_list.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_list.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_list.py Wed Apr 30 15:57:13 2008 @@ -1,4 +1,3 @@ -import unittest import sys from test import test_support, list_tests Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_logging.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_logging.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_logging.py Wed Apr 30 15:57:13 2008 @@ -15,193 +15,281 @@ # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -# -# This file is part of the Python logging distribution. See -# http://www.red-dove.com/python_logging.html -# + """Test harness for the logging module. Run all tests. Copyright (C) 2001-2002 Vinay Sajip. All Rights Reserved. """ +import logging +import logging.handlers +import logging.config + +import copy +import pickle +import io +import gc +import os +import re import select -import os, sys, struct, pickle, io -import socket, tempfile, threading, time -import logging, logging.handlers, logging.config -from test.test_support import run_with_locale - -BANNER = "-- %-10s %-6s ---------------------------------------------------\n" - -FINISH_UP = "Finish up, it's closing time. Messages should bear numbers 0 through 24." - -#---------------------------------------------------------------------------- -# Log receiver -#---------------------------------------------------------------------------- - -TIMEOUT = 10 - +import socket from SocketServer import ThreadingTCPServer, StreamRequestHandler +import string +import struct +import sys +import tempfile +from test.test_support import captured_stdout, run_with_locale, run_unittest +import textwrap +import threading +import time +import types +import unittest +import weakref + + +class BaseTest(unittest.TestCase): + + """Base class for logging tests.""" + + log_format = "%(name)s -> %(levelname)s: %(message)s" + expected_log_pat = r"^([\w.]+) -> ([\w]+): ([\d]+)$" + message_num = 0 + + def setUp(self): + """Setup the default logging stream to an internal StringIO instance, + so that we can examine log output as we want.""" + logger_dict = logging.getLogger().manager.loggerDict + logging._acquireLock() + try: + self.saved_handlers = logging._handlers.copy() + self.saved_handler_list = logging._handlerList[:] + self.saved_loggers = logger_dict.copy() + self.saved_level_names = logging._levelNames.copy() + finally: + logging._releaseLock() -class LogRecordStreamHandler(StreamRequestHandler): - """ - Handler for a streaming logging request. It basically logs the record - using whatever logging policy is configured locally. - """ - - def handle(self): - """ - Handle multiple requests - each expected to be a 4-byte length, - followed by the LogRecord in pickle format. Logs the record - according to whatever policy is configured locally. - """ - while 1: - try: - chunk = self.connection.recv(4) - if len(chunk) < 4: - break - slen = struct.unpack(">L", chunk)[0] - chunk = self.connection.recv(slen) - while len(chunk) < slen: - chunk = chunk + self.connection.recv(slen - len(chunk)) - obj = self.unPickle(chunk) - record = logging.makeLogRecord(obj) - self.handleLogRecord(record) - except: - raise - - def unPickle(self, data): - return pickle.loads(data) - - def handleLogRecord(self, record): - logname = "logrecv.tcp." + record.name - #If the end-of-messages sentinel is seen, tell the server to terminate - if record.msg == FINISH_UP: - self.server.abort = 1 - record.msg = record.msg + " (via " + logname + ")" - logger = logging.getLogger(logname) - logger.handle(record) - -# The server sets socketDataProcessed when it's done. -socketDataProcessed = threading.Event() - -class LogRecordSocketReceiver(ThreadingTCPServer): - """ - A simple-minded TCP socket-based logging receiver suitable for test - purposes. - """ - - allow_reuse_address = 1 + self.root_logger = logging.getLogger("") + self.original_logging_level = self.root_logger.getEffectiveLevel() - def __init__(self, host='localhost', - port=logging.handlers.DEFAULT_TCP_LOGGING_PORT, - handler=LogRecordStreamHandler): - ThreadingTCPServer.__init__(self, (host, port), handler) - self.abort = 0 - self.timeout = 1 + self.stream = io.StringIO() + self.root_logger.setLevel(logging.DEBUG) + self.root_hdlr = logging.StreamHandler(self.stream) + self.root_formatter = logging.Formatter(self.log_format) + self.root_hdlr.setFormatter(self.root_formatter) + self.root_logger.addHandler(self.root_hdlr) + + def tearDown(self): + """Remove our logging stream, and restore the original logging + level.""" + self.stream.close() + self.root_logger.removeHandler(self.root_hdlr) + self.root_logger.setLevel(self.original_logging_level) + logging._acquireLock() + try: + logging._levelNames.clear() + logging._levelNames.update(self.saved_level_names) + logging._handlers.clear() + logging._handlers.update(self.saved_handlers) + logging._handlerList[:] = self.saved_handler_list + loggerDict = logging.getLogger().manager.loggerDict + loggerDict.clear() + loggerDict.update(self.saved_loggers) + finally: + logging._releaseLock() - def serve_until_stopped(self): - while not self.abort: - rd, wr, ex = select.select([self.socket.fileno()], [], [], - self.timeout) - if rd: - self.handle_request() - #notify the main thread that we're about to exit - socketDataProcessed.set() - # close the listen socket - self.server_close() + def assert_log_lines(self, expected_values, stream=None): + """Match the collected log lines against the regular expression + self.expected_log_pat, and compare the extracted group values to + the expected_values list of tuples.""" + stream = stream or self.stream + pat = re.compile(self.expected_log_pat) + try: + stream.reset() + actual_lines = stream.readlines() + except AttributeError: + # StringIO.StringIO lacks a reset() method. + actual_lines = stream.getvalue().splitlines() + self.assertEquals(len(actual_lines), len(expected_values)) + for actual, expected in zip(actual_lines, expected_values): + match = pat.search(actual) + if not match: + self.fail("Log line does not match expected pattern:\n" + + actual) + self.assertEquals(tuple(match.groups()), expected) + s = stream.read() + if s: + self.fail("Remaining output at end of log stream:\n" + s) + + def next_message(self): + """Generate a message consisting solely of an auto-incrementing + integer.""" + self.message_num += 1 + return "%d" % self.message_num + + +class BuiltinLevelsTest(BaseTest): + """Test builtin levels and their inheritance.""" + + def test_flat(self): + #Logging levels in a flat logger namespace. + m = self.next_message + + ERR = logging.getLogger("ERR") + ERR.setLevel(logging.ERROR) + INF = logging.getLogger("INF") + INF.setLevel(logging.INFO) + DEB = logging.getLogger("DEB") + DEB.setLevel(logging.DEBUG) + + # These should log. + ERR.log(logging.CRITICAL, m()) + ERR.error(m()) + + INF.log(logging.CRITICAL, m()) + INF.error(m()) + INF.warn(m()) + INF.info(m()) + + DEB.log(logging.CRITICAL, m()) + DEB.error(m()) + DEB.warn (m()) + DEB.info (m()) + DEB.debug(m()) + + # These should not log. + ERR.warn(m()) + ERR.info(m()) + ERR.debug(m()) + + INF.debug(m()) + + self.assert_log_lines([ + ('ERR', 'CRITICAL', '1'), + ('ERR', 'ERROR', '2'), + ('INF', 'CRITICAL', '3'), + ('INF', 'ERROR', '4'), + ('INF', 'WARNING', '5'), + ('INF', 'INFO', '6'), + ('DEB', 'CRITICAL', '7'), + ('DEB', 'ERROR', '8'), + ('DEB', 'WARNING', '9'), + ('DEB', 'INFO', '10'), + ('DEB', 'DEBUG', '11'), + ]) + + def test_nested_explicit(self): + # Logging levels in a nested namespace, all explicitly set. + m = self.next_message + + INF = logging.getLogger("INF") + INF.setLevel(logging.INFO) + INF_ERR = logging.getLogger("INF.ERR") + INF_ERR.setLevel(logging.ERROR) + + # These should log. + INF_ERR.log(logging.CRITICAL, m()) + INF_ERR.error(m()) + + # These should not log. + INF_ERR.warn(m()) + INF_ERR.info(m()) + INF_ERR.debug(m()) + + self.assert_log_lines([ + ('INF.ERR', 'CRITICAL', '1'), + ('INF.ERR', 'ERROR', '2'), + ]) + + def test_nested_inherited(self): + #Logging levels in a nested namespace, inherited from parent loggers. + m = self.next_message + + INF = logging.getLogger("INF") + INF.setLevel(logging.INFO) + INF_ERR = logging.getLogger("INF.ERR") + INF_ERR.setLevel(logging.ERROR) + INF_UNDEF = logging.getLogger("INF.UNDEF") + INF_ERR_UNDEF = logging.getLogger("INF.ERR.UNDEF") + UNDEF = logging.getLogger("UNDEF") + + # These should log. + INF_UNDEF.log(logging.CRITICAL, m()) + INF_UNDEF.error(m()) + INF_UNDEF.warn(m()) + INF_UNDEF.info(m()) + INF_ERR_UNDEF.log(logging.CRITICAL, m()) + INF_ERR_UNDEF.error(m()) + + # These should not log. + INF_UNDEF.debug(m()) + INF_ERR_UNDEF.warn(m()) + INF_ERR_UNDEF.info(m()) + INF_ERR_UNDEF.debug(m()) + + self.assert_log_lines([ + ('INF.UNDEF', 'CRITICAL', '1'), + ('INF.UNDEF', 'ERROR', '2'), + ('INF.UNDEF', 'WARNING', '3'), + ('INF.UNDEF', 'INFO', '4'), + ('INF.ERR.UNDEF', 'CRITICAL', '5'), + ('INF.ERR.UNDEF', 'ERROR', '6'), + ]) + + def test_nested_with_virtual_parent(self): + # Logging levels when some parent does not exist yet. + m = self.next_message + + INF = logging.getLogger("INF") + GRANDCHILD = logging.getLogger("INF.BADPARENT.UNDEF") + CHILD = logging.getLogger("INF.BADPARENT") + INF.setLevel(logging.INFO) + + # These should log. + GRANDCHILD.log(logging.FATAL, m()) + GRANDCHILD.info(m()) + CHILD.log(logging.FATAL, m()) + CHILD.info(m()) + + # These should not log. + GRANDCHILD.debug(m()) + CHILD.debug(m()) + + self.assert_log_lines([ + ('INF.BADPARENT.UNDEF', 'CRITICAL', '1'), + ('INF.BADPARENT.UNDEF', 'INFO', '2'), + ('INF.BADPARENT', 'CRITICAL', '3'), + ('INF.BADPARENT', 'INFO', '4'), + ]) + + +class BasicFilterTest(BaseTest): + + """Test the bundled Filter class.""" + + def test_filter(self): + # Only messages satisfying the specified criteria pass through the + # filter. + filter_ = logging.Filter("spam.eggs") + handler = self.root_logger.handlers[0] + try: + handler.addFilter(filter_) + spam = logging.getLogger("spam") + spam_eggs = logging.getLogger("spam.eggs") + spam_eggs_fish = logging.getLogger("spam.eggs.fish") + spam_bakedbeans = logging.getLogger("spam.bakedbeans") + + spam.info(self.next_message()) + spam_eggs.info(self.next_message()) # Good. + spam_eggs_fish.info(self.next_message()) # Good. + spam_bakedbeans.info(self.next_message()) + + self.assert_log_lines([ + ('spam.eggs', 'INFO', '2'), + ('spam.eggs.fish', 'INFO', '3'), + ]) + finally: + handler.removeFilter(filter_) - def process_request(self, request, client_address): - #import threading - t = threading.Thread(target = self.finish_request, - args = (request, client_address)) - t.start() - -def runTCP(tcpserver): - tcpserver.serve_until_stopped() - -#---------------------------------------------------------------------------- -# Test 0 -#---------------------------------------------------------------------------- - -msgcount = 0 - -def nextmessage(): - global msgcount - rv = "Message %d" % msgcount - msgcount = msgcount + 1 - return rv - -def test0(): - ERR = logging.getLogger("ERR") - ERR.setLevel(logging.ERROR) - INF = logging.getLogger("INF") - INF.setLevel(logging.INFO) - INF_ERR = logging.getLogger("INF.ERR") - INF_ERR.setLevel(logging.ERROR) - DEB = logging.getLogger("DEB") - DEB.setLevel(logging.DEBUG) - - INF_UNDEF = logging.getLogger("INF.UNDEF") - INF_ERR_UNDEF = logging.getLogger("INF.ERR.UNDEF") - UNDEF = logging.getLogger("UNDEF") - - GRANDCHILD = logging.getLogger("INF.BADPARENT.UNDEF") - CHILD = logging.getLogger("INF.BADPARENT") - - #These should log - ERR.log(logging.FATAL, nextmessage()) - ERR.error(nextmessage()) - - INF.log(logging.FATAL, nextmessage()) - INF.error(nextmessage()) - INF.warn(nextmessage()) - INF.info(nextmessage()) - - INF_UNDEF.log(logging.FATAL, nextmessage()) - INF_UNDEF.error(nextmessage()) - INF_UNDEF.warn (nextmessage()) - INF_UNDEF.info (nextmessage()) - - INF_ERR.log(logging.FATAL, nextmessage()) - INF_ERR.error(nextmessage()) - - INF_ERR_UNDEF.log(logging.FATAL, nextmessage()) - INF_ERR_UNDEF.error(nextmessage()) - - DEB.log(logging.FATAL, nextmessage()) - DEB.error(nextmessage()) - DEB.warn (nextmessage()) - DEB.info (nextmessage()) - DEB.debug(nextmessage()) - - UNDEF.log(logging.FATAL, nextmessage()) - UNDEF.error(nextmessage()) - UNDEF.warn (nextmessage()) - UNDEF.info (nextmessage()) - - GRANDCHILD.log(logging.FATAL, nextmessage()) - CHILD.log(logging.FATAL, nextmessage()) - - #These should not log - ERR.warn(nextmessage()) - ERR.info(nextmessage()) - ERR.debug(nextmessage()) - - INF.debug(nextmessage()) - INF_UNDEF.debug(nextmessage()) - - INF_ERR.warn(nextmessage()) - INF_ERR.info(nextmessage()) - INF_ERR.debug(nextmessage()) - INF_ERR_UNDEF.warn(nextmessage()) - INF_ERR_UNDEF.info(nextmessage()) - INF_ERR_UNDEF.debug(nextmessage()) - - INF.info(FINISH_UP) - -#---------------------------------------------------------------------------- -# Test 1 -#---------------------------------------------------------------------------- # # First, we define our levels. There can be as many as you want - the only @@ -211,16 +299,16 @@ # mapping dictionary to convert between your application levels and the # logging system. # -SILENT = 10 -TACITURN = 9 -TERSE = 8 -EFFUSIVE = 7 -SOCIABLE = 6 -VERBOSE = 5 -TALKATIVE = 4 -GARRULOUS = 3 -CHATTERBOX = 2 -BORING = 1 +SILENT = 120 +TACITURN = 119 +TERSE = 118 +EFFUSIVE = 117 +SOCIABLE = 116 +VERBOSE = 115 +TALKATIVE = 114 +GARRULOUS = 113 +CHATTERBOX = 112 +BORING = 111 LEVEL_RANGE = range(BORING, SILENT + 1) @@ -241,444 +329,495 @@ BORING : 'Boring', } -# -# Now, to demonstrate filtering: suppose for some perverse reason we only -# want to print out all except GARRULOUS messages. Let's create a filter for -# this purpose... -# -class SpecificLevelFilter(logging.Filter): - def __init__(self, lvl): - self.level = lvl +class GarrulousFilter(logging.Filter): - def filter(self, record): - return self.level != record.levelno + """A filter which blocks garrulous messages.""" -class GarrulousFilter(SpecificLevelFilter): - def __init__(self): - SpecificLevelFilter.__init__(self, GARRULOUS) + def filter(self, record): + return record.levelno != GARRULOUS -# -# Now, let's demonstrate filtering at the logger. This time, use a filter -# which excludes SOCIABLE and TACITURN messages. Note that GARRULOUS events -# are still excluded. -# class VerySpecificFilter(logging.Filter): + + """A filter which blocks sociable and taciturn messages.""" + def filter(self, record): return record.levelno not in [SOCIABLE, TACITURN] -def message(s): - sys.stdout.write("%s\n" % s) -SHOULD1 = "This should only be seen at the '%s' logging level (or lower)" +class CustomLevelsAndFiltersTest(BaseTest): -def test1(): -# -# Now, tell the logging system to associate names with our levels. -# - for lvl in my_logging_levels.keys(): - logging.addLevelName(lvl, my_logging_levels[lvl]) + """Test various filtering possibilities with custom logging levels.""" -# -# Now, define a test function which logs an event at each of our levels. -# + # Skip the logger name group. + expected_log_pat = r"^[\w.]+ -> ([\w]+): ([\d]+)$" + + def setUp(self): + BaseTest.setUp(self) + for k, v in list(my_logging_levels.items()): + logging.addLevelName(k, v) - def doLog(log): + def log_at_all_levels(self, logger): for lvl in LEVEL_RANGE: - log.log(lvl, SHOULD1, logging.getLevelName(lvl)) + logger.log(lvl, self.next_message()) - log = logging.getLogger("") - hdlr = log.handlers[0] -# -# Set the logging level to each different value and call the utility -# function to log events. -# In the output, you should see that each time round the loop, the number of -# logging events which are actually output decreases. -# - for lvl in LEVEL_RANGE: - message("-- setting logging level to '%s' -----" % - logging.getLevelName(lvl)) - log.setLevel(lvl) - doLog(log) - # - # Now, we demonstrate level filtering at the handler level. Tell the - # handler defined above to filter at level 'SOCIABLE', and repeat the - # above loop. Compare the output from the two runs. - # - hdlr.setLevel(SOCIABLE) - message("-- Filtering at handler level to SOCIABLE --") - for lvl in LEVEL_RANGE: - message("-- setting logging level to '%s' -----" % - logging.getLevelName(lvl)) - log.setLevel(lvl) - doLog(log) - - hdlr.setLevel(0) #turn off level filtering at the handler - - garr = GarrulousFilter() - hdlr.addFilter(garr) - message("-- Filtering using GARRULOUS filter --") - for lvl in LEVEL_RANGE: - message("-- setting logging level to '%s' -----" % - logging.getLevelName(lvl)) - log.setLevel(lvl) - doLog(log) - spec = VerySpecificFilter() - log.addFilter(spec) - message("-- Filtering using specific filter for SOCIABLE, TACITURN --") - for lvl in LEVEL_RANGE: - message("-- setting logging level to '%s' -----" % - logging.getLevelName(lvl)) - log.setLevel(lvl) - doLog(log) - - log.removeFilter(spec) - hdlr.removeFilter(garr) - #Undo the one level which clashes...for regression tests - logging.addLevelName(logging.DEBUG, "DEBUG") - -#---------------------------------------------------------------------------- -# Test 2 -#---------------------------------------------------------------------------- - -MSG = "-- logging %d at INFO, messages should be seen every 10 events --" -def test2(): - logger = logging.getLogger("") - sh = logger.handlers[0] - sh.close() - logger.removeHandler(sh) - mh = logging.handlers.MemoryHandler(10,logging.WARNING, sh) - logger.setLevel(logging.DEBUG) - logger.addHandler(mh) - message("-- logging at DEBUG, nothing should be seen yet --") - logger.debug("Debug message") - message("-- logging at INFO, nothing should be seen yet --") - logger.info("Info message") - message("-- logging at WARNING, 3 messages should be seen --") - logger.warn("Warn message") - for i in range(102): - message(MSG % i) - logger.info("Info index = %d", i) - mh.close() - logger.removeHandler(mh) - logger.addHandler(sh) - -#---------------------------------------------------------------------------- -# Test 3 -#---------------------------------------------------------------------------- - -FILTER = "a.b" - -def doLog3(): - logging.getLogger("a").info("Info 1") - logging.getLogger("a.b").info("Info 2") - logging.getLogger("a.c").info("Info 3") - logging.getLogger("a.b.c").info("Info 4") - logging.getLogger("a.b.c.d").info("Info 5") - logging.getLogger("a.bb.c").info("Info 6") - logging.getLogger("b").info("Info 7") - logging.getLogger("b.a").info("Info 8") - logging.getLogger("c.a.b").info("Info 9") - logging.getLogger("a.bb").info("Info 10") - -def test3(): - root = logging.getLogger() - root.setLevel(logging.DEBUG) - hand = root.handlers[0] - message("Unfiltered...") - doLog3() - message("Filtered with '%s'..." % FILTER) - filt = logging.Filter(FILTER) - hand.addFilter(filt) - doLog3() - hand.removeFilter(filt) - -#---------------------------------------------------------------------------- -# Test 4 -#---------------------------------------------------------------------------- - -# config0 is a standard configuration. -config0 = """ -[loggers] -keys=root - -[handlers] -keys=hand1 - -[formatters] -keys=form1 - -[logger_root] -level=NOTSET -handlers=hand1 - -[handler_hand1] -class=StreamHandler -level=NOTSET -formatter=form1 -args=(sys.stdout,) - -[formatter_form1] -format=%(levelname)s:%(name)s:%(message)s -datefmt= -""" + def test_logger_filter(self): + # Filter at logger level. + self.root_logger.setLevel(VERBOSE) + # Levels >= 'Verbose' are good. + self.log_at_all_levels(self.root_logger) + self.assert_log_lines([ + ('Verbose', '5'), + ('Sociable', '6'), + ('Effusive', '7'), + ('Terse', '8'), + ('Taciturn', '9'), + ('Silent', '10'), + ]) + + def test_handler_filter(self): + # Filter at handler level. + self.root_logger.handlers[0].setLevel(SOCIABLE) + try: + # Levels >= 'Sociable' are good. + self.log_at_all_levels(self.root_logger) + self.assert_log_lines([ + ('Sociable', '6'), + ('Effusive', '7'), + ('Terse', '8'), + ('Taciturn', '9'), + ('Silent', '10'), + ]) + finally: + self.root_logger.handlers[0].setLevel(logging.NOTSET) -# config1 adds a little to the standard configuration. -config1 = """ -[loggers] -keys=root,parser - -[handlers] -keys=hand1 - -[formatters] -keys=form1 - -[logger_root] -level=NOTSET -handlers=hand1 - -[logger_parser] -level=DEBUG -handlers=hand1 -propagate=1 -qualname=compiler.parser - -[handler_hand1] -class=StreamHandler -level=NOTSET -formatter=form1 -args=(sys.stdout,) - -[formatter_form1] -format=%(levelname)s:%(name)s:%(message)s -datefmt= -""" + def test_specific_filters(self): + # Set a specific filter object on the handler, and then add another + # filter object on the logger itself. + handler = self.root_logger.handlers[0] + specific_filter = None + garr = GarrulousFilter() + handler.addFilter(garr) + try: + self.log_at_all_levels(self.root_logger) + first_lines = [ + # Notice how 'Garrulous' is missing + ('Boring', '1'), + ('Chatterbox', '2'), + ('Talkative', '4'), + ('Verbose', '5'), + ('Sociable', '6'), + ('Effusive', '7'), + ('Terse', '8'), + ('Taciturn', '9'), + ('Silent', '10'), + ] + self.assert_log_lines(first_lines) + + specific_filter = VerySpecificFilter() + self.root_logger.addFilter(specific_filter) + self.log_at_all_levels(self.root_logger) + self.assert_log_lines(first_lines + [ + # Not only 'Garrulous' is still missing, but also 'Sociable' + # and 'Taciturn' + ('Boring', '11'), + ('Chatterbox', '12'), + ('Talkative', '14'), + ('Verbose', '15'), + ('Effusive', '17'), + ('Terse', '18'), + ('Silent', '20'), + ]) + finally: + if specific_filter: + self.root_logger.removeFilter(specific_filter) + handler.removeFilter(garr) + + +class MemoryHandlerTest(BaseTest): + + """Tests for the MemoryHandler.""" + + # Do not bother with a logger name group. + expected_log_pat = r"^[\w.]+ -> ([\w]+): ([\d]+)$" + + def setUp(self): + BaseTest.setUp(self) + self.mem_hdlr = logging.handlers.MemoryHandler(10, logging.WARNING, + self.root_hdlr) + self.mem_logger = logging.getLogger('mem') + self.mem_logger.propagate = 0 + self.mem_logger.addHandler(self.mem_hdlr) + + def tearDown(self): + self.mem_hdlr.close() + BaseTest.tearDown(self) + + def test_flush(self): + # The memory handler flushes to its target handler based on specific + # criteria (message count and message level). + self.mem_logger.debug(self.next_message()) + self.assert_log_lines([]) + self.mem_logger.info(self.next_message()) + self.assert_log_lines([]) + # This will flush because the level is >= logging.WARNING + self.mem_logger.warn(self.next_message()) + lines = [ + ('DEBUG', '1'), + ('INFO', '2'), + ('WARNING', '3'), + ] + self.assert_log_lines(lines) + for n in (4, 14): + for i in range(9): + self.mem_logger.debug(self.next_message()) + self.assert_log_lines(lines) + # This will flush because it's the 10th message since the last + # flush. + self.mem_logger.debug(self.next_message()) + lines = lines + [('DEBUG', str(i)) for i in range(n, n + 10)] + self.assert_log_lines(lines) -# config2 has a subtle configuration error that should be reported -config2 = config1.replace("sys.stdout", "sys.stbout") + self.mem_logger.debug(self.next_message()) + self.assert_log_lines(lines) -# config3 has a less subtle configuration error -config3 = config1.replace("formatter=form1", "formatter=misspelled_name") -def test4(): - for i in range(4): - conf = globals()['config%d' % i] - sys.stdout.write('config%d: ' % i) - loggerDict = logging.getLogger().manager.loggerDict - logging._acquireLock() - try: - saved_handlers = logging._handlers.copy() - saved_handler_list = logging._handlerList[:] - saved_loggers = loggerDict.copy() - finally: - logging._releaseLock() +class ExceptionFormatter(logging.Formatter): + """A special exception formatter.""" + def formatException(self, ei): + return "Got a [%s]" % ei[0].__name__ + + +class ConfigFileTest(BaseTest): + + """Reading logging config from a .ini-style config file.""" + + expected_log_pat = r"^([\w]+) \+\+ ([\w]+)$" + + # config0 is a standard configuration. + config0 = """ + [loggers] + keys=root + + [handlers] + keys=hand1 + + [formatters] + keys=form1 + + [logger_root] + level=WARNING + handlers=hand1 + + [handler_hand1] + class=StreamHandler + level=NOTSET + formatter=form1 + args=(sys.stdout,) + + [formatter_form1] + format=%(levelname)s ++ %(message)s + datefmt= + """ + + # config1 adds a little to the standard configuration. + config1 = """ + [loggers] + keys=root,parser + + [handlers] + keys=hand1 + + [formatters] + keys=form1 + + [logger_root] + level=WARNING + handlers= + + [logger_parser] + level=DEBUG + handlers=hand1 + propagate=1 + qualname=compiler.parser + + [handler_hand1] + class=StreamHandler + level=NOTSET + formatter=form1 + args=(sys.stdout,) + + [formatter_form1] + format=%(levelname)s ++ %(message)s + datefmt= + """ + + # config2 has a subtle configuration error that should be reported + config2 = config1.replace("sys.stdout", "sys.stbout") + + # config3 has a less subtle configuration error + config3 = config1.replace("formatter=form1", "formatter=misspelled_name") + + # config4 specifies a custom formatter class to be loaded + config4 = """ + [loggers] + keys=root + + [handlers] + keys=hand1 + + [formatters] + keys=form1 + + [logger_root] + level=NOTSET + handlers=hand1 + + [handler_hand1] + class=StreamHandler + level=NOTSET + formatter=form1 + args=(sys.stdout,) + + [formatter_form1] + class=""" + __name__ + """.ExceptionFormatter + format=%(levelname)s:%(name)s:%(message)s + datefmt= + """ + + def apply_config(self, conf): try: fn = tempfile.mktemp(".ini") f = open(fn, "w") - f.write(conf) + f.write(textwrap.dedent(conf)) f.close() - try: - logging.config.fileConfig(fn) - #call again to make sure cleanup is correct - logging.config.fileConfig(fn) - except: - t = sys.exc_info()[0] - message(str(t)) - else: - message('ok.') - os.remove(fn) + logging.config.fileConfig(fn) finally: - logging._acquireLock() + os.remove(fn) + + def test_config0_ok(self): + # A simple config file which overrides the default settings. + with captured_stdout() as output: + self.apply_config(self.config0) + logger = logging.getLogger() + # Won't output anything + logger.info(self.next_message()) + # Outputs a message + logger.error(self.next_message()) + self.assert_log_lines([ + ('ERROR', '2'), + ], stream=output) + # Original logger output is empty. + self.assert_log_lines([]) + + def test_config1_ok(self): + # A config file defining a sub-parser as well. + with captured_stdout() as output: + self.apply_config(self.config1) + logger = logging.getLogger("compiler.parser") + # Both will output a message + logger.info(self.next_message()) + logger.error(self.next_message()) + self.assert_log_lines([ + ('INFO', '1'), + ('ERROR', '2'), + ], stream=output) + # Original logger output is empty. + self.assert_log_lines([]) + + def test_config2_failure(self): + # A simple config file which overrides the default settings. + self.assertRaises(Exception, self.apply_config, self.config2) + + def test_config3_failure(self): + # A simple config file which overrides the default settings. + self.assertRaises(Exception, self.apply_config, self.config3) + + def test_config4_ok(self): + # A config file specifying a custom formatter class. + with captured_stdout() as output: + self.apply_config(self.config4) + logger = logging.getLogger() try: - logging._handlers.clear() - logging._handlers.update(saved_handlers) - logging._handlerList[:] = saved_handler_list - loggerDict = logging.getLogger().manager.loggerDict - loggerDict.clear() - loggerDict.update(saved_loggers) - finally: - logging._releaseLock() - -#---------------------------------------------------------------------------- -# Test 5 -#---------------------------------------------------------------------------- - -test5_config = """ -[loggers] -keys=root - -[handlers] -keys=hand1 - -[formatters] -keys=form1 - -[logger_root] -level=NOTSET -handlers=hand1 - -[handler_hand1] -class=StreamHandler -level=NOTSET -formatter=form1 -args=(sys.stdout,) - -[formatter_form1] -class=test.test_logging.FriendlyFormatter -format=%(levelname)s:%(name)s:%(message)s -datefmt= -""" + raise RuntimeError() + except RuntimeError: + logging.exception("just testing") + sys.stdout.seek(0) + self.assertEquals(output.getvalue(), + "ERROR:root:just testing\nGot a [RuntimeError]\n") + # Original logger output is empty + self.assert_log_lines([]) -class FriendlyFormatter (logging.Formatter): - def formatException(self, ei): - return "%s... Don't panic!" % str(ei[0]) +class LogRecordStreamHandler(StreamRequestHandler): -def test5(): - loggerDict = logging.getLogger().manager.loggerDict - logging._acquireLock() - try: - saved_handlers = logging._handlers.copy() - saved_handler_list = logging._handlerList[:] - saved_loggers = loggerDict.copy() - finally: - logging._releaseLock() - try: - fn = tempfile.mktemp(".ini") - f = open(fn, "w") - f.write(test5_config) - f.close() - logging.config.fileConfig(fn) - try: - raise KeyError - except KeyError: - logging.exception("just testing") - os.remove(fn) - hdlr = logging.getLogger().handlers[0] - logging.getLogger().handlers.remove(hdlr) - finally: - logging._acquireLock() + """Handler for a streaming logging request. It saves the log message in the + TCP server's 'log_output' attribute.""" + + TCP_LOG_END = "!!!END!!!" + + def handle(self): + """Handle multiple requests - each expected to be of 4-byte length, + followed by the LogRecord in pickle format. Logs the record + according to whatever policy is configured locally.""" + while True: + chunk = self.connection.recv(4) + if len(chunk) < 4: + break + slen = struct.unpack(">L", chunk)[0] + chunk = self.connection.recv(slen) + while len(chunk) < slen: + chunk = chunk + self.connection.recv(slen - len(chunk)) + obj = self.unpickle(chunk) + record = logging.makeLogRecord(obj) + self.handle_log_record(record) + + def unpickle(self, data): + return pickle.loads(data) + + def handle_log_record(self, record): + # If the end-of-messages sentinel is seen, tell the server to + # terminate. + if self.TCP_LOG_END in record.msg: + self.server.abort = 1 + return + self.server.log_output += record.msg + "\n" + + +class LogRecordSocketReceiver(ThreadingTCPServer): + + """A simple-minded TCP socket-based logging receiver suitable for test + purposes.""" + + allow_reuse_address = 1 + log_output = "" + + def __init__(self, host='localhost', + port=logging.handlers.DEFAULT_TCP_LOGGING_PORT, + handler=LogRecordStreamHandler): + ThreadingTCPServer.__init__(self, (host, port), handler) + self.abort = False + self.timeout = 0.1 + self.finished = threading.Event() + + def serve_until_stopped(self): + while not self.abort: + rd, wr, ex = select.select([self.socket.fileno()], [], [], + self.timeout) + if rd: + self.handle_request() + # Notify the main thread that we're about to exit + self.finished.set() + # close the listen socket + self.server_close() + + +class SocketHandlerTest(BaseTest): + + """Test for SocketHandler objects.""" + + def setUp(self): + """Set up a TCP server to receive log messages, and a SocketHandler + pointing to that server's address and port.""" + BaseTest.setUp(self) + self.tcpserver = LogRecordSocketReceiver(port=0) + self.port = self.tcpserver.socket.getsockname()[1] + self.threads = [ + threading.Thread(target=self.tcpserver.serve_until_stopped)] + for thread in self.threads: + thread.start() + + self.sock_hdlr = logging.handlers.SocketHandler('localhost', self.port) + self.sock_hdlr.setFormatter(self.root_formatter) + self.root_logger.removeHandler(self.root_logger.handlers[0]) + self.root_logger.addHandler(self.sock_hdlr) + + def tearDown(self): + """Shutdown the TCP server.""" try: - logging._handlers.clear() - logging._handlers.update(saved_handlers) - logging._handlerList[:] = saved_handler_list - loggerDict = logging.getLogger().manager.loggerDict - loggerDict.clear() - loggerDict.update(saved_loggers) + self.tcpserver.abort = True + del self.tcpserver + self.root_logger.removeHandler(self.sock_hdlr) + self.sock_hdlr.close() + for thread in self.threads: + thread.join(2.0) finally: - logging._releaseLock() + BaseTest.tearDown(self) + def get_output(self): + """Get the log output as received by the TCP server.""" + # Signal the TCP receiver and wait for it to terminate. + self.root_logger.critical(LogRecordStreamHandler.TCP_LOG_END) + self.tcpserver.finished.wait(2.0) + return self.tcpserver.log_output + + def test_output(self): + # The log message sent to the SocketHandler is properly received. + logger = logging.getLogger("tcp") + logger.error("spam") + logger.debug("eggs") + self.assertEquals(self.get_output(), "spam\neggs\n") + + +class MemoryTest(BaseTest): + + """Test memory persistence of logger objects.""" + + def setUp(self): + """Create a dict to remember potentially destroyed objects.""" + BaseTest.setUp(self) + self._survivors = {} + + def _watch_for_survival(self, *args): + """Watch the given objects for survival, by creating weakrefs to + them.""" + for obj in args: + key = id(obj), repr(obj) + self._survivors[key] = weakref.ref(obj) + + def _assert_survival(self): + """Assert that all objects watched for survival have survived.""" + # Trigger cycle breaking. + gc.collect() + dead = [] + for (id_, repr_), ref in list(self._survivors.items()): + if ref() is None: + dead.append(repr_) + if dead: + self.fail("%d objects should have survived " + "but have been destroyed: %s" % (len(dead), ", ".join(dead))) + + def test_persistent_loggers(self): + # Logger objects are persistent and retain their configuration, even + # if visible references are destroyed. + self.root_logger.setLevel(logging.INFO) + foo = logging.getLogger("foo") + self._watch_for_survival(foo) + foo.setLevel(logging.DEBUG) + self.root_logger.debug(self.next_message()) + foo.debug(self.next_message()) + self.assert_log_lines([ + ('foo', 'DEBUG', '2'), + ]) + del foo + # foo has survived. + self._assert_survival() + # foo has retained its settings. + bar = logging.getLogger("foo") + bar.debug(self.next_message()) + self.assert_log_lines([ + ('foo', 'DEBUG', '2'), + ('foo', 'DEBUG', '3'), + ]) -#---------------------------------------------------------------------------- -# Test Harness -#---------------------------------------------------------------------------- -def banner(nm, typ): - sep = BANNER % (nm, typ) - sys.stdout.write(sep) - sys.stdout.flush() - -def test_main_inner(): - rootLogger = logging.getLogger("") - rootLogger.setLevel(logging.DEBUG) - hdlr = logging.StreamHandler(sys.stdout) - fmt = logging.Formatter(logging.BASIC_FORMAT) - hdlr.setFormatter(fmt) - rootLogger.addHandler(hdlr) - - # Find an unused port number - port = logging.handlers.DEFAULT_TCP_LOGGING_PORT - while port < logging.handlers.DEFAULT_TCP_LOGGING_PORT+100: - try: - tcpserver = LogRecordSocketReceiver(port=port) - except socket.error: - port += 1 - else: - break - else: - raise ImportError("Could not find unused port") - - - #Set up a handler such that all events are sent via a socket to the log - #receiver (logrecv). - #The handler will only be added to the rootLogger for some of the tests - shdlr = logging.handlers.SocketHandler('localhost', port) - - #Configure the logger for logrecv so events do not propagate beyond it. - #The sockLogger output is buffered in memory until the end of the test, - #and printed at the end. - sockOut = io.StringIO() - sockLogger = logging.getLogger("logrecv") - sockLogger.setLevel(logging.DEBUG) - sockhdlr = logging.StreamHandler(sockOut) - sockhdlr.setFormatter(logging.Formatter( - "%(name)s -> %(levelname)s: %(message)s")) - sockLogger.addHandler(sockhdlr) - sockLogger.propagate = 0 - - #Set up servers - threads = [] - #sys.stdout.write("About to start TCP server...\n") - threads.append(threading.Thread(target=runTCP, args=(tcpserver,))) - - for thread in threads: - thread.start() - try: - banner("log_test0", "begin") - - rootLogger.addHandler(shdlr) - test0() - # XXX(nnorwitz): Try to fix timing related test failures. - # This sleep gives us some extra time to read messages. - # The test generally only fails on Solaris without this sleep. - time.sleep(2.0) - shdlr.close() - rootLogger.removeHandler(shdlr) - - banner("log_test0", "end") - - for t in range(1,6): - banner("log_test%d" % t, "begin") - globals()['test%d' % t]() - banner("log_test%d" % t, "end") - - finally: - #wait for TCP receiver to terminate - socketDataProcessed.wait() - # ensure the server dies - tcpserver.abort = 1 - for thread in threads: - thread.join(2.0) - banner("logrecv output", "begin") - sys.stdout.write(sockOut.getvalue()) - sockOut.close() - sockLogger.removeHandler(sockhdlr) - sockhdlr.close() - banner("logrecv output", "end") - sys.stdout.flush() - try: - hdlr.close() - except: - pass - rootLogger.removeHandler(hdlr) # Set the locale to the platform-dependent default. I have no idea # why the test does this, but in any case we save the current locale # first and restore it at the end. @run_with_locale('LC_ALL', '') def test_main(): - # Save and restore the original root logger level across the tests. - # Otherwise, e.g., if any test using cookielib runs after test_logging, - # cookielib's debug-level logger tries to log messages, leading to - # confusing: - # No handlers could be found for logger "cookielib" - # output while the tests are running. - root_logger = logging.getLogger("") - original_logging_level = root_logger.getEffectiveLevel() - try: - test_main_inner() - finally: - root_logger.setLevel(original_logging_level) + run_unittest(BuiltinLevelsTest, BasicFilterTest, + CustomLevelsAndFiltersTest, MemoryHandlerTest, + ConfigFileTest, SocketHandlerTest, MemoryTest) if __name__ == "__main__": - sys.stdout.write("test_logging\n") test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_long.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_long.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_long.py Wed Apr 30 15:57:13 2008 @@ -482,7 +482,7 @@ eq(x > y, Rcmp > 0, Frm("%r > %r %d", x, y, Rcmp)) eq(x >= y, Rcmp >= 0, Frm("%r >= %r %d", x, y, Rcmp)) - def test_format(self): + def test__format__(self): self.assertEqual(format(123456789, 'd'), '123456789') self.assertEqual(format(123456789, 'd'), '123456789') @@ -526,16 +526,27 @@ self.assertEqual(format(1234, "+b"), "+10011010010") self.assertEqual(format(-1234, "+b"), "-10011010010") - # conversion to float - self.assertEqual(format(0, 'f'), '0.000000') - # make sure these are errors self.assertRaises(ValueError, format, 3, "1.3") # precision disallowed self.assertRaises(ValueError, format, 3, "+c") # sign not allowed # with 'c' - self.assertRaises(ValueError, format, 3, "R") # bogus format type - # conversion to string should fail - self.assertRaises(ValueError, format, 3, "s") + + # ensure that only int and float type specifiers work + for format_spec in ([chr(x) for x in range(ord('a'), ord('z')+1)] + + [chr(x) for x in range(ord('A'), ord('Z')+1)]): + if not format_spec in 'bcdoxXeEfFgGn%': + self.assertRaises(ValueError, format, 0, format_spec) + self.assertRaises(ValueError, format, 1, format_spec) + self.assertRaises(ValueError, format, -1, format_spec) + self.assertRaises(ValueError, format, 2**100, format_spec) + self.assertRaises(ValueError, format, -(2**100), format_spec) + + # ensure that float type specifiers work; format converts + # the int to a float + for format_spec in 'eEfFgGn%': + for value in [0, 1, -1, 100, -100, 1234567890, -1234567890]: + self.assertEqual(format(value, format_spec), + format(float(value), format_spec)) def test_nan_inf(self): self.assertRaises(OverflowError, int, float('inf')) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_mailbox.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_mailbox.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_mailbox.py Wed Apr 30 15:57:13 2008 @@ -374,7 +374,7 @@ def test_flush(self): # Write changes to disk - self._test_flush_or_close(self._box.flush) + self._test_flush_or_close(self._box.flush, True) def test_lock_unlock(self): # Lock and unlock the mailbox @@ -386,15 +386,17 @@ def test_close(self): # Close mailbox and flush changes to disk - self._test_flush_or_close(self._box.close) + self._test_flush_or_close(self._box.close, False) - def _test_flush_or_close(self, method): + def _test_flush_or_close(self, method, should_call_close): contents = [self._template % i for i in range(3)] self._box.add(contents[0]) self._box.add(contents[1]) self._box.add(contents[2]) oldbox = self._box method() + if should_call_close: + self._box.close() self._box = self._factory(self._path) keys = self._box.keys() self.assertEqual(len(keys), 3) @@ -408,8 +410,7 @@ _sample_message, io.StringIO(_sample_message)): output = io.StringIO() self._box._dump_message(input, output) - self.assertEqual(output.getvalue(), - _sample_message.replace('\n', os.linesep)) + self.assertEqual(output.getvalue(), _sample_message) output = io.StringIO() self.assertRaises(TypeError, lambda: self._box._dump_message(None, output)) @@ -517,6 +518,7 @@ class FakeMessage(mailbox.MaildirMessage): pass box = mailbox.Maildir(self._path, factory=FakeMessage) + box.colon = self._box.colon msg2 = box.get_message(key) self.assert_(isinstance(msg2, FakeMessage)) @@ -624,9 +626,9 @@ "tmp")), "File in wrong location: '%s'" % head) match = pattern.match(tail) - self.assert_(match != None, "Invalid file name: '%s'" % tail) + self.assert_(match is not None, "Invalid file name: '%s'" % tail) groups = match.groups() - if previous_groups != None: + if previous_groups is not None: self.assert_(int(groups[0] >= previous_groups[0]), "Non-monotonic seconds: '%s' before '%s'" % (previous_groups[0], groups[0])) @@ -754,7 +756,7 @@ self._box._file.seek(0) contents = self._box._file.read() self._box.close() - self.assertEqual(contents, open(self._path, 'r').read()) + self.assertEqual(contents, open(self._path, 'r', newline='').read()) self._box = self._factory(self._path) def test_lock_conflict(self): Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_math.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_math.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_math.py Wed Apr 30 15:57:13 2008 @@ -4,9 +4,45 @@ from test.test_support import run_unittest, verbose import unittest import math +import os +import sys -seps='1e-05' -eps = eval(seps) +eps = 1E-05 +NAN = float('nan') +INF = float('inf') +NINF = float('-inf') + +# locate file with test values +if __name__ == '__main__': + file = sys.argv[0] +else: + file = __file__ +test_dir = os.path.dirname(file) or os.curdir +test_file = os.path.join(test_dir, 'cmath_testcases.txt') + +def parse_testfile(fname): + """Parse a file with test values + + Empty lines or lines starting with -- are ignored + yields id, fn, arg_real, arg_imag, exp_real, exp_imag + """ + with open(fname) as fp: + for line in fp: + # skip comment lines and blank lines + if line.startswith('--') or not line.strip(): + continue + + lhs, rhs = line.split('->') + id, fn, arg_real, arg_imag = lhs.split() + rhs_pieces = rhs.split() + exp_real, exp_imag = rhs_pieces[0], rhs_pieces[1] + flags = rhs_pieces[2:] + + yield (id, fn, + float(arg_real), float(arg_imag), + float(exp_real), float(exp_imag), + flags + ) class MathTests(unittest.TestCase): @@ -28,18 +64,57 @@ self.ftest('acos(-1)', math.acos(-1), math.pi) self.ftest('acos(0)', math.acos(0), math.pi/2) self.ftest('acos(1)', math.acos(1), 0) + self.assertRaises(ValueError, math.acos, INF) + self.assertRaises(ValueError, math.acos, NINF) + self.assert_(math.isnan(math.acos(NAN))) + + def testAcosh(self): + self.assertRaises(TypeError, math.acosh) + self.ftest('acosh(1)', math.acosh(1), 0) + self.ftest('acosh(2)', math.acosh(2), 1.3169578969248168) + self.assertRaises(ValueError, math.acosh, 0) + self.assertRaises(ValueError, math.acosh, -1) + self.assertEquals(math.acosh(INF), INF) + self.assertRaises(ValueError, math.acosh, NINF) + self.assert_(math.isnan(math.acosh(NAN))) def testAsin(self): self.assertRaises(TypeError, math.asin) self.ftest('asin(-1)', math.asin(-1), -math.pi/2) self.ftest('asin(0)', math.asin(0), 0) self.ftest('asin(1)', math.asin(1), math.pi/2) + self.assertRaises(ValueError, math.asin, INF) + self.assertRaises(ValueError, math.asin, NINF) + self.assert_(math.isnan(math.asin(NAN))) + + def testAsinh(self): + self.assertRaises(TypeError, math.asinh) + self.ftest('asinh(0)', math.asinh(0), 0) + self.ftest('asinh(1)', math.asinh(1), 0.88137358701954305) + self.ftest('asinh(-1)', math.asinh(-1), -0.88137358701954305) + self.assertEquals(math.asinh(INF), INF) + self.assertEquals(math.asinh(NINF), NINF) + self.assert_(math.isnan(math.asinh(NAN))) def testAtan(self): self.assertRaises(TypeError, math.atan) self.ftest('atan(-1)', math.atan(-1), -math.pi/4) self.ftest('atan(0)', math.atan(0), 0) self.ftest('atan(1)', math.atan(1), math.pi/4) + self.ftest('atan(inf)', math.atan(INF), math.pi/2) + self.ftest('atan(-inf)', math.atan(NINF), -math.pi/2) + self.assert_(math.isnan(math.atan(NAN))) + + def testAtanh(self): + self.assertRaises(TypeError, math.atan) + self.ftest('atanh(0)', math.atanh(0), 0) + self.ftest('atanh(0.5)', math.atanh(0.5), 0.54930614433405489) + self.ftest('atanh(-0.5)', math.atanh(-0.5), -0.54930614433405489) + self.assertRaises(ValueError, math.atanh, 1) + self.assertRaises(ValueError, math.atanh, -1) + self.assertRaises(ValueError, math.atanh, INF) + self.assertRaises(ValueError, math.atanh, NINF) + self.assert_(math.isnan(math.atanh(NAN))) def testAtan2(self): self.assertRaises(TypeError, math.atan2) @@ -49,6 +124,59 @@ self.ftest('atan2(1, 1)', math.atan2(1, 1), math.pi/4) self.ftest('atan2(1, 0)', math.atan2(1, 0), math.pi/2) + # math.atan2(0, x) + self.ftest('atan2(0., -inf)', math.atan2(0., NINF), math.pi) + self.ftest('atan2(0., -2.3)', math.atan2(0., -2.3), math.pi) + self.ftest('atan2(0., -0.)', math.atan2(0., -0.), math.pi) + self.assertEqual(math.atan2(0., 0.), 0.) + self.assertEqual(math.atan2(0., 2.3), 0.) + self.assertEqual(math.atan2(0., INF), 0.) + self.assert_(math.isnan(math.atan2(0., NAN))) + # math.atan2(-0, x) + self.ftest('atan2(-0., -inf)', math.atan2(-0., NINF), -math.pi) + self.ftest('atan2(-0., -2.3)', math.atan2(-0., -2.3), -math.pi) + self.ftest('atan2(-0., -0.)', math.atan2(-0., -0.), -math.pi) + self.assertEqual(math.atan2(-0., 0.), -0.) + self.assertEqual(math.atan2(-0., 2.3), -0.) + self.assertEqual(math.atan2(-0., INF), -0.) + self.assert_(math.isnan(math.atan2(-0., NAN))) + # math.atan2(INF, x) + self.ftest('atan2(inf, -inf)', math.atan2(INF, NINF), math.pi*3/4) + self.ftest('atan2(inf, -2.3)', math.atan2(INF, -2.3), math.pi/2) + self.ftest('atan2(inf, -0.)', math.atan2(INF, -0.0), math.pi/2) + self.ftest('atan2(inf, 0.)', math.atan2(INF, 0.0), math.pi/2) + self.ftest('atan2(inf, 2.3)', math.atan2(INF, 2.3), math.pi/2) + self.ftest('atan2(inf, inf)', math.atan2(INF, INF), math.pi/4) + self.assert_(math.isnan(math.atan2(INF, NAN))) + # math.atan2(NINF, x) + self.ftest('atan2(-inf, -inf)', math.atan2(NINF, NINF), -math.pi*3/4) + self.ftest('atan2(-inf, -2.3)', math.atan2(NINF, -2.3), -math.pi/2) + self.ftest('atan2(-inf, -0.)', math.atan2(NINF, -0.0), -math.pi/2) + self.ftest('atan2(-inf, 0.)', math.atan2(NINF, 0.0), -math.pi/2) + self.ftest('atan2(-inf, 2.3)', math.atan2(NINF, 2.3), -math.pi/2) + self.ftest('atan2(-inf, inf)', math.atan2(NINF, INF), -math.pi/4) + self.assert_(math.isnan(math.atan2(NINF, NAN))) + # math.atan2(+finite, x) + self.ftest('atan2(2.3, -inf)', math.atan2(2.3, NINF), math.pi) + self.ftest('atan2(2.3, -0.)', math.atan2(2.3, -0.), math.pi/2) + self.ftest('atan2(2.3, 0.)', math.atan2(2.3, 0.), math.pi/2) + self.assertEqual(math.atan2(2.3, INF), 0.) + self.assert_(math.isnan(math.atan2(2.3, NAN))) + # math.atan2(-finite, x) + self.ftest('atan2(-2.3, -inf)', math.atan2(-2.3, NINF), -math.pi) + self.ftest('atan2(-2.3, -0.)', math.atan2(-2.3, -0.), -math.pi/2) + self.ftest('atan2(-2.3, 0.)', math.atan2(-2.3, 0.), -math.pi/2) + self.assertEqual(math.atan2(-2.3, INF), -0.) + self.assert_(math.isnan(math.atan2(-2.3, NAN))) + # math.atan2(NAN, x) + self.assert_(math.isnan(math.atan2(NAN, NINF))) + self.assert_(math.isnan(math.atan2(NAN, -2.3))) + self.assert_(math.isnan(math.atan2(NAN, -0.))) + self.assert_(math.isnan(math.atan2(NAN, 0.))) + self.assert_(math.isnan(math.atan2(NAN, 2.3))) + self.assert_(math.isnan(math.atan2(NAN, INF))) + self.assert_(math.isnan(math.atan2(NAN, NAN))) + def testCeil(self): self.assertRaises(TypeError, math.ceil) self.assertEquals(int, type(math.ceil(0.5))) @@ -58,6 +186,9 @@ self.ftest('ceil(-0.5)', math.ceil(-0.5), 0) self.ftest('ceil(-1.0)', math.ceil(-1.0), -1) self.ftest('ceil(-1.5)', math.ceil(-1.5), -1) + #self.assertEquals(math.ceil(INF), INF) + #self.assertEquals(math.ceil(NINF), NINF) + #self.assert_(math.isnan(math.ceil(NAN))) class TestCeil: def __ceil__(self): @@ -72,17 +203,55 @@ self.assertRaises(TypeError, math.ceil, t) self.assertRaises(TypeError, math.ceil, t, 0) + if float.__getformat__("double").startswith("IEEE"): + def testCopysign(self): + self.assertRaises(TypeError, math.copysign) + # copysign should let us distinguish signs of zeros + self.assertEquals(copysign(1., 0.), 1.) + self.assertEquals(copysign(1., -0.), -1.) + self.assertEquals(copysign(INF, 0.), INF) + self.assertEquals(copysign(INF, -0.), NINF) + self.assertEquals(copysign(NINF, 0.), INF) + self.assertEquals(copysign(NINF, -0.), NINF) + # and of infinities + self.assertEquals(copysign(1., INF), 1.) + self.assertEquals(copysign(1., NINF), -1.) + self.assertEquals(copysign(INF, INF), INF) + self.assertEquals(copysign(INF, NINF), NINF) + self.assertEquals(copysign(NINF, INF), INF) + self.assertEquals(copysign(NINF, NINF), NINF) + self.assert_(math.isnan(copysign(NAN, 1.))) + self.assert_(math.isnan(copysign(NAN, INF))) + self.assert_(math.isnan(copysign(NAN, NINF))) + self.assert_(math.isnan(copysign(NAN, NAN))) + # copysign(INF, NAN) may be INF or it may be NINF, since + # we don't know whether the sign bit of NAN is set on any + # given platform. + self.assert_(math.isinf(copysign(INF, NAN))) + # similarly, copysign(2., NAN) could be 2. or -2. + self.assertEquals(abs(copysign(2., NAN)), 2.) + def testCos(self): self.assertRaises(TypeError, math.cos) self.ftest('cos(-pi/2)', math.cos(-math.pi/2), 0) self.ftest('cos(0)', math.cos(0), 1) self.ftest('cos(pi/2)', math.cos(math.pi/2), 0) self.ftest('cos(pi)', math.cos(math.pi), -1) + try: + self.assert_(math.isnan(math.cos(INF))) + self.assert_(math.isnan(math.cos(NINF))) + except ValueError: + self.assertRaises(ValueError, math.cos, INF) + self.assertRaises(ValueError, math.cos, NINF) + self.assert_(math.isnan(math.cos(NAN))) def testCosh(self): self.assertRaises(TypeError, math.cosh) self.ftest('cosh(0)', math.cosh(0), 1) self.ftest('cosh(2)-2*cosh(1)**2', math.cosh(2)-2*math.cosh(1)**2, -1) # Thanks to Lambert + self.assertEquals(math.cosh(INF), INF) + self.assertEquals(math.cosh(NINF), INF) + self.assert_(math.isnan(math.cosh(NAN))) def testDegrees(self): self.assertRaises(TypeError, math.degrees) @@ -95,6 +264,9 @@ self.ftest('exp(-1)', math.exp(-1), 1/math.e) self.ftest('exp(0)', math.exp(0), 1) self.ftest('exp(1)', math.exp(1), math.e) + self.assertEquals(math.exp(INF), INF) + self.assertEquals(math.exp(NINF), 0.) + self.assert_(math.isnan(math.exp(NAN))) def testFabs(self): self.assertRaises(TypeError, math.fabs) @@ -115,6 +287,9 @@ # This fails on some platforms - so check it here self.ftest('floor(1.23e167)', math.floor(1.23e167), 1.23e167) self.ftest('floor(-1.23e167)', math.floor(-1.23e167), -1.23e167) + #self.assertEquals(math.ceil(INF), INF) + #self.assertEquals(math.ceil(NINF), NINF) + #self.assert_(math.isnan(math.floor(NAN))) class TestFloor: def __floor__(self): @@ -137,6 +312,19 @@ self.ftest('fmod(-10,1)', math.fmod(-10,1), 0) self.ftest('fmod(-10,0.5)', math.fmod(-10,0.5), 0) self.ftest('fmod(-10,1.5)', math.fmod(-10,1.5), -1) + self.assert_(math.isnan(math.fmod(NAN, 1.))) + self.assert_(math.isnan(math.fmod(1., NAN))) + self.assert_(math.isnan(math.fmod(NAN, NAN))) + self.assertRaises(ValueError, math.fmod, 1., 0.) + self.assertRaises(ValueError, math.fmod, INF, 1.) + self.assertRaises(ValueError, math.fmod, NINF, 1.) + self.assertRaises(ValueError, math.fmod, INF, 0.) + self.assertEquals(math.fmod(3.0, INF), 3.0) + self.assertEquals(math.fmod(-3.0, INF), -3.0) + self.assertEquals(math.fmod(3.0, NINF), 3.0) + self.assertEquals(math.fmod(-3.0, NINF), -3.0) + self.assertEquals(math.fmod(0.0, 3.0), 0.0) + self.assertEquals(math.fmod(0.0, NINF), 0.0) def testFrexp(self): self.assertRaises(TypeError, math.frexp) @@ -152,10 +340,20 @@ testfrexp('frexp(1)', math.frexp(1), (0.5, 1)) testfrexp('frexp(2)', math.frexp(2), (0.5, 2)) + self.assertEquals(math.frexp(INF)[0], INF) + self.assertEquals(math.frexp(NINF)[0], NINF) + self.assert_(math.isnan(math.frexp(NAN)[0])) + def testHypot(self): self.assertRaises(TypeError, math.hypot) self.ftest('hypot(0,0)', math.hypot(0,0), 0) self.ftest('hypot(3,4)', math.hypot(3,4), 5) + self.assertEqual(math.hypot(NAN, INF), INF) + self.assertEqual(math.hypot(INF, NAN), INF) + self.assertEqual(math.hypot(NAN, NINF), INF) + self.assertEqual(math.hypot(NINF, NAN), INF) + self.assert_(math.isnan(math.hypot(1.0, NAN))) + self.assert_(math.isnan(math.hypot(NAN, -2.0))) def testLdexp(self): self.assertRaises(TypeError, math.ldexp) @@ -163,6 +361,13 @@ self.ftest('ldexp(1,1)', math.ldexp(1,1), 2) self.ftest('ldexp(1,-1)', math.ldexp(1,-1), 0.5) self.ftest('ldexp(-1,1)', math.ldexp(-1,1), -2) + self.assertRaises(OverflowError, math.ldexp, 1., 1000000) + self.assertRaises(OverflowError, math.ldexp, -1., 1000000) + self.assertEquals(math.ldexp(1., -1000000), 0.) + self.assertEquals(math.ldexp(-1., -1000000), -0.) + self.assertEquals(math.ldexp(INF, 30), INF) + self.assertEquals(math.ldexp(NINF, -213), NINF) + self.assert_(math.isnan(math.ldexp(NAN, 0))) def testLog(self): self.assertRaises(TypeError, math.log) @@ -172,12 +377,31 @@ self.ftest('log(32,2)', math.log(32,2), 5) self.ftest('log(10**40, 10)', math.log(10**40, 10), 40) self.ftest('log(10**40, 10**20)', math.log(10**40, 10**20), 2) + self.assertEquals(math.log(INF), INF) + self.assertRaises(ValueError, math.log, NINF) + self.assert_(math.isnan(math.log(NAN))) + + def testLog1p(self): + self.assertRaises(TypeError, math.log1p) + self.ftest('log1p(1/e -1)', math.log1p(1/math.e-1), -1) + self.ftest('log1p(0)', math.log1p(0), 0) + self.ftest('log1p(e-1)', math.log1p(math.e-1), 1) + self.ftest('log1p(1)', math.log1p(1), math.log(2)) + self.assertEquals(math.log1p(INF), INF) + self.assertRaises(ValueError, math.log1p, NINF) + self.assert_(math.isnan(math.log1p(NAN))) + n= 2**90 + self.assertAlmostEquals(math.log1p(n), 62.383246250395075) + self.assertAlmostEquals(math.log1p(n), math.log1p(float(n))) def testLog10(self): self.assertRaises(TypeError, math.log10) self.ftest('log10(0.1)', math.log10(0.1), -1) self.ftest('log10(1)', math.log10(1), 0) self.ftest('log10(10)', math.log10(10), 1) + self.assertEquals(math.log(INF), INF) + self.assertRaises(ValueError, math.log10, NINF) + self.assert_(math.isnan(math.log10(NAN))) def testModf(self): self.assertRaises(TypeError, math.modf) @@ -191,12 +415,161 @@ testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0)) testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0)) + self.assertEquals(math.modf(INF), (0.0, INF)) + self.assertEquals(math.modf(NINF), (-0.0, NINF)) + + modf_nan = math.modf(NAN) + self.assert_(math.isnan(modf_nan[0])) + self.assert_(math.isnan(modf_nan[1])) + def testPow(self): self.assertRaises(TypeError, math.pow) self.ftest('pow(0,1)', math.pow(0,1), 0) self.ftest('pow(1,0)', math.pow(1,0), 1) self.ftest('pow(2,1)', math.pow(2,1), 2) self.ftest('pow(2,-1)', math.pow(2,-1), 0.5) + self.assertEqual(math.pow(INF, 1), INF) + self.assertEqual(math.pow(NINF, 1), NINF) + self.assertEqual((math.pow(1, INF)), 1.) + self.assertEqual((math.pow(1, NINF)), 1.) + self.assert_(math.isnan(math.pow(NAN, 1))) + self.assert_(math.isnan(math.pow(2, NAN))) + self.assert_(math.isnan(math.pow(0, NAN))) + self.assertEqual(math.pow(1, NAN), 1) + + # pow(0., x) + self.assertEqual(math.pow(0., INF), 0.) + self.assertEqual(math.pow(0., 3.), 0.) + self.assertEqual(math.pow(0., 2.3), 0.) + self.assertEqual(math.pow(0., 2.), 0.) + self.assertEqual(math.pow(0., 0.), 1.) + self.assertEqual(math.pow(0., -0.), 1.) + self.assertRaises(ValueError, math.pow, 0., -2.) + self.assertRaises(ValueError, math.pow, 0., -2.3) + self.assertRaises(ValueError, math.pow, 0., -3.) + self.assertRaises(ValueError, math.pow, 0., NINF) + self.assert_(math.isnan(math.pow(0., NAN))) + + # pow(INF, x) + self.assertEqual(math.pow(INF, INF), INF) + self.assertEqual(math.pow(INF, 3.), INF) + self.assertEqual(math.pow(INF, 2.3), INF) + self.assertEqual(math.pow(INF, 2.), INF) + self.assertEqual(math.pow(INF, 0.), 1.) + self.assertEqual(math.pow(INF, -0.), 1.) + self.assertEqual(math.pow(INF, -2.), 0.) + self.assertEqual(math.pow(INF, -2.3), 0.) + self.assertEqual(math.pow(INF, -3.), 0.) + self.assertEqual(math.pow(INF, NINF), 0.) + self.assert_(math.isnan(math.pow(INF, NAN))) + + # pow(-0., x) + self.assertEqual(math.pow(-0., INF), 0.) + self.assertEqual(math.pow(-0., 3.), -0.) + self.assertEqual(math.pow(-0., 2.3), 0.) + self.assertEqual(math.pow(-0., 2.), 0.) + self.assertEqual(math.pow(-0., 0.), 1.) + self.assertEqual(math.pow(-0., -0.), 1.) + self.assertRaises(ValueError, math.pow, -0., -2.) + self.assertRaises(ValueError, math.pow, -0., -2.3) + self.assertRaises(ValueError, math.pow, -0., -3.) + self.assertRaises(ValueError, math.pow, -0., NINF) + self.assert_(math.isnan(math.pow(-0., NAN))) + + # pow(NINF, x) + self.assertEqual(math.pow(NINF, INF), INF) + self.assertEqual(math.pow(NINF, 3.), NINF) + self.assertEqual(math.pow(NINF, 2.3), INF) + self.assertEqual(math.pow(NINF, 2.), INF) + self.assertEqual(math.pow(NINF, 0.), 1.) + self.assertEqual(math.pow(NINF, -0.), 1.) + self.assertEqual(math.pow(NINF, -2.), 0.) + self.assertEqual(math.pow(NINF, -2.3), 0.) + self.assertEqual(math.pow(NINF, -3.), -0.) + self.assertEqual(math.pow(NINF, NINF), 0.) + self.assert_(math.isnan(math.pow(NINF, NAN))) + + # pow(-1, x) + self.assertEqual(math.pow(-1., INF), 1.) + self.assertEqual(math.pow(-1., 3.), -1.) + self.assertRaises(ValueError, math.pow, -1., 2.3) + self.assertEqual(math.pow(-1., 2.), 1.) + self.assertEqual(math.pow(-1., 0.), 1.) + self.assertEqual(math.pow(-1., -0.), 1.) + self.assertEqual(math.pow(-1., -2.), 1.) + self.assertRaises(ValueError, math.pow, -1., -2.3) + self.assertEqual(math.pow(-1., -3.), -1.) + self.assertEqual(math.pow(-1., NINF), 1.) + self.assert_(math.isnan(math.pow(-1., NAN))) + + # pow(1, x) + self.assertEqual(math.pow(1., INF), 1.) + self.assertEqual(math.pow(1., 3.), 1.) + self.assertEqual(math.pow(1., 2.3), 1.) + self.assertEqual(math.pow(1., 2.), 1.) + self.assertEqual(math.pow(1., 0.), 1.) + self.assertEqual(math.pow(1., -0.), 1.) + self.assertEqual(math.pow(1., -2.), 1.) + self.assertEqual(math.pow(1., -2.3), 1.) + self.assertEqual(math.pow(1., -3.), 1.) + self.assertEqual(math.pow(1., NINF), 1.) + self.assertEqual(math.pow(1., NAN), 1.) + + # pow(x, 0) should be 1 for any x + self.assertEqual(math.pow(2.3, 0.), 1.) + self.assertEqual(math.pow(-2.3, 0.), 1.) + self.assertEqual(math.pow(NAN, 0.), 1.) + self.assertEqual(math.pow(2.3, -0.), 1.) + self.assertEqual(math.pow(-2.3, -0.), 1.) + self.assertEqual(math.pow(NAN, -0.), 1.) + + # pow(x, y) is invalid if x is negative and y is not integral + self.assertRaises(ValueError, math.pow, -1., 2.3) + self.assertRaises(ValueError, math.pow, -15., -3.1) + + # pow(x, NINF) + self.assertEqual(math.pow(1.9, NINF), 0.) + self.assertEqual(math.pow(1.1, NINF), 0.) + self.assertEqual(math.pow(0.9, NINF), INF) + self.assertEqual(math.pow(0.1, NINF), INF) + self.assertEqual(math.pow(-0.1, NINF), INF) + self.assertEqual(math.pow(-0.9, NINF), INF) + self.assertEqual(math.pow(-1.1, NINF), 0.) + self.assertEqual(math.pow(-1.9, NINF), 0.) + + # pow(x, INF) + self.assertEqual(math.pow(1.9, INF), INF) + self.assertEqual(math.pow(1.1, INF), INF) + self.assertEqual(math.pow(0.9, INF), 0.) + self.assertEqual(math.pow(0.1, INF), 0.) + self.assertEqual(math.pow(-0.1, INF), 0.) + self.assertEqual(math.pow(-0.9, INF), 0.) + self.assertEqual(math.pow(-1.1, INF), INF) + self.assertEqual(math.pow(-1.9, INF), INF) + + # pow(x, y) should work for x negative, y an integer + self.ftest('(-2.)**3.', math.pow(-2.0, 3.0), -8.0) + self.ftest('(-2.)**2.', math.pow(-2.0, 2.0), 4.0) + self.ftest('(-2.)**1.', math.pow(-2.0, 1.0), -2.0) + self.ftest('(-2.)**0.', math.pow(-2.0, 0.0), 1.0) + self.ftest('(-2.)**-0.', math.pow(-2.0, -0.0), 1.0) + self.ftest('(-2.)**-1.', math.pow(-2.0, -1.0), -0.5) + self.ftest('(-2.)**-2.', math.pow(-2.0, -2.0), 0.25) + self.ftest('(-2.)**-3.', math.pow(-2.0, -3.0), -0.125) + self.assertRaises(ValueError, math.pow, -2.0, -0.5) + self.assertRaises(ValueError, math.pow, -2.0, 0.5) + + # the following tests have been commented out since they don't + # really belong here: the implementation of ** for floats is + # independent of the implemention of math.pow + #self.assertEqual(1**NAN, 1) + #self.assertEqual(1**INF, 1) + #self.assertEqual(1**NINF, 1) + #self.assertEqual(1**0, 1) + #self.assertEqual(1.**NAN, 1) + #self.assertEqual(1.**INF, 1) + #self.assertEqual(1.**NINF, 1) + #self.assertEqual(1.**0, 1) def testRadians(self): self.assertRaises(TypeError, math.radians) @@ -209,29 +582,89 @@ self.ftest('sin(0)', math.sin(0), 0) self.ftest('sin(pi/2)', math.sin(math.pi/2), 1) self.ftest('sin(-pi/2)', math.sin(-math.pi/2), -1) + try: + self.assert_(math.isnan(math.sin(INF))) + self.assert_(math.isnan(math.sin(NINF))) + except ValueError: + self.assertRaises(ValueError, math.sin, INF) + self.assertRaises(ValueError, math.sin, NINF) + self.assert_(math.isnan(math.sin(NAN))) def testSinh(self): self.assertRaises(TypeError, math.sinh) self.ftest('sinh(0)', math.sinh(0), 0) self.ftest('sinh(1)**2-cosh(1)**2', math.sinh(1)**2-math.cosh(1)**2, -1) self.ftest('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0) + self.assertEquals(math.sinh(INF), INF) + self.assertEquals(math.sinh(NINF), NINF) + self.assert_(math.isnan(math.sinh(NAN))) def testSqrt(self): self.assertRaises(TypeError, math.sqrt) self.ftest('sqrt(0)', math.sqrt(0), 0) self.ftest('sqrt(1)', math.sqrt(1), 1) self.ftest('sqrt(4)', math.sqrt(4), 2) + self.assertEquals(math.sqrt(INF), INF) + self.assertRaises(ValueError, math.sqrt, NINF) + self.assert_(math.isnan(math.sqrt(NAN))) def testTan(self): self.assertRaises(TypeError, math.tan) self.ftest('tan(0)', math.tan(0), 0) self.ftest('tan(pi/4)', math.tan(math.pi/4), 1) self.ftest('tan(-pi/4)', math.tan(-math.pi/4), -1) + try: + self.assert_(math.isnan(math.tan(INF))) + self.assert_(math.isnan(math.tan(NINF))) + except: + self.assertRaises(ValueError, math.tan, INF) + self.assertRaises(ValueError, math.tan, NINF) + self.assert_(math.isnan(math.tan(NAN))) def testTanh(self): self.assertRaises(TypeError, math.tanh) self.ftest('tanh(0)', math.tanh(0), 0) self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0) + self.ftest('tanh(inf)', math.tanh(INF), 1) + self.ftest('tanh(-inf)', math.tanh(NINF), -1) + self.assert_(math.isnan(math.tanh(NAN))) + # check that tanh(-0.) == -0. on IEEE 754 systems + if float.__getformat__("double").startswith("IEEE"): + self.assertEqual(math.tanh(-0.), -0.) + self.assertEqual(math.copysign(1., math.tanh(-0.)), + math.copysign(1., -0.)) + + def test_trunc(self): + self.assertEqual(math.trunc(1), 1) + self.assertEqual(math.trunc(-1), -1) + self.assertEqual(type(math.trunc(1)), int) + self.assertEqual(type(math.trunc(1.5)), int) + self.assertEqual(math.trunc(1.5), 1) + self.assertEqual(math.trunc(-1.5), -1) + self.assertEqual(math.trunc(1.999999), 1) + self.assertEqual(math.trunc(-1.999999), -1) + self.assertEqual(math.trunc(-0.999999), -0) + self.assertEqual(math.trunc(-100.999), -100) + + class TestTrunc(object): + def __trunc__(self): + return 23 + + class TestNoTrunc(object): + pass + + self.assertEqual(math.trunc(TestTrunc()), 23) + + self.assertRaises(TypeError, math.trunc) + self.assertRaises(TypeError, math.trunc, 1, 2) + self.assertRaises(TypeError, math.trunc, TestNoTrunc()) + + # XXX Doesn't work because the method is looked up on + # the type only. + #t = TestNoTrunc() + #t.__trunc__ = lambda *args: args + #self.assertEquals((), math.trunc(t)) + #self.assertRaises(TypeError, math.trunc, t, 0) def testCopysign(self): self.assertEqual(math.copysign(1, 42), 1.0) @@ -294,9 +727,32 @@ else: self.fail("sqrt(-1) didn't raise ValueError") + def test_testfile(self): + if not float.__getformat__("double").startswith("IEEE"): + return + for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file): + # Skip if either the input or result is complex, or if + # flags is nonempty + if ai != 0. or ei != 0. or flags: + continue + if fn in ['rect', 'polar']: + # no real versions of rect, polar + continue + func = getattr(math, fn) + try: + result = func(ar) + except ValueError: + message = ("Unexpected ValueError in " + + "test %s:%s(%r)\n" % (id, fn, ar)) + self.fail(message) + self.ftest("%s:%s(%r)" % (id, fn, ar), result, er) def test_main(): - run_unittest(MathTests) + from doctest import DocFileSuite + suite = unittest.TestSuite() + suite.addTest(unittest.makeSuite(MathTests)) + suite.addTest(DocFileSuite("ieee754.txt")) + run_unittest(suite) if __name__ == '__main__': test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_metaclass.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_metaclass.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_metaclass.py Wed Apr 30 15:57:13 2008 @@ -78,7 +78,7 @@ >>> class C(object, metaclass=M, other="haha"): ... pass ... - Prepare called: ('C', (,)) {'other': 'haha'} + Prepare called: ('C', (,)) {'other': 'haha'} New called: {'other': 'haha'} >>> C.__class__ is M True @@ -104,7 +104,7 @@ >>> kwds = {'metaclass': M, 'other': 'haha'} >>> class C(*bases, **kwds): pass ... - Prepare called: ('C', (,)) {'other': 'haha'} + Prepare called: ('C', (,)) {'other': 'haha'} New called: {'other': 'haha'} >>> C.__class__ is M True @@ -114,7 +114,7 @@ >>> kwds = {'other': 'haha'} >>> class C(B, metaclass=M, *bases, **kwds): pass ... - Prepare called: ('C', (, )) {'other': 'haha'} + Prepare called: ('C', (, )) {'other': 'haha'} New called: {'other': 'haha'} >>> C.__class__ is M True Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_minidom.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_minidom.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_minidom.py Wed Apr 30 15:57:13 2008 @@ -3,7 +3,6 @@ import os import sys import pickle -import traceback from io import StringIO from test.test_support import verbose, run_unittest, TestSkipped import unittest @@ -791,6 +790,14 @@ "testNormalize -- single empty node removed") doc.unlink() + def testBug1433694(self): + doc = parseString("t") + node = doc.documentElement + node.childNodes[1].nodeValue = "" + node.normalize() + self.confirm(node.childNodes[-1].nextSibling == None, + "Final child's .nextSibling should be None") + def testSiblings(self): doc = parseString("text?") root = doc.documentElement Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_mmap.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_mmap.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_mmap.py Wed Apr 30 15:57:13 2008 @@ -158,6 +158,7 @@ pass else: self.fail("Able to resize readonly memory map") + f.close() del m, f self.assertEqual(open(TESTFN, "rb").read(), b'a'*mapsize, "Readonly memory map data file was modified") @@ -214,6 +215,7 @@ "Copy-on-write test data file should not be modified.") # Ensuring copy-on-write maps cannot be resized self.assertRaises(TypeError, m.resize, 2*mapsize) + f.close() del m, f # Ensuring invalid access parameter raises exception @@ -425,6 +427,20 @@ return mmap.mmap.__new__(klass, -1, *args, **kwargs) anon_mmap(PAGESIZE) + def test_prot_readonly(self): + if not hasattr(mmap, 'PROT_READ'): + return + mapsize = 10 + open(TESTFN, "wb").write(b"a"*mapsize) + f = open(TESTFN, "rb") + m = mmap.mmap(f.fileno(), mapsize, prot=mmap.PROT_READ) + self.assertRaises(TypeError, m.write, "foo") + f.close() + + def test_error(self): + self.assert_(issubclass(mmap.error, EnvironmentError)) + self.assert_("mmap.error" in str(mmap.error)) + def test_main(): run_unittest(MmapTests) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_module.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_module.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_module.py Wed Apr 30 15:57:13 2008 @@ -1,6 +1,6 @@ # Test the module type import unittest -from test.test_support import verbose, run_unittest +from test.test_support import run_unittest import sys ModuleType = type(sys) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_modulefinder.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_modulefinder.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_modulefinder.py Wed Apr 30 15:57:13 2008 @@ -1,5 +1,5 @@ import __future__ -import sys, os +import os import unittest import distutils.dir_util import tempfile Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_multibytecodec_support.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_multibytecodec_support.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_multibytecodec_support.py Wed Apr 30 15:57:13 2008 @@ -4,7 +4,7 @@ # Common Unittest Routines for CJK codecs # -import sys, codecs, os.path +import sys, codecs import unittest, re from test import test_support from io import BytesIO @@ -276,7 +276,10 @@ def __init__(self, *args, **kw): unittest.TestCase.__init__(self, *args, **kw) - self.open_mapping_file() # test it to report the error early + try: + self.open_mapping_file() # test it to report the error early + except IOError: + raise test_support.TestSkipped("Could not retrieve "+self.mapfileurl) def open_mapping_file(self): return test_support.open_urlresource(self.mapfileurl) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_nis.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_nis.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_nis.py Wed Apr 30 15:57:13 2008 @@ -1,4 +1,4 @@ -from test.test_support import verbose, run_unittest +from test import test_support import unittest import nis @@ -8,8 +8,10 @@ maps = nis.maps() except nis.error as msg: # NIS is probably not active, so this test isn't useful - if verbose: - self.fail("(failing because of verbose mode) %s" % msg) + if test_support.verbose: + print("Test Skipped:", msg) + # Can't raise TestSkipped as regrtest only recognizes the exception + # import time. return try: # On some systems, this map is only accessible to the @@ -35,7 +37,7 @@ break def test_main(): - run_unittest(NisTests) + test_support.run_unittest(NisTests) if __name__ == '__main__': test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_ntpath.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_ntpath.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_ntpath.py Wed Apr 30 15:57:13 2008 @@ -1,174 +1,187 @@ import ntpath -from test.test_support import verbose, TestFailed import os +from test.test_support import verbose, TestFailed +import test.test_support as test_support +import unittest -errors = 0 def tester(fn, wantResult): - global errors fn = fn.replace("\\", "\\\\") gotResult = eval(fn) if wantResult != gotResult: - print("error!") - print("evaluated: " + str(fn)) - print("should be: " + str(wantResult)) - print(" returned: " + str(gotResult)) - print("") - errors = errors + 1 - -tester('ntpath.splitext("foo.ext")', ('foo', '.ext')) -tester('ntpath.splitext("/foo/foo.ext")', ('/foo/foo', '.ext')) -tester('ntpath.splitext(".ext")', ('.ext', '')) -tester('ntpath.splitext("\\foo.ext\\foo")', ('\\foo.ext\\foo', '')) -tester('ntpath.splitext("foo.ext\\")', ('foo.ext\\', '')) -tester('ntpath.splitext("")', ('', '')) -tester('ntpath.splitext("foo.bar.ext")', ('foo.bar', '.ext')) -tester('ntpath.splitext("xx/foo.bar.ext")', ('xx/foo.bar', '.ext')) -tester('ntpath.splitext("xx\\foo.bar.ext")', ('xx\\foo.bar', '.ext')) -tester('ntpath.splitext("c:a/b\\c.d")', ('c:a/b\\c', '.d')) - -tester('ntpath.splitdrive("c:\\foo\\bar")', - ('c:', '\\foo\\bar')) -tester('ntpath.splitunc("\\\\conky\\mountpoint\\foo\\bar")', - ('\\\\conky\\mountpoint', '\\foo\\bar')) -tester('ntpath.splitdrive("c:/foo/bar")', - ('c:', '/foo/bar')) -tester('ntpath.splitunc("//conky/mountpoint/foo/bar")', - ('//conky/mountpoint', '/foo/bar')) - -tester('ntpath.split("c:\\foo\\bar")', ('c:\\foo', 'bar')) -tester('ntpath.split("\\\\conky\\mountpoint\\foo\\bar")', - ('\\\\conky\\mountpoint\\foo', 'bar')) - -tester('ntpath.split("c:\\")', ('c:\\', '')) -tester('ntpath.split("\\\\conky\\mountpoint\\")', - ('\\\\conky\\mountpoint', '')) - -tester('ntpath.split("c:/")', ('c:/', '')) -tester('ntpath.split("//conky/mountpoint/")', ('//conky/mountpoint', '')) - -tester('ntpath.isabs("c:\\")', 1) -tester('ntpath.isabs("\\\\conky\\mountpoint\\")', 1) -tester('ntpath.isabs("\\foo")', 1) -tester('ntpath.isabs("\\foo\\bar")', 1) - -tester('ntpath.commonprefix(["/home/swenson/spam", "/home/swen/spam"])', - "/home/swen") -tester('ntpath.commonprefix(["\\home\\swen\\spam", "\\home\\swen\\eggs"])', - "\\home\\swen\\") -tester('ntpath.commonprefix(["/home/swen/spam", "/home/swen/spam"])', - "/home/swen/spam") - -tester('ntpath.join("")', '') -tester('ntpath.join("", "", "")', '') -tester('ntpath.join("a")', 'a') -tester('ntpath.join("/a")', '/a') -tester('ntpath.join("\\a")', '\\a') -tester('ntpath.join("a:")', 'a:') -tester('ntpath.join("a:", "b")', 'a:b') -tester('ntpath.join("a:", "/b")', 'a:/b') -tester('ntpath.join("a:", "\\b")', 'a:\\b') -tester('ntpath.join("a", "/b")', '/b') -tester('ntpath.join("a", "\\b")', '\\b') -tester('ntpath.join("a", "b", "c")', 'a\\b\\c') -tester('ntpath.join("a\\", "b", "c")', 'a\\b\\c') -tester('ntpath.join("a", "b\\", "c")', 'a\\b\\c') -tester('ntpath.join("a", "b", "\\c")', '\\c') -tester('ntpath.join("d:\\", "\\pleep")', 'd:\\pleep') -tester('ntpath.join("d:\\", "a", "b")', 'd:\\a\\b') -tester("ntpath.join('c:', '/a')", 'c:/a') -tester("ntpath.join('c:/', '/a')", 'c:/a') -tester("ntpath.join('c:/a', '/b')", '/b') -tester("ntpath.join('c:', 'd:/')", 'd:/') -tester("ntpath.join('c:/', 'd:/')", 'd:/') -tester("ntpath.join('c:/', 'd:/a/b')", 'd:/a/b') - -tester("ntpath.join('')", '') -tester("ntpath.join('', '', '', '', '')", '') -tester("ntpath.join('a')", 'a') -tester("ntpath.join('', 'a')", 'a') -tester("ntpath.join('', '', '', '', 'a')", 'a') -tester("ntpath.join('a', '')", 'a\\') -tester("ntpath.join('a', '', '', '', '')", 'a\\') -tester("ntpath.join('a\\', '')", 'a\\') -tester("ntpath.join('a\\', '', '', '', '')", 'a\\') - -tester("ntpath.normpath('A//////././//.//B')", r'A\B') -tester("ntpath.normpath('A/./B')", r'A\B') -tester("ntpath.normpath('A/foo/../B')", r'A\B') -tester("ntpath.normpath('C:A//B')", r'C:A\B') -tester("ntpath.normpath('D:A/./B')", r'D:A\B') -tester("ntpath.normpath('e:A/foo/../B')", r'e:A\B') - -tester("ntpath.normpath('C:///A//B')", r'C:\A\B') -tester("ntpath.normpath('D:///A/./B')", r'D:\A\B') -tester("ntpath.normpath('e:///A/foo/../B')", r'e:\A\B') - -tester("ntpath.normpath('..')", r'..') -tester("ntpath.normpath('.')", r'.') -tester("ntpath.normpath('')", r'.') -tester("ntpath.normpath('/')", '\\') -tester("ntpath.normpath('c:/')", 'c:\\') -tester("ntpath.normpath('/../.././..')", '\\') -tester("ntpath.normpath('c:/../../..')", 'c:\\') -tester("ntpath.normpath('../.././..')", r'..\..\..') -tester("ntpath.normpath('K:../.././..')", r'K:..\..\..') -tester("ntpath.normpath('C:////a/b')", r'C:\a\b') -tester("ntpath.normpath('//machine/share//a/b')", r'\\machine\share\a\b') - -oldenv = os.environ.copy() -try: - os.environ.clear() - os.environ["foo"] = "bar" - os.environ["{foo"] = "baz1" - os.environ["{foo}"] = "baz2" - tester('ntpath.expandvars("foo")', "foo") - tester('ntpath.expandvars("$foo bar")', "bar bar") - tester('ntpath.expandvars("${foo}bar")', "barbar") - tester('ntpath.expandvars("$[foo]bar")', "$[foo]bar") - tester('ntpath.expandvars("$bar bar")', "$bar bar") - tester('ntpath.expandvars("$?bar")', "$?bar") - tester('ntpath.expandvars("${foo}bar")', "barbar") - tester('ntpath.expandvars("$foo}bar")', "bar}bar") - tester('ntpath.expandvars("${foo")', "${foo") - tester('ntpath.expandvars("${{foo}}")', "baz1}") - tester('ntpath.expandvars("$foo$foo")', "barbar") - tester('ntpath.expandvars("$bar$bar")', "$bar$bar") - tester('ntpath.expandvars("%foo% bar")', "bar bar") - tester('ntpath.expandvars("%foo%bar")', "barbar") - tester('ntpath.expandvars("%foo%%foo%")', "barbar") - tester('ntpath.expandvars("%%foo%%foo%foo%")', "%foo%foobar") - tester('ntpath.expandvars("%?bar%")', "%?bar%") - tester('ntpath.expandvars("%foo%%bar")', "bar%bar") - tester('ntpath.expandvars("\'%foo%\'%bar")', "\'%foo%\'%bar") -finally: - os.environ.clear() - os.environ.update(oldenv) - -# ntpath.abspath() can only be used on a system with the "nt" module -# (reasonably), so we protect this test with "import nt". This allows -# the rest of the tests for the ntpath module to be run to completion -# on any platform, since most of the module is intended to be usable -# from any platform. -try: - import nt -except ImportError: - pass -else: - tester('ntpath.abspath("C:\\")', "C:\\") - -currentdir = os.path.split(os.getcwd())[-1] -tester('ntpath.relpath("a")', 'a') -tester('ntpath.relpath(os.path.abspath("a"))', 'a') -tester('ntpath.relpath("a/b")', 'a\\b') -tester('ntpath.relpath("../a/b")', '..\\a\\b') -tester('ntpath.relpath("a", "../b")', '..\\'+currentdir+'\\a') -tester('ntpath.relpath("a/b", "../c")', '..\\'+currentdir+'\\a\\b') -tester('ntpath.relpath("a", "b/c")', '..\\..\\a') -tester('ntpath.relpath("//conky/mountpoint/a", "//conky/mountpoint/b/c")', '..\\..\\a') -tester('ntpath.relpath("a", "a")', '.') - -if errors: - raise TestFailed(str(errors) + " errors.") -elif verbose: - print("No errors. Thank your lucky stars.") + raise TestFailed("%s should return: %s but returned: %s" \ + %(str(fn), str(wantResult), str(gotResult))) + + +class TestNtpath(unittest.TestCase): + def test_splitext(self): + tester('ntpath.splitext("foo.ext")', ('foo', '.ext')) + tester('ntpath.splitext("/foo/foo.ext")', ('/foo/foo', '.ext')) + tester('ntpath.splitext(".ext")', ('.ext', '')) + tester('ntpath.splitext("\\foo.ext\\foo")', ('\\foo.ext\\foo', '')) + tester('ntpath.splitext("foo.ext\\")', ('foo.ext\\', '')) + tester('ntpath.splitext("")', ('', '')) + tester('ntpath.splitext("foo.bar.ext")', ('foo.bar', '.ext')) + tester('ntpath.splitext("xx/foo.bar.ext")', ('xx/foo.bar', '.ext')) + tester('ntpath.splitext("xx\\foo.bar.ext")', ('xx\\foo.bar', '.ext')) + tester('ntpath.splitext("c:a/b\\c.d")', ('c:a/b\\c', '.d')) + + def test_splitdrive(self): + tester('ntpath.splitdrive("c:\\foo\\bar")', + ('c:', '\\foo\\bar')) + tester('ntpath.splitdrive("c:/foo/bar")', + ('c:', '/foo/bar')) + + def test_splitunc(self): + tester('ntpath.splitunc("\\\\conky\\mountpoint\\foo\\bar")', + ('\\\\conky\\mountpoint', '\\foo\\bar')) + tester('ntpath.splitunc("//conky/mountpoint/foo/bar")', + ('//conky/mountpoint', '/foo/bar')) + + def test_split(self): + tester('ntpath.split("c:\\foo\\bar")', ('c:\\foo', 'bar')) + tester('ntpath.split("\\\\conky\\mountpoint\\foo\\bar")', + ('\\\\conky\\mountpoint\\foo', 'bar')) + + tester('ntpath.split("c:\\")', ('c:\\', '')) + tester('ntpath.split("\\\\conky\\mountpoint\\")', + ('\\\\conky\\mountpoint', '')) + + tester('ntpath.split("c:/")', ('c:/', '')) + tester('ntpath.split("//conky/mountpoint/")', ('//conky/mountpoint', '')) + + def test_isabs(self): + tester('ntpath.isabs("c:\\")', 1) + tester('ntpath.isabs("\\\\conky\\mountpoint\\")', 1) + tester('ntpath.isabs("\\foo")', 1) + tester('ntpath.isabs("\\foo\\bar")', 1) + + def test_commonprefix(self): + tester('ntpath.commonprefix(["/home/swenson/spam", "/home/swen/spam"])', + "/home/swen") + tester('ntpath.commonprefix(["\\home\\swen\\spam", "\\home\\swen\\eggs"])', + "\\home\\swen\\") + tester('ntpath.commonprefix(["/home/swen/spam", "/home/swen/spam"])', + "/home/swen/spam") + + def test_join(self): + tester('ntpath.join("")', '') + tester('ntpath.join("", "", "")', '') + tester('ntpath.join("a")', 'a') + tester('ntpath.join("/a")', '/a') + tester('ntpath.join("\\a")', '\\a') + tester('ntpath.join("a:")', 'a:') + tester('ntpath.join("a:", "b")', 'a:b') + tester('ntpath.join("a:", "/b")', 'a:/b') + tester('ntpath.join("a:", "\\b")', 'a:\\b') + tester('ntpath.join("a", "/b")', '/b') + tester('ntpath.join("a", "\\b")', '\\b') + tester('ntpath.join("a", "b", "c")', 'a\\b\\c') + tester('ntpath.join("a\\", "b", "c")', 'a\\b\\c') + tester('ntpath.join("a", "b\\", "c")', 'a\\b\\c') + tester('ntpath.join("a", "b", "\\c")', '\\c') + tester('ntpath.join("d:\\", "\\pleep")', 'd:\\pleep') + tester('ntpath.join("d:\\", "a", "b")', 'd:\\a\\b') + tester("ntpath.join('c:', '/a')", 'c:/a') + tester("ntpath.join('c:/', '/a')", 'c:/a') + tester("ntpath.join('c:/a', '/b')", '/b') + tester("ntpath.join('c:', 'd:/')", 'd:/') + tester("ntpath.join('c:/', 'd:/')", 'd:/') + tester("ntpath.join('c:/', 'd:/a/b')", 'd:/a/b') + + tester("ntpath.join('')", '') + tester("ntpath.join('', '', '', '', '')", '') + tester("ntpath.join('a')", 'a') + tester("ntpath.join('', 'a')", 'a') + tester("ntpath.join('', '', '', '', 'a')", 'a') + tester("ntpath.join('a', '')", 'a\\') + tester("ntpath.join('a', '', '', '', '')", 'a\\') + tester("ntpath.join('a\\', '')", 'a\\') + tester("ntpath.join('a\\', '', '', '', '')", 'a\\') + + def test_normpath(self): + tester("ntpath.normpath('A//////././//.//B')", r'A\B') + tester("ntpath.normpath('A/./B')", r'A\B') + tester("ntpath.normpath('A/foo/../B')", r'A\B') + tester("ntpath.normpath('C:A//B')", r'C:A\B') + tester("ntpath.normpath('D:A/./B')", r'D:A\B') + tester("ntpath.normpath('e:A/foo/../B')", r'e:A\B') + + tester("ntpath.normpath('C:///A//B')", r'C:\A\B') + tester("ntpath.normpath('D:///A/./B')", r'D:\A\B') + tester("ntpath.normpath('e:///A/foo/../B')", r'e:\A\B') + + tester("ntpath.normpath('..')", r'..') + tester("ntpath.normpath('.')", r'.') + tester("ntpath.normpath('')", r'.') + tester("ntpath.normpath('/')", '\\') + tester("ntpath.normpath('c:/')", 'c:\\') + tester("ntpath.normpath('/../.././..')", '\\') + tester("ntpath.normpath('c:/../../..')", 'c:\\') + tester("ntpath.normpath('../.././..')", r'..\..\..') + tester("ntpath.normpath('K:../.././..')", r'K:..\..\..') + tester("ntpath.normpath('C:////a/b')", r'C:\a\b') + tester("ntpath.normpath('//machine/share//a/b')", r'\\machine\share\a\b') + + def test_expandvars(self): + oldenv = os.environ.copy() + try: + os.environ.clear() + os.environ["foo"] = "bar" + os.environ["{foo"] = "baz1" + os.environ["{foo}"] = "baz2" + tester('ntpath.expandvars("foo")', "foo") + tester('ntpath.expandvars("$foo bar")', "bar bar") + tester('ntpath.expandvars("${foo}bar")', "barbar") + tester('ntpath.expandvars("$[foo]bar")', "$[foo]bar") + tester('ntpath.expandvars("$bar bar")', "$bar bar") + tester('ntpath.expandvars("$?bar")', "$?bar") + tester('ntpath.expandvars("${foo}bar")', "barbar") + tester('ntpath.expandvars("$foo}bar")', "bar}bar") + tester('ntpath.expandvars("${foo")', "${foo") + tester('ntpath.expandvars("${{foo}}")', "baz1}") + tester('ntpath.expandvars("$foo$foo")', "barbar") + tester('ntpath.expandvars("$bar$bar")', "$bar$bar") + tester('ntpath.expandvars("%foo% bar")', "bar bar") + tester('ntpath.expandvars("%foo%bar")', "barbar") + tester('ntpath.expandvars("%foo%%foo%")', "barbar") + tester('ntpath.expandvars("%%foo%%foo%foo%")', "%foo%foobar") + tester('ntpath.expandvars("%?bar%")', "%?bar%") + tester('ntpath.expandvars("%foo%%bar")', "bar%bar") + tester('ntpath.expandvars("\'%foo%\'%bar")', "\'%foo%\'%bar") + finally: + os.environ.clear() + os.environ.update(oldenv) + + def test_abspath(self): + # ntpath.abspath() can only be used on a system with the "nt" module + # (reasonably), so we protect this test with "import nt". This allows + # the rest of the tests for the ntpath module to be run to completion + # on any platform, since most of the module is intended to be usable + # from any platform. + try: + import nt + except ImportError: + pass + else: + tester('ntpath.abspath("C:\\")', "C:\\") + + def test_relpath(self): + currentdir = os.path.split(os.getcwd())[-1] + tester('ntpath.relpath("a")', 'a') + tester('ntpath.relpath(os.path.abspath("a"))', 'a') + tester('ntpath.relpath("a/b")', 'a\\b') + tester('ntpath.relpath("../a/b")', '..\\a\\b') + tester('ntpath.relpath("a", "../b")', '..\\'+currentdir+'\\a') + tester('ntpath.relpath("a/b", "../c")', '..\\'+currentdir+'\\a\\b') + tester('ntpath.relpath("a", "b/c")', '..\\..\\a') + tester('ntpath.relpath("//conky/mountpoint/a", "//conky/mountpoint/b/c")', '..\\..\\a') + tester('ntpath.relpath("a", "a")', '.') + + +def test_main(): + test_support.run_unittest(TestNtpath) + + +if __name__ == "__main__": + unittest.main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_operator.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_operator.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_operator.py Wed Apr 30 15:57:13 2008 @@ -137,15 +137,6 @@ self.failUnless(operator.delitem(a, 1) is None) self.assert_(a == [4, 2, 1]) - def test_delslice(self): - a = list(range(10)) - self.failUnlessRaises(TypeError, operator.delslice, a) - self.failUnlessRaises(TypeError, operator.delslice, a, None, None) - self.failUnless(operator.delslice(a, 2, 8) is None) - self.assert_(a == [0, 1, 8, 9]) - operator.delslice(a, 0, test_support.MAX_Py_ssize_t) - self.assertEqual(a, []) - def test_floordiv(self): self.failUnlessRaises(TypeError, operator.floordiv, 5) self.failUnlessRaises(TypeError, operator.floordiv, None, None) @@ -162,14 +153,6 @@ self.failUnlessRaises(TypeError, operator.getitem, a, None) self.failUnless(operator.getitem(a, 2) == 2) - def test_getslice(self): - a = list(range(10)) - self.failUnlessRaises(TypeError, operator.getslice) - self.failUnlessRaises(TypeError, operator.getslice, a, None, None) - self.failUnless(operator.getslice(a, 4, 6) == [4, 5]) - b = operator.getslice(a, 0, test_support.MAX_Py_ssize_t) - self.assertEqual(b, a) - def test_indexOf(self): self.failUnlessRaises(TypeError, operator.indexOf) self.failUnlessRaises(TypeError, operator.indexOf, None, None) @@ -298,15 +281,6 @@ self.assert_(a == [2, 1, 2]) self.assertRaises(IndexError, operator.setitem, a, 4, 2) - def test_setslice(self): - a = list(range(4)) - self.failUnlessRaises(TypeError, operator.setslice, a) - self.failUnlessRaises(TypeError, operator.setslice, a, None, None, None) - self.failUnless(operator.setslice(a, 1, 3, [2, 1]) is None) - self.assert_(a == [0, 2, 1, 3]) - operator.setslice(a, 0, test_support.MAX_Py_ssize_t, []) - self.assertEqual(a, []) - def test_sub(self): self.failUnlessRaises(TypeError, operator.sub) self.failUnlessRaises(TypeError, operator.sub, None, None) @@ -368,6 +342,26 @@ raise SyntaxError self.failUnlessRaises(SyntaxError, operator.attrgetter('foo'), C()) + # recursive gets + a = A() + a.name = 'arthur' + a.child = A() + a.child.name = 'thomas' + f = operator.attrgetter('child.name') + self.assertEqual(f(a), 'thomas') + self.assertRaises(AttributeError, f, a.child) + f = operator.attrgetter('name', 'child.name') + self.assertEqual(f(a), ('arthur', 'thomas')) + f = operator.attrgetter('name', 'child.name', 'child.child.name') + self.assertRaises(AttributeError, f, a) + + a.child.child = A() + a.child.child.name = 'johnson' + f = operator.attrgetter('child.child.name') + self.assertEqual(f(a), 'johnson') + f = operator.attrgetter('name', 'child.name', 'child.child.name') + self.assertEqual(f(a), ('arthur', 'thomas', 'johnson')) + def test_itemgetter(self): a = 'ABCDE' f = operator.itemgetter(2) @@ -402,6 +396,24 @@ self.assertEqual(operator.itemgetter(2,10,5)(data), ('2', '10', '5')) self.assertRaises(TypeError, operator.itemgetter(2, 'x', 5), data) + def test_methodcaller(self): + self.assertRaises(TypeError, operator.methodcaller) + class A: + def foo(self, *args, **kwds): + return args[0] + args[1] + def bar(self, f=42): + return f + a = A() + f = operator.methodcaller('foo') + self.assertRaises(IndexError, f, a) + f = operator.methodcaller('foo', 1, 2) + self.assertEquals(f(a), 3) + f = operator.methodcaller('bar') + self.assertEquals(f(a), 42) + self.assertRaises(TypeError, f, a, a) + f = operator.methodcaller('bar', f=5) + self.assertEquals(f(a), 5) + def test_inplace(self): class C(object): def __iadd__ (self, other): return "iadd" Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_optparse.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_optparse.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_optparse.py Wed Apr 30 15:57:13 2008 @@ -15,7 +15,6 @@ import unittest from io import StringIO -from pprint import pprint from test import test_support Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_os.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_os.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_os.py Wed Apr 30 15:57:13 2008 @@ -26,6 +26,114 @@ os.closerange(f, f+2) self.assertRaises(OSError, os.write, f, "a") +class TemporaryFileTests(unittest.TestCase): + def setUp(self): + self.files = [] + os.mkdir(test_support.TESTFN) + + def tearDown(self): + for name in self.files: + os.unlink(name) + os.rmdir(test_support.TESTFN) + + def check_tempfile(self, name): + # make sure it doesn't already exist: + self.failIf(os.path.exists(name), + "file already exists for temporary file") + # make sure we can create the file + open(name, "w") + self.files.append(name) + + def test_tempnam(self): + if not hasattr(os, "tempnam"): + return + warnings.filterwarnings("ignore", "tempnam", RuntimeWarning, + r"test_os$") + self.check_tempfile(os.tempnam()) + + name = os.tempnam(test_support.TESTFN) + self.check_tempfile(name) + + name = os.tempnam(test_support.TESTFN, "pfx") + self.assert_(os.path.basename(name)[:3] == "pfx") + self.check_tempfile(name) + + def test_tmpfile(self): + if not hasattr(os, "tmpfile"): + return + # As with test_tmpnam() below, the Windows implementation of tmpfile() + # attempts to create a file in the root directory of the current drive. + # On Vista and Server 2008, this test will always fail for normal users + # as writing to the root directory requires elevated privileges. With + # XP and below, the semantics of tmpfile() are the same, but the user + # running the test is more likely to have administrative privileges on + # their account already. If that's the case, then os.tmpfile() should + # work. In order to make this test as useful as possible, rather than + # trying to detect Windows versions or whether or not the user has the + # right permissions, just try and create a file in the root directory + # and see if it raises a 'Permission denied' OSError. If it does, then + # test that a subsequent call to os.tmpfile() raises the same error. If + # it doesn't, assume we're on XP or below and the user running the test + # has administrative privileges, and proceed with the test as normal. + if sys.platform == 'win32': + name = '\\python_test_os_test_tmpfile.txt' + if os.path.exists(name): + os.remove(name) + try: + fp = open(name, 'w') + except IOError as first: + # open() failed, assert tmpfile() fails in the same way. + # Although open() raises an IOError and os.tmpfile() raises an + # OSError(), 'args' will be (13, 'Permission denied') in both + # cases. + try: + fp = os.tmpfile() + except OSError as second: + self.assertEqual(first.args, second.args) + else: + self.fail("expected os.tmpfile() to raise OSError") + return + else: + # open() worked, therefore, tmpfile() should work. Close our + # dummy file and proceed with the test as normal. + fp.close() + os.remove(name) + + fp = os.tmpfile() + fp.write("foobar") + fp.seek(0,0) + s = fp.read() + fp.close() + self.assert_(s == "foobar") + + def test_tmpnam(self): + import sys + if not hasattr(os, "tmpnam"): + return + warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning, + r"test_os$") + name = os.tmpnam() + if sys.platform in ("win32",): + # The Windows tmpnam() seems useless. From the MS docs: + # + # The character string that tmpnam creates consists of + # the path prefix, defined by the entry P_tmpdir in the + # file STDIO.H, followed by a sequence consisting of the + # digit characters '0' through '9'; the numerical value + # of this string is in the range 1 - 65,535. Changing the + # definitions of L_tmpnam or P_tmpdir in STDIO.H does not + # change the operation of tmpnam. + # + # The really bizarre part is that, at least under MSVC6, + # P_tmpdir is "\\". That is, the path returned refers to + # the root of the current drive. That's a terrible place to + # put temp files, and, depending on privileges, the user + # may not even be able to open a file in the root directory. + self.failIf(os.path.exists(name), + "file already exists for temporary file") + else: + self.check_tempfile(name) + # Test attributes on return values from os.*stat* family. class StatAttributeTests(unittest.TestCase): def setUp(self): Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_ossaudiodev.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_ossaudiodev.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_ossaudiodev.py Wed Apr 30 15:57:13 2008 @@ -1,14 +1,11 @@ from test import test_support test_support.requires('audio') -from test.test_support import verbose, findfile, TestSkipped +from test.test_support import findfile, TestSkipped import errno -import fcntl import ossaudiodev -import os import sys -import select import sunaudio import time import audioop Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_parser.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_parser.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_parser.py Wed Apr 30 15:57:13 2008 @@ -1,5 +1,6 @@ import parser import unittest +import sys from test import test_support # @@ -450,11 +451,31 @@ st = parser.suite('a = "\\u1"') self.assertRaises(SyntaxError, parser.compilest, st) +class ParserStackLimitTestCase(unittest.TestCase): + """try to push the parser to/over it's limits. + see http://bugs.python.org/issue1881 for a discussion + """ + def _nested_expression(self, level): + return "["*level+"]"*level + + def test_deeply_nested_list(self): + # XXX used to be 99 levels in 2.x + e = self._nested_expression(93) + st = parser.expr(e) + st.compile() + + def test_trigger_memory_error(self): + e = self._nested_expression(100) + print("Expecting 's_push: parser stack overflow' in next line", + file=sys.stderr) + self.assertRaises(MemoryError, parser.expr, e) + def test_main(): test_support.run_unittest( RoundtripLegalSyntaxTestCase, IllegalSyntaxTestCase, CompileTestCase, + ParserStackLimitTestCase, ) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_pep247.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_pep247.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_pep247.py Wed Apr 30 15:57:13 2008 @@ -1,48 +1,68 @@ -# -# Test suite to check compliance with PEP 247, the standard API for -# hashing algorithms. -# +""" +Test suite to check compilance with PEP 247, the standard API +for hashing algorithms +""" import hmac +import unittest +from hashlib import md5, sha1, sha224, sha256, sha384, sha512 +from test import test_support + +class Pep247Test(unittest.TestCase): + + def check_module(self, module, key=None): + self.assert_(hasattr(module, 'digest_size')) + self.assert_(module.digest_size is None or module.digest_size > 0) + self.check_object(module.new, module.digest_size, key) + + def check_object(self, cls, digest_size, key): + if key is not None: + obj1 = cls(key) + obj2 = cls(key, b'string') + h1 = cls(key, b'string').digest() + obj3 = cls(key) + obj3.update(b'string') + h2 = obj3.digest() + else: + obj1 = cls() + obj2 = cls(b'string') + h1 = cls(b'string').digest() + obj3 = cls() + obj3.update(b'string') + h2 = obj3.digest() + self.assertEquals(h1, h2) + self.assert_(hasattr(obj1, 'digest_size')) + + if digest_size is not None: + self.assertEquals(obj1.digest_size, digest_size) + + self.assertEquals(obj1.digest_size, len(h1)) + obj1.update(b'string') + obj_copy = obj1.copy() + self.assertEquals(obj1.digest(), obj_copy.digest()) + self.assertEquals(obj1.hexdigest(), obj_copy.hexdigest()) + + digest, hexdigest = obj1.digest(), obj1.hexdigest() + hd2 = "" + for byte in digest: + hd2 += '%02x' % byte + self.assertEquals(hd2, hexdigest) + + def test_md5(self): + self.check_object(md5, None, None) + + def test_sha(self): + self.check_object(sha1, None, None) + self.check_object(sha224, None, None) + self.check_object(sha256, None, None) + self.check_object(sha384, None, None) + self.check_object(sha512, None, None) -def check_hash_module(module, key=None): - assert hasattr(module, 'digest_size'), "Must have digest_size" - assert (module.digest_size is None or - module.digest_size > 0), "digest_size must be None or positive" - - if key is not None: - obj1 = module.new(key) - obj2 = module.new(key, "string") - - h1 = module.new(key, "string").digest() - obj3 = module.new(key) ; obj3.update("string") ; h2 = obj3.digest() - assert h1 == h2, "Hashes must match" - - else: - obj1 = module.new() - obj2 = module.new("string") - - h1 = module.new("string").digest() - obj3 = module.new() ; obj3.update("string") ; h2 = obj3.digest() - assert h1 == h2, "Hashes must match" - - assert hasattr(obj1, 'digest_size'), "Objects must have digest_size attr" - if module.digest_size is not None: - assert obj1.digest_size == module.digest_size, "digest_size must match" - assert obj1.digest_size == len(h1), "digest_size must match actual size" - obj1.update("string") - obj_copy = obj1.copy() - assert obj1.digest() == obj_copy.digest(), "Copied objects must match" - assert obj1.hexdigest() == obj_copy.hexdigest(), \ - "Copied objects must match" - digest, hexdigest = obj1.digest(), obj1.hexdigest() - hd2 = "" - for byte in digest: - hd2 += "%02x" % ord(byte) - assert hd2 == hexdigest, "hexdigest doesn't appear correct" - - print('Module', module.__name__, 'seems to comply with PEP 247') + def test_hmac(self): + self.check_module(hmac, key=b'abc') +def test_main(): + test_support.run_unittest(Pep247Test) if __name__ == '__main__': - check_hash_module(hmac, key='abc') + test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_pep263.py ============================================================================== Binary files. No diff available. Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_pickle.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_pickle.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_pickle.py Wed Apr 30 15:57:13 2008 @@ -1,5 +1,4 @@ import pickle -import unittest import io from test import test_support @@ -13,23 +12,19 @@ module = pickle error = KeyError - def dumps(self, arg, proto=0, fast=0): - # Ignore fast + def dumps(self, arg, proto=None): return pickle.dumps(arg, proto) def loads(self, buf): - # Ignore fast return pickle.loads(buf) class PicklerTests(AbstractPickleTests): error = KeyError - def dumps(self, arg, proto=0, fast=0): + def dumps(self, arg, proto=None): f = io.BytesIO() p = pickle.Pickler(f, proto) - if fast: - p.fast = fast p.dump(arg) f.seek(0) return bytes(f.read()) @@ -41,14 +36,12 @@ class PersPicklerTests(AbstractPersistentPicklerTests): - def dumps(self, arg, proto=0, fast=0): + def dumps(self, arg, proto=None): class PersPickler(pickle.Pickler): def persistent_id(subself, obj): return self.persistent_id(obj) f = io.BytesIO() p = PersPickler(f, proto) - if fast: - p.fast = fast p.dump(arg) f.seek(0) return f.read() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_pickletools.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_pickletools.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_pickletools.py Wed Apr 30 15:57:13 2008 @@ -1,3 +1,24 @@ +import pickle import pickletools from test import test_support -test_support.run_doctest(pickletools) +from test.pickletester import AbstractPickleTests +from test.pickletester import AbstractPickleModuleTests + +class OptimizedPickleTests(AbstractPickleTests, AbstractPickleModuleTests): + + def dumps(self, arg, proto=None): + return pickletools.optimize(pickle.dumps(arg, proto)) + + def loads(self, buf): + return pickle.loads(buf) + + module = pickle + error = KeyError + +def test_main(): + test_support.run_unittest(OptimizedPickleTests) + test_support.run_doctest(pickletools) + + +if __name__ == "__main__": + test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_pkg.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_pkg.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_pkg.py Wed Apr 30 15:57:13 2008 @@ -4,7 +4,6 @@ import os import tempfile import textwrap -import traceback import unittest from test import test_support @@ -47,6 +46,7 @@ def setUp(self): self.root = None + self.pkgname = None self.syspath = list(sys.path) self.sysmodules = sys.modules.copy() @@ -57,6 +57,13 @@ del self.sysmodules cleanout(self.root) + # delete all modules concerning the tested hiearchy + if self.pkgname: + modules = [name for name in sys.modules + if self.pkgname in name.split('.')] + for name in modules: + del sys.modules[name] + def run_code(self, code): exec(textwrap.dedent(code), globals(), {"self": self}) @@ -79,6 +86,8 @@ f.write('\n') f.close() self.root = root + # package name is the name of the first item + self.pkgname = descr[0][0] def test_1(self): hier = [("t1", None), ("t1 __init__.py", "")] Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_plistlib.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_plistlib.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_plistlib.py Wed Apr 30 15:57:13 2008 @@ -3,7 +3,6 @@ import unittest import plistlib import os -import time import datetime from test import test_support Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_poll.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_poll.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_poll.py Wed Apr 30 15:57:13 2008 @@ -1,6 +1,6 @@ # Test case for the os.poll() function -import sys, os, select, random, unittest +import os, select, random, unittest from test.test_support import TestSkipped, TESTFN, run_unittest try: @@ -34,7 +34,8 @@ for i in range(NUM_PIPES): rd, wr = os.pipe() - p.register(rd, select.POLLIN) + p.register(rd) + p.modify(rd, select.POLLIN) p.register(wr, select.POLLOUT) readers.append(rd) writers.append(wr) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_poplib.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_poplib.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_poplib.py Wed Apr 30 15:57:13 2008 @@ -6,14 +6,10 @@ from unittest import TestCase from test import test_support +HOST = test_support.HOST -def server(ready, evt): - serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - serv.settimeout(3) - serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - serv.bind(("", 9091)) +def server(evt, serv): serv.listen(5) - ready.set() try: conn, addr = serv.accept() except socket.timeout: @@ -29,27 +25,29 @@ def setUp(self): self.evt = threading.Event() - self.ready = threading.Event() - threading.Thread(target=server, args=(self.ready, self.evt,)).start() - self.ready.wait() + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.sock.settimeout(3) + self.port = test_support.bind_port(self.sock) + threading.Thread(target=server, args=(self.evt,self.sock)).start() + time.sleep(.1) def tearDown(self): self.evt.wait() def testBasic(self): # connects - pop = poplib.POP3("localhost", 9091) + pop = poplib.POP3(HOST, self.port) pop.sock.close() def testTimeoutDefault(self): # default - pop = poplib.POP3("localhost", 9091) + pop = poplib.POP3(HOST, self.port) self.assertTrue(pop.sock.gettimeout() is None) pop.sock.close() def testTimeoutValue(self): # a value - pop = poplib.POP3("localhost", 9091, timeout=30) + pop = poplib.POP3(HOST, self.port, timeout=30) self.assertEqual(pop.sock.gettimeout(), 30) pop.sock.close() @@ -58,7 +56,7 @@ previous = socket.getdefaulttimeout() socket.setdefaulttimeout(30) try: - pop = poplib.POP3("localhost", 9091, timeout=None) + pop = poplib.POP3(HOST, self.port, timeout=None) finally: socket.setdefaulttimeout(previous) self.assertEqual(pop.sock.gettimeout(), 30) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_posix.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_posix.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_posix.py Wed Apr 30 15:57:13 2008 @@ -9,7 +9,7 @@ import time import os -import sys +import pwd import unittest import warnings warnings.filterwarnings('ignore', '.* potential security risk .*', @@ -142,6 +142,33 @@ if hasattr(posix, 'stat'): self.assert_(posix.stat(test_support.TESTFN)) + if hasattr(posix, 'chown'): + def test_chown(self): + # raise an OSError if the file does not exist + os.unlink(test_support.TESTFN) + self.assertRaises(OSError, posix.chown, test_support.TESTFN, -1, -1) + + # re-create the file + open(test_support.TESTFN, 'w').close() + if os.getuid() == 0: + try: + # Many linux distros have a nfsnobody user as MAX_UID-2 + # that makes a good test case for signedness issues. + # http://bugs.python.org/issue1747858 + # This part of the test only runs when run as root. + # Only scary people run their tests as root. + ent = pwd.getpwnam('nfsnobody') + posix.chown(test_support.TESTFN, ent.pw_uid, ent.pw_gid) + except KeyError: + pass + else: + # non-root cannot chown to root, raises OSError + self.assertRaises(OSError, posix.chown, + test_support.TESTFN, 0, 0) + + # test a successful chown call + posix.chown(test_support.TESTFN, os.getuid(), os.getgid()) + def test_chdir(self): if hasattr(posix, 'chdir'): posix.chdir(os.curdir) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_pprint.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_pprint.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_pprint.py Wed Apr 30 15:57:13 2008 @@ -197,186 +197,186 @@ self.assertEqual(pprint.pformat(frozenset(range(3))), 'frozenset({0, 1, 2})') cube_repr_tgt = """\ {frozenset(): frozenset({frozenset({2}), frozenset({0}), frozenset({1})}), - frozenset({0}): frozenset([frozenset(), + frozenset({0}): frozenset({frozenset(), frozenset({0, 2}), - frozenset({0, 1})]), - frozenset({1}): frozenset([frozenset(), + frozenset({0, 1})}), + frozenset({1}): frozenset({frozenset(), frozenset({1, 2}), - frozenset({0, 1})]), - frozenset({2}): frozenset([frozenset(), + frozenset({0, 1})}), + frozenset({2}): frozenset({frozenset(), frozenset({1, 2}), - frozenset({0, 2})]), - frozenset({1, 2}): frozenset([frozenset({2}), + frozenset({0, 2})}), + frozenset({1, 2}): frozenset({frozenset({2}), frozenset({1}), - frozenset({0, 1, 2})]), - frozenset({0, 2}): frozenset([frozenset({2}), + frozenset({0, 1, 2})}), + frozenset({0, 2}): frozenset({frozenset({2}), frozenset({0}), - frozenset({0, 1, 2})]), - frozenset({0, 1}): frozenset([frozenset({0}), + frozenset({0, 1, 2})}), + frozenset({0, 1}): frozenset({frozenset({0}), frozenset({1}), - frozenset({0, 1, 2})]), - frozenset({0, 1, 2}): frozenset([frozenset({1, 2}), + frozenset({0, 1, 2})}), + frozenset({0, 1, 2}): frozenset({frozenset({1, 2}), frozenset({0, 2}), - frozenset({0, 1})])}""" + frozenset({0, 1})})}""" cube = test.test_set.cube(3) self.assertEqual(pprint.pformat(cube), cube_repr_tgt) cubo_repr_tgt = """\ -{frozenset({frozenset({0, 2}), frozenset({0})}): frozenset([frozenset([frozenset([0, - 2]), - frozenset([0, - 1, - 2])]), - frozenset([frozenset([0]), - frozenset([0, - 1])]), - frozenset([frozenset(), - frozenset([0])]), - frozenset([frozenset([2]), - frozenset([0, - 2])])]), - frozenset({frozenset({0, 1}), frozenset({1})}): frozenset([frozenset([frozenset([0, - 1]), - frozenset([0, - 1, - 2])]), - frozenset([frozenset([0]), - frozenset([0, - 1])]), - frozenset([frozenset([1]), - frozenset([1, - 2])]), - frozenset([frozenset(), - frozenset([1])])]), - frozenset({frozenset({1, 2}), frozenset({1})}): frozenset([frozenset([frozenset([1, - 2]), - frozenset([0, - 1, - 2])]), - frozenset([frozenset([2]), - frozenset([1, - 2])]), - frozenset([frozenset(), - frozenset([1])]), - frozenset([frozenset([1]), - frozenset([0, - 1])])]), - frozenset({frozenset({1, 2}), frozenset({2})}): frozenset([frozenset([frozenset([1, - 2]), - frozenset([0, - 1, - 2])]), - frozenset([frozenset([1]), - frozenset([1, - 2])]), - frozenset([frozenset([2]), - frozenset([0, - 2])]), - frozenset([frozenset(), - frozenset([2])])]), - frozenset({frozenset(), frozenset({0})}): frozenset([frozenset([frozenset([0]), - frozenset([0, - 1])]), - frozenset([frozenset([0]), - frozenset([0, - 2])]), - frozenset([frozenset(), - frozenset([1])]), - frozenset([frozenset(), - frozenset([2])])]), - frozenset({frozenset(), frozenset({1})}): frozenset([frozenset([frozenset(), - frozenset([0])]), - frozenset([frozenset([1]), - frozenset([1, - 2])]), - frozenset([frozenset(), - frozenset([2])]), - frozenset([frozenset([1]), - frozenset([0, - 1])])]), - frozenset({frozenset({2}), frozenset()}): frozenset([frozenset([frozenset([2]), - frozenset([1, - 2])]), - frozenset([frozenset(), - frozenset([0])]), - frozenset([frozenset(), - frozenset([1])]), - frozenset([frozenset([2]), - frozenset([0, - 2])])]), - frozenset({frozenset({0, 1, 2}), frozenset({0, 1})}): frozenset([frozenset([frozenset([1, - 2]), - frozenset([0, - 1, - 2])]), - frozenset([frozenset([0, - 2]), - frozenset([0, - 1, - 2])]), - frozenset([frozenset([0]), - frozenset([0, - 1])]), - frozenset([frozenset([1]), - frozenset([0, - 1])])]), - frozenset({frozenset({0}), frozenset({0, 1})}): frozenset([frozenset([frozenset(), - frozenset([0])]), - frozenset([frozenset([0, - 1]), - frozenset([0, - 1, - 2])]), - frozenset([frozenset([0]), - frozenset([0, - 2])]), - frozenset([frozenset([1]), - frozenset([0, - 1])])]), - frozenset({frozenset({2}), frozenset({0, 2})}): frozenset([frozenset([frozenset([0, - 2]), - frozenset([0, - 1, - 2])]), - frozenset([frozenset([2]), - frozenset([1, - 2])]), - frozenset([frozenset([0]), - frozenset([0, - 2])]), - frozenset([frozenset(), - frozenset([2])])]), - frozenset({frozenset({0, 1, 2}), frozenset({0, 2})}): frozenset([frozenset([frozenset([1, - 2]), - frozenset([0, - 1, - 2])]), - frozenset([frozenset([0, - 1]), - frozenset([0, - 1, - 2])]), - frozenset([frozenset([0]), - frozenset([0, - 2])]), - frozenset([frozenset([2]), - frozenset([0, - 2])])]), - frozenset({frozenset({1, 2}), frozenset({0, 1, 2})}): frozenset([frozenset([frozenset([0, - 2]), - frozenset([0, - 1, - 2])]), - frozenset([frozenset([0, - 1]), - frozenset([0, - 1, - 2])]), - frozenset([frozenset([2]), - frozenset([1, - 2])]), - frozenset([frozenset([1]), - frozenset([1, - 2])])])}""" +{frozenset({frozenset({0, 2}), frozenset({0})}): frozenset({frozenset({frozenset({0, + 2}), + frozenset({0, + 1, + 2})}), + frozenset({frozenset({0}), + frozenset({0, + 1})}), + frozenset({frozenset(), + frozenset({0})}), + frozenset({frozenset({2}), + frozenset({0, + 2})})}), + frozenset({frozenset({0, 1}), frozenset({1})}): frozenset({frozenset({frozenset({0, + 1}), + frozenset({0, + 1, + 2})}), + frozenset({frozenset({0}), + frozenset({0, + 1})}), + frozenset({frozenset({1}), + frozenset({1, + 2})}), + frozenset({frozenset(), + frozenset({1})})}), + frozenset({frozenset({1, 2}), frozenset({1})}): frozenset({frozenset({frozenset({1, + 2}), + frozenset({0, + 1, + 2})}), + frozenset({frozenset({2}), + frozenset({1, + 2})}), + frozenset({frozenset(), + frozenset({1})}), + frozenset({frozenset({1}), + frozenset({0, + 1})})}), + frozenset({frozenset({1, 2}), frozenset({2})}): frozenset({frozenset({frozenset({1, + 2}), + frozenset({0, + 1, + 2})}), + frozenset({frozenset({1}), + frozenset({1, + 2})}), + frozenset({frozenset({2}), + frozenset({0, + 2})}), + frozenset({frozenset(), + frozenset({2})})}), + frozenset({frozenset(), frozenset({0})}): frozenset({frozenset({frozenset({0}), + frozenset({0, + 1})}), + frozenset({frozenset({0}), + frozenset({0, + 2})}), + frozenset({frozenset(), + frozenset({1})}), + frozenset({frozenset(), + frozenset({2})})}), + frozenset({frozenset(), frozenset({1})}): frozenset({frozenset({frozenset(), + frozenset({0})}), + frozenset({frozenset({1}), + frozenset({1, + 2})}), + frozenset({frozenset(), + frozenset({2})}), + frozenset({frozenset({1}), + frozenset({0, + 1})})}), + frozenset({frozenset({2}), frozenset()}): frozenset({frozenset({frozenset({2}), + frozenset({1, + 2})}), + frozenset({frozenset(), + frozenset({0})}), + frozenset({frozenset(), + frozenset({1})}), + frozenset({frozenset({2}), + frozenset({0, + 2})})}), + frozenset({frozenset({0, 1, 2}), frozenset({0, 1})}): frozenset({frozenset({frozenset({1, + 2}), + frozenset({0, + 1, + 2})}), + frozenset({frozenset({0, + 2}), + frozenset({0, + 1, + 2})}), + frozenset({frozenset({0}), + frozenset({0, + 1})}), + frozenset({frozenset({1}), + frozenset({0, + 1})})}), + frozenset({frozenset({0}), frozenset({0, 1})}): frozenset({frozenset({frozenset(), + frozenset({0})}), + frozenset({frozenset({0, + 1}), + frozenset({0, + 1, + 2})}), + frozenset({frozenset({0}), + frozenset({0, + 2})}), + frozenset({frozenset({1}), + frozenset({0, + 1})})}), + frozenset({frozenset({2}), frozenset({0, 2})}): frozenset({frozenset({frozenset({0, + 2}), + frozenset({0, + 1, + 2})}), + frozenset({frozenset({2}), + frozenset({1, + 2})}), + frozenset({frozenset({0}), + frozenset({0, + 2})}), + frozenset({frozenset(), + frozenset({2})})}), + frozenset({frozenset({0, 1, 2}), frozenset({0, 2})}): frozenset({frozenset({frozenset({1, + 2}), + frozenset({0, + 1, + 2})}), + frozenset({frozenset({0, + 1}), + frozenset({0, + 1, + 2})}), + frozenset({frozenset({0}), + frozenset({0, + 2})}), + frozenset({frozenset({2}), + frozenset({0, + 2})})}), + frozenset({frozenset({1, 2}), frozenset({0, 1, 2})}): frozenset({frozenset({frozenset({0, + 2}), + frozenset({0, + 1, + 2})}), + frozenset({frozenset({0, + 1}), + frozenset({0, + 1, + 2})}), + frozenset({frozenset({2}), + frozenset({1, + 2})}), + frozenset({frozenset({1}), + frozenset({1, + 2})})})}""" cubo = test.test_set.linegraph(cube) self.assertEqual(pprint.pformat(cubo), cubo_repr_tgt) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_profile.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_profile.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_profile.py Wed Apr 30 15:57:13 2008 @@ -1,123 +1,134 @@ """Test suite for the profile module.""" -import profile, pstats, sys +import os +import sys +import pstats +import unittest +from difflib import unified_diff +from io import StringIO +from test.test_support import run_unittest + +import profile +from test.profilee import testfunc, timer + + +class ProfileTest(unittest.TestCase): + + profilerclass = profile.Profile + methodnames = ['print_stats', 'print_callers', 'print_callees'] + expected_output = {} + + @classmethod + def do_profiling(cls): + results = [] + prof = cls.profilerclass(timer, 0.001) + start_timer = timer() + prof.runctx("testfunc()", globals(), locals()) + results.append(timer() - start_timer) + for methodname in cls.methodnames: + s = StringIO() + stats = pstats.Stats(prof, stream=s) + stats.strip_dirs().sort_stats("stdname") + getattr(stats, methodname)() + output = s.getvalue().splitlines() + mod_name = testfunc.__module__.rsplit('.', 1)[1] + # Only compare against stats originating from the test file. + # Prevents outside code (e.g., the io module) from causing + # unexpected output. + output = [line.rstrip() for line in output if mod_name in line] + results.append('\n'.join(output)) + return results + + def test_cprofile(self): + results = self.do_profiling() + self.assertEqual(results[0], 1000) + for i, method in enumerate(self.methodnames): + if results[i+1] != self.expected_output[method]: + print("Stats.%s output for %s doesn't fit expectation!" % + (method, self.profilerclass.__name__)) + print('\n'.join(unified_diff( + results[i+1].split('\n'), + self.expected_output[method].split('\n')))) + + +def regenerate_expected_output(filename, cls): + filename = filename.rstrip('co') + print('Regenerating %s...' % filename) + results = cls.do_profiling() + + newfile = [] + with open(filename, 'r') as f: + for line in f: + newfile.append(line) + if line.startswith('#--cut'): + break + + with open(filename, 'w') as f: + f.writelines(newfile) + for i, method in enumerate(cls.methodnames): + f.write('%s.expected_output[%r] = """\\\n%s"""\n' % ( + cls.__name__, method, results[i+1])) + f.write('\nif __name__ == "__main__":\n main()\n') -# In order to have reproducible time, we simulate a timer in the global -# variable 'ticks', which represents simulated time in milliseconds. -# (We can't use a helper function increment the timer since it would be -# included in the profile and would appear to consume all the time.) -ticks = 0 - -# IMPORTANT: this is an output test. *ALL* NUMBERS in the expected -# output are relevant. If you change the formatting of pstats, -# please don't just regenerate output/test_profile without checking -# very carefully that not a single number has changed. def test_main(): - global ticks - ticks = 42000 - prof = profile.Profile(timer) - prof.runctx("testfunc()", globals(), locals()) - assert ticks == 43000, ticks - st = pstats.Stats(prof) - st.strip_dirs().sort_stats('stdname').print_stats() - st.print_callees() - st.print_callers() - -def timer(): - return ticks*0.001 - -def testfunc(): - # 1 call - # 1000 ticks total: 270 ticks local, 730 ticks in subfunctions - global ticks - ticks += 99 - helper() # 300 - helper() # 300 - ticks += 171 - factorial(14) # 130 - -def factorial(n): - # 23 calls total - # 170 ticks total, 150 ticks local - # 3 primitive calls, 130, 20 and 20 ticks total - # including 116, 17, 17 ticks local - global ticks - if n > 0: - ticks += n - return mul(n, factorial(n-1)) + run_unittest(ProfileTest) + +def main(): + if '-r' not in sys.argv: + test_main() else: - ticks += 11 - return 1 + regenerate_expected_output(__file__, ProfileTest) + -def mul(a, b): - # 20 calls - # 1 tick, local - global ticks - ticks += 1 - return a * b - -def helper(): - # 2 calls - # 300 ticks total: 20 ticks local, 260 ticks in subfunctions - global ticks - ticks += 1 - helper1() # 30 - ticks += 2 - helper1() # 30 - ticks += 6 - helper2() # 50 - ticks += 3 - helper2() # 50 - ticks += 2 - helper2() # 50 - ticks += 5 - helper2_indirect() # 70 - ticks += 1 - -def helper1(): - # 4 calls - # 30 ticks total: 29 ticks local, 1 tick in subfunctions - global ticks - ticks += 10 - hasattr(C(), "foo") # 1 - ticks += 19 - lst = [] - lst.append(42) # 0 - sys.exc_info() # 0 - -def helper2_indirect(): - helper2() # 50 - factorial(3) # 20 - -def helper2(): - # 8 calls - # 50 ticks local: 39 ticks local, 11 ticks in subfunctions - global ticks - ticks += 11 - hasattr(C(), "bar") # 1 - ticks += 13 - subhelper() # 10 - ticks += 15 - -def subhelper(): - # 8 calls - # 10 ticks total: 8 ticks local, 2 ticks in subfunctions - global ticks - ticks += 2 - for i in range(2): # 0 - try: - C().foo # 1 x 2 - except AttributeError: - ticks += 3 # 3 x 2 - -class C: - def __getattr__(self, name): - # 28 calls - # 1 tick, local - global ticks - ticks += 1 - raise AttributeError +# Don't remove this comment. Everything below it is auto-generated. +#--cut-------------------------------------------------------------------------- +ProfileTest.expected_output['print_stats'] = """\ + 28 27.972 0.999 27.972 0.999 profilee.py:110(__getattr__) + 1 269.996 269.996 999.769 999.769 profilee.py:25(testfunc) + 23/3 149.937 6.519 169.917 56.639 profilee.py:35(factorial) + 20 19.980 0.999 19.980 0.999 profilee.py:48(mul) + 2 39.986 19.993 599.830 299.915 profilee.py:55(helper) + 4 115.984 28.996 119.964 29.991 profilee.py:73(helper1) + 2 -0.006 -0.003 139.946 69.973 profilee.py:84(helper2_indirect) + 8 311.976 38.997 399.912 49.989 profilee.py:88(helper2) + 8 63.976 7.997 79.960 9.995 profilee.py:98(subhelper)""" +ProfileTest.expected_output['print_callers'] = """\ +:0(append) <- profilee.py:73(helper1)(4) 119.964 +:0(exc_info) <- profilee.py:73(helper1)(4) 119.964 +:0(hasattr) <- profilee.py:73(helper1)(4) 119.964 + profilee.py:88(helper2)(8) 399.912 +profilee.py:110(__getattr__) <- :0(hasattr)(12) 11.964 + profilee.py:98(subhelper)(16) 79.960 +profilee.py:25(testfunc) <- :1()(1) 999.767 +profilee.py:35(factorial) <- profilee.py:25(testfunc)(1) 999.769 + profilee.py:35(factorial)(20) 169.917 + profilee.py:84(helper2_indirect)(2) 139.946 +profilee.py:48(mul) <- profilee.py:35(factorial)(20) 169.917 +profilee.py:55(helper) <- profilee.py:25(testfunc)(2) 999.769 +profilee.py:73(helper1) <- profilee.py:55(helper)(4) 599.830 +profilee.py:84(helper2_indirect) <- profilee.py:55(helper)(2) 599.830 +profilee.py:88(helper2) <- profilee.py:55(helper)(6) 599.830 + profilee.py:84(helper2_indirect)(2) 139.946 +profilee.py:98(subhelper) <- profilee.py:88(helper2)(8) 399.912""" +ProfileTest.expected_output['print_callees'] = """\ +:0(hasattr) -> profilee.py:110(__getattr__)(12) 27.972 +:1() -> profilee.py:25(testfunc)(1) 999.769 +profilee.py:110(__getattr__) -> +profilee.py:25(testfunc) -> profilee.py:35(factorial)(1) 169.917 + profilee.py:55(helper)(2) 599.830 +profilee.py:35(factorial) -> profilee.py:35(factorial)(20) 169.917 + profilee.py:48(mul)(20) 19.980 +profilee.py:48(mul) -> +profilee.py:55(helper) -> profilee.py:73(helper1)(4) 119.964 + profilee.py:84(helper2_indirect)(2) 139.946 + profilee.py:88(helper2)(6) 399.912 +profilee.py:73(helper1) -> :0(append)(4) -0.004 +profilee.py:84(helper2_indirect) -> profilee.py:35(factorial)(2) 169.917 + profilee.py:88(helper2)(2) 399.912 +profilee.py:88(helper2) -> :0(hasattr)(8) 11.964 + profilee.py:98(subhelper)(8) 79.960 +profilee.py:98(subhelper) -> profilee.py:110(__getattr__)(16) 27.972""" if __name__ == "__main__": - test_main() + main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_pty.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_pty.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_pty.py Wed Apr 30 15:57:13 2008 @@ -157,7 +157,8 @@ break if not data: break - sys.stdout.write(data.replace('\r\n', '\n').decode('ascii')) + sys.stdout.write(str(data.replace(b'\r\n', b'\n'), + encoding='ascii')) ##line = os.read(master_fd, 80) ##lines = line.replace('\r\n', '\n').split('\n') Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_pyclbr.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_pyclbr.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_pyclbr.py Wed Apr 30 15:57:13 2008 @@ -3,7 +3,7 @@ Nick Mathewson ''' from test.test_support import run_unittest -import unittest, sys +import sys from types import FunctionType, MethodType, BuiltinFunctionType import pyclbr from unittest import TestCase @@ -55,7 +55,7 @@ ignore = set(ignore) | set(['object']) - if module == None: + if module is None: # Import it. # ('' is to work around an API silliness in __import__) module = __import__(moduleName, globals(), {}, ['']) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_queue.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_queue.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_queue.py Wed Apr 30 15:57:13 2008 @@ -4,8 +4,8 @@ import sys import threading import time - -from test.test_support import verify, TestFailed, verbose +import unittest +from test import test_support QUEUE_SIZE = 5 @@ -33,50 +33,178 @@ self.startedEvent.set() self.fn(*self.args) + # Execute a function that blocks, and in a separate thread, a function that -# triggers the release. Returns the result of the blocking function. -# Caution: block_func must guarantee to block until trigger_func is -# called, and trigger_func must guarantee to change queue state so that -# block_func can make enough progress to return. In particular, a -# block_func that just raises an exception regardless of whether trigger_func -# is called will lead to timing-dependent sporadic failures, and one of -# those went rarely seen but undiagnosed for years. Now block_func -# must be unexceptional. If block_func is supposed to raise an exception, -# call _doExceptionalBlockingTest() instead. -def _doBlockingTest(block_func, block_args, trigger_func, trigger_args): - t = _TriggerThread(trigger_func, trigger_args) - t.start() - result = block_func(*block_args) - # If block_func returned before our thread made the call, we failed! - if not t.startedEvent.isSet(): - raise TestFailed("blocking function '%r' appeared not to block" % - block_func) - t.join(10) # make sure the thread terminates - if t.isAlive(): - raise TestFailed("trigger function '%r' appeared to not return" % - trigger_func) - return result - -# Call this instead if block_func is supposed to raise an exception. -def _doExceptionalBlockingTest(block_func, block_args, trigger_func, - trigger_args, expected_exception_class): - t = _TriggerThread(trigger_func, trigger_args) - t.start() - try: - try: - block_func(*block_args) - except expected_exception_class: - raise +# triggers the release. Returns the result of the blocking function. Caution: +# block_func must guarantee to block until trigger_func is called, and +# trigger_func must guarantee to change queue state so that block_func can make +# enough progress to return. In particular, a block_func that just raises an +# exception regardless of whether trigger_func is called will lead to +# timing-dependent sporadic failures, and one of those went rarely seen but +# undiagnosed for years. Now block_func must be unexceptional. If block_func +# is supposed to raise an exception, call do_exceptional_blocking_test() +# instead. + +class BlockingTestMixin: + + def do_blocking_test(self, block_func, block_args, trigger_func, trigger_args): + self.t = _TriggerThread(trigger_func, trigger_args) + self.t.start() + self.result = block_func(*block_args) + # If block_func returned before our thread made the call, we failed! + if not self.t.startedEvent.isSet(): + self.fail("blocking function '%r' appeared not to block" % + block_func) + self.t.join(10) # make sure the thread terminates + if self.t.isAlive(): + self.fail("trigger function '%r' appeared to not return" % + trigger_func) + return self.result + + # Call this instead if block_func is supposed to raise an exception. + def do_exceptional_blocking_test(self,block_func, block_args, trigger_func, + trigger_args, expected_exception_class): + self.t = _TriggerThread(trigger_func, trigger_args) + self.t.start() + try: + try: + block_func(*block_args) + except expected_exception_class: + raise + else: + self.fail("expected exception of kind %r" % + expected_exception_class) + finally: + self.t.join(10) # make sure the thread terminates + if self.t.isAlive(): + self.fail("trigger function '%r' appeared to not return" % + trigger_func) + if not self.t.startedEvent.isSet(): + self.fail("trigger thread ended but event never set") + + +class BaseQueueTest(unittest.TestCase, BlockingTestMixin): + def setUp(self): + self.cum = 0 + self.cumlock = threading.Lock() + + def simple_queue_test(self, q): + if q.qsize(): + raise RuntimeError("Call this function with an empty queue") + # I guess we better check things actually queue correctly a little :) + q.put(111) + q.put(333) + q.put(222) + target_order = dict(Queue = [111, 333, 222], + LifoQueue = [222, 333, 111], + PriorityQueue = [111, 222, 333]) + actual_order = [q.get(), q.get(), q.get()] + self.assertEquals(actual_order, target_order[q.__class__.__name__], + "Didn't seem to queue the correct data!") + for i in range(QUEUE_SIZE-1): + q.put(i) + self.assert_(q.qsize(), "Queue should not be empty") + self.assert_(not qfull(q), "Queue should not be full") + last = 2 * QUEUE_SIZE + full = 3 * 2 * QUEUE_SIZE + q.put(last) + self.assert_(qfull(q), "Queue should be full") + try: + q.put(full, block=0) + self.fail("Didn't appear to block with a full queue") + except Queue.Full: + pass + try: + q.put(full, timeout=0.01) + self.fail("Didn't appear to time-out with a full queue") + except Queue.Full: + pass + # Test a blocking put + self.do_blocking_test(q.put, (full,), q.get, ()) + self.do_blocking_test(q.put, (full, True, 10), q.get, ()) + # Empty it + for i in range(QUEUE_SIZE): + q.get() + self.assert_(not q.qsize(), "Queue should be empty") + try: + q.get(block=0) + self.fail("Didn't appear to block with an empty queue") + except Queue.Empty: + pass + try: + q.get(timeout=0.01) + self.fail("Didn't appear to time-out with an empty queue") + except Queue.Empty: + pass + # Test a blocking get + self.do_blocking_test(q.get, (), q.put, ('empty',)) + self.do_blocking_test(q.get, (True, 10), q.put, ('empty',)) + + + def worker(self, q): + while True: + x = q.get() + if x < 0: + q.task_done() + return + with self.cumlock: + self.cum += x + q.task_done() + + def queue_join_test(self, q): + self.cum = 0 + for i in (0,1): + threading.Thread(target=self.worker, args=(q,)).start() + for i in range(100): + q.put(i) + q.join() + self.assertEquals(self.cum, sum(range(100)), + "q.join() did not block until all tasks were done") + for i in (0,1): + q.put(-1) # instruct the threads to close + q.join() # verify that you can join twice + + def test_queue_task_done(self): + # Test to make sure a queue task completed successfully. + q = self.type2test() + try: + q.task_done() + except ValueError: + pass else: - raise TestFailed("expected exception of kind %r" % - expected_exception_class) - finally: - t.join(10) # make sure the thread terminates - if t.isAlive(): - raise TestFailed("trigger function '%r' appeared to not return" % - trigger_func) - if not t.startedEvent.isSet(): - raise TestFailed("trigger thread ended but event never set") + self.fail("Did not detect task count going negative") + + def test_queue_join(self): + # Test that a queue join()s successfully, and before anything else + # (done twice for insurance). + q = self.type2test() + self.queue_join_test(q) + self.queue_join_test(q) + try: + q.task_done() + except ValueError: + pass + else: + self.fail("Did not detect task count going negative") + + def test_simple_queue(self): + # Do it a couple of times on the same queue. + # Done twice to make sure works with same instance reused. + q = self.type2test(QUEUE_SIZE) + self.simple_queue_test(q) + self.simple_queue_test(q) + + +class QueueTest(BaseQueueTest): + type2test = Queue.Queue + +class LifoQueueTest(BaseQueueTest): + type2test = Queue.LifoQueue + +class PriorityQueueTest(BaseQueueTest): + type2test = Queue.PriorityQueue + + # A Queue subclass that can provoke failure at a moment's notice :) class FailingQueueException(Exception): @@ -98,195 +226,101 @@ raise FailingQueueException("You Lose") return Queue.Queue._get(self) -def FailingQueueTest(q): - if q.qsize(): - raise RuntimeError("Call this function with an empty queue") - for i in range(QUEUE_SIZE-1): - q.put(i) - # Test a failing non-blocking put. - q.fail_next_put = True - try: - q.put("oops", block=0) - raise TestFailed("The queue didn't fail when it should have") - except FailingQueueException: - pass - q.fail_next_put = True - try: - q.put("oops", timeout=0.1) - raise TestFailed("The queue didn't fail when it should have") - except FailingQueueException: - pass - q.put("last") - verify(qfull(q), "Queue should be full") - # Test a failing blocking put - q.fail_next_put = True - try: - _doBlockingTest(q.put, ("full",), q.get, ()) - raise TestFailed("The queue didn't fail when it should have") - except FailingQueueException: - pass - # Check the Queue isn't damaged. - # put failed, but get succeeded - re-add - q.put("last") - # Test a failing timeout put - q.fail_next_put = True - try: - _doExceptionalBlockingTest(q.put, ("full", True, 10), q.get, (), - FailingQueueException) - raise TestFailed("The queue didn't fail when it should have") - except FailingQueueException: - pass - # Check the Queue isn't damaged. - # put failed, but get succeeded - re-add - q.put("last") - verify(qfull(q), "Queue should be full") - q.get() - verify(not qfull(q), "Queue should not be full") - q.put("last") - verify(qfull(q), "Queue should be full") - # Test a blocking put - _doBlockingTest( q.put, ("full",), q.get, ()) - # Empty it - for i in range(QUEUE_SIZE): - q.get() - verify(not q.qsize(), "Queue should be empty") - q.put("first") - q.fail_next_get = True - try: +class FailingQueueTest(unittest.TestCase, BlockingTestMixin): + + def failing_queue_test(self, q): + if q.qsize(): + raise RuntimeError("Call this function with an empty queue") + for i in range(QUEUE_SIZE-1): + q.put(i) + # Test a failing non-blocking put. + q.fail_next_put = True + try: + q.put("oops", block=0) + self.fail("The queue didn't fail when it should have") + except FailingQueueException: + pass + q.fail_next_put = True + try: + q.put("oops", timeout=0.1) + self.fail("The queue didn't fail when it should have") + except FailingQueueException: + pass + q.put("last") + self.assert_(qfull(q), "Queue should be full") + # Test a failing blocking put + q.fail_next_put = True + try: + self.do_blocking_test(q.put, ("full",), q.get, ()) + self.fail("The queue didn't fail when it should have") + except FailingQueueException: + pass + # Check the Queue isn't damaged. + # put failed, but get succeeded - re-add + q.put("last") + # Test a failing timeout put + q.fail_next_put = True + try: + self.do_exceptional_blocking_test(q.put, ("full", True, 10), q.get, (), + FailingQueueException) + self.fail("The queue didn't fail when it should have") + except FailingQueueException: + pass + # Check the Queue isn't damaged. + # put failed, but get succeeded - re-add + q.put("last") + self.assert_(qfull(q), "Queue should be full") q.get() - raise TestFailed("The queue didn't fail when it should have") - except FailingQueueException: - pass - verify(q.qsize(), "Queue should not be empty") - q.fail_next_get = True - try: - q.get(timeout=0.1) - raise TestFailed("The queue didn't fail when it should have") - except FailingQueueException: - pass - verify(q.qsize(), "Queue should not be empty") - q.get() - verify(not q.qsize(), "Queue should be empty") - q.fail_next_get = True - try: - _doExceptionalBlockingTest(q.get, (), q.put, ('empty',), - FailingQueueException) - raise TestFailed("The queue didn't fail when it should have") - except FailingQueueException: - pass - # put succeeded, but get failed. - verify(q.qsize(), "Queue should not be empty") - q.get() - verify(not q.qsize(), "Queue should be empty") - -def SimpleQueueTest(q): - if q.qsize(): - raise RuntimeError("Call this function with an empty queue") - # I guess we better check things actually queue correctly a little :) - q.put(111) - q.put(333) - q.put(222) - target_order = dict(Queue = [111, 333, 222], - LifoQueue = [222, 333, 111], - PriorityQueue = [111, 222, 333]) - actual_order = [q.get(), q.get(), q.get()] - verify(actual_order == target_order[q.__class__.__name__], - "Didn't seem to queue the correct data!") - for i in range(QUEUE_SIZE-1): - q.put(i) - verify(q.qsize(), "Queue should not be empty") - verify(not qfull(q), "Queue should not be full") - last = 2*QUEUE_SIZE - full = 3*2*QUEUE_SIZE - q.put(last) - verify(qfull(q), "Queue should be full") - try: - q.put(full, block=0) - raise TestFailed("Didn't appear to block with a full queue") - except Queue.Full: - pass - try: - q.put(full, timeout=0.01) - raise TestFailed("Didn't appear to time-out with a full queue") - except Queue.Full: - pass - # Test a blocking put - _doBlockingTest(q.put, (full,), q.get, ()) - _doBlockingTest(q.put, (full, True, 10), q.get, ()) - # Empty it - for i in range(QUEUE_SIZE): + self.assert_(not qfull(q), "Queue should not be full") + q.put("last") + self.assert_(qfull(q), "Queue should be full") + # Test a blocking put + self.do_blocking_test(q.put, ("full",), q.get, ()) + # Empty it + for i in range(QUEUE_SIZE): + q.get() + self.assert_(not q.qsize(), "Queue should be empty") + q.put("first") + q.fail_next_get = True + try: + q.get() + self.fail("The queue didn't fail when it should have") + except FailingQueueException: + pass + self.assert_(q.qsize(), "Queue should not be empty") + q.fail_next_get = True + try: + q.get(timeout=0.1) + self.fail("The queue didn't fail when it should have") + except FailingQueueException: + pass + self.assert_(q.qsize(), "Queue should not be empty") q.get() - verify(not q.qsize(), "Queue should be empty") - try: - q.get(block=0) - raise TestFailed("Didn't appear to block with an empty queue") - except Queue.Empty: - pass - try: - q.get(timeout=0.01) - raise TestFailed("Didn't appear to time-out with an empty queue") - except Queue.Empty: - pass - # Test a blocking get - _doBlockingTest(q.get, (), q.put, ('empty',)) - _doBlockingTest(q.get, (True, 10), q.put, ('empty',)) - -cum = 0 -cumlock = threading.Lock() - -def worker(q): - global cum - while True: - x = q.get() - if x is None: - q.task_done() - return - cumlock.acquire() + self.assert_(not q.qsize(), "Queue should be empty") + q.fail_next_get = True try: - cum += x - finally: - cumlock.release() - q.task_done() + self.do_exceptional_blocking_test(q.get, (), q.put, ('empty',), + FailingQueueException) + self.fail("The queue didn't fail when it should have") + except FailingQueueException: + pass + # put succeeded, but get failed. + self.assert_(q.qsize(), "Queue should not be empty") + q.get() + self.assert_(not q.qsize(), "Queue should be empty") + + def test_failing_queue(self): + # Test to make sure a queue is functioning correctly. + # Done twice to the same instance. + q = FailingQueue(QUEUE_SIZE) + self.failing_queue_test(q) + self.failing_queue_test(q) + + +def test_main(): + test_support.run_unittest(QueueTest, LifoQueueTest, PriorityQueueTest, + FailingQueueTest) -def QueueJoinTest(q): - global cum - cum = 0 - for i in (0,1): - threading.Thread(target=worker, args=(q,)).start() - for i in range(100): - q.put(i) - q.join() - verify(cum==sum(range(100)), "q.join() did not block until all tasks were done") - q.put(None) # instruct the threads to close - q.join() # verify that you can join twice - -def QueueTaskDoneTest(q): - try: - q.task_done() - except ValueError: - pass - else: - raise TestFailed("Did not detect task count going negative") - -def test(): - for Q in Queue.Queue, Queue.LifoQueue, Queue.PriorityQueue: - q = Q() - QueueTaskDoneTest(q) - QueueJoinTest(q) - QueueJoinTest(q) - QueueTaskDoneTest(q) - - q = Q(QUEUE_SIZE) - # Do it a couple of times on the same queue - SimpleQueueTest(q) - SimpleQueueTest(q) - if verbose: - print("Simple Queue tests seemed to work for", Q.__name__) - - q = FailingQueue(QUEUE_SIZE) - FailingQueueTest(q) - FailingQueueTest(q) - if verbose: - print("Failing Queue tests seemed to work") -test() +if __name__ == "__main__": + test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_random.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_random.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_random.py Wed Apr 30 15:57:13 2008 @@ -412,6 +412,7 @@ g.random = x[:].pop; g.gammavariate(1.0, 1.0) g.random = x[:].pop; g.gammavariate(200.0, 1.0) g.random = x[:].pop; g.betavariate(3.0, 3.0) + g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0) def test_avg_std(self): # Use integration to test distribution average and standard deviation. @@ -421,6 +422,7 @@ x = [i/float(N) for i in range(1,N)] for variate, args, mu, sigmasqrd in [ (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12), + (g.triangular, (0.0, 1.0, 1.0/3.0), 4.0/9.0, 7.0/9.0/18.0), (g.expovariate, (1.5,), 1/1.5, 1/1.5**2), (g.paretovariate, (5.0,), 5.0/(5.0-1), 5.0/((5.0-1)**2*(5.0-2))), Deleted: python/branches/py3k-ctypes-pep3118/Lib/test/test_rational.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_rational.py Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,376 +0,0 @@ -"""Tests for Lib/rational.py.""" - -from decimal import Decimal -from test.test_support import run_unittest, verbose -import math -import operator -import rational -import unittest -from copy import copy, deepcopy -from cPickle import dumps, loads -R = rational.Rational - -def _components(r): - return (r.numerator, r.denominator) - -class RationalTest(unittest.TestCase): - - def assertTypedEquals(self, expected, actual): - """Asserts that both the types and values are the same.""" - self.assertEquals(type(expected), type(actual)) - self.assertEquals(expected, actual) - - def assertRaisesMessage(self, exc_type, message, - callable, *args, **kwargs): - """Asserts that callable(*args, **kwargs) raises exc_type(message).""" - try: - callable(*args, **kwargs) - except exc_type as e: - self.assertEquals(message, str(e)) - else: - self.fail("%s not raised" % exc_type.__name__) - - def testInit(self): - self.assertEquals((0, 1), _components(R())) - self.assertEquals((7, 1), _components(R(7))) - self.assertEquals((7, 3), _components(R(R(7, 3)))) - - self.assertEquals((-1, 1), _components(R(-1, 1))) - self.assertEquals((-1, 1), _components(R(1, -1))) - self.assertEquals((1, 1), _components(R(-2, -2))) - self.assertEquals((1, 2), _components(R(5, 10))) - self.assertEquals((7, 15), _components(R(7, 15))) - self.assertEquals((10**23, 1), _components(R(10**23))) - - self.assertRaisesMessage(ZeroDivisionError, "Rational(12, 0)", - R, 12, 0) - self.assertRaises(TypeError, R, 1.5) - self.assertRaises(TypeError, R, 1.5 + 3j) - - self.assertRaises(TypeError, R, R(1, 2), 3) - self.assertRaises(TypeError, R, "3/2", 3) - - def testFromString(self): - self.assertEquals((5, 1), _components(R("5"))) - self.assertEquals((3, 2), _components(R("3/2"))) - self.assertEquals((3, 2), _components(R(" \n +3/2"))) - self.assertEquals((-3, 2), _components(R("-3/2 "))) - self.assertEquals((3, 2), _components(R(" 03/02 \n "))) - self.assertEquals((3, 2), _components(R(" 03/02 \n "))) - - self.assertRaisesMessage( - ZeroDivisionError, "Rational(3, 0)", - R, "3/0") - self.assertRaisesMessage( - ValueError, "Invalid literal for Rational: 3/", - R, "3/") - self.assertRaisesMessage( - ValueError, "Invalid literal for Rational: 3 /2", - R, "3 /2") - self.assertRaisesMessage( - # Denominators don't need a sign. - ValueError, "Invalid literal for Rational: 3/+2", - R, "3/+2") - self.assertRaisesMessage( - # Imitate float's parsing. - ValueError, "Invalid literal for Rational: + 3/2", - R, "+ 3/2") - self.assertRaisesMessage( - # Only parse fractions, not decimals. - ValueError, "Invalid literal for Rational: 3.2", - R, "3.2") - - def testImmutable(self): - r = R(7, 3) - r.__init__(2, 15) - self.assertEquals((7, 3), _components(r)) - - def testFromFloat(self): - self.assertRaisesMessage( - TypeError, "Rational.from_float() only takes floats, not 3 (int)", - R.from_float, 3) - - self.assertEquals((0, 1), _components(R.from_float(-0.0))) - self.assertEquals((10, 1), _components(R.from_float(10.0))) - self.assertEquals((-5, 2), _components(R.from_float(-2.5))) - self.assertEquals((99999999999999991611392, 1), - _components(R.from_float(1e23))) - self.assertEquals(float(10**23), float(R.from_float(1e23))) - self.assertEquals((3602879701896397, 1125899906842624), - _components(R.from_float(3.2))) - self.assertEquals(3.2, float(R.from_float(3.2))) - - inf = 1e1000 - nan = inf - inf - self.assertRaisesMessage( - TypeError, "Cannot convert inf to Rational.", - R.from_float, inf) - self.assertRaisesMessage( - TypeError, "Cannot convert -inf to Rational.", - R.from_float, -inf) - self.assertRaisesMessage( - TypeError, "Cannot convert nan to Rational.", - R.from_float, nan) - - def testFromDecimal(self): - self.assertRaisesMessage( - TypeError, - "Rational.from_decimal() only takes Decimals, not 3 (int)", - R.from_decimal, 3) - self.assertEquals(R(0), R.from_decimal(Decimal("-0"))) - self.assertEquals(R(5, 10), R.from_decimal(Decimal("0.5"))) - self.assertEquals(R(5, 1000), R.from_decimal(Decimal("5e-3"))) - self.assertEquals(R(5000), R.from_decimal(Decimal("5e3"))) - self.assertEquals(1 - R(1, 10**30), - R.from_decimal(Decimal("0." + "9" * 30))) - - self.assertRaisesMessage( - TypeError, "Cannot convert Infinity to Rational.", - R.from_decimal, Decimal("inf")) - self.assertRaisesMessage( - TypeError, "Cannot convert -Infinity to Rational.", - R.from_decimal, Decimal("-inf")) - self.assertRaisesMessage( - TypeError, "Cannot convert NaN to Rational.", - R.from_decimal, Decimal("nan")) - self.assertRaisesMessage( - TypeError, "Cannot convert sNaN to Rational.", - R.from_decimal, Decimal("snan")) - - def testFromContinuedFraction(self): - self.assertRaises(TypeError, R.from_continued_fraction, None) - phi = R.from_continued_fraction([1]*100) - self.assertEquals(round(phi - (1 + 5 ** 0.5) / 2, 10), 0.0) - - minusphi = R.from_continued_fraction([-1]*100) - self.assertEquals(round(minusphi + (1 + 5 ** 0.5) / 2, 10), 0.0) - - self.assertEquals(R.from_continued_fraction([0]), R(0)) - self.assertEquals(R.from_continued_fraction([]), R(0)) - - def testAsContinuedFraction(self): - self.assertEqual(R.from_float(math.pi).as_continued_fraction()[:15], - [3, 7, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1, 14, 3, 3]) - self.assertEqual(R.from_float(-math.pi).as_continued_fraction()[:16], - [-4, 1, 6, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1, 14, 3, 3]) - self.assertEqual(R(0).as_continued_fraction(), [0]) - - def testApproximateFrom(self): - self.assertEqual(R.from_float(math.pi).approximate(10000), R(355, 113)) - self.assertEqual(R.from_float(-math.pi).approximate(10000), R(-355, 113)) - self.assertEqual(R.from_float(0.0).approximate(10000), R(0)) - - def testConversions(self): - self.assertTypedEquals(-1, trunc(R(-11, 10))) - self.assertTypedEquals(-2, math.floor(R(-11, 10))) - self.assertTypedEquals(-1, math.ceil(R(-11, 10))) - self.assertTypedEquals(-1, math.ceil(R(-10, 10))) - self.assertTypedEquals(-1, int(R(-11, 10))) - - self.assertTypedEquals(0, round(R(-1, 10))) - self.assertTypedEquals(0, round(R(-5, 10))) - self.assertTypedEquals(-2, round(R(-15, 10))) - self.assertTypedEquals(-1, round(R(-7, 10))) - - self.assertEquals(False, bool(R(0, 1))) - self.assertEquals(True, bool(R(3, 2))) - self.assertTypedEquals(0.1, float(R(1, 10))) - - # Check that __float__ isn't implemented by converting the - # numerator and denominator to float before dividing. - self.assertRaises(OverflowError, float, int('2'*400+'7')) - self.assertAlmostEquals(2.0/3, - float(R(int('2'*400+'7'), int('3'*400+'1')))) - - self.assertTypedEquals(0.1+0j, complex(R(1,10))) - - def testRound(self): - self.assertTypedEquals(R(-200), round(R(-150), -2)) - self.assertTypedEquals(R(-200), round(R(-250), -2)) - self.assertTypedEquals(R(30), round(R(26), -1)) - self.assertTypedEquals(R(-2, 10), round(R(-15, 100), 1)) - self.assertTypedEquals(R(-2, 10), round(R(-25, 100), 1)) - - - def testArithmetic(self): - self.assertEquals(R(1, 2), R(1, 10) + R(2, 5)) - self.assertEquals(R(-3, 10), R(1, 10) - R(2, 5)) - self.assertEquals(R(1, 25), R(1, 10) * R(2, 5)) - self.assertEquals(R(1, 4), R(1, 10) / R(2, 5)) - self.assertTypedEquals(2, R(9, 10) // R(2, 5)) - self.assertTypedEquals(10**23, R(10**23, 1) // R(1)) - self.assertEquals(R(2, 3), R(-7, 3) % R(3, 2)) - self.assertEquals(R(8, 27), R(2, 3) ** R(3)) - self.assertEquals(R(27, 8), R(2, 3) ** R(-3)) - self.assertTypedEquals(2.0, R(4) ** R(1, 2)) - z = pow(R(-1), R(1, 2)) - self.assertAlmostEquals(z.real, 0) - self.assertEquals(z.imag, 1) - - def testMixedArithmetic(self): - self.assertTypedEquals(R(11, 10), R(1, 10) + 1) - self.assertTypedEquals(1.1, R(1, 10) + 1.0) - self.assertTypedEquals(1.1 + 0j, R(1, 10) + (1.0 + 0j)) - self.assertTypedEquals(R(11, 10), 1 + R(1, 10)) - self.assertTypedEquals(1.1, 1.0 + R(1, 10)) - self.assertTypedEquals(1.1 + 0j, (1.0 + 0j) + R(1, 10)) - - self.assertTypedEquals(R(-9, 10), R(1, 10) - 1) - self.assertTypedEquals(-0.9, R(1, 10) - 1.0) - self.assertTypedEquals(-0.9 + 0j, R(1, 10) - (1.0 + 0j)) - self.assertTypedEquals(R(9, 10), 1 - R(1, 10)) - self.assertTypedEquals(0.9, 1.0 - R(1, 10)) - self.assertTypedEquals(0.9 + 0j, (1.0 + 0j) - R(1, 10)) - - self.assertTypedEquals(R(1, 10), R(1, 10) * 1) - self.assertTypedEquals(0.1, R(1, 10) * 1.0) - self.assertTypedEquals(0.1 + 0j, R(1, 10) * (1.0 + 0j)) - self.assertTypedEquals(R(1, 10), 1 * R(1, 10)) - self.assertTypedEquals(0.1, 1.0 * R(1, 10)) - self.assertTypedEquals(0.1 + 0j, (1.0 + 0j) * R(1, 10)) - - self.assertTypedEquals(R(1, 10), R(1, 10) / 1) - self.assertTypedEquals(0.1, R(1, 10) / 1.0) - self.assertTypedEquals(0.1 + 0j, R(1, 10) / (1.0 + 0j)) - self.assertTypedEquals(R(10, 1), 1 / R(1, 10)) - self.assertTypedEquals(10.0, 1.0 / R(1, 10)) - self.assertTypedEquals(10.0 + 0j, (1.0 + 0j) / R(1, 10)) - - self.assertTypedEquals(0, R(1, 10) // 1) - self.assertTypedEquals(0, R(1, 10) // 1.0) - self.assertTypedEquals(10, 1 // R(1, 10)) - self.assertTypedEquals(10**23, 10**22 // R(1, 10)) - self.assertTypedEquals(10, 1.0 // R(1, 10)) - - self.assertTypedEquals(R(1, 10), R(1, 10) % 1) - self.assertTypedEquals(0.1, R(1, 10) % 1.0) - self.assertTypedEquals(R(0, 1), 1 % R(1, 10)) - self.assertTypedEquals(0.0, 1.0 % R(1, 10)) - - # No need for divmod since we don't override it. - - # ** has more interesting conversion rules. - self.assertTypedEquals(R(100, 1), R(1, 10) ** -2) - self.assertTypedEquals(R(100, 1), R(10, 1) ** 2) - self.assertTypedEquals(0.1, R(1, 10) ** 1.0) - self.assertTypedEquals(0.1 + 0j, R(1, 10) ** (1.0 + 0j)) - self.assertTypedEquals(4 , 2 ** R(2, 1)) - z = pow(-1, R(1, 2)) - self.assertAlmostEquals(0, z.real) - self.assertEquals(1, z.imag) - self.assertTypedEquals(R(1, 4) , 2 ** R(-2, 1)) - self.assertTypedEquals(2.0 , 4 ** R(1, 2)) - self.assertTypedEquals(0.25, 2.0 ** R(-2, 1)) - self.assertTypedEquals(1.0 + 0j, (1.0 + 0j) ** R(1, 10)) - - def testMixingWithDecimal(self): - # Decimal refuses mixed comparisons. - self.assertRaisesMessage( - TypeError, - "unsupported operand type(s) for +: 'Rational' and 'Decimal'", - operator.add, R(3,11), Decimal('3.1415926')) - self.assertNotEquals(R(5, 2), Decimal('2.5')) - - def testComparisons(self): - self.assertTrue(R(1, 2) < R(2, 3)) - self.assertFalse(R(1, 2) < R(1, 2)) - self.assertTrue(R(1, 2) <= R(2, 3)) - self.assertTrue(R(1, 2) <= R(1, 2)) - self.assertFalse(R(2, 3) <= R(1, 2)) - self.assertTrue(R(1, 2) == R(1, 2)) - self.assertFalse(R(1, 2) == R(1, 3)) - - def testMixedLess(self): - self.assertTrue(2 < R(5, 2)) - self.assertFalse(2 < R(4, 2)) - self.assertTrue(R(5, 2) < 3) - self.assertFalse(R(4, 2) < 2) - - self.assertTrue(R(1, 2) < 0.6) - self.assertFalse(R(1, 2) < 0.4) - self.assertTrue(0.4 < R(1, 2)) - self.assertFalse(0.5 < R(1, 2)) - - def testMixedLessEqual(self): - self.assertTrue(0.5 <= R(1, 2)) - self.assertFalse(0.6 <= R(1, 2)) - self.assertTrue(R(1, 2) <= 0.5) - self.assertFalse(R(1, 2) <= 0.4) - self.assertTrue(2 <= R(4, 2)) - self.assertFalse(2 <= R(3, 2)) - self.assertTrue(R(4, 2) <= 2) - self.assertFalse(R(5, 2) <= 2) - - def testBigFloatComparisons(self): - # Because 10**23 can't be represented exactly as a float: - self.assertFalse(R(10**23) == float(10**23)) - # The first test demonstrates why these are important. - self.assertFalse(1e23 < float(R(trunc(1e23) + 1))) - self.assertTrue(1e23 < R(trunc(1e23) + 1)) - self.assertFalse(1e23 <= R(trunc(1e23) - 1)) - self.assertTrue(1e23 > R(trunc(1e23) - 1)) - self.assertFalse(1e23 >= R(trunc(1e23) + 1)) - - def testBigComplexComparisons(self): - self.assertFalse(R(10**23) == complex(10**23)) - self.assertTrue(R(10**23) > complex(10**23)) - self.assertFalse(R(10**23) <= complex(10**23)) - - def testMixedEqual(self): - self.assertTrue(0.5 == R(1, 2)) - self.assertFalse(0.6 == R(1, 2)) - self.assertTrue(R(1, 2) == 0.5) - self.assertFalse(R(1, 2) == 0.4) - self.assertTrue(2 == R(4, 2)) - self.assertFalse(2 == R(3, 2)) - self.assertTrue(R(4, 2) == 2) - self.assertFalse(R(5, 2) == 2) - - def testStringification(self): - self.assertEquals("Rational(7,3)", repr(R(7, 3))) - self.assertEquals("7/3", str(R(7, 3))) - self.assertEquals("7", str(R(7, 1))) - - def testHash(self): - self.assertEquals(hash(2.5), hash(R(5, 2))) - self.assertEquals(hash(10**50), hash(R(10**50))) - self.assertNotEquals(hash(float(10**23)), hash(R(10**23))) - - def testApproximatePi(self): - # Algorithm borrowed from - # http://docs.python.org/lib/decimal-recipes.html - three = R(3) - lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24 - while abs(s - lasts) > R(1, 10**9): - lasts = s - n, na = n+na, na+8 - d, da = d+da, da+32 - t = (t * n) / d - s += t - self.assertAlmostEquals(math.pi, s) - - def testApproximateCos1(self): - # Algorithm borrowed from - # http://docs.python.org/lib/decimal-recipes.html - x = R(1) - i, lasts, s, fact, num, sign = 0, 0, R(1), 1, 1, 1 - while abs(s - lasts) > R(1, 10**9): - lasts = s - i += 2 - fact *= i * (i-1) - num *= x * x - sign *= -1 - s += num / fact * sign - self.assertAlmostEquals(math.cos(1), s) - - def test_copy_deepcopy_pickle(self): - r = R(13, 7) - self.assertEqual(r, loads(dumps(r))) - self.assertEqual(id(r), id(copy(r))) - self.assertEqual(id(r), id(deepcopy(r))) - -def test_main(): - run_unittest(RationalTest) - -if __name__ == '__main__': - test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_re.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_re.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_re.py Wed Apr 30 15:57:13 2008 @@ -83,33 +83,22 @@ self.assertEqual(re.sub('\r\n', '\n', 'abc\r\ndef\r\n'), 'abc\ndef\n') -# This test makes no sense until re supports bytes, and should then probably -# test for the *in*ability to mix bytes and str this way :) -# -# def test_bug_1140(self): -# # re.sub(x, y, b'') should return b'', not '', and -# # re.sub(x, y, '') should return '', not b''. -# # Also: -# # re.sub(x, y, str(x)) should return str(y), and -# # re.sub(x, y, bytes(x)) should return -# # str(y) if isinstance(y, str) else unicode(y). -# for x in 'x', u'x': -# for y in 'y', u'y': -# z = re.sub(x, y, u'') -# self.assertEqual(z, u'') -# self.assertEqual(type(z), unicode) -# # -# z = re.sub(x, y, '') -# self.assertEqual(z, '') -# self.assertEqual(type(z), str) -# # -# z = re.sub(x, y, unicode(x)) -# self.assertEqual(z, y) -# self.assertEqual(type(z), unicode) -# # -# z = re.sub(x, y, str(x)) -# self.assertEqual(z, y) -# self.assertEqual(type(z), type(y)) + def test_bug_1140(self): + # re.sub(x, y, b'') should return b'', not '', and + # re.sub(x, y, '') should return '', not b''. + # Also: + # re.sub(x, y, str(x)) should return str(y), and + # re.sub(x, y, bytes(x)) should return + # str(y) if isinstance(y, str) else unicode(y). + for x in 'x', b'x': + for y in 'y', b'y': + z = re.sub(x, y, b'') + self.assertEqual(z, b'') + self.assertEqual(type(z), bytes) + # + z = re.sub(x, y, '') + self.assertEqual(z, '') + self.assertEqual(type(z), str) def test_bug_1661(self): # Verify that flags do not get silently ignored with compiled patterns @@ -599,10 +588,9 @@ self.assertEqual([item.group(0) for item in iter], [":", "::", ":::"]) - # XXX This needs to be restored for str vs. bytes. -## def test_bug_926075(self): -## self.assert_(re.compile('bug_926075') is not -## re.compile(str8('bug_926075'))) + def test_bug_926075(self): + self.assert_(re.compile('bug_926075') is not + re.compile(b'bug_926075')) def test_bug_931848(self): pattern = eval('"[\u002E\u3002\uFF0E\uFF61]"') Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_resource.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_resource.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_resource.py Wed Apr 30 15:57:13 2008 @@ -1,8 +1,8 @@ import unittest from test import test_support - -import os, resource +import resource +import time # This test is checking a few specific problem spots with the resource module. @@ -15,7 +15,6 @@ self.assertRaises(TypeError, resource.setrlimit, 42, 42, 42) def test_fsize_ismax(self): - try: (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE) except AttributeError: @@ -54,6 +53,14 @@ try: f.write(b"Y") f.flush() + # On some systems (e.g., Ubuntu on hppa) the flush() + # doesn't always cause the exception, but the close() + # does eventually. Try flushing several times in + # an attempt to ensure the file is really synced and + # the exception raised. + for i in range(5): + time.sleep(.1) + f.flush() except IOError: if not limit_set: raise @@ -63,10 +70,10 @@ resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max)) finally: f.close() - os.unlink(test_support.TESTFN) finally: if limit_set: resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max)) + test_support.unlink(test_support.TESTFN) def test_fsize_toobig(self): # Be sure that setrlimit is checking for really large values Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_rfc822.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_rfc822.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_rfc822.py Wed Apr 30 15:57:13 2008 @@ -1,5 +1,4 @@ import rfc822 -import sys import unittest from test import test_support Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_richcmp.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_richcmp.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_richcmp.py Wed Apr 30 15:57:13 2008 @@ -254,7 +254,7 @@ def test_recursion(self): # Check that comparison for recursive objects fails gracefully - from UserList import UserList + from collections import UserList a = UserList() b = UserList() a.append(b) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_sax.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_sax.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_sax.py Wed Apr 30 15:57:13 2008 @@ -446,7 +446,8 @@ # ===== InputSource support - def test_expat_inpsource_filename(self): + def XXXtest_expat_inpsource_filename(self): + # FIXME: test blocks indefinitely parser = create_parser() result = StringIO() xmlgen = XMLGenerator(result) @@ -456,7 +457,8 @@ self.assertEquals(result.getvalue(), xml_test_out) - def test_expat_inpsource_sysid(self): + def XXXtest_expat_inpsource_sysid(self): + # FIXME: test blocks indefinitely parser = create_parser() result = StringIO() xmlgen = XMLGenerator(result) @@ -529,7 +531,8 @@ self.assertEquals(parser.getPublicId(), None) self.assertEquals(parser.getLineNumber(), 1) - def test_expat_locator_withinfo(self): + def XXXtest_expat_locator_withinfo(self): + # FIXME: test blocks indefinitely result = StringIO() xmlgen = XMLGenerator(result) parser = create_parser() @@ -684,7 +687,7 @@ self.assertRaises(SAXParseException, parser.parse, sio) -def unittest_main(): +def test_main(): run_unittest(MakeParserTest, SaxutilsTest, XmlgenTest, @@ -693,4 +696,4 @@ XmlReaderTest) if __name__ == "__main__": - unittest_main() + test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_scope.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_scope.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_scope.py Wed Apr 30 15:57:13 2008 @@ -573,6 +573,13 @@ f(4)() + def testFreeingCell(self): + # Test what happens when a finalizer accesses + # the cell where the object was stored. + class Special: + def __del__(self): + nestedcell_get() + def testNonLocalFunction(self): def f(x): Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_scriptpackages.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_scriptpackages.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_scriptpackages.py Wed Apr 30 15:57:13 2008 @@ -1,9 +1,6 @@ # Copyright (C) 2003 Python Software Foundation import unittest -import os -import sys -import tempfile from test import test_support import aetools Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_select.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_select.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_select.py Wed Apr 30 15:57:13 2008 @@ -1,70 +1,52 @@ -# Testing select module -from test.test_support import verbose, reap_children +from test import test_support +import unittest import select import os +import sys -# test some known error conditions -try: - rfd, wfd, xfd = select.select(1, 2, 3) -except TypeError: - pass -else: - print('expected TypeError exception not raised') - -class Nope: - pass - -class Almost: - def fileno(self): - return 'fileno' - -try: - rfd, wfd, xfd = select.select([Nope()], [], []) -except TypeError: - pass -else: - print('expected TypeError exception not raised') - -try: - rfd, wfd, xfd = select.select([Almost()], [], []) -except TypeError: - pass -else: - print('expected TypeError exception not raised') - -try: - rfd, wfd, xfd = select.select([], [], [], 'not a number') -except TypeError: - pass -else: - print('expected TypeError exception not raised') - - -def test(): - import sys - if sys.platform[:3] in ('win', 'mac', 'os2'): - if verbose: - print("Can't test select easily on", sys.platform) - return - cmd = 'for i in 0 1 2 3 4 5 6 7 8 9; do echo testing...; sleep 1; done' - p = os.popen(cmd, 'r') - for tout in (0, 1, 2, 4, 8, 16) + (None,)*10: - if verbose: - print('timeout =', tout) - rfd, wfd, xfd = select.select([p], [], [], tout) - if (rfd, wfd, xfd) == ([], [], []): - continue - if (rfd, wfd, xfd) == ([p], [], []): - line = p.readline() - if verbose: - print(repr(line)) - if not line: - if verbose: - print('EOF') - break - continue - print('Unexpected return values from select():', rfd, wfd, xfd) - p.close() - reap_children() +class SelectTestCase(unittest.TestCase): -test() + class Nope: + pass + + class Almost: + def fileno(self): + return 'fileno' + + def test_error_conditions(self): + self.assertRaises(TypeError, select.select, 1, 2, 3) + self.assertRaises(TypeError, select.select, [self.Nope()], [], []) + self.assertRaises(TypeError, select.select, [self.Almost()], [], []) + self.assertRaises(TypeError, select.select, [], [], [], "not a number") + + def test_select(self): + if sys.platform[:3] in ('win', 'mac', 'os2', 'riscos'): + if test_support.verbose: + print("Can't test select easily on", sys.platform) + return + cmd = 'for i in 0 1 2 3 4 5 6 7 8 9; do echo testing...; sleep 1; done' + p = os.popen(cmd, 'r') + for tout in (0, 1, 2, 4, 8, 16) + (None,)*10: + if test_support.verbose: + print('timeout =', tout) + rfd, wfd, xfd = select.select([p], [], [], tout) + if (rfd, wfd, xfd) == ([], [], []): + continue + if (rfd, wfd, xfd) == ([p], [], []): + line = p.readline() + if test_support.verbose: + print(repr(line)) + if not line: + if test_support.verbose: + print('EOF') + break + continue + self.fail('Unexpected return values from select():', rfd, wfd, xfd) + p.close() + +def test_main(): + test_support.run_unittest(SelectTestCase) + test_support.reap_children() + +if __name__ == "__main__": + test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_set.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_set.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_set.py Wed Apr 30 15:57:13 2008 @@ -295,7 +295,7 @@ self.assertEqual(fo.read(), repr(s)) finally: fo.close() - os.remove(test_support.TESTFN) + test_support.unlink(test_support.TESTFN) def test_do_not_rehash_dict_keys(self): n = 10 @@ -679,7 +679,7 @@ self.assertEqual(fo.read(), repr(self.set)) finally: fo.close() - os.remove(test_support.TESTFN) + test_support.unlink(test_support.TESTFN) def test_length(self): self.assertEqual(len(self.set), self.length) @@ -1560,10 +1560,10 @@ def __next__(self): raise StopIteration -from itertools import chain, imap +from itertools import chain def L(seqn): 'Test multiple tiers of iterators' - return chain(imap(lambda x:x, R(Ig(G(seqn))))) + return chain(map(lambda x:x, R(Ig(G(seqn))))) class TestVariousIteratorArgs(unittest.TestCase): Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_sgmllib.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_sgmllib.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_sgmllib.py Wed Apr 30 15:57:13 2008 @@ -1,4 +1,3 @@ -import htmlentitydefs import pprint import re import sgmllib @@ -116,7 +115,7 @@ try: events = self.get_events(source) except: - import sys + #import sys #print >>sys.stderr, pprint.pformat(self.events) raise if events != expected_events: Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_shelve.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_shelve.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_shelve.py Wed Apr 30 15:57:13 2008 @@ -2,13 +2,13 @@ import shelve import glob from test import test_support -from UserDict import DictMixin +from collections import MutableMapping from test.test_anydbm import dbm_iterator def L1(s): return s.decode("latin-1") -class byteskeydict(DictMixin): +class byteskeydict(MutableMapping): "Mapping that supports bytes keys" def __init__(self): @@ -23,10 +23,15 @@ def __delitem__(self, key): del self.d[L1(key)] + def __len__(self): + return len(self.d) + def iterkeys(self): for k in self.d.keys(): yield k.encode("latin-1") + __iter__ = iterkeys + def keys(self): return list(self.iterkeys()) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_shutil.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_shutil.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_shutil.py Wed Apr 30 15:57:13 2008 @@ -63,17 +63,6 @@ self.assertRaises(OSError, shutil.rmtree, path) os.remove(path) - def test_dont_move_dir_in_itself(self): - src_dir = tempfile.mkdtemp() - try: - dst = os.path.join(src_dir, 'foo') - self.assertRaises(shutil.Error, shutil.move, src_dir, dst) - finally: - try: - os.rmdir(src_dir) - except: - pass - def test_copytree_simple(self): def write_data(path, data): f = open(path, "w") @@ -162,9 +151,123 @@ shutil.rmtree(TESTFN, ignore_errors=True) +class TestMove(unittest.TestCase): + + def setUp(self): + filename = "foo" + self.src_dir = tempfile.mkdtemp() + self.dst_dir = tempfile.mkdtemp() + self.src_file = os.path.join(self.src_dir, filename) + self.dst_file = os.path.join(self.dst_dir, filename) + # Try to create a dir in the current directory, hoping that it is + # not located on the same filesystem as the system tmp dir. + try: + self.dir_other_fs = tempfile.mkdtemp( + dir=os.path.dirname(__file__)) + self.file_other_fs = os.path.join(self.dir_other_fs, + filename) + except OSError: + self.dir_other_fs = None + with open(self.src_file, "wb") as f: + f.write(b"spam") + + def tearDown(self): + for d in (self.src_dir, self.dst_dir, self.dir_other_fs): + try: + if d: + shutil.rmtree(d) + except: + pass + + def _check_move_file(self, src, dst, real_dst): + contents = open(src, "rb").read() + shutil.move(src, dst) + self.assertEqual(contents, open(real_dst, "rb").read()) + self.assertFalse(os.path.exists(src)) + + def _check_move_dir(self, src, dst, real_dst): + contents = sorted(os.listdir(src)) + shutil.move(src, dst) + self.assertEqual(contents, sorted(os.listdir(real_dst))) + self.assertFalse(os.path.exists(src)) + + def test_move_file(self): + # Move a file to another location on the same filesystem. + self._check_move_file(self.src_file, self.dst_file, self.dst_file) + + def test_move_file_to_dir(self): + # Move a file inside an existing dir on the same filesystem. + self._check_move_file(self.src_file, self.dst_dir, self.dst_file) + + def test_move_file_other_fs(self): + # Move a file to an existing dir on another filesystem. + if not self.dir_other_fs: + # skip + return + self._check_move_file(self.src_file, self.file_other_fs, + self.file_other_fs) + + def test_move_file_to_dir_other_fs(self): + # Move a file to another location on another filesystem. + if not self.dir_other_fs: + # skip + return + self._check_move_file(self.src_file, self.dir_other_fs, + self.file_other_fs) + + def test_move_dir(self): + # Move a dir to another location on the same filesystem. + dst_dir = tempfile.mktemp() + try: + self._check_move_dir(self.src_dir, dst_dir, dst_dir) + finally: + try: + shutil.rmtree(dst_dir) + except: + pass + + def test_move_dir_other_fs(self): + # Move a dir to another location on another filesystem. + if not self.dir_other_fs: + # skip + return + dst_dir = tempfile.mktemp(dir=self.dir_other_fs) + try: + self._check_move_dir(self.src_dir, dst_dir, dst_dir) + finally: + try: + shutil.rmtree(dst_dir) + except: + pass + + def test_move_dir_to_dir(self): + # Move a dir inside an existing dir on the same filesystem. + self._check_move_dir(self.src_dir, self.dst_dir, + os.path.join(self.dst_dir, os.path.basename(self.src_dir))) + + def test_move_dir_to_dir_other_fs(self): + # Move a dir inside an existing dir on another filesystem. + if not self.dir_other_fs: + # skip + return + self._check_move_dir(self.src_dir, self.dir_other_fs, + os.path.join(self.dir_other_fs, os.path.basename(self.src_dir))) + + def test_existing_file_inside_dest_dir(self): + # A file with the same name inside the destination dir already exists. + with open(self.dst_file, "wb"): + pass + self.assertRaises(shutil.Error, shutil.move, self.src_file, self.dst_dir) + + def test_dont_move_dir_in_itself(self): + # Moving a dir inside itself raises an Error. + dst = os.path.join(self.src_dir, "bar") + self.assertRaises(shutil.Error, shutil.move, self.src_dir, dst) + + def test_main(): - test_support.run_unittest(TestShutil) + test_support.run_unittest(TestShutil, TestMove) if __name__ == '__main__': test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_signal.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_signal.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_signal.py Wed Apr 30 15:57:13 2008 @@ -1,171 +1,209 @@ import unittest from test import test_support +from contextlib import closing, nested +import gc +import pickle +import select import signal -import os, sys, time +import subprocess +import traceback +import sys, os, time, errno + +if sys.platform[:3] in ('win', 'os2') or sys.platform == 'riscos': + raise test_support.TestSkipped("Can't test signal on %s" % \ + sys.platform) + class HandlerBCalled(Exception): pass + +def exit_subprocess(): + """Use os._exit(0) to exit the current subprocess. + + Otherwise, the test catches the SystemExit and continues executing + in parallel with the original test, so you wind up with an + exponential number of tests running concurrently. + """ + os._exit(0) + + +def ignoring_eintr(__func, *args, **kwargs): + try: + return __func(*args, **kwargs) + except EnvironmentError as e: + if e.errno != errno.EINTR: + raise + return None + + class InterProcessSignalTests(unittest.TestCase): MAX_DURATION = 20 # Entire test should last at most 20 sec. - # Set up a child to send signals to us (the parent) after waiting - # long enough to receive the alarm. It seems we miss the alarm - # for some reason. This will hopefully stop the hangs on - # Tru64/Alpha. Alas, it doesn't. Tru64 appears to miss all the - # signals at times, or seemingly random subsets of them, and - # nothing done in force_test_exit so far has actually helped. - def spawn_force_test_exit_process(self, parent_pid): - # Sigh, both imports seem necessary to avoid errors. - import os - fork_pid = os.fork() - if fork_pid: - # In parent. - return fork_pid + def setUp(self): + self.using_gc = gc.isenabled() + gc.disable() - # In child. - import os, time - try: - # Wait 5 seconds longer than the expected alarm to give enough - # time for the normal sequence of events to occur. This is - # just a stop-gap to try to prevent the test from hanging. - time.sleep(self.MAX_DURATION + 5) - print(" child should not have to kill parent", - file=sys.__stdout__) - for signame in "SIGHUP", "SIGUSR1", "SIGUSR2", "SIGALRM": - os.kill(parent_pid, getattr(signal, signame)) - print(" child sent", signame, "to", - parent_pid, file=sys.__stdout__) - time.sleep(1) - finally: - os._exit(0) + def tearDown(self): + if self.using_gc: + gc.enable() + + def format_frame(self, frame, limit=None): + return ''.join(traceback.format_stack(frame, limit=limit)) - def handlerA(self, *args): + def handlerA(self, signum, frame): self.a_called = True if test_support.verbose: - print("handlerA invoked", args) + print("handlerA invoked from signal %s at:\n%s" % ( + signum, self.format_frame(frame, limit=1))) - def handlerB(self, *args): + def handlerB(self, signum, frame): self.b_called = True if test_support.verbose: - print("handlerB invoked", args) - raise HandlerBCalled(*args) - - def test_main(self): - self.assertEquals(signal.getsignal(signal.SIGHUP), self.handlerA) - self.assertEquals(signal.getsignal(signal.SIGUSR1), self.handlerB) - self.assertEquals(signal.getsignal(signal.SIGUSR2), signal.SIG_IGN) - self.assertEquals(signal.getsignal(signal.SIGALRM), - signal.default_int_handler) - - # Launch an external script to send us signals. - # We expect the external script to: - # send HUP, which invokes handlerA to set a_called - # send USR1, which invokes handlerB to set b_called and raise - # HandlerBCalled - # send USR2, which is ignored - # - # Then we expect the alarm to go off, and its handler raises - # KeyboardInterrupt, finally getting us out of the loop. + print ("handlerB invoked from signal %s at:\n%s" % ( + signum, self.format_frame(frame, limit=1))) + raise HandlerBCalled(signum, self.format_frame(frame)) + + def wait(self, child): + """Wait for child to finish, ignoring EINTR.""" + while True: + try: + child.wait() + return + except OSError as e: + if e.errno != errno.EINTR: + raise + + def run_test(self): + # Install handlers. This function runs in a sub-process, so we + # don't worry about re-setting the default handlers. + signal.signal(signal.SIGHUP, self.handlerA) + signal.signal(signal.SIGUSR1, self.handlerB) + signal.signal(signal.SIGUSR2, signal.SIG_IGN) + signal.signal(signal.SIGALRM, signal.default_int_handler) - if test_support.verbose: - verboseflag = '-x' - else: - verboseflag = '+x' + # Variables the signals will modify: + self.a_called = False + self.b_called = False - pid = self.pid + # Let the sub-processes know who to send signals to. + pid = os.getpid() if test_support.verbose: print("test runner's pid is", pid) - # Shell script that will send us asynchronous signals - script = """ - ( - set %(verboseflag)s - sleep 2 - kill -HUP %(pid)d - sleep 2 - kill -USR1 %(pid)d - sleep 2 - kill -USR2 %(pid)d - ) & - """ % vars() - - signal.alarm(self.MAX_DURATION) - - handler_b_exception_raised = False + child = ignoring_eintr(subprocess.Popen, ['kill', '-HUP', str(pid)]) + if child: + self.wait(child) + if not self.a_called: + time.sleep(1) # Give the signal time to be delivered. + self.assertTrue(self.a_called) + self.assertFalse(self.b_called) + self.a_called = False - os.system(script) + # Make sure the signal isn't delivered while the previous + # Popen object is being destroyed, because __del__ swallows + # exceptions. + del child try: + child = subprocess.Popen(['kill', '-USR1', str(pid)]) + # This wait should be interrupted by the signal's exception. + self.wait(child) + time.sleep(1) # Give the signal time to be delivered. + self.fail('HandlerBCalled exception not thrown') + except HandlerBCalled: + self.assertTrue(self.b_called) + self.assertFalse(self.a_called) if test_support.verbose: - print("starting pause() loop...") - while 1: - try: - if test_support.verbose: - print("call pause()...") - signal.pause() - if test_support.verbose: - print("pause() returned") - except HandlerBCalled: - handler_b_exception_raised = True - if test_support.verbose: - print("HandlerBCalled exception caught") + print("HandlerBCalled exception caught") + child = ignoring_eintr(subprocess.Popen, ['kill', '-USR2', str(pid)]) + if child: + self.wait(child) # Nothing should happen. + + try: + signal.alarm(1) + # The race condition in pause doesn't matter in this case, + # since alarm is going to raise a KeyboardException, which + # will skip the call. + signal.pause() + # But if another signal arrives before the alarm, pause + # may return early. + time.sleep(1) except KeyboardInterrupt: if test_support.verbose: print("KeyboardInterrupt (the alarm() went off)") - - self.assert_(self.a_called) - self.assert_(self.b_called) - self.assert_(handler_b_exception_raised) - - def setUp(self): - # Install handlers. - self.hup = signal.signal(signal.SIGHUP, self.handlerA) - self.usr1 = signal.signal(signal.SIGUSR1, self.handlerB) - self.usr2 = signal.signal(signal.SIGUSR2, signal.SIG_IGN) - self.alrm = signal.signal(signal.SIGALRM, - signal.default_int_handler) - self.a_called = False - self.b_called = False - self.pid = os.getpid() - self.fork_pid = self.spawn_force_test_exit_process(self.pid) - - def tearDown(self): - # Forcibly kill the child we created to ping us if there was a - # test error. - try: - # Make sure we don't kill ourself if there was a fork - # error. - if self.fork_pid > 0: - os.kill(self.fork_pid, signal.SIGKILL) except: - # If the child killed us, it has probably exited. Killing - # a non-existent process will raise an error which we - # don't care about. - pass - - # Restore handlers. - signal.alarm(0) # cancel alarm in case we died early - signal.signal(signal.SIGHUP, self.hup) - signal.signal(signal.SIGUSR1, self.usr1) - signal.signal(signal.SIGUSR2, self.usr2) - signal.signal(signal.SIGALRM, self.alrm) + self.fail("Some other exception woke us from pause: %s" % + traceback.format_exc()) + else: + self.fail("pause returned of its own accord, and the signal" + " didn't arrive after another second.") + + def test_main(self): + # This function spawns a child process to insulate the main + # test-running process from all the signals. It then + # communicates with that child process over a pipe and + # re-raises information about any exceptions the child + # throws. The real work happens in self.run_test(). + os_done_r, os_done_w = os.pipe() + with nested(closing(os.fdopen(os_done_r, 'rb')), + closing(os.fdopen(os_done_w, 'wb'))) as (done_r, done_w): + child = os.fork() + if child == 0: + # In the child process; run the test and report results + # through the pipe. + try: + done_r.close() + # Have to close done_w again here because + # exit_subprocess() will skip the enclosing with block. + with closing(done_w): + try: + self.run_test() + except: + pickle.dump(traceback.format_exc(), done_w) + else: + pickle.dump(None, done_w) + except: + print('Uh oh, raised from pickle.') + traceback.print_exc() + finally: + exit_subprocess() + + done_w.close() + # Block for up to MAX_DURATION seconds for the test to finish. + r, w, x = select.select([done_r], [], [], self.MAX_DURATION) + if done_r in r: + tb = pickle.load(done_r) + if tb: + self.fail(tb) + else: + os.kill(child, signal.SIGKILL) + self.fail('Test deadlocked after %d seconds.' % + self.MAX_DURATION) class BasicSignalTests(unittest.TestCase): + def trivial_signal_handler(self, *args): + pass + def test_out_of_range_signal_number_raises_error(self): self.assertRaises(ValueError, signal.getsignal, 4242) - def trivial_signal_handler(*args): - pass - self.assertRaises(ValueError, signal.signal, 4242, - trivial_signal_handler) + self.trivial_signal_handler) def test_setting_signal_handler_to_none_raises_error(self): self.assertRaises(TypeError, signal.signal, signal.SIGUSR1, None) + def test_getsignal(self): + hup = signal.signal(signal.SIGHUP, self.trivial_signal_handler) + self.assertEquals(signal.getsignal(signal.SIGHUP), + self.trivial_signal_handler) + signal.signal(signal.SIGHUP, hup) + self.assertEquals(signal.getsignal(signal.SIGHUP), hup) + + class WakeupSignalTests(unittest.TestCase): TIMEOUT_FULL = 10 TIMEOUT_HALF = 5 @@ -211,14 +249,143 @@ os.close(self.write) signal.signal(signal.SIGALRM, self.alrm) +class SiginterruptTest(unittest.TestCase): + signum = signal.SIGUSR1 + def readpipe_interrupted(self, cb): + r, w = os.pipe() + ppid = os.getpid() + pid = os.fork() + + oldhandler = signal.signal(self.signum, lambda x,y: None) + cb() + if pid==0: + # child code: sleep, kill, sleep. and then exit, + # which closes the pipe from which the parent process reads + try: + time.sleep(0.2) + os.kill(ppid, self.signum) + time.sleep(0.2) + finally: + exit_subprocess() -def test_main(): - if sys.platform[:3] in ('win', 'os2'): - raise test_support.TestSkipped("Can't test signal on %s" % \ - sys.platform) + try: + os.close(w) + + try: + d=os.read(r, 1) + return False + except OSError as err: + if err.errno != errno.EINTR: + raise + return True + finally: + signal.signal(self.signum, oldhandler) + os.waitpid(pid, 0) + + def test_without_siginterrupt(self): + i=self.readpipe_interrupted(lambda: None) + self.assertEquals(i, True) + + def test_siginterrupt_on(self): + i=self.readpipe_interrupted(lambda: signal.siginterrupt(self.signum, 1)) + self.assertEquals(i, True) + + def test_siginterrupt_off(self): + i=self.readpipe_interrupted(lambda: signal.siginterrupt(self.signum, 0)) + self.assertEquals(i, False) + +class ItimerTest(unittest.TestCase): + def setUp(self): + self.hndl_called = False + self.hndl_count = 0 + self.itimer = None + self.old_alarm = signal.signal(signal.SIGALRM, self.sig_alrm) + + def tearDown(self): + signal.signal(signal.SIGALRM, self.old_alarm) + if self.itimer is not None: # test_itimer_exc doesn't change this attr + # just ensure that itimer is stopped + signal.setitimer(self.itimer, 0) + def sig_alrm(self, *args): + self.hndl_called = True + if test_support.verbose: + print("SIGALRM handler invoked", args) + + def sig_vtalrm(self, *args): + self.hndl_called = True + + if self.hndl_count > 3: + # it shouldn't be here, because it should have been disabled. + raise signal.ItimerError("setitimer didn't disable ITIMER_VIRTUAL " + "timer.") + elif self.hndl_count == 3: + # disable ITIMER_VIRTUAL, this function shouldn't be called anymore + signal.setitimer(signal.ITIMER_VIRTUAL, 0) + if test_support.verbose: + print("last SIGVTALRM handler call") + + self.hndl_count += 1 + + if test_support.verbose: + print("SIGVTALRM handler invoked", args) + + def sig_prof(self, *args): + self.hndl_called = True + signal.setitimer(signal.ITIMER_PROF, 0) + + if test_support.verbose: + print("SIGPROF handler invoked", args) + + def test_itimer_exc(self): + # XXX I'm assuming -1 is an invalid itimer, but maybe some platform + # defines it ? + self.assertRaises(signal.ItimerError, signal.setitimer, -1, 0) + # Negative times are treated as zero on some platforms. + if 0: + self.assertRaises(signal.ItimerError, + signal.setitimer, signal.ITIMER_REAL, -1) + + def test_itimer_real(self): + self.itimer = signal.ITIMER_REAL + signal.setitimer(self.itimer, 1.0) + if test_support.verbose: + print("\ncall pause()...") + signal.pause() + + self.assertEqual(self.hndl_called, True) + + def test_itimer_virtual(self): + self.itimer = signal.ITIMER_VIRTUAL + signal.signal(signal.SIGVTALRM, self.sig_vtalrm) + signal.setitimer(self.itimer, 0.3, 0.2) + + for i in range(100000000): + if signal.getitimer(self.itimer) == (0.0, 0.0): + break # sig_vtalrm handler stopped this itimer + + # virtual itimer should be (0.0, 0.0) now + self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0)) + # and the handler should have been called + self.assertEquals(self.hndl_called, True) + + def test_itimer_prof(self): + self.itimer = signal.ITIMER_PROF + signal.signal(signal.SIGPROF, self.sig_prof) + signal.setitimer(self.itimer, 0.2, 0.2) + + for i in range(100000000): + if signal.getitimer(self.itimer) == (0.0, 0.0): + break # sig_prof handler stopped this itimer + + # profiling itimer should be (0.0, 0.0) now + self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0)) + # and the handler should have been called + self.assertEqual(self.hndl_called, True) + +def test_main(): test_support.run_unittest(BasicSignalTests, InterProcessSignalTests, - WakeupSignalTests) + WakeupSignalTests, SiginterruptTest, ItimerTest) if __name__ == "__main__": Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_site.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_site.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_site.py Wed Apr 30 15:57:13 2008 @@ -5,12 +5,11 @@ """ import unittest -from test.test_support import TestSkipped, TestFailed, run_unittest, TESTFN +from test.test_support import TestSkipped, run_unittest, TESTFN import builtins import os import sys import encodings -import tempfile # Need to make sure to not import 'site' if someone specified ``-S`` at the # command-line. Detect this by just making sure 'site' has not been imported # already. Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_smtplib.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_smtplib.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_smtplib.py Wed Apr 30 15:57:13 2008 @@ -12,20 +12,12 @@ from unittest import TestCase from test import test_support -# PORT is used to communicate the port number assigned to the server -# to the test client -HOST = "localhost" -PORT = None +HOST = test_support.HOST -def server(evt, buf): +def server(evt, buf, serv): + serv.listen(5) + evt.set() try: - serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - serv.settimeout(3) - serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - serv.bind(("", 0)) - global PORT - PORT = serv.getsockname()[1] - serv.listen(5) conn, addr = serv.accept() except socket.timeout: pass @@ -38,75 +30,52 @@ buf = buf[sent:] n -= 1 - time.sleep(0.01) conn.close() finally: serv.close() - PORT = None evt.set() class GeneralTests(TestCase): def setUp(self): self.evt = threading.Event() - servargs = (self.evt, b"220 Hola mundo\n") + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.sock.settimeout(15) + self.port = test_support.bind_port(self.sock) + servargs = (self.evt, b"220 Hola mundo\n", self.sock) threading.Thread(target=server, args=servargs).start() - - # wait until server thread has assigned a port number - n = 500 - while PORT is None and n > 0: - time.sleep(0.01) - n -= 1 - - # wait a little longer (sometimes connections are refused - # on slow machines without this additional wait) - time.sleep(0.5) + self.evt.wait() + self.evt.clear() def tearDown(self): self.evt.wait() def testBasic1(self): # connects - smtp = smtplib.SMTP(HOST, PORT) + smtp = smtplib.SMTP(HOST, self.port) smtp.sock.close() def testBasic2(self): # connects, include port in host name - smtp = smtplib.SMTP("%s:%s" % (HOST, PORT)) + smtp = smtplib.SMTP("%s:%s" % (HOST, self.port)) smtp.sock.close() - def testNotConnected(self): - # Test various operations on an unconnected SMTP object that - # should raise exceptions (at present the attempt in SMTP.send - # to reference the nonexistent 'sock' attribute of the SMTP object - # causes an AttributeError) - smtp = smtplib.SMTP() - self.assertRaises(AttributeError, smtp.ehlo) - self.assertRaises(AttributeError, smtp.send, 'test msg') - def testLocalHostName(self): # check that supplied local_hostname is used - smtp = smtplib.SMTP(HOST, PORT, local_hostname="testhost") + smtp = smtplib.SMTP(HOST, self.port, local_hostname="testhost") self.assertEqual(smtp.local_hostname, "testhost") smtp.sock.close() - def testNonnumericPort(self): - # check that non-numeric port raises socket.error - self.assertRaises(socket.error, smtplib.SMTP, - "localhost", "bogus") - self.assertRaises(socket.error, smtplib.SMTP, - "localhost:bogus") - def testTimeoutDefault(self): # default - smtp = smtplib.SMTP(HOST, PORT) + smtp = smtplib.SMTP(HOST, self.port) self.assertTrue(smtp.sock.gettimeout() is None) smtp.sock.close() def testTimeoutValue(self): # a value - smtp = smtplib.SMTP(HOST, PORT, timeout=30) + smtp = smtplib.SMTP(HOST, self.port, timeout=30) self.assertEqual(smtp.sock.gettimeout(), 30) smtp.sock.close() @@ -115,7 +84,7 @@ previous = socket.getdefaulttimeout() socket.setdefaulttimeout(30) try: - smtp = smtplib.SMTP(HOST, PORT, timeout=None) + smtp = smtplib.SMTP(HOST, self.port, timeout=None) finally: socket.setdefaulttimeout(previous) self.assertEqual(smtp.sock.gettimeout(), 30) @@ -123,10 +92,8 @@ # Test server thread using the specified SMTP server class -def debugging_server(server_class, serv_evt, client_evt): - serv = server_class(("", 0), ('nowhere', -1)) - global PORT - PORT = serv.getsockname()[1] +def debugging_server(serv, serv_evt, client_evt): + serv_evt.set() try: if hasattr(select, 'poll'): @@ -149,12 +116,11 @@ except socket.timeout: pass finally: - # allow some time for the client to read the result - time.sleep(0.5) - serv.close() + if not client_evt.isSet(): + # allow some time for the client to read the result + time.sleep(0.5) + serv.close() asyncore.close_all() - PORT = None - time.sleep(0.5) serv_evt.set() MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n' @@ -176,18 +142,14 @@ self.serv_evt = threading.Event() self.client_evt = threading.Event() - serv_args = (smtpd.DebuggingServer, self.serv_evt, self.client_evt) + self.port = test_support.find_unused_port() + self.serv = smtpd.DebuggingServer((HOST, self.port), ('nowhere', -1)) + serv_args = (self.serv, self.serv_evt, self.client_evt) threading.Thread(target=debugging_server, args=serv_args).start() # wait until server thread has assigned a port number - n = 500 - while PORT is None and n > 0: - time.sleep(0.01) - n -= 1 - - # wait a little longer (sometimes connections are refused - # on slow machines without this additional wait) - time.sleep(0.5) + self.serv_evt.wait() + self.serv_evt.clear() def tearDown(self): # indicate that the client is finished @@ -199,31 +161,31 @@ def testBasic(self): # connect - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) smtp.quit() def testNOOP(self): - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) expected = (250, b'Ok') self.assertEqual(smtp.noop(), expected) smtp.quit() def testRSET(self): - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) expected = (250, b'Ok') self.assertEqual(smtp.rset(), expected) smtp.quit() def testNotImplemented(self): # EHLO isn't implemented in DebuggingServer - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) expected = (502, b'Error: command "EHLO" not implemented') self.assertEqual(smtp.ehlo(), expected) smtp.quit() def testVRFY(self): # VRFY isn't implemented in DebuggingServer - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) expected = (502, b'Error: command "VRFY" not implemented') self.assertEqual(smtp.vrfy('nobody at nowhere.com'), expected) self.assertEqual(smtp.verify('nobody at nowhere.com'), expected) @@ -232,21 +194,21 @@ def testSecondHELO(self): # check that a second HELO returns a message that it's a duplicate # (this behavior is specific to smtpd.SMTPChannel) - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) smtp.helo() expected = (503, b'Duplicate HELO/EHLO') self.assertEqual(smtp.helo(), expected) smtp.quit() def testHELP(self): - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) self.assertEqual(smtp.help(), b'Error: command "HELP" not implemented') smtp.quit() def testSend(self): # connect and send mail m = 'A test message' - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) smtp.sendmail('John', 'Sally', m) smtp.quit() @@ -257,6 +219,26 @@ self.assertEqual(self.output.getvalue(), mexpect) +class NonConnectingTests(TestCase): + + def testNotConnected(self): + # Test various operations on an unconnected SMTP object that + # should raise exceptions (at present the attempt in SMTP.send + # to reference the nonexistent 'sock' attribute of the SMTP object + # causes an AttributeError) + smtp = smtplib.SMTP() + self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo) + self.assertRaises(smtplib.SMTPServerDisconnected, + smtp.send, 'test msg') + + def testNonnumericPort(self): + # check that non-numeric port raises socket.error + self.assertRaises(socket.error, smtplib.SMTP, + "localhost", "bogus") + self.assertRaises(socket.error, smtplib.SMTP, + "localhost:bogus") + + # test response of client to a non-successful HELO message class BadHELOServerTests(TestCase): @@ -266,18 +248,13 @@ sys.stdout = self.output self.evt = threading.Event() - servargs = (self.evt, b"199 no hello for you!\n") + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.sock.settimeout(15) + self.port = test_support.bind_port(self.sock) + servargs = (self.evt, b"199 no hello for you!\n", self.sock) threading.Thread(target=server, args=servargs).start() - - # wait until server thread has assigned a port number - n = 500 - while PORT is None and n > 0: - time.sleep(0.01) - n -= 1 - - # wait a little longer (sometimes connections are refused - # on slow machines without this additional wait) - time.sleep(0.5) + self.evt.wait() + self.evt.clear() def tearDown(self): self.evt.wait() @@ -285,7 +262,7 @@ def testFailingHELO(self): self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP, - HOST, PORT, 'localhost', 3) + HOST, self.port, 'localhost', 3) sim_users = {'Mr.A at somewhere.com':'John A', @@ -350,18 +327,14 @@ def setUp(self): self.serv_evt = threading.Event() self.client_evt = threading.Event() - serv_args = (SimSMTPServer, self.serv_evt, self.client_evt) + self.port = test_support.find_unused_port() + self.serv = SimSMTPServer((HOST, self.port), ('nowhere', -1)) + serv_args = (self.serv, self.serv_evt, self.client_evt) threading.Thread(target=debugging_server, args=serv_args).start() # wait until server thread has assigned a port number - n = 500 - while PORT is None and n > 0: - time.sleep(0.01) - n -= 1 - - # wait a little longer (sometimes connections are refused - # on slow machines without this additional wait) - time.sleep(0.5) + self.serv_evt.wait() + self.serv_evt.clear() def tearDown(self): # indicate that the client is finished @@ -371,11 +344,11 @@ def testBasic(self): # smoke test - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15) smtp.quit() def testEHLO(self): - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15) # no features should be present before the EHLO self.assertEqual(smtp.esmtp_features, {}) @@ -396,7 +369,7 @@ smtp.quit() def testVRFY(self): - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15) for email, name in sim_users.items(): expected_known = (250, bytes('%s %s' % @@ -411,7 +384,7 @@ smtp.quit() def testEXPN(self): - smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3) + smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15) for listname, members in sim_lists.items(): users = [] @@ -429,6 +402,7 @@ def test_main(verbose=None): test_support.run_unittest(GeneralTests, DebuggingServerTests, + NonConnectingTests, BadHELOServerTests, SMTPSimTests) if __name__ == '__main__': Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_socket.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_socket.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_socket.py Wed Apr 30 15:57:13 2008 @@ -3,10 +3,12 @@ import unittest from test import test_support +import errno import socket import select -import time import thread, threading +import time +import traceback import Queue import sys import os @@ -14,17 +16,14 @@ from weakref import proxy import signal -PORT = 50007 -HOST = 'localhost' +HOST = test_support.HOST MSG = b'Michael Gilfix was here\n' class SocketTCPTest(unittest.TestCase): def setUp(self): self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - global PORT - PORT = test_support.bind_port(self.serv, HOST, PORT) + self.port = test_support.bind_port(self.serv) self.serv.listen(1) def tearDown(self): @@ -35,9 +34,7 @@ def setUp(self): self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - global PORT - PORT = test_support.bind_port(self.serv, HOST, PORT) + self.port = test_support.bind_port(self.serv) def tearDown(self): self.serv.close() @@ -189,7 +186,7 @@ def clientSetUp(self): ThreadedTCPSocketTest.clientSetUp(self) - self.cli.connect((HOST, PORT)) + self.cli.connect((HOST, self.port)) self.serv_conn = self.cli def clientTearDown(self): @@ -469,16 +466,23 @@ # XXX The following don't test module-level functionality... def testSockName(self): - # Testing getsockname() + # Testing getsockname(). Use a temporary socket to elicit an unused + # ephemeral port that we can use later in the test. + tempsock = socket.socket() + tempsock.bind(("0.0.0.0", 0)) + (host, port) = tempsock.getsockname() + tempsock.close() + del tempsock + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.bind(("0.0.0.0", PORT+1)) + sock.bind(("0.0.0.0", port)) name = sock.getsockname() # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate # it reasonable to get the host's addr in addition to 0.0.0.0. # At least for eCos. This is required for the S/390 to pass. my_ip_addr = socket.gethostbyname(socket.gethostname()) self.assert_(name[0] in ("0.0.0.0", my_ip_addr), '%s invalid' % name[0]) - self.assertEqual(name[1], PORT+1) + self.assertEqual(name[1], port) def testGetSockOpt(self): # Testing getsockopt() @@ -614,7 +618,7 @@ self.assertEqual(msg, MSG) def _testSendtoAndRecv(self): - self.cli.sendto(MSG, 0, (HOST, PORT)) + self.cli.sendto(MSG, 0, (HOST, self.port)) def testRecvFrom(self): # Testing recvfrom() over UDP @@ -622,14 +626,14 @@ self.assertEqual(msg, MSG) def _testRecvFrom(self): - self.cli.sendto(MSG, 0, (HOST, PORT)) + self.cli.sendto(MSG, 0, (HOST, self.port)) def testRecvFromNegative(self): # Negative lengths passed to recvfrom should give ValueError. self.assertRaises(ValueError, self.serv.recvfrom, -1) def _testRecvFromNegative(self): - self.cli.sendto(MSG, 0, (HOST, PORT)) + self.cli.sendto(MSG, 0, (HOST, self.port)) class TCPCloserTest(ThreadedTCPSocketTest): @@ -647,7 +651,7 @@ conn.close() def _testClose(self): - self.cli.connect((HOST, PORT)) + self.cli.connect((HOST, self.port)) time.sleep(1.0) class BasicSocketPairTest(SocketPairTest): @@ -705,7 +709,7 @@ def _testAccept(self): time.sleep(0.1) - self.cli.connect((HOST, PORT)) + self.cli.connect((HOST, self.port)) def testConnect(self): # Testing non-blocking connect @@ -713,7 +717,7 @@ def _testConnect(self): self.cli.settimeout(10) - self.cli.connect((HOST, PORT)) + self.cli.connect((HOST, self.port)) def testRecv(self): # Testing non-blocking recv @@ -733,7 +737,7 @@ self.fail("Error during select call to non-blocking socket.") def _testRecv(self): - self.cli.connect((HOST, PORT)) + self.cli.connect((HOST, self.port)) time.sleep(0.1) self.cli.send(MSG) @@ -882,7 +886,9 @@ """Prove network connection.""" def clientSetUp(self): - self.cli = socket.create_connection((HOST, PORT)) + # We're inherited below by BasicTCPTest2, which also inherits + # BasicTCPTest, which defines self.port referenced below. + self.cli = socket.create_connection((HOST, self.port)) self.serv_conn = self.cli class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest): @@ -892,7 +898,11 @@ class NetworkConnectionNoServer(unittest.TestCase): def testWithoutServer(self): - self.failUnlessRaises(socket.error, lambda: socket.create_connection((HOST, PORT))) + port = test_support.find_unused_port() + self.failUnlessRaises( + socket.error, + lambda: socket.create_connection((HOST, port)) + ) class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest): @@ -913,22 +923,22 @@ testFamily = _justAccept def _testFamily(self): - self.cli = socket.create_connection((HOST, PORT), timeout=30) + self.cli = socket.create_connection((HOST, self.port), timeout=30) self.assertEqual(self.cli.family, 2) testTimeoutDefault = _justAccept def _testTimeoutDefault(self): - self.cli = socket.create_connection((HOST, PORT)) + self.cli = socket.create_connection((HOST, self.port)) self.assertTrue(self.cli.gettimeout() is None) testTimeoutValueNamed = _justAccept def _testTimeoutValueNamed(self): - self.cli = socket.create_connection((HOST, PORT), timeout=30) + self.cli = socket.create_connection((HOST, self.port), timeout=30) self.assertEqual(self.cli.gettimeout(), 30) testTimeoutValueNonamed = _justAccept def _testTimeoutValueNonamed(self): - self.cli = socket.create_connection((HOST, PORT), 30) + self.cli = socket.create_connection((HOST, self.port), 30) self.assertEqual(self.cli.gettimeout(), 30) testTimeoutNone = _justAccept @@ -936,7 +946,7 @@ previous = socket.getdefaulttimeout() socket.setdefaulttimeout(30) try: - self.cli = socket.create_connection((HOST, PORT), timeout=None) + self.cli = socket.create_connection((HOST, self.port), timeout=None) finally: socket.setdefaulttimeout(previous) self.assertEqual(self.cli.gettimeout(), 30) @@ -963,12 +973,12 @@ testOutsideTimeout = testInsideTimeout def _testInsideTimeout(self): - self.cli = sock = socket.create_connection((HOST, PORT)) + self.cli = sock = socket.create_connection((HOST, self.port)) data = sock.recv(5) self.assertEqual(data, b"done!") def _testOutsideTimeout(self): - self.cli = sock = socket.create_connection((HOST, PORT), timeout=1) + self.cli = sock = socket.create_connection((HOST, self.port), timeout=1) self.failUnlessRaises(socket.timeout, lambda: sock.recv(5)) @@ -1016,10 +1026,13 @@ except Alarm: pass except: - self.fail("caught other exception instead of Alarm") + self.fail("caught other exception instead of Alarm:" + " %s(%s):\n%s" % + (sys.exc_info()[:2] + (traceback.format_exc(),))) else: self.fail("nothing caught") - signal.alarm(0) # shut off alarm + finally: + signal.alarm(0) # shut off alarm except Alarm: self.fail("got Alarm in wrong place") finally: Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_socketserver.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_socketserver.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_socketserver.py Wed Apr 30 15:57:13 2008 @@ -1,44 +1,36 @@ -# Test suite for SocketServer.py +""" +Test suite for SocketServer.py. +""" -from test import test_support -from test.test_support import (verbose, verify, TESTFN, TestSkipped, - reap_children) -test_support.requires('network') - -from SocketServer import * -import socket +import contextlib import errno +import imp +import os import select -import time +import signal +import socket +import tempfile import threading -import os +import time +import unittest +import SocketServer + +import test.test_support +from test.test_support import reap_children, verbose, TestSkipped +from test.test_support import TESTFN as TEST_FILE -NREQ = 3 -DELAY = 0.5 +test.test_support.requires("network") -class MyMixinHandler: - def handle(self): - time.sleep(DELAY) - line = self.rfile.readline() - time.sleep(DELAY) - self.wfile.write(line) - -class MyStreamHandler(MyMixinHandler, StreamRequestHandler): - pass - -class MyDatagramHandler(MyMixinHandler, DatagramRequestHandler): - pass - -class MyMixinServer: - def serve_a_few(self): - for i in range(NREQ): - self.handle_request() - def handle_error(self, request, client_address): - self.close_request(request) - self.server_close() - raise +TEST_STR = b"hello world\n" +HOST = test.test_support.HOST -teststring = b"hello world\n" +HAVE_UNIX_SOCKETS = hasattr(socket, "AF_UNIX") +HAVE_FORKING = hasattr(os, "fork") and os.name != "os2" + +def signal_alarm(n): + """Call signal.alarm when it exists (i.e. not on Windows).""" + if hasattr(signal, 'alarm'): + signal.alarm(n) def receive(sock, n, timeout=20): r, w, x = select.select([sock], [], [], timeout) @@ -47,177 +39,218 @@ else: raise RuntimeError("timed out on %r" % (sock,)) -def testdgram(proto, addr): - s = socket.socket(proto, socket.SOCK_DGRAM) - s.sendto(teststring, addr) - buf = data = receive(s, 100) - while data and b'\n' not in buf: - data = receive(s, 100) - buf += data - verify(buf == teststring) - s.close() - -def teststream(proto, addr): - s = socket.socket(proto, socket.SOCK_STREAM) - s.connect(addr) - s.sendall(teststring) - buf = data = receive(s, 100) - while data and b'\n' not in buf: - data = receive(s, 100) - buf += data - verify(buf == teststring) - s.close() - -class ServerThread(threading.Thread): - def __init__(self, addr, svrcls, hdlrcls): - threading.Thread.__init__(self) - self.__addr = addr - self.__svrcls = svrcls - self.__hdlrcls = hdlrcls - self.ready = threading.Event() - def run(self): - class svrcls(MyMixinServer, self.__svrcls): - pass - if verbose: print("thread: creating server") - svr = svrcls(self.__addr, self.__hdlrcls) - # pull the address out of the server in case it changed - # this can happen if another process is using the port - addr = svr.server_address - if addr: - self.__addr = addr - if self.__addr != svr.socket.getsockname(): - raise RuntimeError('server_address was %s, expected %s' % - (self.__addr, svr.socket.getsockname())) - self.ready.set() - if verbose: print("thread: serving three times") - svr.serve_a_few() - if verbose: print("thread: done") - -seed = 0 -def pickport(): - global seed - seed += 1 - return 10000 + (os.getpid() % 1000)*10 + seed - -host = "localhost" -testfiles = [] -def pickaddr(proto): - if proto == socket.AF_INET: - return (host, pickport()) - else: - fn = TESTFN + str(pickport()) - if os.name == 'os2': - # AF_UNIX socket names on OS/2 require a specific prefix - # which can't include a drive letter and must also use - # backslashes as directory separators - if fn[1] == ':': - fn = fn[2:] - if fn[0] in (os.sep, os.altsep): - fn = fn[1:] - fn = os.path.join('\socket', fn) - if os.sep == '/': - fn = fn.replace(os.sep, os.altsep) - else: - fn = fn.replace(os.altsep, os.sep) - testfiles.append(fn) - return fn - -def cleanup(): - for fn in testfiles: - try: - os.remove(fn) - except os.error: - pass - testfiles[:] = [] - -def testloop(proto, servers, hdlrcls, testfunc): - for svrcls in servers: - addr = pickaddr(proto) +if HAVE_UNIX_SOCKETS: + class ForkingUnixStreamServer(SocketServer.ForkingMixIn, + SocketServer.UnixStreamServer): + pass + + class ForkingUnixDatagramServer(SocketServer.ForkingMixIn, + SocketServer.UnixDatagramServer): + pass + + + at contextlib.contextmanager +def simple_subprocess(testcase): + pid = os.fork() + if pid == 0: + # Don't throw an exception; it would be caught by the test harness. + os._exit(72) + yield None + pid2, status = os.waitpid(pid, 0) + testcase.assertEquals(pid2, pid) + testcase.assertEquals(72 << 8, status) + + +class SocketServerTest(unittest.TestCase): + """Test all socket servers.""" + + def setUp(self): + signal_alarm(20) # Kill deadlocks after 20 seconds. + self.port_seed = 0 + self.test_files = [] + + def tearDown(self): + signal_alarm(0) # Didn't deadlock. + reap_children() + + for fn in self.test_files: + try: + os.remove(fn) + except os.error: + pass + self.test_files[:] = [] + + def pickaddr(self, proto): + if proto == socket.AF_INET: + return (HOST, 0) + else: + # XXX: We need a way to tell AF_UNIX to pick its own name + # like AF_INET provides port==0. + dir = None + if os.name == 'os2': + dir = '\socket' + fn = tempfile.mktemp(prefix='unix_socket.', dir=dir) + if os.name == 'os2': + # AF_UNIX socket names on OS/2 require a specific prefix + # which can't include a drive letter and must also use + # backslashes as directory separators + if fn[1] == ':': + fn = fn[2:] + if fn[0] in (os.sep, os.altsep): + fn = fn[1:] + if os.sep == '/': + fn = fn.replace(os.sep, os.altsep) + else: + fn = fn.replace(os.altsep, os.sep) + self.test_files.append(fn) + return fn + + def make_server(self, addr, svrcls, hdlrbase): + class MyServer(svrcls): + def handle_error(self, request, client_address): + self.close_request(request) + self.server_close() + raise + + class MyHandler(hdlrbase): + def handle(self): + line = self.rfile.readline() + self.wfile.write(line) + + if verbose: print("creating server") + server = MyServer(addr, MyHandler) + self.assertEquals(server.server_address, server.socket.getsockname()) + return server + + def run_server(self, svrcls, hdlrbase, testfunc): + server = self.make_server(self.pickaddr(svrcls.address_family), + svrcls, hdlrbase) + # We had the OS pick a port, so pull the real address out of + # the server. + addr = server.server_address if verbose: print("ADDR =", addr) print("CLASS =", svrcls) - t = ServerThread(addr, svrcls, hdlrcls) - if verbose: print("server created") + + t = threading.Thread( + name='%s serving' % svrcls, + target=server.serve_forever, + # Short poll interval to make the test finish quickly. + # Time between requests is short enough that we won't wake + # up spuriously too many times. + kwargs={'poll_interval':0.01}) + t.setDaemon(True) # In case this function raises. t.start() if verbose: print("server running") - for i in range(NREQ): - t.ready.wait(10*DELAY) - if not t.ready.isSet(): - raise RuntimeError("Server not ready within a reasonable time") + for i in range(3): if verbose: print("test client", i) - testfunc(proto, addr) + testfunc(svrcls.address_family, addr) if verbose: print("waiting for server") + server.shutdown() t.join() if verbose: print("done") -class ForgivingTCPServer(TCPServer): - # prevent errors if another process is using the port we want - def server_bind(self): - host, default_port = self.server_address - # this code shamelessly stolen from test.test_support - # the ports were changed to protect the innocent - import sys - for port in [default_port, 3434, 8798, 23833]: - try: - self.server_address = host, port - TCPServer.server_bind(self) - break - except socket.error as e: - (err, msg) = e - if err != errno.EADDRINUSE: - raise - print(' WARNING: failed to listen on port %d, trying another' % port, file=sys.__stderr__) - -tcpservers = [ForgivingTCPServer, ThreadingTCPServer] -if hasattr(os, 'fork') and os.name not in ('os2',): - tcpservers.append(ForkingTCPServer) -udpservers = [UDPServer, ThreadingUDPServer] -if hasattr(os, 'fork') and os.name not in ('os2',): - udpservers.append(ForkingUDPServer) - -if not hasattr(socket, 'AF_UNIX'): - streamservers = [] - dgramservers = [] -else: - class ForkingUnixStreamServer(ForkingMixIn, UnixStreamServer): pass - streamservers = [UnixStreamServer, ThreadingUnixStreamServer] - if hasattr(os, 'fork') and os.name not in ('os2',): - streamservers.append(ForkingUnixStreamServer) - class ForkingUnixDatagramServer(ForkingMixIn, UnixDatagramServer): pass - dgramservers = [UnixDatagramServer, ThreadingUnixDatagramServer] - if hasattr(os, 'fork') and os.name not in ('os2',): - dgramservers.append(ForkingUnixDatagramServer) - -def sloppy_cleanup(): - # See http://python.org/sf/1540386 - # We need to reap children here otherwise a child from one server - # can be left running for the next server and cause a test failure. - time.sleep(DELAY) - reap_children() - -def testall(): - testloop(socket.AF_INET, tcpservers, MyStreamHandler, teststream) - sloppy_cleanup() - testloop(socket.AF_INET, udpservers, MyDatagramHandler, testdgram) - if hasattr(socket, 'AF_UNIX'): - sloppy_cleanup() - testloop(socket.AF_UNIX, streamservers, MyStreamHandler, teststream) - # Alas, on Linux (at least) recvfrom() doesn't return a meaningful - # client address so this cannot work: - ##testloop(socket.AF_UNIX, dgramservers, MyDatagramHandler, testdgram) + def stream_examine(self, proto, addr): + s = socket.socket(proto, socket.SOCK_STREAM) + s.connect(addr) + s.sendall(TEST_STR) + buf = data = receive(s, 100) + while data and b'\n' not in buf: + data = receive(s, 100) + buf += data + self.assertEquals(buf, TEST_STR) + s.close() + + def dgram_examine(self, proto, addr): + s = socket.socket(proto, socket.SOCK_DGRAM) + s.sendto(TEST_STR, addr) + buf = data = receive(s, 100) + while data and b'\n' not in buf: + data = receive(s, 100) + buf += data + self.assertEquals(buf, TEST_STR) + s.close() + + def test_TCPServer(self): + self.run_server(SocketServer.TCPServer, + SocketServer.StreamRequestHandler, + self.stream_examine) + + def test_ThreadingTCPServer(self): + self.run_server(SocketServer.ThreadingTCPServer, + SocketServer.StreamRequestHandler, + self.stream_examine) + + if HAVE_FORKING: + def test_ForkingTCPServer(self): + with simple_subprocess(self): + self.run_server(SocketServer.ForkingTCPServer, + SocketServer.StreamRequestHandler, + self.stream_examine) + + if HAVE_UNIX_SOCKETS: + def test_UnixStreamServer(self): + self.run_server(SocketServer.UnixStreamServer, + SocketServer.StreamRequestHandler, + self.stream_examine) + + def test_ThreadingUnixStreamServer(self): + self.run_server(SocketServer.ThreadingUnixStreamServer, + SocketServer.StreamRequestHandler, + self.stream_examine) + + if HAVE_FORKING: + def test_ForkingUnixStreamServer(self): + with simple_subprocess(self): + self.run_server(ForkingUnixStreamServer, + SocketServer.StreamRequestHandler, + self.stream_examine) + + def test_UDPServer(self): + self.run_server(SocketServer.UDPServer, + SocketServer.DatagramRequestHandler, + self.dgram_examine) + + def test_ThreadingUDPServer(self): + self.run_server(SocketServer.ThreadingUDPServer, + SocketServer.DatagramRequestHandler, + self.dgram_examine) + + if HAVE_FORKING: + def test_ForkingUDPServer(self): + with simple_subprocess(self): + self.run_server(SocketServer.ForkingUDPServer, + SocketServer.DatagramRequestHandler, + self.dgram_examine) + + # Alas, on Linux (at least) recvfrom() doesn't return a meaningful + # client address so this cannot work: + + # if HAVE_UNIX_SOCKETS: + # def test_UnixDatagramServer(self): + # self.run_server(SocketServer.UnixDatagramServer, + # SocketServer.DatagramRequestHandler, + # self.dgram_examine) + # + # def test_ThreadingUnixDatagramServer(self): + # self.run_server(SocketServer.ThreadingUnixDatagramServer, + # SocketServer.DatagramRequestHandler, + # self.dgram_examine) + # + # if HAVE_FORKING: + # def test_ForkingUnixDatagramServer(self): + # self.run_server(SocketServer.ForkingUnixDatagramServer, + # SocketServer.DatagramRequestHandler, + # self.dgram_examine) + def test_main(): - import imp if imp.lock_held(): - # If the import lock is held, the threads will hang. + # If the import lock is held, the threads will hang raise TestSkipped("can't run when import lock is held") - reap_children() - try: - testall() - finally: - cleanup() - reap_children() + test.test_support.run_unittest(SocketServerTest) if __name__ == "__main__": test_main() + signal_alarm(3) # Shutdown shouldn't take more than 3 seconds. Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_sort.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_sort.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_sort.py Wed Apr 30 15:57:13 2008 @@ -6,6 +6,15 @@ verbose = test_support.verbose nerrors = 0 +def CmpToKey(mycmp): + 'Convert a cmp= function into a key= function' + class K(object): + def __init__(self, obj): + self.obj = obj + def __lt__(self, other): + return mycmp(self.obj, other.obj) == -1 + return K + def check(tag, expected, raw, compare=None): global nerrors @@ -14,7 +23,7 @@ orig = raw[:] # save input in case of error if compare: - raw.sort(compare) + raw.sort(key=CmpToKey(compare)) else: raw.sort() @@ -99,7 +108,7 @@ print(" Checking against an insane comparison function.") print(" If the implementation isn't careful, this may segfault.") s = x[:] - s.sort(lambda a, b: int(random.random() * 3) - 1) + s.sort(key=CmpToKey(lambda a, b: int(random.random() * 3) - 1)) check("an insane function left some permutation", x, s) x = [Complains(i) for i in x] @@ -141,14 +150,6 @@ L = [C() for i in range(50)] self.assertRaises(ValueError, L.sort) - def test_cmpNone(self): - # Testing None as a comparison function. - - L = list(range(50)) - random.shuffle(L) - L.sort(None) - self.assertEqual(L, list(range(50))) - def test_undetected_mutation(self): # Python 2.4a1 did not always detect mutation memorywaster = [] @@ -158,12 +159,12 @@ L.pop() return cmp(x, y) L = [1,2] - self.assertRaises(ValueError, L.sort, mutating_cmp) + self.assertRaises(ValueError, L.sort, key=CmpToKey(mutating_cmp)) def mutating_cmp(x, y): L.append(3) del L[:] return cmp(x, y) - self.assertRaises(ValueError, L.sort, mutating_cmp) + self.assertRaises(ValueError, L.sort, key=CmpToKey(mutating_cmp)) memorywaster = [memorywaster] #============================================================================== @@ -175,11 +176,11 @@ copy = data[:] random.shuffle(data) data.sort(key=str.lower) - copy.sort(cmp=lambda x,y: cmp(x.lower(), y.lower())) + copy.sort(key=CmpToKey(lambda x,y: cmp(x.lower(), y.lower()))) def test_baddecorator(self): data = 'The quick Brown fox Jumped over The lazy Dog'.split() - self.assertRaises(TypeError, data.sort, None, lambda x,y: 0) + self.assertRaises(TypeError, data.sort, key=lambda x,y: 0) def test_stability(self): data = [(random.randrange(100), i) for i in range(200)] @@ -188,25 +189,11 @@ copy.sort() # sort using both fields self.assertEqual(data, copy) # should get the same result - def test_cmp_and_key_combination(self): - # Verify that the wrapper has been removed - def compare(x, y): - self.assertEqual(type(x), str) - self.assertEqual(type(x), str) - return cmp(x, y) - data = 'The quick Brown fox Jumped over The lazy Dog'.split() - data.sort(cmp=compare, key=str.lower) - - def test_badcmp_with_key(self): - # Verify that the wrapper has been removed - data = 'The quick Brown fox Jumped over The lazy Dog'.split() - self.assertRaises(TypeError, data.sort, "bad", str.lower) - def test_key_with_exception(self): # Verify that the wrapper has been removed data = list(range(-2, 2)) dup = data[:] - self.assertRaises(ZeroDivisionError, data.sort, None, lambda x: 1/x) + self.assertRaises(ZeroDivisionError, data.sort, key=lambda x: 1/x) self.assertEqual(data, dup) def test_key_with_mutation(self): @@ -254,14 +241,13 @@ random.shuffle(data) data.sort(reverse=True) self.assertEqual(data, list(range(99,-1,-1))) - self.assertRaises(TypeError, data.sort, "wrong type") def test_reverse_stability(self): data = [(random.randrange(100), i) for i in range(200)] copy1 = data[:] copy2 = data[:] - data.sort(cmp=lambda x,y: cmp(x[0],y[0]), reverse=True) - copy1.sort(cmp=lambda x,y: cmp(y[0],x[0])) + data.sort(key=CmpToKey(lambda x,y: cmp(x[0],y[0])), reverse=True) + copy1.sort(key=CmpToKey(lambda x,y: cmp(y[0],x[0]))) self.assertEqual(data, copy1) copy2.sort(key=lambda x: x[0], reverse=True) self.assertEqual(data, copy2) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_sqlite.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_sqlite.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_sqlite.py Wed Apr 30 15:57:13 2008 @@ -1,17 +1,17 @@ from test.test_support import run_unittest, TestSkipped -import unittest try: import _sqlite3 except ImportError: raise TestSkipped('no sqlite available') from sqlite3.test import (dbapi, types, userfunctions, - factory, transactions, hooks, regression) + factory, transactions, hooks, regression, + dump) def test_main(): run_unittest(dbapi.suite(), types.suite(), userfunctions.suite(), - factory.suite(), transactions.suite(), hooks.suite(), - regression.suite()) + factory.suite(), transactions.suite(), + hooks.suite(), regression.suite(), dump.suite()) if __name__ == "__main__": test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_ssl.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_ssl.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_ssl.py Wed Apr 30 15:57:13 2008 @@ -25,11 +25,10 @@ except ImportError: skip_expected = True +HOST = test_support.HOST CERTFILE = None SVN_PYTHON_ORG_ROOT_CERT = None -TESTPORT = 10025 - def handle_error(prefix): exc_format = ' '.join(traceback.format_exception(*sys.exc_info())) if test_support.verbose: @@ -299,7 +298,7 @@ except: handle_error('') - def __init__(self, port, certificate, ssl_version=None, + def __init__(self, certificate, ssl_version=None, certreqs=None, cacerts=None, expect_bad_connects=False, chatty=True, connectionchatty=False, starttls_server=False): if ssl_version is None: @@ -315,12 +314,8 @@ self.connectionchatty = connectionchatty self.starttls_server = starttls_server self.sock = socket.socket() + self.port = test_support.bind_port(self.sock) self.flag = None - if hasattr(socket, 'SO_REUSEADDR'): - self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - if hasattr(socket, 'SO_REUSEPORT'): - self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) - self.sock.bind(('127.0.0.1', port)) self.active = False threading.Thread.__init__(self) self.setDaemon(False) @@ -368,6 +363,7 @@ # we assume the certfile contains both private key and certificate self.certfile = certfile self.active = False + self.active_lock = threading.Lock() self.allow_reuse_address = True def __str__(self): @@ -398,23 +394,33 @@ # We want this to run in a thread, so we use a slightly # modified version of "forever". self.active = True - while self.active: + while 1: try: - self.handle_request() + # We need to lock while handling the request. + # Another thread can close the socket after self.active + # has been checked and before the request is handled. + # This causes an exception when using the closed socket. + with self.active_lock: + if not self.active: + break + self.handle_request() except socket.timeout: pass except KeyboardInterrupt: self.server_close() return except: - sys.stdout.write(''.join(traceback.format_exception(*sys.exc_info()))); + sys.stdout.write(''.join(traceback.format_exception(*sys.exc_info()))) + break + time.sleep(0.1) def server_close(self): # Again, we want this to run in a thread, so we need to override # close to clear the "active" flag, so that serve_forever() will # terminate. - HTTPServer.server_close(self) - self.active = False + with self.active_lock: + HTTPServer.server_close(self) + self.active = False class RootedHTTPRequestHandler(SimpleHTTPRequestHandler): @@ -460,12 +466,13 @@ format%args)) - def __init__(self, port, certfile): + def __init__(self, certfile): self.flag = None self.active = False self.RootedHTTPRequestHandler.root = os.path.split(CERTFILE)[0] + self.port = test_support.find_unused_port() self.server = self.HTTPSServer( - ('', port), self.RootedHTTPRequestHandler, certfile) + (HOST, self.port), self.RootedHTTPRequestHandler, certfile) threading.Thread.__init__(self) self.setDaemon(True) @@ -546,10 +553,11 @@ def handle_error(self): raise - def __init__(self, port, certfile): + def __init__(self, certfile): self.flag = None self.active = False - self.server = self.EchoServer(port, certfile) + self.port = test_support.find_unused_port() + self.server = self.EchoServer(self.port, certfile) threading.Thread.__init__(self) self.setDaemon(True) @@ -575,7 +583,7 @@ self.server.close() def badCertTest (certfile): - server = ThreadedEchoServer(TESTPORT, CERTFILE, + server = ThreadedEchoServer(CERTFILE, certreqs=ssl.CERT_REQUIRED, cacerts=CERTFILE, chatty=False, connectionchatty=False) @@ -589,7 +597,7 @@ s = ssl.wrap_socket(socket.socket(), certfile=certfile, ssl_version=ssl.PROTOCOL_TLSv1) - s.connect(('127.0.0.1', TESTPORT)) + s.connect((HOST, server.port)) except ssl.SSLError as x: if test_support.verbose: sys.stdout.write("\nSSLError is %s\n" % x) @@ -605,7 +613,7 @@ indata="FOO\n", chatty=False, connectionchatty=False): - server = ThreadedEchoServer(TESTPORT, certfile, + server = ThreadedEchoServer(certfile, certreqs=certreqs, ssl_version=protocol, cacerts=cacertsfile, @@ -625,7 +633,7 @@ ca_certs=cacertsfile, cert_reqs=certreqs, ssl_version=client_protocol) - s.connect(('127.0.0.1', TESTPORT)) + s.connect((HOST, server.port)) except ssl.SSLError as x: raise test_support.TestFailed("Unexpected SSL error: " + str(x)) except Exception as x: @@ -660,7 +668,7 @@ expectedToWork, certsreqs=None): - if certsreqs == None: + if certsreqs is None: certsreqs = ssl.CERT_NONE if certsreqs == ssl.CERT_NONE: @@ -705,7 +713,7 @@ if test_support.verbose: sys.stdout.write("\n") s2 = socket.socket() - server = ThreadedEchoServer(TESTPORT, CERTFILE, + server = ThreadedEchoServer(CERTFILE, certreqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_SSLv23, cacerts=CERTFILE, @@ -722,7 +730,7 @@ ca_certs=CERTFILE, cert_reqs=ssl.CERT_REQUIRED, ssl_version=ssl.PROTOCOL_SSLv23) - s.connect(('127.0.0.1', TESTPORT)) + s.connect((HOST, server.port)) except ssl.SSLError as x: raise test_support.TestFailed( "Unexpected SSL error: " + str(x)) @@ -749,7 +757,7 @@ not in cert['subject']): raise test_support.TestFailed( "Missing or invalid 'organizationName' field in certificate subject; " - "should be 'Python Software Foundation'."); + "should be 'Python Software Foundation'.") s.close() finally: server.stop() @@ -769,6 +777,7 @@ listener_ready = threading.Event() listener_gone = threading.Event() + port = test_support.find_unused_port() # `listener` runs in a thread. It opens a socket listening on # PORT, and sits in an accept() until the main thread connects. @@ -776,11 +785,7 @@ # to let the main thread know the socket is gone. def listener(): s = socket.socket() - if hasattr(socket, 'SO_REUSEADDR'): - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - if hasattr(socket, 'SO_REUSEPORT'): - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) - s.bind(('127.0.0.1', TESTPORT)) + s.bind((HOST, port)) s.listen(5) listener_ready.set() s.accept() @@ -790,7 +795,7 @@ def connector(): listener_ready.wait() s = socket.socket() - s.connect(('127.0.0.1', TESTPORT)) + s.connect((HOST, port)) listener_gone.wait() try: ssl_sock = ssl.wrap_socket(s) @@ -862,7 +867,7 @@ msgs = ("msg 1", "MSG 2", "STARTTLS", "MSG 3", "msg 4") - server = ThreadedEchoServer(TESTPORT, CERTFILE, + server = ThreadedEchoServer(CERTFILE, ssl_version=ssl.PROTOCOL_TLSv1, starttls_server=True, chatty=True, @@ -877,7 +882,7 @@ try: s = socket.socket() s.setblocking(1) - s.connect(('127.0.0.1', TESTPORT)) + s.connect((HOST, server.port)) except Exception as x: raise test_support.TestFailed("Unexpected exception: " + str(x)) else: @@ -925,7 +930,7 @@ def testSocketServer(self): - server = OurHTTPSServer(TESTPORT, CERTFILE) + server = OurHTTPSServer(CERTFILE) flag = threading.Event() server.start(flag) # wait for it to start @@ -937,8 +942,8 @@ d1 = open(CERTFILE, 'rb').read() d2 = '' # now fetch the same data from the HTTPS server - url = 'https://127.0.0.1:%d/%s' % ( - TESTPORT, os.path.split(CERTFILE)[1]) + url = 'https://%s:%d/%s' % ( + HOST, server.port, os.path.split(CERTFILE)[1]) f = urllib.urlopen(url) dlen = f.info().getheader("content-length") if dlen and (int(dlen) > 0): @@ -960,7 +965,11 @@ raise test_support.TestFailed( "Couldn't fetch data from HTTPS server") finally: + if test_support.verbose: + sys.stdout.write('stopping server\n') server.stop() + if test_support.verbose: + sys.stdout.write('joining thread\n') server.join() def testAsyncoreServer(self): @@ -969,7 +978,7 @@ sys.stdout.write("\n") indata="FOO\n" - server = AsyncoreEchoServer(TESTPORT, CERTFILE) + server = AsyncoreEchoServer(CERTFILE) flag = threading.Event() server.start(flag) # wait for it to start @@ -977,7 +986,7 @@ # try to connect try: s = ssl.wrap_socket(socket.socket()) - s.connect(('127.0.0.1', TESTPORT)) + s.connect((HOST, server.port)) except ssl.SSLError as x: raise test_support.TestFailed("Unexpected SSL error: " + str(x)) except Exception as x: @@ -1004,30 +1013,11 @@ server.stop() server.join() - -def findtestsocket(start, end): - def testbind(i): - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - try: - s.bind(("127.0.0.1", i)) - except: - return 0 - else: - return 1 - finally: - s.close() - - for i in range(start, end): - if testbind(i) and testbind(i+1): - return i - return 0 - - def test_main(verbose=False): if skip_expected: raise test_support.TestSkipped("No SSL support") - global CERTFILE, TESTPORT, SVN_PYTHON_ORG_ROOT_CERT + global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir, "keycert.pem") SVN_PYTHON_ORG_ROOT_CERT = os.path.join( @@ -1038,10 +1028,6 @@ not os.path.exists(SVN_PYTHON_ORG_ROOT_CERT)): raise test_support.TestFailed("Can't read certificate files!") - TESTPORT = findtestsocket(10025, 12000) - if not TESTPORT: - raise test_support.TestFailed("Can't find open port to test servers on!") - tests = [BasicTests] if test_support.is_resource_enabled('network'): Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_strftime.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_strftime.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_strftime.py Wed Apr 30 15:57:13 2008 @@ -1,158 +1,185 @@ -#! /usr/bin/env python +""" +Unittest for time.strftime +""" + +import calendar +import sys +import os +import re +from test import test_support +import time +import unittest -# Sanity checker for time.strftime -import time, calendar, sys, os, re -from test.test_support import verbose - -def main(): - global verbose - # For C Python, these tests expect C locale, so we try to set that - # explicitly. For Jython, Finn says we need to be in the US locale; my - # understanding is that this is the closest Java gets to C's "C" locale. - # Jython ought to supply an _locale module which Does The Right Thing, but - # this is the best we can do given today's state of affairs. - try: - import java - java.util.Locale.setDefault(java.util.Locale.US) - except ImportError: - # Can't do this first because it will succeed, even in Jython - import locale - locale.setlocale(locale.LC_TIME, 'C') - now = time.time() - strftest(now) - verbose = 0 - # Try a bunch of dates and times, chosen to vary through time of - # day and daylight saving time - for j in range(-5, 5): - for i in range(25): - strftest(now + (i + j*100)*23*3603) +# helper functions +def fixasctime(s): + if s[8] == ' ': + s = s[:8] + '0' + s[9:] + return s def escapestr(text, ampm): - """Escape text to deal with possible locale values that have regex - syntax while allowing regex syntax used for the comparison.""" + """ + Escape text to deal with possible locale values that have regex + syntax while allowing regex syntax used for comparison. + """ new_text = re.escape(text) new_text = new_text.replace(re.escape(ampm), ampm) - new_text = new_text.replace("\%", "%") - new_text = new_text.replace("\:", ":") - new_text = new_text.replace("\?", "?") + new_text = new_text.replace('\%', '%') + new_text = new_text.replace('\:', ':') + new_text = new_text.replace('\?', '?') return new_text -def strftest(now): - if verbose: - print("strftime test for", time.ctime(now)) - nowsecs = str(int(now))[:-1] - gmt = time.gmtime(now) - now = time.localtime(now) - - if now[3] < 12: ampm='(AM|am)' - else: ampm='(PM|pm)' - - jan1 = time.localtime(time.mktime((now[0], 1, 1, 0, 0, 0, 0, 1, 0))) - - try: - if now[8]: tz = time.tzname[1] - else: tz = time.tzname[0] - except AttributeError: - tz = '' - - if now[3] > 12: clock12 = now[3] - 12 - elif now[3] > 0: clock12 = now[3] - else: clock12 = 12 - - # Make sure any characters that could be taken as regex syntax is - # escaped in escapestr() - expectations = ( - ('%a', calendar.day_abbr[now[6]], 'abbreviated weekday name'), - ('%A', calendar.day_name[now[6]], 'full weekday name'), - ('%b', calendar.month_abbr[now[1]], 'abbreviated month name'), - ('%B', calendar.month_name[now[1]], 'full month name'), - # %c see below - ('%d', '%02d' % now[2], 'day of month as number (00-31)'), - ('%H', '%02d' % now[3], 'hour (00-23)'), - ('%I', '%02d' % clock12, 'hour (01-12)'), - ('%j', '%03d' % now[7], 'julian day (001-366)'), - ('%m', '%02d' % now[1], 'month as number (01-12)'), - ('%M', '%02d' % now[4], 'minute, (00-59)'), - ('%p', ampm, 'AM or PM as appropriate'), - ('%S', '%02d' % now[5], 'seconds of current time (00-60)'), - ('%U', '%02d' % ((now[7] + jan1[6])//7), - 'week number of the year (Sun 1st)'), - ('%w', '0?%d' % ((1+now[6]) % 7), 'weekday as a number (Sun 1st)'), - ('%W', '%02d' % ((now[7] + (jan1[6] - 1)%7)//7), - 'week number of the year (Mon 1st)'), - # %x see below - ('%X', '%02d:%02d:%02d' % (now[3], now[4], now[5]), '%H:%M:%S'), - ('%y', '%02d' % (now[0]%100), 'year without century'), - ('%Y', '%d' % now[0], 'year with century'), - # %Z see below - ('%%', '%', 'single percent sign'), - ) - nonstandard_expectations = ( - # These are standard but don't have predictable output - ('%c', fixasctime(time.asctime(now)), 'near-asctime() format'), - ('%x', '%02d/%02d/%02d' % (now[1], now[2], (now[0]%100)), - '%m/%d/%y %H:%M:%S'), - ('%Z', '%s' % tz, 'time zone name'), - - # These are some platform specific extensions - ('%D', '%02d/%02d/%02d' % (now[1], now[2], (now[0]%100)), 'mm/dd/yy'), - ('%e', '%2d' % now[2], 'day of month as number, blank padded ( 0-31)'), - ('%h', calendar.month_abbr[now[1]], 'abbreviated month name'), - ('%k', '%2d' % now[3], 'hour, blank padded ( 0-23)'), - ('%n', '\n', 'newline character'), - ('%r', '%02d:%02d:%02d %s' % (clock12, now[4], now[5], ampm), - '%I:%M:%S %p'), - ('%R', '%02d:%02d' % (now[3], now[4]), '%H:%M'), - ('%s', nowsecs, 'seconds since the Epoch in UCT'), - ('%t', '\t', 'tab character'), - ('%T', '%02d:%02d:%02d' % (now[3], now[4], now[5]), '%H:%M:%S'), - ('%3y', '%03d' % (now[0]%100), - 'year without century rendered using fieldwidth'), - ) +class StrftimeTest(unittest.TestCase): + + def _update_variables(self, now): + # we must update the local variables on every cycle + self.gmt = time.gmtime(now) + now = time.localtime(now) - if verbose: - print("Strftime test, platform: %s, Python version: %s" % \ - (sys.platform, sys.version.split()[0])) + if now[3] < 12: self.ampm='(AM|am)' + else: self.ampm='(PM|pm)' + + self.jan1 = time.localtime(time.mktime((now[0], 1, 1, 0, 0, 0, 0, 1, 0))) - for e in expectations: try: - result = time.strftime(e[0], now) - except ValueError as error: - print("Standard '%s' format gave error:" % e[0], error) - continue - if re.match(escapestr(e[1], ampm), result): continue - if not result or result[0] == '%': - print("Does not support standard '%s' format (%s)" % (e[0], e[2])) - else: - print("Conflict for %s (%s):" % (e[0], e[2])) - print(" Expected %s, but got %s" % (e[1], result)) + if now[8]: self.tz = time.tzname[1] + else: self.tz = time.tzname[0] + except AttributeError: + self.tz = '' + + if now[3] > 12: self.clock12 = now[3] - 12 + elif now[3] > 0: self.clock12 = now[3] + else: self.clock12 = 12 + + self.now = now - for e in nonstandard_expectations: + def setUp(self): try: - result = time.strftime(e[0], now) - except ValueError as result: - if verbose: - print("Error for nonstandard '%s' format (%s): %s" % \ - (e[0], e[2], str(result))) - continue - if re.match(escapestr(e[1], ampm), result): - if verbose: - print("Supports nonstandard '%s' format (%s)" % (e[0], e[2])) - elif not result or result[0] == '%': - if verbose: - print("Does not appear to support '%s' format (%s)" % (e[0], - e[2])) - else: - if verbose: - print("Conflict for nonstandard '%s' format (%s):" % (e[0], - e[2])) + import java + java.util.Locale.setDefault(java.util.Locale.US) + except ImportError: + import locale + locale.setlocale(locale.LC_TIME, 'C') + + def test_strftime(self): + now = time.time() + self._update_variables(now) + self.strftest1(now) + self.strftest2(now) + + if test_support.verbose: + print("Strftime test, platform: %s, Python version: %s" % \ + (sys.platform, sys.version.split()[0])) + + for j in range(-5, 5): + for i in range(25): + arg = now + (i+j*100)*23*3603 + self._update_variables(arg) + self.strftest1(arg) + self.strftest2(arg) + + def strftest1(self, now): + if test_support.verbose: + print("strftime test for", time.ctime(now)) + now = self.now + # Make sure any characters that could be taken as regex syntax is + # escaped in escapestr() + expectations = ( + ('%a', calendar.day_abbr[now[6]], 'abbreviated weekday name'), + ('%A', calendar.day_name[now[6]], 'full weekday name'), + ('%b', calendar.month_abbr[now[1]], 'abbreviated month name'), + ('%B', calendar.month_name[now[1]], 'full month name'), + # %c see below + ('%d', '%02d' % now[2], 'day of month as number (00-31)'), + ('%H', '%02d' % now[3], 'hour (00-23)'), + ('%I', '%02d' % self.clock12, 'hour (01-12)'), + ('%j', '%03d' % now[7], 'julian day (001-366)'), + ('%m', '%02d' % now[1], 'month as number (01-12)'), + ('%M', '%02d' % now[4], 'minute, (00-59)'), + ('%p', self.ampm, 'AM or PM as appropriate'), + ('%S', '%02d' % now[5], 'seconds of current time (00-60)'), + ('%U', '%02d' % ((now[7] + self.jan1[6])//7), + 'week number of the year (Sun 1st)'), + ('%w', '0?%d' % ((1+now[6]) % 7), 'weekday as a number (Sun 1st)'), + ('%W', '%02d' % ((now[7] + (self.jan1[6] - 1)%7)//7), + 'week number of the year (Mon 1st)'), + # %x see below + ('%X', '%02d:%02d:%02d' % (now[3], now[4], now[5]), '%H:%M:%S'), + ('%y', '%02d' % (now[0]%100), 'year without century'), + ('%Y', '%d' % now[0], 'year with century'), + # %Z see below + ('%%', '%', 'single percent sign'), + ) + + for e in expectations: + # musn't raise a value error + try: + result = time.strftime(e[0], now) + except ValueError as error: + print("Standard '%s' format gaver error:" % (e[0], error)) + continue + if re.match(escapestr(e[1], self.ampm), result): + continue + if not result or result[0] == '%': + print("Does not support standard '%s' format (%s)" % \ + (e[0], e[2])) + else: + print("Conflict for %s (%s):" % (e[0], e[2])) print(" Expected %s, but got %s" % (e[1], result)) -def fixasctime(s): - if s[8] == ' ': - s = s[:8] + '0' + s[9:] - return s + def strftest2(self, now): + nowsecs = str(int(now))[:-1] + now = self.now + + nonstandard_expectations = ( + # These are standard but don't have predictable output + ('%c', fixasctime(time.asctime(now)), 'near-asctime() format'), + ('%x', '%02d/%02d/%02d' % (now[1], now[2], (now[0]%100)), + '%m/%d/%y %H:%M:%S'), + ('%Z', '%s' % self.tz, 'time zone name'), + + # These are some platform specific extensions + ('%D', '%02d/%02d/%02d' % (now[1], now[2], (now[0]%100)), 'mm/dd/yy'), + ('%e', '%2d' % now[2], 'day of month as number, blank padded ( 0-31)'), + ('%h', calendar.month_abbr[now[1]], 'abbreviated month name'), + ('%k', '%2d' % now[3], 'hour, blank padded ( 0-23)'), + ('%n', '\n', 'newline character'), + ('%r', '%02d:%02d:%02d %s' % (self.clock12, now[4], now[5], self.ampm), + '%I:%M:%S %p'), + ('%R', '%02d:%02d' % (now[3], now[4]), '%H:%M'), + ('%s', nowsecs, 'seconds since the Epoch in UCT'), + ('%t', '\t', 'tab character'), + ('%T', '%02d:%02d:%02d' % (now[3], now[4], now[5]), '%H:%M:%S'), + ('%3y', '%03d' % (now[0]%100), + 'year without century rendered using fieldwidth'), + ) + + + for e in nonstandard_expectations: + try: + result = time.strftime(e[0], now) + except ValueError as result: + msg = "Error for nonstandard '%s' format (%s): %s" % \ + (e[0], e[2], str(result)) + if test_support.verbose: + print(msg) + continue + if re.match(escapestr(e[1], self.ampm), result): + if test_support.verbose: + print("Supports nonstandard '%s' format (%s)" % (e[0], e[2])) + elif not result or result[0] == '%': + if test_support.verbose: + print("Does not appear to support '%s' format (%s)" % \ + (e[0], e[2])) + else: + if test_support.verbose: + print("Conflict for nonstandard '%s' format (%s):" % \ + (e[0], e[2])) + print(" Expected %s, but got %s" % (e[1], result)) + +def test_main(): + test_support.run_unittest(StrftimeTest) -main() +if __name__ == '__main__': + test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_strptime.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_strptime.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_strptime.py Wed Apr 30 15:57:13 2008 @@ -208,11 +208,11 @@ def test_ValueError(self): # Make sure ValueError is raised when match fails or format is bad - self.assertRaises(ValueError, _strptime.strptime, data_string="%d", + self.assertRaises(ValueError, _strptime._strptime_time, data_string="%d", format="%A") for bad_format in ("%", "% ", "%e"): try: - _strptime.strptime("2005", bad_format) + _strptime._strptime_time("2005", bad_format) except ValueError: continue except Exception as err: @@ -223,12 +223,12 @@ def test_unconverteddata(self): # Check ValueError is raised when there is unconverted data - self.assertRaises(ValueError, _strptime.strptime, "10 12", "%m") + self.assertRaises(ValueError, _strptime._strptime_time, "10 12", "%m") def helper(self, directive, position): """Helper fxn in testing.""" strf_output = time.strftime("%" + directive, self.time_tuple) - strp_output = _strptime.strptime(strf_output, "%" + directive) + strp_output = _strptime._strptime_time(strf_output, "%" + directive) self.failUnless(strp_output[position] == self.time_tuple[position], "testing of '%s' directive failed; '%s' -> %s != %s" % (directive, strf_output, strp_output[position], @@ -241,7 +241,7 @@ # Must also make sure %y values are correct for bounds set by Open Group for century, bounds in ((1900, ('69', '99')), (2000, ('00', '68'))): for bound in bounds: - strp_output = _strptime.strptime(bound, '%y') + strp_output = _strptime._strptime_time(bound, '%y') expected_result = century + int(bound) self.failUnless(strp_output[0] == expected_result, "'y' test failed; passed in '%s' " @@ -260,7 +260,7 @@ # Test hour directives self.helper('H', 3) strf_output = time.strftime("%I %p", self.time_tuple) - strp_output = _strptime.strptime(strf_output, "%I %p") + strp_output = _strptime._strptime_time(strf_output, "%I %p") self.failUnless(strp_output[3] == self.time_tuple[3], "testing of '%%I %%p' directive failed; '%s' -> %s != %s" % (strf_output, strp_output[3], self.time_tuple[3])) @@ -273,6 +273,12 @@ # Test second directives self.helper('S', 5) + def test_fraction(self): + import datetime + now = datetime.datetime.now() + tup, frac = _strptime._strptime(str(now), format="%Y-%m-%d %H:%M:%S.%f") + self.assertEqual(frac, now.microsecond) + def test_weekday(self): # Test weekday directives for directive in ('A', 'a', 'w'): @@ -287,16 +293,16 @@ # When gmtime() is used with %Z, entire result of strftime() is empty. # Check for equal timezone names deals with bad locale info when this # occurs; first found in FreeBSD 4.4. - strp_output = _strptime.strptime("UTC", "%Z") + strp_output = _strptime._strptime_time("UTC", "%Z") self.failUnlessEqual(strp_output.tm_isdst, 0) - strp_output = _strptime.strptime("GMT", "%Z") + strp_output = _strptime._strptime_time("GMT", "%Z") self.failUnlessEqual(strp_output.tm_isdst, 0) if sys.platform == "mac": # Timezones don't really work on MacOS9 return time_tuple = time.localtime() strf_output = time.strftime("%Z") #UTC does not have a timezone - strp_output = _strptime.strptime(strf_output, "%Z") + strp_output = _strptime._strptime_time(strf_output, "%Z") locale_time = _strptime.LocaleTime() if time.tzname[0] != time.tzname[1] or not time.daylight: self.failUnless(strp_output[8] == time_tuple[8], @@ -320,7 +326,7 @@ original_daylight = time.daylight time.tzname = (tz_name, tz_name) time.daylight = 1 - tz_value = _strptime.strptime(tz_name, "%Z")[8] + tz_value = _strptime._strptime_time(tz_name, "%Z")[8] self.failUnlessEqual(tz_value, -1, "%s lead to a timezone value of %s instead of -1 when " "time.daylight set to %s and passing in %s" % @@ -347,7 +353,7 @@ def test_percent(self): # Make sure % signs are handled properly strf_output = time.strftime("%m %% %Y", self.time_tuple) - strp_output = _strptime.strptime(strf_output, "%m %% %Y") + strp_output = _strptime._strptime_time(strf_output, "%m %% %Y") self.failUnless(strp_output[0] == self.time_tuple[0] and strp_output[1] == self.time_tuple[1], "handling of percent sign failed") @@ -355,17 +361,17 @@ def test_caseinsensitive(self): # Should handle names case-insensitively. strf_output = time.strftime("%B", self.time_tuple) - self.failUnless(_strptime.strptime(strf_output.upper(), "%B"), + self.failUnless(_strptime._strptime_time(strf_output.upper(), "%B"), "strptime does not handle ALL-CAPS names properly") - self.failUnless(_strptime.strptime(strf_output.lower(), "%B"), + self.failUnless(_strptime._strptime_time(strf_output.lower(), "%B"), "strptime does not handle lowercase names properly") - self.failUnless(_strptime.strptime(strf_output.capitalize(), "%B"), + self.failUnless(_strptime._strptime_time(strf_output.capitalize(), "%B"), "strptime does not handle capword names properly") def test_defaults(self): # Default return value should be (1900, 1, 1, 0, 0, 0, 0, 1, 0) defaults = (1900, 1, 1, 0, 0, 0, 0, 1, -1) - strp_output = _strptime.strptime('1', '%m') + strp_output = _strptime._strptime_time('1', '%m') self.failUnless(strp_output == defaults, "Default values for strptime() are incorrect;" " %s != %s" % (strp_output, defaults)) @@ -377,7 +383,7 @@ # escaped. # Test instigated by bug #796149 . need_escaping = ".^$*+?{}\[]|)(" - self.failUnless(_strptime.strptime(need_escaping, need_escaping)) + self.failUnless(_strptime._strptime_time(need_escaping, need_escaping)) class Strptime12AMPMTests(unittest.TestCase): """Test a _strptime regression in '%I %p' at 12 noon (12 PM)""" @@ -386,8 +392,8 @@ eq = self.assertEqual eq(time.strptime('12 PM', '%I %p')[3], 12) eq(time.strptime('12 AM', '%I %p')[3], 0) - eq(_strptime.strptime('12 PM', '%I %p')[3], 12) - eq(_strptime.strptime('12 AM', '%I %p')[3], 0) + eq(_strptime._strptime_time('12 PM', '%I %p')[3], 12) + eq(_strptime._strptime_time('12 AM', '%I %p')[3], 0) class JulianTests(unittest.TestCase): @@ -397,7 +403,7 @@ eq = self.assertEqual for i in range(1, 367): # use 2004, since it is a leap year, we have 366 days - eq(_strptime.strptime('%d 2004' % i, '%j %Y')[7], i) + eq(_strptime._strptime_time('%d 2004' % i, '%j %Y')[7], i) class CalculationTests(unittest.TestCase): """Test that strptime() fills in missing info correctly""" @@ -408,7 +414,7 @@ def test_julian_calculation(self): # Make sure that when Julian is missing that it is calculated format_string = "%Y %m %d %H %M %S %w %Z" - result = _strptime.strptime(time.strftime(format_string, self.time_tuple), + result = _strptime._strptime_time(time.strftime(format_string, self.time_tuple), format_string) self.failUnless(result.tm_yday == self.time_tuple.tm_yday, "Calculation of tm_yday failed; %s != %s" % @@ -417,7 +423,7 @@ def test_gregorian_calculation(self): # Test that Gregorian date can be calculated from Julian day format_string = "%Y %H %M %S %w %j %Z" - result = _strptime.strptime(time.strftime(format_string, self.time_tuple), + result = _strptime._strptime_time(time.strftime(format_string, self.time_tuple), format_string) self.failUnless(result.tm_year == self.time_tuple.tm_year and result.tm_mon == self.time_tuple.tm_mon and @@ -431,7 +437,7 @@ def test_day_of_week_calculation(self): # Test that the day of the week is calculated as needed format_string = "%Y %m %d %H %S %j %Z" - result = _strptime.strptime(time.strftime(format_string, self.time_tuple), + result = _strptime._strptime_time(time.strftime(format_string, self.time_tuple), format_string) self.failUnless(result.tm_wday == self.time_tuple.tm_wday, "Calculation of day of the week failed;" @@ -445,7 +451,7 @@ format_string = "%%Y %%%s %%w" % directive dt_date = datetime_date(*ymd_tuple) strp_input = dt_date.strftime(format_string) - strp_output = _strptime.strptime(strp_input, format_string) + strp_output = _strptime._strptime_time(strp_input, format_string) self.failUnless(strp_output[:3] == ymd_tuple, "%s(%s) test failed w/ '%s': %s != %s (%s != %s)" % (test_reason, directive, strp_input, @@ -484,11 +490,11 @@ def test_time_re_recreation(self): # Make sure cache is recreated when current locale does not match what # cached object was created with. - _strptime.strptime("10", "%d") - _strptime.strptime("2005", "%Y") + _strptime._strptime_time("10", "%d") + _strptime._strptime_time("2005", "%Y") _strptime._TimeRE_cache.locale_time.lang = "Ni" original_time_re = id(_strptime._TimeRE_cache) - _strptime.strptime("10", "%d") + _strptime._strptime_time("10", "%d") self.failIfEqual(original_time_re, id(_strptime._TimeRE_cache)) self.failUnlessEqual(len(_strptime._regex_cache), 1) @@ -502,7 +508,7 @@ while len(_strptime._regex_cache) <= _strptime._CACHE_MAX_SIZE: _strptime._regex_cache[bogus_key] = None bogus_key += 1 - _strptime.strptime("10", "%d") + _strptime._strptime_time("10", "%d") self.failUnlessEqual(len(_strptime._regex_cache), 1) def test_new_localetime(self): @@ -510,7 +516,7 @@ # is created. locale_time_id = id(_strptime._TimeRE_cache.locale_time) _strptime._TimeRE_cache.locale_time.lang = "Ni" - _strptime.strptime("10", "%d") + _strptime._strptime_time("10", "%d") self.failIfEqual(locale_time_id, id(_strptime._TimeRE_cache.locale_time)) @@ -522,13 +528,13 @@ except locale.Error: return try: - _strptime.strptime('10', '%d') + _strptime._strptime_time('10', '%d') # Get id of current cache object. first_time_re_id = id(_strptime._TimeRE_cache) try: # Change the locale and force a recreation of the cache. locale.setlocale(locale.LC_TIME, ('de_DE', 'UTF8')) - _strptime.strptime('10', '%d') + _strptime._strptime_time('10', '%d') # Get the new cache object's id. second_time_re_id = id(_strptime._TimeRE_cache) # They should not be equal. Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_struct.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_struct.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_struct.py Wed Apr 30 15:57:13 2008 @@ -84,8 +84,8 @@ if sz * 3 != struct.calcsize('iii'): raise TestFailed('inconsistent sizes') -fmt = 'cbxxxxxxhhhhiillffdt' -fmt3 = '3c3b18x12h6i6l6f3d3t' +fmt = 'cbxxxxxxhhhhiillffd?' +fmt3 = '3c3b18x12h6i6l6f3d3?' sz = struct.calcsize(fmt) sz3 = struct.calcsize(fmt3) if sz * 3 != sz3: @@ -111,7 +111,7 @@ t = True for prefix in ('', '@', '<', '>', '=', '!'): - for format in ('xcbhilfdt', 'xcBHILfdt'): + for format in ('xcbhilfd?', 'xcBHILfd?'): format = prefix + format if verbose: print("trying:", format) @@ -160,11 +160,11 @@ ('f', -2.0, '\300\000\000\000', '\000\000\000\300', 0), ('d', -2.0, '\300\000\000\000\000\000\000\000', '\000\000\000\000\000\000\000\300', 0), - ('t', 0, '\0', '\0', 0), - ('t', 3, '\1', '\1', 1), - ('t', True, '\1', '\1', 0), - ('t', [], '\0', '\0', 1), - ('t', (1,), '\1', '\1', 1), + ('?', 0, '\0', '\0', 0), + ('?', 3, '\1', '\1', 1), + ('?', True, '\1', '\1', 0), + ('?', [], '\0', '\0', 1), + ('?', (1,), '\1', '\1', 1), ] for fmt, arg, big, lil, asy in tests: @@ -490,7 +490,7 @@ except OverflowError: pass else: - TestFailed("expected OverflowError") + raise TestFailed("expected OverflowError") test_705836() @@ -646,13 +646,13 @@ false = (), [], [], '', 0 true = [1], 'test', 5, -1, 0xffffffff+1, 0xffffffff/2 - falseFormat = prefix + 't' * len(false) + falseFormat = prefix + '?' * len(false) if verbose: print('trying bool pack/unpack on', false, 'using format', falseFormat) packedFalse = struct.pack(falseFormat, *false) unpackedFalse = struct.unpack(falseFormat, packedFalse) - trueFormat = prefix + 't' * len(true) + trueFormat = prefix + '?' * len(true) if verbose: print('trying bool pack/unpack on', true, 'using format', trueFormat) packedTrue = struct.pack(trueFormat, *true) @@ -671,10 +671,10 @@ raise TestFailed('%r did not unpack as false' % t) if prefix and verbose: - print('trying size of bool with format %r' % (prefix+'t')) - packed = struct.pack(prefix+'t', 1) + print('trying size of bool with format %r' % (prefix+'?')) + packed = struct.pack(prefix+'?', 1) - if len(packed) != struct.calcsize(prefix+'t'): + if len(packed) != struct.calcsize(prefix+'?'): raise TestFailed('packed length is not equal to calculated size') if len(packed) != 1 and prefix: @@ -682,8 +682,8 @@ elif not prefix and verbose: print('size of bool in native format is %i' % (len(packed))) - for c in b'\x01\x7f\xff\x0f\xf0': - if struct.unpack('>t', bytes([c]))[0] is not True: + for c in [b'\x01', b'\x7f', b'\xff', b'\x0f', b'\xf0']: + if struct.unpack('>?', c)[0] is not True: raise TestFailed('%c did not unpack as True' % c) test_bool() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_structmembers.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_structmembers.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_structmembers.py Wed Apr 30 15:57:13 2008 @@ -101,12 +101,6 @@ def test_main(verbose=None): - # Obscure hack so that this test passes after reloads or repeated calls - # to test_main (regrtest -R). - if '__warningregistry__' in globals(): - del globals()['__warningregistry__'] - if hasattr(sys, '__warningregistry__'): - del sys.__warningregistry__ test_support.run_unittest(__name__) if __name__ == "__main__": Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_subprocess.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_subprocess.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_subprocess.py Wed Apr 30 15:57:13 2008 @@ -584,6 +584,29 @@ os.remove(fname) self.assertEqual(rc, 47) + def test_send_signal(self): + p = subprocess.Popen([sys.executable, + "-c", "input()"]) + + self.assert_(p.poll() is None, p.poll()) + p.send_signal(signal.SIGINT) + self.assertNotEqual(p.wait(), 0) + + def test_kill(self): + p = subprocess.Popen([sys.executable, + "-c", "input()"]) + + self.assert_(p.poll() is None, p.poll()) + p.kill() + self.assertEqual(p.wait(), -signal.SIGKILL) + + def test_terminate(self): + p = subprocess.Popen([sys.executable, + "-c", "input()"]) + + self.assert_(p.poll() is None, p.poll()) + p.terminate() + self.assertEqual(p.wait(), -signal.SIGTERM) # # Windows tests @@ -655,6 +678,29 @@ ' -c "import sys; sys.exit(47)"') self.assertEqual(rc, 47) + def test_send_signal(self): + p = subprocess.Popen([sys.executable, + "-c", "input()"]) + + self.assert_(p.poll() is None, p.poll()) + p.send_signal(signal.SIGTERM) + self.assertNotEqual(p.wait(), 0) + + def test_kill(self): + p = subprocess.Popen([sys.executable, + "-c", "input()"]) + + self.assert_(p.poll() is None, p.poll()) + p.kill() + self.assertNotEqual(p.wait(), 0) + + def test_terminate(self): + p = subprocess.Popen([sys.executable, + "-c", "input()"]) + + self.assert_(p.poll() is None, p.poll()) + p.terminate() + self.assertNotEqual(p.wait(), 0) def test_main(): test_support.run_unittest(ProcessTestCase) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_sundry.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_sundry.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_sundry.py Wed Apr 30 15:57:13 2008 @@ -1,111 +1,118 @@ """Do a minimal test of all the modules that aren't otherwise tested.""" -from test.test_support import catch_warning +from test import test_support import sys +import unittest import warnings -with catch_warning(): - from test.test_support import verbose +class TestUntestedModules(unittest.TestCase): + def test_at_least_import_untested_modules(self): + with test_support.catch_warning(): + import BaseHTTPServer + import DocXMLRPCServer + import CGIHTTPServer + import SimpleHTTPServer + import SimpleXMLRPCServer + import aifc + import bdb + import cgitb + import cmd + import code + import compileall + + import distutils.archive_util + import distutils.bcppcompiler + import distutils.ccompiler + import distutils.cmd + import distutils.core + import distutils.cygwinccompiler + import distutils.dep_util + import distutils.dir_util + import distutils.emxccompiler + import distutils.errors + import distutils.extension + import distutils.file_util + import distutils.filelist + import distutils.log + if sys.platform.startswith('win'): + import distutils.msvccompiler + import distutils.mwerkscompiler + import distutils.sysconfig + import distutils.text_file + import distutils.unixccompiler + import distutils.util + import distutils.version + + import distutils.command.bdist_dumb + if sys.platform.startswith('win'): + import distutils.command.bdist_msi + import distutils.command.bdist + import distutils.command.bdist_rpm + import distutils.command.bdist_wininst + import distutils.command.build_clib + import distutils.command.build_ext + import distutils.command.build + import distutils.command.build_py + import distutils.command.build_scripts + import distutils.command.clean + import distutils.command.config + import distutils.command.install_data + import distutils.command.install_egg_info + import distutils.command.install_headers + import distutils.command.install_lib + import distutils.command.install + import distutils.command.install_scripts + import distutils.command.register + import distutils.command.sdist + import distutils.command.upload + + import encodings + import formatter + import ftplib + import getpass + import htmlentitydefs + import ihooks + import imghdr + import imputil + import keyword + import linecache + import macurl2path + import mailcap + import mutex + import nntplib + import nturl2path + import opcode + import os2emxpath + import pdb + import pstats + import py_compile + import rlcompleter + import sched + import smtplib + import sndhdr + import statvfs + import sunau + import sunaudio + import symbol + import tabnanny + import telnetlib + import timeit + import token + try: + import tty # not available on Windows + except ImportError: + if test_support.verbose: + print("skipping tty") + + # Can't test the "user" module -- if the user has a ~/.pythonrc.py, it + # can screw up all sorts of things (esp. if it prints!). + #import user + import webbrowser + import xml - import BaseHTTPServer - import DocXMLRPCServer - import CGIHTTPServer - import SimpleHTTPServer - import SimpleXMLRPCServer - import aifc - import bdb - import cgitb - import cmd - import code - import compileall - - import distutils.archive_util - import distutils.bcppcompiler - import distutils.ccompiler - import distutils.cmd - import distutils.core - import distutils.cygwinccompiler - import distutils.dep_util - import distutils.dir_util - import distutils.emxccompiler - import distutils.errors - import distutils.extension - import distutils.file_util - import distutils.filelist - import distutils.log - if sys.platform.startswith('win'): - import distutils.msvccompiler - import distutils.mwerkscompiler - import distutils.sysconfig - import distutils.text_file - import distutils.unixccompiler - import distutils.util - import distutils.version - - import distutils.command.bdist_dumb - if sys.platform.startswith('win'): - import distutils.command.bdist_msi - import distutils.command.bdist - import distutils.command.bdist_rpm - import distutils.command.bdist_wininst - import distutils.command.build_clib - import distutils.command.build_ext - import distutils.command.build - import distutils.command.build_py - import distutils.command.build_scripts - import distutils.command.clean - import distutils.command.config - import distutils.command.install_data - import distutils.command.install_egg_info - import distutils.command.install_headers - import distutils.command.install_lib - import distutils.command.install - import distutils.command.install_scripts - import distutils.command.register - import distutils.command.sdist - import distutils.command.upload - - import encodings - import formatter - import ftplib - import getpass - import htmlentitydefs - import ihooks - import imghdr - import imputil - import keyword - import linecache - import macurl2path - import mailcap - import mutex - import nntplib - import nturl2path - import opcode - import os2emxpath - import pdb - import pstats - import py_compile - import pydoc - import rlcompleter - import sched - import smtplib - import sndhdr - import statvfs - import sunau - import sunaudio - import symbol - import tabnanny - import telnetlib - import timeit - import token - try: - import tty # not available on Windows - except ImportError: - if verbose: - print("skipping tty") - - # Can't test the "user" module -- if the user has a ~/.pythonrc.py, it - # can screw up all sorts of things (esp. if it prints!). - #import user - import webbrowser - import xml + +def test_main(): + test_support.run_unittest(TestUntestedModules) + +if __name__ == "__main__": + test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_support.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_support.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_support.py Wed Apr 30 15:57:13 2008 @@ -9,8 +9,8 @@ import sys import os import os.path +import shutil import warnings -import types import unittest class Error(Exception): @@ -65,6 +65,14 @@ except OSError: pass +def rmtree(path): + try: + shutil.rmtree(path) + except OSError as e: + # Unix returns ENOENT, Windows returns ESRCH. + if e.errno not in (errno.ENOENT, errno.ESRCH): + raise + def forget(modname): '''"Forget" a module was ever imported by removing it from sys.modules and deleting any .pyc and .pyo files.''' @@ -95,31 +103,100 @@ msg = "Use of the `%s' resource not enabled" % resource raise ResourceDenied(msg) -def bind_port(sock, host='', preferred_port=54321): - """Try to bind the sock to a port. If we are running multiple - tests and we don't try multiple ports, the test can fails. This - makes the test more robust.""" - - # Find some random ports that hopefully no one is listening on. - # Ideally each test would clean up after itself and not continue listening - # on any ports. However, this isn't the case. The last port (0) is - # a stop-gap that asks the O/S to assign a port. Whenever the warning - # message below is printed, the test that is listening on the port should - # be fixed to close the socket at the end of the test. - # Another reason why we can't use a port is another process (possibly - # another instance of the test suite) is using the same port. - for port in [preferred_port, 9907, 10243, 32999, 0]: - try: - sock.bind((host, port)) - if port == 0: - port = sock.getsockname()[1] - return port - except socket.error as e: - (err, msg) = e.args - if err != errno.EADDRINUSE: - raise - print(' WARNING: failed to listen on port %d, trying another' % port, file=sys.__stderr__) - raise TestFailed('unable to find port to listen on') +HOST = 'localhost' + +def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM): + """Returns an unused port that should be suitable for binding. This is + achieved by creating a temporary socket with the same family and type as + the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to + the specified host address (defaults to 0.0.0.0) with the port set to 0, + eliciting an unused ephemeral port from the OS. The temporary socket is + then closed and deleted, and the ephemeral port is returned. + + Either this method or bind_port() should be used for any tests where a + server socket needs to be bound to a particular port for the duration of + the test. Which one to use depends on whether the calling code is creating + a python socket, or if an unused port needs to be provided in a constructor + or passed to an external program (i.e. the -accept argument to openssl's + s_server mode). Always prefer bind_port() over find_unused_port() where + possible. Hard coded ports should *NEVER* be used. As soon as a server + socket is bound to a hard coded port, the ability to run multiple instances + of the test simultaneously on the same host is compromised, which makes the + test a ticking time bomb in a buildbot environment. On Unix buildbots, this + may simply manifest as a failed test, which can be recovered from without + intervention in most cases, but on Windows, the entire python process can + completely and utterly wedge, requiring someone to log in to the buildbot + and manually kill the affected process. + + (This is easy to reproduce on Windows, unfortunately, and can be traced to + the SO_REUSEADDR socket option having different semantics on Windows versus + Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind, + listen and then accept connections on identical host/ports. An EADDRINUSE + socket.error will be raised at some point (depending on the platform and + the order bind and listen were called on each socket). + + However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE + will ever be raised when attempting to bind two identical host/ports. When + accept() is called on each socket, the second caller's process will steal + the port from the first caller, leaving them both in an awkwardly wedged + state where they'll no longer respond to any signals or graceful kills, and + must be forcibly killed via OpenProcess()/TerminateProcess(). + + The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option + instead of SO_REUSEADDR, which effectively affords the same semantics as + SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open + Source world compared to Windows ones, this is a common mistake. A quick + look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when + openssl.exe is called with the 's_server' option, for example. See + http://bugs.python.org/issue2550 for more info. The following site also + has a very thorough description about the implications of both REUSEADDR + and EXCLUSIVEADDRUSE on Windows: + http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx) + + XXX: although this approach is a vast improvement on previous attempts to + elicit unused ports, it rests heavily on the assumption that the ephemeral + port returned to us by the OS won't immediately be dished back out to some + other process when we close and delete our temporary socket but before our + calling code has a chance to bind the returned port. We can deal with this + issue if/when we come across it. + """ + + tempsock = socket.socket(family, socktype) + port = bind_port(tempsock) + tempsock.close() + del tempsock + return port + +def bind_port(sock, host=HOST): + """Bind the socket to a free port and return the port number. Relies on + ephemeral ports in order to ensure we are using an unbound port. This is + important as many tests may be running simultaneously, especially in a + buildbot environment. This method raises an exception if the sock.family + is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR + or SO_REUSEPORT set on it. Tests should *never* set these socket options + for TCP/IP sockets. The only case for setting these options is testing + multicasting via multiple UDP sockets. + + Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e. + on Windows), it will be set on the socket. This will prevent anyone else + from bind()'ing to our host/port for the duration of the test. + """ + + if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM: + if hasattr(socket, 'SO_REUSEADDR'): + if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1: + raise TestFailed("tests should never set the SO_REUSEADDR " \ + "socket option on TCP/IP sockets!") + if hasattr(socket, 'SO_REUSEPORT'): + if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1: + raise TestFailed("tests should never set the SO_REUSEPORT " \ + "socket option on TCP/IP sockets!") + if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'): + sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) + + sock.bind((host, 0)) + port = sock.getsockname()[1] + return port FUZZ = 1e-6 @@ -179,9 +256,9 @@ except UnicodeEncodeError: pass else: - print('WARNING: The filename %r CAN be encoded by the filesystem. ' \ - 'Unicode filename tests may not be effective' \ - % TESTFN_UNICODE_UNENCODEABLE) + print('WARNING: The filename %r CAN be encoded by the filesystem. ' + 'Unicode filename tests may not be effective' + % TESTFN_UNICODE_UNENCODEABLE) # Make sure we can write to TESTFN, try in /tmp if we can't fp = None @@ -277,14 +354,26 @@ self.filename = None self.lineno = None - def _showwarning(self, message, category, filename, lineno, file=None): + def _showwarning(self, message, category, filename, lineno, file=None, + line=None): self.message = message self.category = category self.filename = filename self.lineno = lineno + self.line = line + + def reset(self): + self._showwarning(*((None,)*6)) + + def __str__(self): + return ("{message : %r, category : %r, filename : %r, lineno : %s, " + "line : %r}" % (self.message, + self.category.__name__ if self.category else None, + self.filename, self.lineno, self.line)) + @contextlib.contextmanager -def catch_warning(): +def catch_warning(module=warnings): """ Guard the warnings filter from being permanently changed and record the data of the last warning that has been issued. @@ -295,15 +384,15 @@ warnings.warn("foo") assert str(w.message) == "foo" """ - warning = WarningMessage() - original_filters = warnings.filters[:] - original_showwarning = warnings.showwarning - warnings.showwarning = warning._showwarning + warning_obj = WarningMessage() + original_filters = module.filters[:] + original_showwarning = module.showwarning + module.showwarning = warning_obj._showwarning try: - yield warning + yield warning_obj finally: - warnings.showwarning = original_showwarning - warnings.filters = original_filters + module.showwarning = original_showwarning + module.filters = original_filters class EnvironmentVarGuard(object): @@ -372,19 +461,23 @@ @contextlib.contextmanager -def captured_stdout(): - """Run the with statement body using a StringIO object as sys.stdout. - Example use:: +def captured_output(stream_name): + """Run the 'with' statement body using a StringIO object in place of a + specific attribute on the sys module. + Example use (with 'stream_name=stdout'):: with captured_stdout() as s: print "hello" assert s.getvalue() == "hello" """ import io - orig_stdout = sys.stdout - sys.stdout = io.StringIO() - yield sys.stdout - sys.stdout = orig_stdout + orig_stdout = getattr(sys, stream_name) + setattr(sys, stream_name, io.StringIO()) + yield getattr(sys, stream_name) + setattr(sys, stream_name, orig_stdout) + +def captured_stdout(): + return captured_output("stdout") #======================================================================= @@ -424,7 +517,8 @@ return decorator #======================================================================= -# Big-memory-test support. Separate from 'resources' because memory use should be configurable. +# Big-memory-test support. Separate from 'resources' because memory use +# should be configurable. # Some handy shorthands. Note that these are used for byte-limits as well # as size-limits, in the various bigmem tests @@ -460,7 +554,7 @@ 'minsize' is the minimum useful size for the test (in arbitrary, test-interpreted units.) 'memuse' is the number of 'bytes per size' for the test, or a good estimate of it. 'overhead' specifies fixed overhead, - independant of the testsize, and defaults to 5Mb. + independent of the testsize, and defaults to 5Mb. The decorator tries to guess a good value for 'size' and passes it to the decorated test function. If minsize * memuse is more than the @@ -578,7 +672,8 @@ finally: sys.stdout = save_stdout if verbose: - print('doctest (%s) ... %d tests with zero failures' % (module.__name__, t)) + print('doctest (%s) ... %d tests with zero failures' % + (module.__name__, t)) return f, t #======================================================================= Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_sys.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_sys.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_sys.py Wed Apr 30 15:57:13 2008 @@ -330,6 +330,23 @@ self.assertEqual(type(getattr(sys.flags, attr)), int, attr) self.assert_(repr(sys.flags)) + def test_clear_type_cache(self): + sys._clear_type_cache() + + def test_compact_freelists(self): + sys._compact_freelists() + r = sys._compact_freelists() + ## freed blocks shouldn't change + #self.assertEqual(r[0][2], 0) + ## fill freelists + #ints = list(range(10000)) + #floats = [float(i) for i in ints] + #del ints + #del floats + ## should free more than 100 blocks + #r = sys._compact_freelists() + #self.assert_(r[0][1] > 100, r[0][1]) + #self.assert_(r[0][2] > 100, r[0][2]) def test_main(): test.test_support.run_unittest(SysModuleTest) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_tarfile.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_tarfile.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_tarfile.py Wed Apr 30 15:57:13 2008 @@ -207,6 +207,15 @@ self.assert_(tarinfo.type == tarfile.DIRTYPE, "v7 dirtype failed") + def test_xstar_type(self): + # The xstar format stores extra atime and ctime fields inside the + # space reserved for the prefix field. The prefix field must be + # ignored in this case, otherwise it will mess up the name. + try: + self.tar.getmember("misc/regtype-xstar") + except KeyError: + self.fail("failed to find misc/regtype-xstar (mangled prefix?)") + def test_check_members(self): for tarinfo in self.tar: self.assert_(int(tarinfo.mtime) == 0o7606136617, Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_telnetlib.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_telnetlib.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_telnetlib.py Wed Apr 30 15:57:13 2008 @@ -6,14 +6,11 @@ from unittest import TestCase from test import test_support +HOST = test_support.HOST -def server(evt, ready): - serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - serv.settimeout(3) - serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - serv.bind(("", 9091)) +def server(evt, serv): serv.listen(5) - ready.set() + evt.set() try: conn, addr = serv.accept() except socket.timeout: @@ -26,33 +23,37 @@ def setUp(self): self.evt = threading.Event() - ready = threading.Event() - threading.Thread(target=server, args=(self.evt, ready)).start() - ready.wait() + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.sock.settimeout(3) + self.port = test_support.bind_port(self.sock) + threading.Thread(target=server, args=(self.evt,self.sock)).start() + self.evt.wait() + self.evt.clear() + time.sleep(.1) def tearDown(self): self.evt.wait() def testBasic(self): # connects - telnet = telnetlib.Telnet("localhost", 9091) + telnet = telnetlib.Telnet(HOST, self.port) telnet.sock.close() def testTimeoutDefault(self): # default - telnet = telnetlib.Telnet("localhost", 9091) + telnet = telnetlib.Telnet(HOST, self.port) self.assertTrue(telnet.sock.gettimeout() is None) telnet.sock.close() def testTimeoutValue(self): # a value - telnet = telnetlib.Telnet("localhost", 9091, timeout=30) + telnet = telnetlib.Telnet(HOST, self.port, timeout=30) self.assertEqual(telnet.sock.gettimeout(), 30) telnet.sock.close() def testTimeoutDifferentOrder(self): telnet = telnetlib.Telnet(timeout=30) - telnet.open("localhost", 9091) + telnet.open(HOST, self.port) self.assertEqual(telnet.sock.gettimeout(), 30) telnet.sock.close() @@ -61,7 +62,7 @@ previous = socket.getdefaulttimeout() socket.setdefaulttimeout(30) try: - telnet = telnetlib.Telnet("localhost", 9091, timeout=None) + telnet = telnetlib.Telnet(HOST, self.port, timeout=None) finally: socket.setdefaulttimeout(previous) self.assertEqual(telnet.sock.gettimeout(), 30) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_tempfile.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_tempfile.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_tempfile.py Wed Apr 30 15:57:13 2008 @@ -1,5 +1,4 @@ # tempfile.py unit tests. - import tempfile import os import sys @@ -619,7 +618,6 @@ def test_multiple_close(self): # A NamedTemporaryFile can be closed many times without error - f = tempfile.NamedTemporaryFile() f.write(b'abc\n') f.close() @@ -629,6 +627,16 @@ except: self.failOnException("close") + def test_context_manager(self): + # A NamedTemporaryFile can be used as a context manager + with tempfile.NamedTemporaryFile() as f: + self.failUnless(os.path.exists(f.name)) + self.failIf(os.path.exists(f.name)) + def use_closed(): + with f: + pass + self.failUnlessRaises(ValueError, use_closed) + # How to test the mode and bufsize parameters? test_classes.append(test_NamedTemporaryFile) @@ -707,10 +715,23 @@ self.failUnless(f.fileno() > 0) self.failUnless(f._rolled) - def test_multiple_close(self): + def test_multiple_close_before_rollover(self): # A SpooledTemporaryFile can be closed many times without error f = tempfile.SpooledTemporaryFile() f.write(b'abc\n') + self.failIf(f._rolled) + f.close() + try: + f.close() + f.close() + except: + self.failOnException("close") + + def test_multiple_close_after_rollover(self): + # A SpooledTemporaryFile can be closed many times without error + f = tempfile.SpooledTemporaryFile(max_size=1) + f.write(b'abc\n') + self.failUnless(f._rolled) f.close() try: f.close() @@ -759,6 +780,46 @@ self.assertEqual(f.read(), "\u039B\r\n" + ("\u039B" * 20) + "\r\n") self.failUnless(f._rolled) + def test_context_manager_before_rollover(self): + # A SpooledTemporaryFile can be used as a context manager + with tempfile.SpooledTemporaryFile(max_size=1) as f: + self.failIf(f._rolled) + self.failIf(f.closed) + self.failUnless(f.closed) + def use_closed(): + with f: + pass + self.failUnlessRaises(ValueError, use_closed) + + def test_context_manager_during_rollover(self): + # A SpooledTemporaryFile can be used as a context manager + with tempfile.SpooledTemporaryFile(max_size=1) as f: + self.failIf(f._rolled) + f.write(b'abc\n') + f.flush() + self.failUnless(f._rolled) + self.failIf(f.closed) + self.failUnless(f.closed) + def use_closed(): + with f: + pass + self.failUnlessRaises(ValueError, use_closed) + + def test_context_manager_after_rollover(self): + # A SpooledTemporaryFile can be used as a context manager + f = tempfile.SpooledTemporaryFile(max_size=1) + f.write(b'abc\n') + f.flush() + self.failUnless(f._rolled) + with f: + self.failIf(f.closed) + self.failUnless(f.closed) + def use_closed(): + with f: + pass + self.failUnlessRaises(ValueError, use_closed) + + test_classes.append(test_SpooledTemporaryFile) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_thread.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_thread.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_thread.py Wed Apr 30 15:57:13 2008 @@ -1,160 +1,165 @@ -# Very rudimentary test of thread module - -# Create a bunch of threads, let each do some work, wait until all are done - -from test.test_support import verbose +import os +import unittest import random +from test import test_support import thread import time -mutex = thread.allocate_lock() -rmutex = thread.allocate_lock() # for calls to random -running = 0 -done = thread.allocate_lock() -done.acquire() - -numtasks = 10 - -def task(ident): - global running - rmutex.acquire() - delay = random.random() * numtasks - rmutex.release() - if verbose: - print('task', ident, 'will run for', round(delay, 1), 'sec') - time.sleep(delay) - if verbose: - print('task', ident, 'done') - mutex.acquire() - running = running - 1 - if running == 0: - done.release() - mutex.release() - -next_ident = 0 -def newtask(): - global next_ident, running - mutex.acquire() - next_ident = next_ident + 1 - if verbose: - print('creating task', next_ident) - thread.start_new_thread(task, (next_ident,)) - running = running + 1 - mutex.release() - -for i in range(numtasks): - newtask() - -print('waiting for all tasks to complete') -done.acquire() -print('all tasks done') - -class barrier: - def __init__(self, n): - self.n = n + +NUMTASKS = 10 +NUMTRIPS = 3 + +_print_mutex = thread.allocate_lock() + +def verbose_print(arg): + """Helper function for printing out debugging output.""" + if test_support.verbose: + with _print_mutex: + print(arg) + +class BasicThreadTest(unittest.TestCase): + + def setUp(self): + self.done_mutex = thread.allocate_lock() + self.done_mutex.acquire() + self.running_mutex = thread.allocate_lock() + self.random_mutex = thread.allocate_lock() + self.running = 0 + self.next_ident = 0 + + +class ThreadRunningTests(BasicThreadTest): + + def newtask(self): + with self.running_mutex: + self.next_ident += 1 + verbose_print("creating task %s" % self.next_ident) + thread.start_new_thread(self.task, (self.next_ident,)) + self.running += 1 + + def task(self, ident): + with self.random_mutex: + delay = random.random() / 10000.0 + verbose_print("task %s will run for %sus" % (ident, round(delay*1e6))) + time.sleep(delay) + verbose_print("task %s done" % ident) + with self.running_mutex: + self.running -= 1 + if self.running == 0: + self.done_mutex.release() + + def test_starting_threads(self): + # Basic test for thread creation. + for i in range(NUMTASKS): + self.newtask() + verbose_print("waiting for tasks to complete...") + self.done_mutex.acquire() + verbose_print("all tasks done") + + def test_stack_size(self): + # Various stack size tests. + self.assertEquals(thread.stack_size(), 0, "intial stack size is not 0") + + thread.stack_size(0) + self.assertEquals(thread.stack_size(), 0, "stack_size not reset to default") + + if os.name not in ("nt", "os2", "posix"): + return + + tss_supported = True + try: + thread.stack_size(4096) + except ValueError: + verbose_print("caught expected ValueError setting " + "stack_size(4096)") + except thread.error: + tss_supported = False + verbose_print("platform does not support changing thread stack " + "size") + + if tss_supported: + fail_msg = "stack_size(%d) failed - should succeed" + for tss in (262144, 0x100000, 0): + thread.stack_size(tss) + self.assertEquals(thread.stack_size(), tss, fail_msg % tss) + verbose_print("successfully set stack_size(%d)" % tss) + + for tss in (262144, 0x100000): + verbose_print("trying stack_size = (%d)" % tss) + self.next_ident = 0 + for i in range(NUMTASKS): + self.newtask() + + verbose_print("waiting for all tasks to complete") + self.done_mutex.acquire() + verbose_print("all tasks done") + + thread.stack_size(0) + + +class Barrier: + def __init__(self, num_threads): + self.num_threads = num_threads self.waiting = 0 - self.checkin = thread.allocate_lock() - self.checkout = thread.allocate_lock() - self.checkout.acquire() + self.checkin_mutex = thread.allocate_lock() + self.checkout_mutex = thread.allocate_lock() + self.checkout_mutex.acquire() def enter(self): - checkin, checkout = self.checkin, self.checkout - - checkin.acquire() + self.checkin_mutex.acquire() self.waiting = self.waiting + 1 - if self.waiting == self.n: - self.waiting = self.n - 1 - checkout.release() + if self.waiting == self.num_threads: + self.waiting = self.num_threads - 1 + self.checkout_mutex.release() return - checkin.release() + self.checkin_mutex.release() - checkout.acquire() + self.checkout_mutex.acquire() self.waiting = self.waiting - 1 if self.waiting == 0: - checkin.release() + self.checkin_mutex.release() return - checkout.release() + self.checkout_mutex.release() -numtrips = 3 -def task2(ident): - global running - for i in range(numtrips): - if ident == 0: - # give it a good chance to enter the next - # barrier before the others are all out - # of the current one - delay = 0.001 - else: - rmutex.acquire() - delay = random.random() * numtasks - rmutex.release() - if verbose: - print('task', ident, 'will run for', round(delay, 1), 'sec') - time.sleep(delay) - if verbose: - print('task', ident, 'entering barrier', i) - bar.enter() - if verbose: - print('task', ident, 'leaving barrier', i) - mutex.acquire() - running -= 1 - # Must release mutex before releasing done, else the main thread can - # exit and set mutex to None as part of global teardown; then - # mutex.release() raises AttributeError. - finished = running == 0 - mutex.release() - if finished: - done.release() - -print('\n*** Barrier Test ***') -if done.acquire(0): - raise ValueError("'done' should have remained acquired") -bar = barrier(numtasks) -running = numtasks -for i in range(numtasks): - thread.start_new_thread(task2, (i,)) -done.acquire() -print('all tasks done') - -# not all platforms support changing thread stack size -print('\n*** Changing thread stack size ***') -if thread.stack_size() != 0: - raise ValueError("initial stack_size not 0") - -thread.stack_size(0) -if thread.stack_size() != 0: - raise ValueError("stack_size not reset to default") - -from os import name as os_name -if os_name in ("nt", "os2", "posix"): - - tss_supported = 1 - try: - thread.stack_size(4096) - except ValueError: - print('caught expected ValueError setting stack_size(4096)') - except thread.error: - tss_supported = 0 - print('platform does not support changing thread stack size') - - if tss_supported: - failed = lambda s, e: s != e - fail_msg = "stack_size(%d) failed - should succeed" - for tss in (262144, 0x100000, 0): - thread.stack_size(tss) - if failed(thread.stack_size(), tss): - raise ValueError(fail_msg % tss) - print('successfully set stack_size(%d)' % tss) - - for tss in (262144, 0x100000): - print('trying stack_size = %d' % tss) - next_ident = 0 - for i in range(numtasks): - newtask() - - print('waiting for all tasks to complete') - done.acquire() - print('all tasks done') - # reset stack size to default - thread.stack_size(0) +class BarrierTest(BasicThreadTest): + + def test_barrier(self): + self.bar = Barrier(NUMTASKS) + self.running = NUMTASKS + for i in range(NUMTASKS): + thread.start_new_thread(self.task2, (i,)) + verbose_print("waiting for tasks to end") + self.done_mutex.acquire() + verbose_print("tasks done") + + def task2(self, ident): + for i in range(NUMTRIPS): + if ident == 0: + # give it a good chance to enter the next + # barrier before the others are all out + # of the current one + delay = 0 + else: + with self.random_mutex: + delay = random.random() / 10000.0 + verbose_print("task %s will run for %sus" % + (ident, round(delay * 1e6))) + time.sleep(delay) + verbose_print("task %s entering %s" % (ident, i)) + self.bar.enter() + verbose_print("task %s leaving barrier" % ident) + with self.running_mutex: + self.running -= 1 + # Must release mutex before releasing done, else the main thread can + # exit and set mutex to None as part of global teardown; then + # mutex.release() raises AttributeError. + finished = self.running == 0 + if finished: + self.done_mutex.release() + +def test_main(): + test_support.run_unittest(ThreadRunningTests, BarrierTest) + +if __name__ == "__main__": + test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_threading.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_threading.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_threading.py Wed Apr 30 15:57:13 2008 @@ -8,6 +8,7 @@ import thread import time import unittest +import weakref # A trivial mutable counter. class Counter(object): @@ -29,32 +30,27 @@ self.nrunning = nrunning def run(self): - delay = random.random() * 2 + delay = random.random() / 10000.0 if verbose: - print('task', self.getName(), 'will run for', delay, 'sec') + print('task %s will run for %.1f usec' % + (self.getName(), delay * 1e6)) - self.sema.acquire() + with self.sema: + with self.mutex: + self.nrunning.inc() + if verbose: + print(self.nrunning.get(), 'tasks are running') + self.testcase.assert_(self.nrunning.get() <= 3) - self.mutex.acquire() - self.nrunning.inc() - if verbose: - print(self.nrunning.get(), 'tasks are running') - self.testcase.assert_(self.nrunning.get() <= 3) - self.mutex.release() - - time.sleep(delay) - if verbose: - print('task', self.getName(), 'done') - - self.mutex.acquire() - self.nrunning.dec() - self.testcase.assert_(self.nrunning.get() >= 0) - if verbose: - print(self.getName(), 'is finished.', self.nrunning.get(), \ - 'tasks are running') - self.mutex.release() - - self.sema.release() + time.sleep(delay) + if verbose: + print('task', self.getName(), 'done') + with self.mutex: + self.nrunning.dec() + self.testcase.assert_(self.nrunning.get() >= 0) + if verbose: + print('%s is finished. %d tasks are running' % + (self.getName(), self.nrunning.get())) class ThreadTests(unittest.TestCase): @@ -217,6 +213,10 @@ rc = subprocess.call([sys.executable, "-c", """if 1: import ctypes, sys, time, thread + # This lock is used as a simple event variable. + ready = thread.allocate_lock() + ready.acquire() + # Module globals are cleared before __del__ is run # So we save the functions in class dict class C: @@ -228,22 +228,54 @@ def waitingThread(): x = C() + ready.release() time.sleep(100) thread.start_new_thread(waitingThread, ()) - time.sleep(1) # be sure the other thread is waiting + ready.acquire() # Be sure the other thread is waiting. sys.exit(42) """]) self.assertEqual(rc, 42) + def test_finalize_with_trace(self): + # Issue1733757 + # Avoid a deadlock when sys.settrace steps into threading._shutdown + import subprocess + rc = subprocess.call([sys.executable, "-c", """if 1: + import sys, threading + + # A deadlock-killer, to prevent the + # testsuite to hang forever + def killer(): + import os, time + time.sleep(2) + print('program blocked; aborting') + os._exit(2) + t = threading.Thread(target=killer) + t.setDaemon(True) + t.start() + + # This is the trace function + def func(frame, event, arg): + threading.currentThread() + return func + + sys.settrace(func) + """]) + self.failIf(rc == 2, "interpreted was blocked") + self.failUnless(rc == 0, "Unexpected error") + + def test_enumerate_after_join(self): # Try hard to trigger #1703448: a thread is still returned in # threading.enumerate() after it has been join()ed. enum = threading.enumerate old_interval = sys.getcheckinterval() - sys.setcheckinterval(1) try: - for i in range(1, 1000): + for i in range(1, 100): + # Try a couple times at each thread-switching interval + # to get more interleavings. + sys.setcheckinterval(i // 5) t = threading.Thread(target=lambda: None) t.start() t.join() @@ -253,6 +285,37 @@ finally: sys.setcheckinterval(old_interval) + def test_no_refcycle_through_target(self): + class RunSelfFunction(object): + def __init__(self, should_raise): + # The links in this refcycle from Thread back to self + # should be cleaned up when the thread completes. + self.should_raise = should_raise + self.thread = threading.Thread(target=self._run, + args=(self,), + kwargs={'yet_another':self}) + self.thread.start() + + def _run(self, other_ref, yet_another): + if self.should_raise: + raise SystemExit + + cyclic_object = RunSelfFunction(should_raise=False) + weak_cyclic_object = weakref.ref(cyclic_object) + cyclic_object.thread.join() + del cyclic_object + self.assertEquals(None, weak_cyclic_object(), + msg=('%d references still around' % + sys.getrefcount(weak_cyclic_object()))) + + raising_cyclic_object = RunSelfFunction(should_raise=True) + weak_raising_cyclic_object = weakref.ref(raising_cyclic_object) + raising_cyclic_object.thread.join() + del raising_cyclic_object + self.assertEquals(None, weak_raising_cyclic_object(), + msg=('%d references still around' % + sys.getrefcount(weak_raising_cyclic_object()))) + class ThreadingExceptionTests(unittest.TestCase): # A RuntimeError should be raised if Thread.start() is called Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_timeout.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_timeout.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_timeout.py Wed Apr 30 15:57:13 2008 @@ -107,19 +107,19 @@ self.sock.close() def testConnectTimeout(self): + # Choose a private address that is unlikely to exist to prevent + # failures due to the connect succeeding before the timeout. + # Use a dotted IP address to avoid including the DNS lookup time + # with the connect time. This avoids failing the assertion that + # the timeout occurred fast enough. + addr = ('10.0.0.0', 12345) + # Test connect() timeout _timeout = 0.001 self.sock.settimeout(_timeout) - # If we are too close to www.python.org, this test will fail. - # Pick a host that should be farther away. - if (socket.getfqdn().split('.')[-2:] == ['python', 'org'] or - socket.getfqdn().split('.')[-2:-1] == ['xs4all']): - self.addr_remote = ('tut.fi', 80) - _t1 = time.time() - self.failUnlessRaises(socket.error, self.sock.connect, - self.addr_remote) + self.failUnlessRaises(socket.error, self.sock.connect, addr) _t2 = time.time() _delta = abs(_t1 - _t2) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_tokenize.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_tokenize.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_tokenize.py Wed Apr 30 15:57:13 2008 @@ -1,143 +1,573 @@ -"""Tests for the tokenize module. +# -*- coding: utf-8 -*- -The tests were originally written in the old Python style, where the -test output was compared to a golden file. This docstring represents -the first steps towards rewriting the entire test as a doctest. +doctests = """ +Tests for the tokenize module. -The tests can be really simple. Given a small fragment of source -code, print out a table with the tokens. The ENDMARK is omitted for +The tests can be really simple. Given a small fragment of source +code, print out a table with tokens. The ENDMARK is omitted for brevity. ->>> dump_tokens("1 + 1") -NUMBER '1' (1, 0) (1, 1) -OP '+' (1, 2) (1, 3) -NUMBER '1' (1, 4) (1, 5) - -A comment generates a token here, unlike in the parser module. The -comment token is followed by an NL or a NEWLINE token, depending on -whether the line contains the completion of a statement. - ->>> dump_tokens("if False:\\n" -... " # NL\\n" -... " a = False # NEWLINE\\n") -NAME 'if' (1, 0) (1, 2) -NAME 'False' (1, 3) (1, 8) -OP ':' (1, 8) (1, 9) -NEWLINE '\\n' (1, 9) (1, 10) -COMMENT '# NL' (2, 4) (2, 8) -NL '\\n' (2, 8) (2, 9) -INDENT ' ' (3, 0) (3, 4) -NAME 'a' (3, 4) (3, 5) -OP '=' (3, 9) (3, 10) -NAME 'False' (3, 11) (3, 16) -COMMENT '# NEWLINE' (3, 17) (3, 26) -NEWLINE '\\n' (3, 26) (3, 27) -DEDENT '' (4, 0) (4, 0) - -' # Emacs hint - -There will be a bunch more tests of specific source patterns. - -The tokenize module also defines an untokenize function that should -regenerate the original program text from the tokens. - -There are some standard formatting practices that are easy to get right. - ->>> roundtrip("if x == 1:\\n" -... " print(x)\\n") -if x == 1: - print(x) + >>> dump_tokens("1 + 1") + ENCODING 'utf-8' (0, 0) (0, 0) + NUMBER '1' (1, 0) (1, 1) + OP '+' (1, 2) (1, 3) + NUMBER '1' (1, 4) (1, 5) + + >>> dump_tokens("if False:\\n" + ... " # NL\\n" + ... " True = False # NEWLINE\\n") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'if' (1, 0) (1, 2) + NAME 'False' (1, 3) (1, 8) + OP ':' (1, 8) (1, 9) + NEWLINE '\\n' (1, 9) (1, 10) + COMMENT '# NL' (2, 4) (2, 8) + NL '\\n' (2, 8) (2, 9) + INDENT ' ' (3, 0) (3, 4) + NAME 'True' (3, 4) (3, 8) + OP '=' (3, 9) (3, 10) + NAME 'False' (3, 11) (3, 16) + COMMENT '# NEWLINE' (3, 17) (3, 26) + NEWLINE '\\n' (3, 26) (3, 27) + DEDENT '' (4, 0) (4, 0) + + >>> indent_error_file = \""" + ... def k(x): + ... x += 2 + ... x += 5 + ... \""" + >>> readline = BytesIO(indent_error_file.encode('utf-8')).readline + >>> for tok in tokenize(readline): pass + Traceback (most recent call last): + ... + IndentationError: unindent does not match any outer indentation level + +There are some standard formattig practises that are easy to get right. + + >>> roundtrip("if x == 1:\\n" + ... " print(x)\\n") + True + + >>> roundtrip("# This is a comment\\n# This also") + True Some people use different formatting conventions, which makes -untokenize a little trickier. Note that this test involves trailing -whitespace after the colon. Note that we use hex escapes to make the +untokenize a little trickier. Note that this test involves trailing +whitespace after the colon. Note that we use hex escapes to make the two trailing blanks apparent in the expected output. ->>> roundtrip("if x == 1 : \\n" -... " print(x)\\n") -if x == 1 :\x20\x20 - print(x) - -Comments need to go in the right place. - ->>> roundtrip("if x == 1:\\n" -... " # A comment by itself.\\n" -... " print(x) # Comment here, too.\\n" -... " # Another comment.\\n" -... "after_if = True\\n") -if x == 1: - # A comment by itself. - print(x) # Comment here, too. - # Another comment. -after_if = True - ->>> roundtrip("if (x # The comments need to go in the right place\\n" -... " == 1):\\n" -... " print('x == 1')\\n") -if (x # The comments need to go in the right place - == 1): - print('x == 1') - + >>> roundtrip("if x == 1 : \\n" + ... " print(x)\\n") + True + + >>> f = test_support.findfile("tokenize_tests.txt") + >>> roundtrip(open(f, 'rb')) + True + + >>> roundtrip("if x == 1:\\n" + ... " # A comment by itself.\\n" + ... " print(x) # Comment here, too.\\n" + ... " # Another comment.\\n" + ... "after_if = True\\n") + True + + >>> roundtrip("if (x # The comments need to go in the right place\\n" + ... " == 1):\\n" + ... " print('x==1')\\n") + True + + >>> roundtrip("class Test: # A comment here\\n" + ... " # A comment with weird indent\\n" + ... " after_com = 5\\n" + ... " def x(m): return m*5 # a one liner\\n" + ... " def y(m): # A whitespace after the colon\\n" + ... " return y*4 # 3-space indent\\n") + True + +Some error-handling code + + >>> roundtrip("try: import somemodule\\n" + ... "except ImportError: # comment\\n" + ... " print('Can not import' # comment2\\n)" + ... "else: print 'Loaded'\\n") + True + +Balancing continuation + + >>> roundtrip("a = (3,4, \\n" + ... "5,6)\\n" + ... "y = [3, 4,\\n" + ... "5]\\n" + ... "z = {'a': 5,\\n" + ... "'b':15, 'c':True}\\n" + ... "x = len(y) + 5 - a[\\n" + ... "3] - a[2]\\n" + ... "+ len(z) - z[\\n" + ... "'b']\\n") + True + +Ordinary integers and binary operators + + >>> dump_tokens("0xff <= 255") + ENCODING 'utf-8' (0, 0) (0, 0) + NUMBER '0xff' (1, 0) (1, 4) + OP '<=' (1, 5) (1, 7) + NUMBER '255' (1, 8) (1, 11) + >>> dump_tokens("0b10 <= 255") + ENCODING 'utf-8' (0, 0) (0, 0) + NUMBER '0b10' (1, 0) (1, 4) + OP '<=' (1, 5) (1, 7) + NUMBER '255' (1, 8) (1, 11) + >>> dump_tokens("0o123 <= 0O123") + ENCODING 'utf-8' (0, 0) (0, 0) + NUMBER '0o123' (1, 0) (1, 5) + OP '<=' (1, 6) (1, 8) + NUMBER '0O123' (1, 9) (1, 14) + >>> dump_tokens("1234567 > ~0x15") + ENCODING 'utf-8' (0, 0) (0, 0) + NUMBER '1234567' (1, 0) (1, 7) + OP '>' (1, 8) (1, 9) + OP '~' (1, 10) (1, 11) + NUMBER '0x15' (1, 11) (1, 15) + >>> dump_tokens("2134568 != 1231515") + ENCODING 'utf-8' (0, 0) (0, 0) + NUMBER '2134568' (1, 0) (1, 7) + OP '!=' (1, 8) (1, 10) + NUMBER '1231515' (1, 11) (1, 18) + >>> dump_tokens("(-124561-1) & 200000000") + ENCODING 'utf-8' (0, 0) (0, 0) + OP '(' (1, 0) (1, 1) + OP '-' (1, 1) (1, 2) + NUMBER '124561' (1, 2) (1, 8) + OP '-' (1, 8) (1, 9) + NUMBER '1' (1, 9) (1, 10) + OP ')' (1, 10) (1, 11) + OP '&' (1, 12) (1, 13) + NUMBER '200000000' (1, 14) (1, 23) + >>> dump_tokens("0xdeadbeef != -1") + ENCODING 'utf-8' (0, 0) (0, 0) + NUMBER '0xdeadbeef' (1, 0) (1, 10) + OP '!=' (1, 11) (1, 13) + OP '-' (1, 14) (1, 15) + NUMBER '1' (1, 15) (1, 16) + >>> dump_tokens("0xdeadc0de & 12345") + ENCODING 'utf-8' (0, 0) (0, 0) + NUMBER '0xdeadc0de' (1, 0) (1, 10) + OP '&' (1, 11) (1, 12) + NUMBER '12345' (1, 13) (1, 18) + >>> dump_tokens("0xFF & 0x15 | 1234") + ENCODING 'utf-8' (0, 0) (0, 0) + NUMBER '0xFF' (1, 0) (1, 4) + OP '&' (1, 5) (1, 6) + NUMBER '0x15' (1, 7) (1, 11) + OP '|' (1, 12) (1, 13) + NUMBER '1234' (1, 14) (1, 18) + +Long integers + + >>> dump_tokens("x = 0") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'x' (1, 0) (1, 1) + OP '=' (1, 2) (1, 3) + NUMBER '0' (1, 4) (1, 5) + >>> dump_tokens("x = 0xfffffffffff") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'x' (1, 0) (1, 1) + OP '=' (1, 2) (1, 3) + NUMBER '0xffffffffff (1, 4) (1, 17) + >>> dump_tokens("x = 123141242151251616110") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'x' (1, 0) (1, 1) + OP '=' (1, 2) (1, 3) + NUMBER '123141242151 (1, 4) (1, 25) + >>> dump_tokens("x = -15921590215012591") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'x' (1, 0) (1, 1) + OP '=' (1, 2) (1, 3) + OP '-' (1, 4) (1, 5) + NUMBER '159215902150 (1, 5) (1, 22) + +Floating point numbers + + >>> dump_tokens("x = 3.14159") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'x' (1, 0) (1, 1) + OP '=' (1, 2) (1, 3) + NUMBER '3.14159' (1, 4) (1, 11) + >>> dump_tokens("x = 314159.") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'x' (1, 0) (1, 1) + OP '=' (1, 2) (1, 3) + NUMBER '314159.' (1, 4) (1, 11) + >>> dump_tokens("x = .314159") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'x' (1, 0) (1, 1) + OP '=' (1, 2) (1, 3) + NUMBER '.314159' (1, 4) (1, 11) + >>> dump_tokens("x = 3e14159") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'x' (1, 0) (1, 1) + OP '=' (1, 2) (1, 3) + NUMBER '3e14159' (1, 4) (1, 11) + >>> dump_tokens("x = 3E123") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'x' (1, 0) (1, 1) + OP '=' (1, 2) (1, 3) + NUMBER '3E123' (1, 4) (1, 9) + >>> dump_tokens("x+y = 3e-1230") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'x' (1, 0) (1, 1) + OP '+' (1, 1) (1, 2) + NAME 'y' (1, 2) (1, 3) + OP '=' (1, 4) (1, 5) + NUMBER '3e-1230' (1, 6) (1, 13) + >>> dump_tokens("x = 3.14e159") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'x' (1, 0) (1, 1) + OP '=' (1, 2) (1, 3) + NUMBER '3.14e159' (1, 4) (1, 12) + +String literals + + >>> dump_tokens("x = ''; y = \\\"\\\"") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'x' (1, 0) (1, 1) + OP '=' (1, 2) (1, 3) + STRING "''" (1, 4) (1, 6) + OP ';' (1, 6) (1, 7) + NAME 'y' (1, 8) (1, 9) + OP '=' (1, 10) (1, 11) + STRING '""' (1, 12) (1, 14) + >>> dump_tokens("x = '\\\"'; y = \\\"'\\\"") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'x' (1, 0) (1, 1) + OP '=' (1, 2) (1, 3) + STRING '\\'"\\'' (1, 4) (1, 7) + OP ';' (1, 7) (1, 8) + NAME 'y' (1, 9) (1, 10) + OP '=' (1, 11) (1, 12) + STRING '"\\'"' (1, 13) (1, 16) + >>> dump_tokens("x = \\\"doesn't \\\"shrink\\\", does it\\\"") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'x' (1, 0) (1, 1) + OP '=' (1, 2) (1, 3) + STRING '"doesn\\'t "' (1, 4) (1, 14) + NAME 'shrink' (1, 14) (1, 20) + STRING '", does it"' (1, 20) (1, 31) + >>> dump_tokens("x = 'abc' + 'ABC'") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'x' (1, 0) (1, 1) + OP '=' (1, 2) (1, 3) + STRING "'abc'" (1, 4) (1, 9) + OP '+' (1, 10) (1, 11) + STRING "'ABC'" (1, 12) (1, 17) + >>> dump_tokens('y = "ABC" + "ABC"') + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'y' (1, 0) (1, 1) + OP '=' (1, 2) (1, 3) + STRING '"ABC"' (1, 4) (1, 9) + OP '+' (1, 10) (1, 11) + STRING '"ABC"' (1, 12) (1, 17) + >>> dump_tokens("x = r'abc' + r'ABC' + R'ABC' + R'ABC'") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'x' (1, 0) (1, 1) + OP '=' (1, 2) (1, 3) + STRING "r'abc'" (1, 4) (1, 10) + OP '+' (1, 11) (1, 12) + STRING "r'ABC'" (1, 13) (1, 19) + OP '+' (1, 20) (1, 21) + STRING "R'ABC'" (1, 22) (1, 28) + OP '+' (1, 29) (1, 30) + STRING "R'ABC'" (1, 31) (1, 37) + >>> dump_tokens('y = r"abc" + r"ABC" + R"ABC" + R"ABC"') + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'y' (1, 0) (1, 1) + OP '=' (1, 2) (1, 3) + STRING 'r"abc"' (1, 4) (1, 10) + OP '+' (1, 11) (1, 12) + STRING 'r"ABC"' (1, 13) (1, 19) + OP '+' (1, 20) (1, 21) + STRING 'R"ABC"' (1, 22) (1, 28) + OP '+' (1, 29) (1, 30) + STRING 'R"ABC"' (1, 31) (1, 37) + +Operators + + >>> dump_tokens("def d22(a, b, c=2, d=2, *k): pass") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'def' (1, 0) (1, 3) + NAME 'd22' (1, 4) (1, 7) + OP '(' (1, 7) (1, 8) + NAME 'a' (1, 8) (1, 9) + OP ',' (1, 9) (1, 10) + NAME 'b' (1, 11) (1, 12) + OP ',' (1, 12) (1, 13) + NAME 'c' (1, 14) (1, 15) + OP '=' (1, 15) (1, 16) + NUMBER '2' (1, 16) (1, 17) + OP ',' (1, 17) (1, 18) + NAME 'd' (1, 19) (1, 20) + OP '=' (1, 20) (1, 21) + NUMBER '2' (1, 21) (1, 22) + OP ',' (1, 22) (1, 23) + OP '*' (1, 24) (1, 25) + NAME 'k' (1, 25) (1, 26) + OP ')' (1, 26) (1, 27) + OP ':' (1, 27) (1, 28) + NAME 'pass' (1, 29) (1, 33) + >>> dump_tokens("def d01v_(a=1, *k, **w): pass") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'def' (1, 0) (1, 3) + NAME 'd01v_' (1, 4) (1, 9) + OP '(' (1, 9) (1, 10) + NAME 'a' (1, 10) (1, 11) + OP '=' (1, 11) (1, 12) + NUMBER '1' (1, 12) (1, 13) + OP ',' (1, 13) (1, 14) + OP '*' (1, 15) (1, 16) + NAME 'k' (1, 16) (1, 17) + OP ',' (1, 17) (1, 18) + OP '**' (1, 19) (1, 21) + NAME 'w' (1, 21) (1, 22) + OP ')' (1, 22) (1, 23) + OP ':' (1, 23) (1, 24) + NAME 'pass' (1, 25) (1, 29) + +Comparison + + >>> dump_tokens("if 1 < 1 > 1 == 1 >= 5 <= 0x15 <= 0x12 != " + + ... "1 and 5 in 1 not in 1 is 1 or 5 is not 1: pass") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'if' (1, 0) (1, 2) + NUMBER '1' (1, 3) (1, 4) + OP '<' (1, 5) (1, 6) + NUMBER '1' (1, 7) (1, 8) + OP '>' (1, 9) (1, 10) + NUMBER '1' (1, 11) (1, 12) + OP '==' (1, 13) (1, 15) + NUMBER '1' (1, 16) (1, 17) + OP '>=' (1, 18) (1, 20) + NUMBER '5' (1, 21) (1, 22) + OP '<=' (1, 23) (1, 25) + NUMBER '0x15' (1, 26) (1, 30) + OP '<=' (1, 31) (1, 33) + NUMBER '0x12' (1, 34) (1, 38) + OP '!=' (1, 39) (1, 41) + NUMBER '1' (1, 42) (1, 43) + NAME 'and' (1, 44) (1, 47) + NUMBER '5' (1, 48) (1, 49) + NAME 'in' (1, 50) (1, 52) + NUMBER '1' (1, 53) (1, 54) + NAME 'not' (1, 55) (1, 58) + NAME 'in' (1, 59) (1, 61) + NUMBER '1' (1, 62) (1, 63) + NAME 'is' (1, 64) (1, 66) + NUMBER '1' (1, 67) (1, 68) + NAME 'or' (1, 69) (1, 71) + NUMBER '5' (1, 72) (1, 73) + NAME 'is' (1, 74) (1, 76) + NAME 'not' (1, 77) (1, 80) + NUMBER '1' (1, 81) (1, 82) + OP ':' (1, 82) (1, 83) + NAME 'pass' (1, 84) (1, 88) + +Shift + + >>> dump_tokens("x = 1 << 1 >> 5") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'x' (1, 0) (1, 1) + OP '=' (1, 2) (1, 3) + NUMBER '1' (1, 4) (1, 5) + OP '<<' (1, 6) (1, 8) + NUMBER '1' (1, 9) (1, 10) + OP '>>' (1, 11) (1, 13) + NUMBER '5' (1, 14) (1, 15) + +Additive + + >>> dump_tokens("x = 1 - y + 15 - 1 + 0x124 + z + a[5]") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'x' (1, 0) (1, 1) + OP '=' (1, 2) (1, 3) + NUMBER '1' (1, 4) (1, 5) + OP '-' (1, 6) (1, 7) + NAME 'y' (1, 8) (1, 9) + OP '+' (1, 10) (1, 11) + NUMBER '15' (1, 12) (1, 14) + OP '-' (1, 15) (1, 16) + NUMBER '1' (1, 17) (1, 18) + OP '+' (1, 19) (1, 20) + NUMBER '0x124' (1, 21) (1, 26) + OP '+' (1, 27) (1, 28) + NAME 'z' (1, 29) (1, 30) + OP '+' (1, 31) (1, 32) + NAME 'a' (1, 33) (1, 34) + OP '[' (1, 34) (1, 35) + NUMBER '5' (1, 35) (1, 36) + OP ']' (1, 36) (1, 37) + +Multiplicative + + >>> dump_tokens("x = 1//1*1/5*12%0x12") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'x' (1, 0) (1, 1) + OP '=' (1, 2) (1, 3) + NUMBER '1' (1, 4) (1, 5) + OP '//' (1, 5) (1, 7) + NUMBER '1' (1, 7) (1, 8) + OP '*' (1, 8) (1, 9) + NUMBER '1' (1, 9) (1, 10) + OP '/' (1, 10) (1, 11) + NUMBER '5' (1, 11) (1, 12) + OP '*' (1, 12) (1, 13) + NUMBER '12' (1, 13) (1, 15) + OP '%' (1, 15) (1, 16) + NUMBER '0x12' (1, 16) (1, 20) + +Unary + + >>> dump_tokens("~1 ^ 1 & 1 |1 ^ -1") + ENCODING 'utf-8' (0, 0) (0, 0) + OP '~' (1, 0) (1, 1) + NUMBER '1' (1, 1) (1, 2) + OP '^' (1, 3) (1, 4) + NUMBER '1' (1, 5) (1, 6) + OP '&' (1, 7) (1, 8) + NUMBER '1' (1, 9) (1, 10) + OP '|' (1, 11) (1, 12) + NUMBER '1' (1, 12) (1, 13) + OP '^' (1, 14) (1, 15) + OP '-' (1, 16) (1, 17) + NUMBER '1' (1, 17) (1, 18) + >>> dump_tokens("-1*1/1+1*1//1 - ---1**1") + ENCODING 'utf-8' (0, 0) (0, 0) + OP '-' (1, 0) (1, 1) + NUMBER '1' (1, 1) (1, 2) + OP '*' (1, 2) (1, 3) + NUMBER '1' (1, 3) (1, 4) + OP '/' (1, 4) (1, 5) + NUMBER '1' (1, 5) (1, 6) + OP '+' (1, 6) (1, 7) + NUMBER '1' (1, 7) (1, 8) + OP '*' (1, 8) (1, 9) + NUMBER '1' (1, 9) (1, 10) + OP '//' (1, 10) (1, 12) + NUMBER '1' (1, 12) (1, 13) + OP '-' (1, 14) (1, 15) + OP '-' (1, 16) (1, 17) + OP '-' (1, 17) (1, 18) + OP '-' (1, 18) (1, 19) + NUMBER '1' (1, 19) (1, 20) + OP '**' (1, 20) (1, 22) + NUMBER '1' (1, 22) (1, 23) + +Selector + + >>> dump_tokens("import sys, time\\nx = sys.modules['time'].time()") + ENCODING 'utf-8' (0, 0) (0, 0) + NAME 'import' (1, 0) (1, 6) + NAME 'sys' (1, 7) (1, 10) + OP ',' (1, 10) (1, 11) + NAME 'time' (1, 12) (1, 16) + NEWLINE '\\n' (1, 16) (1, 17) + NAME 'x' (2, 0) (2, 1) + OP '=' (2, 2) (2, 3) + NAME 'sys' (2, 4) (2, 7) + OP '.' (2, 7) (2, 8) + NAME 'modules' (2, 8) (2, 15) + OP '[' (2, 15) (2, 16) + STRING "'time'" (2, 16) (2, 22) + OP ']' (2, 22) (2, 23) + OP '.' (2, 23) (2, 24) + NAME 'time' (2, 24) (2, 28) + OP '(' (2, 28) (2, 29) + OP ')' (2, 29) (2, 30) + +Methods + + >>> dump_tokens("@staticmethod\\ndef foo(x,y): pass") + ENCODING 'utf-8' (0, 0) (0, 0) + OP '@' (1, 0) (1, 1) + NAME 'staticmethod (1, 1) (1, 13) + NEWLINE '\\n' (1, 13) (1, 14) + NAME 'def' (2, 0) (2, 3) + NAME 'foo' (2, 4) (2, 7) + OP '(' (2, 7) (2, 8) + NAME 'x' (2, 8) (2, 9) + OP ',' (2, 9) (2, 10) + NAME 'y' (2, 10) (2, 11) + OP ')' (2, 11) (2, 12) + OP ':' (2, 12) (2, 13) + NAME 'pass' (2, 14) (2, 18) + +Backslash means line continuation, except for comments + + >>> roundtrip("x=1+\\\\n" + ... "1\\n" + ... "# This is a comment\\\\n" + ... "# This also\\n") + True + >>> roundtrip("# Comment \\\\nx = 0") + True + +Two string literals on the same line + + >>> roundtrip("'' ''") + True + +Test roundtrip on random python modules. +pass the '-ucompiler' option to process the full directory. + + >>> import random + >>> tempdir = os.path.dirname(f) or os.curdir + >>> testfiles = glob.glob(os.path.join(tempdir, "test*.py")) + + >>> if not test_support.is_resource_enabled("compiler"): + ... testfiles = random.sample(testfiles, 10) + ... + >>> for testfile in testfiles: + ... if not roundtrip(open(testfile, 'rb')): + ... print("Roundtrip failed for file %s" % testfile) + ... break + ... else: True + True """ -# ' Emacs hint - -import os, glob, random, time, sys -import re -from io import StringIO -from test.test_support import (verbose, findfile, is_resource_enabled, - TestFailed) -from tokenize import (tokenize, generate_tokens, untokenize, tok_name, - ENDMARKER, NUMBER, NAME, OP, STRING, COMMENT) - -# How much time in seconds can pass before we print a 'Still working' message. -_PRINT_WORKING_MSG_INTERVAL = 5 * 60 - -# Test roundtrip for `untokenize`. `f` is a file path. The source code in f -# is tokenized, converted back to source code via tokenize.untokenize(), -# and tokenized again from the latter. The test fails if the second -# tokenization doesn't match the first. -def test_roundtrip(f): - ## print('Testing:', f) - # Get the encoding first - fobj = open(f, encoding="latin-1") - first2lines = fobj.readline() + fobj.readline() - fobj.close() - m = re.search(r"coding:\s*(\S+)", first2lines) - if m: - encoding = m.group(1) - ## print(" coding:", encoding) - else: - encoding = "utf-8" - fobj = open(f, encoding=encoding) - try: - fulltok = list(generate_tokens(fobj.readline)) - finally: - fobj.close() - - t1 = [tok[:2] for tok in fulltok] - newtext = untokenize(t1) - readline = iter(newtext.splitlines(1)).__next__ - t2 = [tok[:2] for tok in generate_tokens(readline)] - if t1 != t2: - raise TestFailed("untokenize() roundtrip failed for %r" % f) +from test import test_support +from tokenize import (tokenize, _tokenize, untokenize, NUMBER, NAME, OP, + STRING, ENDMARKER, tok_name, detect_encoding) +from io import BytesIO +from unittest import TestCase +import os, sys, glob def dump_tokens(s): """Print out the tokens in s in a table format. The ENDMARKER is omitted. """ - f = StringIO(s) - for type, token, start, end, line in generate_tokens(f.readline): + f = BytesIO(s.encode('utf-8')) + for type, token, start, end, line in tokenize(f.readline): if type == ENDMARKER: break type = tok_name[type] - print("%(type)-10.10s %(token)-13.13r %(start)s %(end)s" % locals()) + print("%(type)-10.10s %(token)-13.13r %(start)s %(end)s" % locals()) -def roundtrip(s): - f = StringIO(s) - source = untokenize(generate_tokens(f.readline)) - print(source, end="") +def roundtrip(f): + """ + Test roundtrip for `untokenize`. `f` is an open file or a string. + The source code in f is tokenized, converted back to source code via + tokenize.untokenize(), and tokenized again from the latter. The test + fails if the second tokenization doesn't match the first. + """ + if isinstance(f, str): + f = BytesIO(f.encode('utf-8')) + token_list = list(tokenize(f.readline)) + f.close() + tokens1 = [tok[:2] for tok in token_list] + new_bytes = untokenize(tokens1) + readline = (line for line in new_bytes.splitlines(1)).__next__ + tokens2 = [tok[:2] for tok in tokenize(readline)] + return tokens1 == tokens2 # This is an example from the docs, set up as a doctest. def decistmt(s): @@ -162,9 +592,8 @@ >>> exec(decistmt(s)) -3.217160342717258261933904529E-7 """ - result = [] - g = generate_tokens(StringIO(s).readline) # tokenize the string + g = tokenize(BytesIO(s.encode('utf-8')).readline) # tokenize the string for toknum, tokval, _, _, _ in g: if toknum == NUMBER and '.' in tokval: # replace NUMBER tokens result.extend([ @@ -175,84 +604,249 @@ ]) else: result.append((toknum, tokval)) - return untokenize(result) - -def test_main(): - if verbose: - print('starting...') + return untokenize(result).decode('utf-8') - next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL - # Validate the tokenize_tests.txt file. - # This makes sure it compiles, and displays any errors in it. - f = open(findfile('tokenize_tests.txt')) - sf = f.read() - f.close() - cf = compile(sf, 'tokenize_tests.txt', 'exec') +class TestTokenizerAdheresToPep0263(TestCase): + """ + Test that tokenizer adheres to the coding behaviour stipulated in PEP 0263. + """ - # This displays the tokenization of tokenize_tests.py to stdout, and - # regrtest.py checks that this equals the expected output (in the - # test/output/ directory). - f = open(findfile('tokenize_tests.txt')) - tokenize(f.readline) - f.close() + def _testFile(self, filename): + path = os.path.join(os.path.dirname(__file__), filename) + return roundtrip(open(path, 'rb')) + + def test_utf8_coding_cookie_and_no_utf8_bom(self): + f = 'tokenize_tests-utf8-coding-cookie-and-utf8-bom-sig.txt' + self.assertTrue(self._testFile(f)) + + def test_latin1_coding_cookie_and_utf8_bom(self): + """ + As per PEP 0263, if a file starts with a utf-8 BOM signature, the only + allowed encoding for the comment is 'utf-8'. The text file used in + this test starts with a BOM signature, but specifies latin1 as the + coding, so verify that a SyntaxError is raised, which matches the + behaviour of the interpreter when it encounters a similar condition. + """ + f = 'tokenize_tests-latin1-coding-cookie-and-utf8-bom-sig.txt' + self.failUnlessRaises(SyntaxError, self._testFile, f) + + def test_no_coding_cookie_and_utf8_bom(self): + f = 'tokenize_tests-no-coding-cookie-and-utf8-bom-sig-only.txt' + self.assertTrue(self._testFile(f)) + + def test_utf8_coding_cookie_and_utf8_bom(self): + f = 'tokenize_tests-utf8-coding-cookie-and-utf8-bom-sig.txt' + self.assertTrue(self._testFile(f)) + + +class Test_Tokenize(TestCase): + + def test__tokenize_decodes_with_specified_encoding(self): + literal = '"??????????"' + line = literal.encode('utf-8') + first = False + def readline(): + nonlocal first + if not first: + first = True + return line + else: + return b'' + + # skip the initial encoding token and the end token + tokens = list(_tokenize(readline, encoding='utf-8'))[1:-1] + expected_tokens = [(3, '"??????????"', (1, 0), (1, 7), '"??????????"')] + self.assertEquals(tokens, expected_tokens, + "bytes not decoded with encoding") + + def test__tokenize_does_not_decode_with_encoding_none(self): + literal = '"??????????"' + first = False + def readline(): + nonlocal first + if not first: + first = True + return literal + else: + return b'' + + # skip the end token + tokens = list(_tokenize(readline, encoding=None))[:-1] + expected_tokens = [(3, '"??????????"', (1, 0), (1, 7), '"??????????"')] + self.assertEquals(tokens, expected_tokens, + "string not tokenized when encoding is None") + + +class TestDetectEncoding(TestCase): + + def get_readline(self, lines): + index = 0 + def readline(): + nonlocal index + if index == len(lines): + raise StopIteration + line = lines[index] + index += 1 + return line + return readline + + def test_no_bom_no_encoding_cookie(self): + lines = ( + b'# something\n', + b'print(something)\n', + b'do_something(else)\n' + ) + encoding, consumed_lines = detect_encoding(self.get_readline(lines)) + self.assertEquals(encoding, 'utf-8') + self.assertEquals(consumed_lines, list(lines[:2])) + + def test_bom_no_cookie(self): + lines = ( + b'\xef\xbb\xbf# something\n', + b'print(something)\n', + b'do_something(else)\n' + ) + encoding, consumed_lines = detect_encoding(self.get_readline(lines)) + self.assertEquals(encoding, 'utf-8') + self.assertEquals(consumed_lines, + [b'# something\n', b'print(something)\n']) + + def test_cookie_first_line_no_bom(self): + lines = ( + b'# -*- coding: latin-1 -*-\n', + b'print(something)\n', + b'do_something(else)\n' + ) + encoding, consumed_lines = detect_encoding(self.get_readline(lines)) + self.assertEquals(encoding, 'latin-1') + self.assertEquals(consumed_lines, [b'# -*- coding: latin-1 -*-\n']) + + def test_matched_bom_and_cookie_first_line(self): + lines = ( + b'\xef\xbb\xbf# coding=utf-8\n', + b'print(something)\n', + b'do_something(else)\n' + ) + encoding, consumed_lines = detect_encoding(self.get_readline(lines)) + self.assertEquals(encoding, 'utf-8') + self.assertEquals(consumed_lines, [b'# coding=utf-8\n']) + + def test_mismatched_bom_and_cookie_first_line_raises_syntaxerror(self): + lines = ( + b'\xef\xbb\xbf# vim: set fileencoding=ascii :\n', + b'print(something)\n', + b'do_something(else)\n' + ) + readline = self.get_readline(lines) + self.assertRaises(SyntaxError, detect_encoding, readline) + + def test_cookie_second_line_no_bom(self): + lines = ( + b'#! something\n', + b'# vim: set fileencoding=ascii :\n', + b'print(something)\n', + b'do_something(else)\n' + ) + encoding, consumed_lines = detect_encoding(self.get_readline(lines)) + self.assertEquals(encoding, 'ascii') + expected = [b'#! something\n', b'# vim: set fileencoding=ascii :\n'] + self.assertEquals(consumed_lines, expected) + + def test_matched_bom_and_cookie_second_line(self): + lines = ( + b'\xef\xbb\xbf#! something\n', + b'f# coding=utf-8\n', + b'print(something)\n', + b'do_something(else)\n' + ) + encoding, consumed_lines = detect_encoding(self.get_readline(lines)) + self.assertEquals(encoding, 'utf-8') + self.assertEquals(consumed_lines, + [b'#! something\n', b'f# coding=utf-8\n']) + + def test_mismatched_bom_and_cookie_second_line_raises_syntaxerror(self): + lines = ( + b'\xef\xbb\xbf#! something\n', + b'# vim: set fileencoding=ascii :\n', + b'print(something)\n', + b'do_something(else)\n' + ) + readline = self.get_readline(lines) + self.assertRaises(SyntaxError, detect_encoding, readline) + + def test_short_files(self): + readline = self.get_readline((b'print(something)\n',)) + encoding, consumed_lines = detect_encoding(readline) + self.assertEquals(encoding, 'utf-8') + self.assertEquals(consumed_lines, [b'print(something)\n']) + + encoding, consumed_lines = detect_encoding(self.get_readline(())) + self.assertEquals(encoding, 'utf-8') + self.assertEquals(consumed_lines, []) + + readline = self.get_readline((b'\xef\xbb\xbfprint(something)\n',)) + encoding, consumed_lines = detect_encoding(readline) + self.assertEquals(encoding, 'utf-8') + self.assertEquals(consumed_lines, [b'print(something)\n']) + + readline = self.get_readline((b'\xef\xbb\xbf',)) + encoding, consumed_lines = detect_encoding(readline) + self.assertEquals(encoding, 'utf-8') + self.assertEquals(consumed_lines, []) + + +class TestTokenize(TestCase): + + def test_tokenize(self): + import tokenize as tokenize_module + encoding = object() + encoding_used = None + def mock_detect_encoding(readline): + return encoding, ['first', 'second'] + + def mock__tokenize(readline, encoding): + nonlocal encoding_used + encoding_used = encoding + out = [] + while True: + next_line = readline() + if next_line: + out.append(next_line) + continue + return out + + counter = 0 + def mock_readline(): + nonlocal counter + counter += 1 + if counter == 5: + return b'' + return counter + + orig_detect_encoding = tokenize_module.detect_encoding + orig__tokenize = tokenize_module._tokenize + tokenize_module.detect_encoding = mock_detect_encoding + tokenize_module._tokenize = mock__tokenize + try: + results = tokenize(mock_readline) + self.assertEquals(list(results), ['first', 'second', 1, 2, 3, 4]) + finally: + tokenize_module.detect_encoding = orig_detect_encoding + tokenize_module._tokenize = orig__tokenize - # Now run test_roundtrip() over test_tokenize.py too, and over all - # (if the "compiler" resource is enabled) or a small random sample (if - # "compiler" is not enabled) of the test*.py files. - f = findfile('test_tokenize.py') - if verbose: - print(' round trip: ', f, file=sys.__stdout__) - test_roundtrip(f) - - testdir = os.path.dirname(f) or os.curdir - testfiles = glob.glob(testdir + os.sep + 'test*.py') - if not is_resource_enabled('compiler'): - testfiles = random.sample(testfiles, 10) - - for f in testfiles: - # Print still working message since this test can be really slow - if verbose: - print(' round trip: ', f, file=sys.__stdout__) - if next_time <= time.time(): - next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL - print(' test_main still working, be patient...', file=sys.__stdout__) - sys.__stdout__.flush() - - test_roundtrip(f) - - # Test detecton of IndentationError. - sampleBadText = """\ -def foo(): - bar - baz -""" + self.assertTrue(encoding_used, encoding) - try: - for tok in generate_tokens(StringIO(sampleBadText).readline): - pass - except IndentationError: - pass - else: - raise TestFailed("Did not detect IndentationError:") - - # Run the doctests in this module. - from test import test_tokenize # i.e., this module - from test.test_support import run_doctest - run_doctest(test_tokenize, verbose) - if verbose: - print('finished') +__test__ = {"doctests" : doctests, 'decistmt': decistmt} -def test_rarrow(): - """ - This function exists solely to test the tokenization of the RARROW - operator. - - >>> tokenize(iter(['->']).__next__) #doctest: +NORMALIZE_WHITESPACE - 1,0-1,2:\tOP\t'->' - 2,0-2,0:\tENDMARKER\t'' - """ +def test_main(): + from test import test_tokenize + test_support.run_doctest(test_tokenize, True) + test_support.run_unittest(TestTokenizerAdheresToPep0263) + test_support.run_unittest(Test_Tokenize) + test_support.run_unittest(TestDetectEncoding) + test_support.run_unittest(TestTokenize) if __name__ == "__main__": test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_trace.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_trace.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_trace.py Wed Apr 30 15:57:13 2008 @@ -252,14 +252,16 @@ "\n".join(difflib.ndiff([str(x) for x in expected_events], [str(x) for x in events]))) - - def run_test(self, func): + def run_and_compare(self, func, events): tracer = Tracer() sys.settrace(tracer.trace) func() sys.settrace(None) self.compare_events(func.__code__.co_firstlineno, - tracer.events, func.events) + tracer.events, events) + + def run_test(self, func): + self.run_and_compare(func, func.events) def run_test2(self, func): tracer = Tracer() @@ -321,6 +323,59 @@ self.compare_events(generator_example.__code__.co_firstlineno, tracer.events, generator_example.events) + def test_14_onliner_if(self): + def onliners(): + if True: False + else: True + return 0 + self.run_and_compare( + onliners, + [(0, 'call'), + (1, 'line'), + (3, 'line'), + (3, 'return')]) + + def test_15_loops(self): + # issue1750076: "while" expression is skipped by debugger + def for_example(): + for x in range(2): + pass + self.run_and_compare( + for_example, + [(0, 'call'), + (1, 'line'), + (2, 'line'), + (1, 'line'), + (2, 'line'), + (1, 'line'), + (1, 'return')]) + + def while_example(): + # While expression should be traced on every loop + x = 2 + while x > 0: + x -= 1 + self.run_and_compare( + while_example, + [(0, 'call'), + (2, 'line'), + (3, 'line'), + (4, 'line'), + (3, 'line'), + (4, 'line'), + (3, 'line'), + (3, 'return')]) + + def test_16_blank_lines(self): + namespace = {} + exec("def f():\n" + "\n" * 256 + " pass", namespace) + self.run_and_compare( + namespace["f"], + [(0, 'call'), + (257, 'line'), + (257, 'return')]) + + class RaisingTraceFuncTestCase(unittest.TestCase): def trace(self, frame, event, arg): """A trace function that raises an exception in response to a Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_tuple.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_tuple.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_tuple.py Wed Apr 30 15:57:13 2008 @@ -1,4 +1,3 @@ -import unittest from test import test_support, seq_tests class TupleTest(seq_tests.CommonTest): Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_types.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_types.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_types.py Wed Apr 30 15:57:13 2008 @@ -1,8 +1,9 @@ # Python test set -- part 6, built-in types -from test.test_support import run_unittest +from test.test_support import run_unittest, run_with_locale import unittest import sys +import locale class TypesTests(unittest.TestCase): @@ -63,15 +64,15 @@ try: 5 / 0 except ZeroDivisionError: pass - else: self.fail("5 / 0L didn't raise ZeroDivisionError") + else: self.fail("5 / 0 didn't raise ZeroDivisionError") try: 5 // 0 except ZeroDivisionError: pass - else: self.fail("5 // 0L didn't raise ZeroDivisionError") + else: self.fail("5 // 0 didn't raise ZeroDivisionError") try: 5 % 0 except ZeroDivisionError: pass - else: self.fail("5 % 0L didn't raise ZeroDivisionError") + else: self.fail("5 % 0 didn't raise ZeroDivisionError") def test_numeric_types(self): if 0 != 0 or 0 != 0.0 or 0 != 0.0: self.fail('mixed comparisons') @@ -80,7 +81,7 @@ self.fail('int/long/float value not equal') # calling built-in types without argument must return 0 if int() != 0: self.fail('int() does not return 0') - if int() != 0: self.fail('long() does not return 0L') + if int() != 0: self.fail('long() does not return 0') if float() != 0.0: self.fail('float() does not return 0.0') if int(1.9) == 1 == int(1.1) and int(-1.1) == -1 == int(-1.9): pass else: self.fail('int() does not round properly') @@ -89,6 +90,29 @@ if float(1) == 1.0 and float(-1) == -1.0 and float(0) == 0.0: pass else: self.fail('float() does not work properly') + def test_float_to_string(self): + def test(f, result): + self.assertEqual(f.__format__('e'), result) + self.assertEqual('%e' % f, result) + + # test all 2 digit exponents, both with __format__ and with + # '%' formatting + for i in range(-99, 100): + test(float('1.5e'+str(i)), '1.500000e{0:+03d}'.format(i)) + + # test some 3 digit exponents + self.assertEqual(1.5e100.__format__('e'), '1.500000e+100') + self.assertEqual('%e' % 1.5e100, '1.500000e+100') + + self.assertEqual(1.5e101.__format__('e'), '1.500000e+101') + self.assertEqual('%e' % 1.5e101, '1.500000e+101') + + self.assertEqual(1.5e-100.__format__('e'), '1.500000e-100') + self.assertEqual('%e' % 1.5e-100, '1.500000e-100') + + self.assertEqual(1.5e-101.__format__('e'), '1.500000e-101') + self.assertEqual('%e' % 1.5e-101, '1.500000e-101') + def test_normal_integers(self): # Ensure the first 256 integers are shared a = 256 @@ -203,6 +227,270 @@ self.assertRaises(TypeError, type, 1, 2) self.assertRaises(TypeError, type, 1, 2, 3, 4) + def test_int__format__(self): + def test(i, format_spec, result): + # just make sure I'm not accidentally checking longs + assert type(i) == int + assert type(format_spec) == str + self.assertEqual(i.__format__(format_spec), result) + + test(123456789, 'd', '123456789') + test(123456789, 'd', '123456789') + + test(1, 'c', '\01') + + # sign and aligning are interdependent + test(1, "-", '1') + test(-1, "-", '-1') + test(1, "-3", ' 1') + test(-1, "-3", ' -1') + test(1, "+3", ' +1') + test(-1, "+3", ' -1') + test(1, " 3", ' 1') + test(-1, " 3", ' -1') + test(1, " ", ' 1') + test(-1, " ", '-1') + + # hex + test(3, "x", "3") + test(3, "X", "3") + test(1234, "x", "4d2") + test(-1234, "x", "-4d2") + test(1234, "8x", " 4d2") + test(-1234, "8x", " -4d2") + test(1234, "x", "4d2") + test(-1234, "x", "-4d2") + test(-3, "x", "-3") + test(-3, "X", "-3") + test(int('be', 16), "x", "be") + test(int('be', 16), "X", "BE") + test(-int('be', 16), "x", "-be") + test(-int('be', 16), "X", "-BE") + + # octal + test(3, "o", "3") + test(-3, "o", "-3") + test(65, "o", "101") + test(-65, "o", "-101") + test(1234, "o", "2322") + test(-1234, "o", "-2322") + test(1234, "-o", "2322") + test(-1234, "-o", "-2322") + test(1234, " o", " 2322") + test(-1234, " o", "-2322") + test(1234, "+o", "+2322") + test(-1234, "+o", "-2322") + + # binary + test(3, "b", "11") + test(-3, "b", "-11") + test(1234, "b", "10011010010") + test(-1234, "b", "-10011010010") + test(1234, "-b", "10011010010") + test(-1234, "-b", "-10011010010") + test(1234, " b", " 10011010010") + test(-1234, " b", "-10011010010") + test(1234, "+b", "+10011010010") + test(-1234, "+b", "-10011010010") + + # make sure these are errors + + # precision disallowed + self.assertRaises(ValueError, 3 .__format__, "1.3") + # sign not allowed with 'c' + self.assertRaises(ValueError, 3 .__format__, "+c") + # format spec must be string + self.assertRaises(TypeError, 3 .__format__, None) + self.assertRaises(TypeError, 3 .__format__, 0) + + # ensure that only int and float type specifiers work + for format_spec in ([chr(x) for x in range(ord('a'), ord('z')+1)] + + [chr(x) for x in range(ord('A'), ord('Z')+1)]): + if not format_spec in 'bcdoxXeEfFgGn%': + self.assertRaises(ValueError, 0 .__format__, format_spec) + self.assertRaises(ValueError, 1 .__format__, format_spec) + self.assertRaises(ValueError, (-1) .__format__, format_spec) + + # ensure that float type specifiers work; format converts + # the int to a float + for format_spec in 'eEfFgGn%': + for value in [0, 1, -1, 100, -100, 1234567890, -1234567890]: + self.assertEqual(value.__format__(format_spec), + float(value).__format__(format_spec)) + + def test_long__format__(self): + def test(i, format_spec, result): + # make sure we're not accidentally checking ints + assert type(i) == int + assert type(format_spec) == str + self.assertEqual(i.__format__(format_spec), result) + + test(10**100, 'd', '1' + '0' * 100) + test(10**100+100, 'd', '1' + '0' * 97 + '100') + + test(123456789, 'd', '123456789') + test(123456789, 'd', '123456789') + + # sign and aligning are interdependent + test(1, "-", '1') + test(-1, "-", '-1') + test(1, "-3", ' 1') + test(-1, "-3", ' -1') + test(1, "+3", ' +1') + test(-1, "+3", ' -1') + test(1, " 3", ' 1') + test(-1, " 3", ' -1') + test(1, " ", ' 1') + test(-1, " ", '-1') + + test(1, 'c', '\01') + + # hex + test(3, "x", "3") + test(3, "X", "3") + test(1234, "x", "4d2") + test(-1234, "x", "-4d2") + test(1234, "8x", " 4d2") + test(-1234, "8x", " -4d2") + test(1234, "x", "4d2") + test(-1234, "x", "-4d2") + test(-3, "x", "-3") + test(-3, "X", "-3") + + # octal + test(3, "o", "3") + test(-3, "o", "-3") + test(65, "o", "101") + test(-65, "o", "-101") + test(1234, "o", "2322") + test(-1234, "o", "-2322") + test(1234, "-o", "2322") + test(-1234, "-o", "-2322") + test(1234, " o", " 2322") + test(-1234, " o", "-2322") + test(1234, "+o", "+2322") + test(-1234, "+o", "-2322") + + # binary + test(3, "b", "11") + test(-3, "b", "-11") + test(1234, "b", "10011010010") + test(-1234, "b", "-10011010010") + test(1234, "-b", "10011010010") + test(-1234, "-b", "-10011010010") + test(1234, " b", " 10011010010") + test(-1234, " b", "-10011010010") + test(1234, "+b", "+10011010010") + test(-1234, "+b", "-10011010010") + + # make sure these are errors + + # precision disallowed + self.assertRaises(ValueError, 3 .__format__, "1.3") + # sign not allowed with 'c' + self.assertRaises(ValueError, 3 .__format__, "+c") + # format spec must be string + self.assertRaises(TypeError, 3 .__format__, None) + self.assertRaises(TypeError, 3 .__format__, 0) + + # ensure that only int and float type specifiers work + for format_spec in ([chr(x) for x in range(ord('a'), ord('z')+1)] + + [chr(x) for x in range(ord('A'), ord('Z')+1)]): + if not format_spec in 'bcdoxXeEfFgGn%': + self.assertRaises(ValueError, 0 .__format__, format_spec) + self.assertRaises(ValueError, 1 .__format__, format_spec) + self.assertRaises(ValueError, (-1) .__format__, format_spec) + + # ensure that float type specifiers work; format converts + # the long to a float + for format_spec in 'eEfFgGn%': + for value in [0, 1, -1, 100, -100, 1234567890, -1234567890]: + self.assertEqual(value.__format__(format_spec), + float(value).__format__(format_spec)) + + @run_with_locale('LC_NUMERIC', 'en_US.UTF8') + def test_float__format__locale(self): + # test locale support for __format__ code 'n' + + for i in range(-10, 10): + x = 1234567890.0 * (10.0 ** i) + self.assertEqual(locale.format('%g', x, grouping=True), format(x, 'n')) + self.assertEqual(locale.format('%.10g', x, grouping=True), format(x, '.10n')) + + def test_float__format__(self): + # these should be rewritten to use both format(x, spec) and + # x.__format__(spec) + + def test(f, format_spec, result): + assert type(f) == float + assert type(format_spec) == str + self.assertEqual(f.__format__(format_spec), result) + + test(0.0, 'f', '0.000000') + + # the default is 'g', except for empty format spec + test(0.0, '', '0.0') + test(0.01, '', '0.01') + test(0.01, 'g', '0.01') + + test( 1.0, ' g', ' 1') + test(-1.0, ' g', '-1') + test( 1.0, '+g', '+1') + test(-1.0, '+g', '-1') + test(1.1234e200, 'g', '1.1234e+200') + test(1.1234e200, 'G', '1.1234E+200') + + + test(1.0, 'f', '1.000000') + + test(-1.0, 'f', '-1.000000') + + test( 1.0, ' f', ' 1.000000') + test(-1.0, ' f', '-1.000000') + test( 1.0, '+f', '+1.000000') + test(-1.0, '+f', '-1.000000') + test(1.1234e90, 'f', '1.1234e+90') + test(1.1234e90, 'F', '1.1234e+90') + test(1.1234e200, 'f', '1.1234e+200') + test(1.1234e200, 'F', '1.1234e+200') + + test( 1.0, 'e', '1.000000e+00') + test(-1.0, 'e', '-1.000000e+00') + test( 1.0, 'E', '1.000000E+00') + test(-1.0, 'E', '-1.000000E+00') + test(1.1234e20, 'e', '1.123400e+20') + test(1.1234e20, 'E', '1.123400E+20') + + # No format code means use g, but must have a decimal + # and a number after the decimal. This is tricky, because + # a totaly empty format specifier means something else. + # So, just use a sign flag + test(1e200, '+g', '+1e+200') + test(1e200, '+', '+1.0e+200') + test(1.1e200, '+g', '+1.1e+200') + test(1.1e200, '+', '+1.1e+200') + + # % formatting + test(-1.0, '%', '-100.000000%') + + # format spec must be string + self.assertRaises(TypeError, 3.0.__format__, None) + self.assertRaises(TypeError, 3.0.__format__, 0) + + # other format specifiers shouldn't work on floats, + # in particular int specifiers + for format_spec in ([chr(x) for x in range(ord('a'), ord('z')+1)] + + [chr(x) for x in range(ord('A'), ord('Z')+1)]): + if not format_spec in 'eEfFgGn%': + self.assertRaises(ValueError, format, 0.0, format_spec) + self.assertRaises(ValueError, format, 1.0, format_spec) + self.assertRaises(ValueError, format, -1.0, format_spec) + self.assertRaises(ValueError, format, 1e100, format_spec) + self.assertRaises(ValueError, format, -1e100, format_spec) + self.assertRaises(ValueError, format, 1e-100, format_spec) + self.assertRaises(ValueError, format, -1e-100, format_spec) + + def test_main(): run_unittest(TypesTests) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_unicode.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_unicode.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_unicode.py Wed Apr 30 15:57:13 2008 @@ -68,6 +68,8 @@ self.assertRaises(SyntaxError, eval, '\'\\Ufffffffe\'') self.assertRaises(SyntaxError, eval, '\'\\Uffffffff\'') self.assertRaises(SyntaxError, eval, '\'\\U%08x\'' % 0x110000) + # raw strings should not have unicode escapes + self.assertNotEquals(r"\u0020", " ") def test_repr(self): if not sys.platform.startswith('java'): @@ -973,12 +975,26 @@ print('def\n', file=out) def test_ucs4(self): - if sys.maxunicode == 0xFFFF: - return x = '\U00100000' y = x.encode("raw-unicode-escape").decode("raw-unicode-escape") self.assertEqual(x, y) + # FIXME + #y = r'\U00100000' + #x = y.encode("raw-unicode-escape").decode("raw-unicode-escape") + #self.assertEqual(x, y) + #y = r'\U00010000' + #x = y.encode("raw-unicode-escape").decode("raw-unicode-escape") + #self.assertEqual(x, y) + + #try: + # '\U11111111'.decode("raw-unicode-escape") + #except UnicodeDecodeError as e: + # self.assertEqual(e.start, 0) + # self.assertEqual(e.end, 10) + #else: + # self.fail("Should have raised UnicodeDecodeError") + def test_conversion(self): # Make sure __unicode__() works properly class Foo0: Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_unicode_file.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_unicode_file.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_unicode_file.py Wed Apr 30 15:57:13 2008 @@ -49,6 +49,22 @@ self.failUnless(base in file_list) + # Do as many "equivalancy' tests as we can - ie, check that although we + # have different types for the filename, they refer to the same file. + def _do_equivalent(self, filename1, filename2): + # Note we only check "filename1 against filename2" - we don't bother + # checking "filename2 against 1", as we assume we are called again with + # the args reversed. + self.failUnless(type(filename1)!=type(filename2), + "No point checking equivalent filenames of the same type") + # stat and lstat should return the same results. + self.failUnlessEqual(os.stat(filename1), + os.stat(filename2)) + self.failUnlessEqual(os.lstat(filename1), + os.lstat(filename2)) + # Copy/rename etc tests using equivalent filename + self._do_copyish(filename1, filename2) + # Tests that copy, move, etc one file to another. def _do_copyish(self, filename1, filename2): # Should be able to rename the file using either name. @@ -58,31 +74,20 @@ os.rename(filename1 + ".new", filename2) self.failUnless(os.path.isfile(filename2)) - # Try using shutil on the filenames. - try: - filename1==filename2 - except UnicodeDecodeError: - # these filenames can't be compared - shutil.copy tries to do - # just that. This is really a bug in 'shutil' - if one of shutil's - # 2 params are Unicode and the other isn't, it should coerce the - # string to Unicode with the filesystem encoding before comparison. - pass - else: - # filenames can be compared. - shutil.copy(filename1, filename2 + ".new") - os.unlink(filename1 + ".new") # remove using equiv name. - # And a couple of moves, one using each name. - shutil.move(filename1, filename2 + ".new") - self.failUnless(not os.path.exists(filename2)) - shutil.move(filename1 + ".new", filename2) - self.failUnless(os.path.exists(filename1)) - # Note - due to the implementation of shutil.move, - # it tries a rename first. This only fails on Windows when on - # different file systems - and this test can't ensure that. - # So we test the shutil.copy2 function, which is the thing most - # likely to fail. - shutil.copy2(filename1, filename2 + ".new") - os.unlink(filename1 + ".new") + shutil.copy(filename1, filename2 + ".new") + os.unlink(filename1 + ".new") # remove using equiv name. + # And a couple of moves, one using each name. + shutil.move(filename1, filename2 + ".new") + self.failUnless(not os.path.exists(filename2)) + shutil.move(filename1 + ".new", filename2) + self.failUnless(os.path.exists(filename1)) + # Note - due to the implementation of shutil.move, + # it tries a rename first. This only fails on Windows when on + # different file systems - and this test can't ensure that. + # So we test the shutil.copy2 function, which is the thing most + # likely to fail. + shutil.copy2(filename1, filename2 + ".new") + os.unlink(filename1 + ".new") def _do_directory(self, make_name, chdir_name, encoded): cwd = os.getcwd() @@ -127,6 +132,16 @@ finally: os.unlink(filename) + def _test_equivalent(self, filename1, filename2): + remove_if_exists(filename1) + self.failUnless(not os.path.exists(filename2)) + f = file(filename1, "w") + f.close() + try: + self._do_equivalent(filename1, filename2) + finally: + os.unlink(filename1) + # The 'test' functions are unittest entry points, and simply call our # _test functions with each of the filename combinations we wish to test def test_single_files(self): @@ -135,6 +150,9 @@ self._test_single(TESTFN_UNICODE_UNENCODEABLE) def test_directories(self): + # For all 'equivalent' combinations: + # Make dir with encoded, chdir with unicode, checkdir with encoded + # (or unicode/encoded/unicode, etc ext = ".dir" self._do_directory(TESTFN_UNICODE+ext, TESTFN_UNICODE+ext, False) # Our directory name that can't use a non-unicode name. Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_unpack.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_unpack.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_unpack.py Wed Apr 30 15:57:13 2008 @@ -122,7 +122,6 @@ __test__ = {'doctests' : doctests} def test_main(verbose=False): - import sys from test import test_support from test import test_unpack test_support.run_doctest(test_unpack, verbose) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_unpack_ex.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_unpack_ex.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_unpack_ex.py Wed Apr 30 15:57:13 2008 @@ -143,6 +143,23 @@ ... SyntaxError: can use starred expression only as assignment target +Some size constraints (all fail.) + + >>> s = ", ".join("a%d" % i for i in range(1<<8)) + ", *rest = range(1<<8 + 1)" + >>> compile(s, 'test', 'exec') # doctest:+ELLIPSIS + Traceback (most recent call last): + ... + SyntaxError: too many expressions in star-unpacking assignment + + >>> s = ", ".join("a%d" % i for i in range(1<<8 + 1)) + ", *rest = range(1<<8 + 2)" + >>> compile(s, 'test', 'exec') # doctest:+ELLIPSIS + Traceback (most recent call last): + ... + SyntaxError: too many expressions in star-unpacking assignment + +(there is an additional limit, on the number of expressions after the +'*rest', but it's 1<<24 and testing it takes too much memory.) + """ __test__ = {'doctests' : doctests} Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_urllib.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_urllib.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_urllib.py Wed Apr 30 15:57:13 2008 @@ -8,10 +8,6 @@ import os import mimetools import tempfile -import ftplib -import threading -import socket -import time def hexescape(char): """Escape char as RFC 2396 specifies""" Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_urllib2.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_urllib2.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_urllib2.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,7 @@ import unittest from test import test_support -import os, socket +import os import io import urllib2 @@ -584,7 +584,7 @@ self.assertEqual(int(headers["Content-length"]), len(data)) def test_file(self): - import time, rfc822, socket + import rfc822, socket h = urllib2.FileHandler() o = h.parent = MockOpener() @@ -817,6 +817,8 @@ method = getattr(h, "http_error_%s" % code) req = Request(from_url, data) req.add_header("Nonsense", "viking=withhold") + if data is not None: + req.add_header("Content-Length", str(len(data))) req.add_unredirected_header("Spam", "spam") try: method(req, MockFile(), code, "Blah", @@ -829,6 +831,13 @@ self.assertEqual(o.req.get_method(), "GET") except AttributeError: self.assert_(not o.req.has_data()) + + # now it's a GET, there should not be headers regarding content + # (possibly dragged from before being a POST) + headers = [x.lower() for x in o.req.headers] + self.assertTrue("content-length" not in headers) + self.assertTrue("content-type" not in headers) + self.assertEqual(o.req.headers["Nonsense"], "viking=withhold") self.assert_("Spam" not in o.req.headers) @@ -897,13 +906,14 @@ self.assertEqual([(handlers[0], "http_open")], [tup[0:2] for tup in o.calls]) - def test_basic_auth(self): + def test_basic_auth(self, quote_char='"'): opener = OpenerDirector() password_manager = MockPasswordManager() auth_handler = urllib2.HTTPBasicAuthHandler(password_manager) realm = "ACME Widget Store" http_handler = MockHTTPHandler( - 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm) + 401, 'WWW-Authenticate: Basic realm=%s%s%s\r\n\r\n' % + (quote_char, realm, quote_char) ) opener.add_handler(auth_handler) opener.add_handler(http_handler) self._test_basic_auth(opener, auth_handler, "Authorization", @@ -912,6 +922,9 @@ "http://acme.example.com/protected", ) + def test_basic_auth_with_single_quoted_realm(self): + self.test_basic_auth(quote_char="'") + def test_proxy_basic_auth(self): opener = OpenerDirector() ph = urllib2.ProxyHandler(dict(http="proxy.example.com:3128")) @@ -979,7 +992,7 @@ def _test_basic_auth(self, opener, auth_handler, auth_header, realm, http_handler, password_manager, request_url, protected_url): - import base64, httplib + import base64 user, password = "wile", "coyote" # .add_password() fed through to password manager Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_urllib2_localnet.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_urllib2_localnet.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_urllib2_localnet.py Wed Apr 30 15:57:13 2008 @@ -1,6 +1,6 @@ #!/usr/bin/env python -import sys +import mimetools import threading import urlparse import urllib2 @@ -218,7 +218,7 @@ # Test cases class ProxyAuthTests(unittest.TestCase): - URL = "http://www.foo.com" + URL = "http://localhost" USER = "tester" PASSWD = "test123" @@ -280,6 +280,202 @@ pass result.close() + +def GetRequestHandler(responses): + + class FakeHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): + + server_version = "TestHTTP/" + requests = [] + headers_received = [] + port = 80 + + def do_GET(self): + body = self.send_head() + if body: + self.wfile.write(body) + + def do_POST(self): + content_length = self.headers['Content-Length'] + post_data = self.rfile.read(int(content_length)) + self.do_GET() + self.requests.append(post_data) + + def send_head(self): + FakeHTTPRequestHandler.headers_received = self.headers + self.requests.append(self.path) + response_code, headers, body = responses.pop(0) + + self.send_response(response_code) + + for (header, value) in headers: + self.send_header(header, value % self.port) + if body: + self.send_header('Content-type', 'text/plain') + self.end_headers() + return body + self.end_headers() + + def log_message(self, *args): + pass + + + return FakeHTTPRequestHandler + + +class TestUrlopen(unittest.TestCase): + """Tests urllib2.urlopen using the network. + + These tests are not exhaustive. Assuming that testing using files does a + good job overall of some of the basic interface features. There are no + tests exercising the optional 'data' and 'proxies' arguments. No tests + for transparent redirection have been written. + """ + + def start_server(self, responses): + handler = GetRequestHandler(responses) + + self.server = LoopbackHttpServerThread(handler) + self.server.start() + self.server.ready.wait() + port = self.server.port + handler.port = port + return handler + + + def test_redirection(self): + expected_response = b'We got here...' + responses = [ + (302, [('Location', 'http://localhost:%s/somewhere_else')], ''), + (200, [], expected_response) + ] + + handler = self.start_server(responses) + + try: + f = urllib2.urlopen('http://localhost:%s/' % handler.port) + data = f.read() + f.close() + + self.assertEquals(data, expected_response) + self.assertEquals(handler.requests, ['/', '/somewhere_else']) + finally: + self.server.stop() + + + def test_404(self): + expected_response = b'Bad bad bad...' + handler = self.start_server([(404, [], expected_response)]) + + try: + try: + urllib2.urlopen('http://localhost:%s/weeble' % handler.port) + except urllib2.URLError as f: + data = f.read() + f.close() + else: + self.fail('404 should raise URLError') + + self.assertEquals(data, expected_response) + self.assertEquals(handler.requests, ['/weeble']) + finally: + self.server.stop() + + + def test_200(self): + expected_response = b'pycon 2008...' + handler = self.start_server([(200, [], expected_response)]) + + try: + f = urllib2.urlopen('http://localhost:%s/bizarre' % handler.port) + data = f.read() + f.close() + + self.assertEquals(data, expected_response) + self.assertEquals(handler.requests, ['/bizarre']) + finally: + self.server.stop() + + def test_200_with_parameters(self): + expected_response = b'pycon 2008...' + handler = self.start_server([(200, [], expected_response)]) + + try: + f = urllib2.urlopen('http://localhost:%s/bizarre' % handler.port, b'get=with_feeling') + data = f.read() + f.close() + + self.assertEquals(data, expected_response) + self.assertEquals(handler.requests, ['/bizarre', b'get=with_feeling']) + finally: + self.server.stop() + + + def test_sending_headers(self): + handler = self.start_server([(200, [], b"we don't care")]) + + try: + req = urllib2.Request("http://localhost:%s/" % handler.port, + headers={'Range': 'bytes=20-39'}) + urllib2.urlopen(req) + self.assertEqual(handler.headers_received['Range'], 'bytes=20-39') + finally: + self.server.stop() + + def test_basic(self): + handler = self.start_server([(200, [], b"we don't care")]) + + try: + open_url = urllib2.urlopen("http://localhost:%s" % handler.port) + for attr in ("read", "close", "info", "geturl"): + self.assert_(hasattr(open_url, attr), "object returned from " + "urlopen lacks the %s attribute" % attr) + try: + self.assert_(open_url.read(), "calling 'read' failed") + finally: + open_url.close() + finally: + self.server.stop() + + def test_info(self): + handler = self.start_server([(200, [], b"we don't care")]) + + try: + open_url = urllib2.urlopen("http://localhost:%s" % handler.port) + info_obj = open_url.info() + self.assert_(isinstance(info_obj, mimetools.Message), + "object returned by 'info' is not an instance of " + "mimetools.Message") + self.assertEqual(info_obj.getsubtype(), "plain") + finally: + self.server.stop() + + def test_geturl(self): + # Make sure same URL as opened is returned by geturl. + handler = self.start_server([(200, [], b"we don't care")]) + + try: + open_url = urllib2.urlopen("http://localhost:%s" % handler.port) + url = open_url.geturl() + self.assertEqual(url, "http://localhost:%s" % handler.port) + finally: + self.server.stop() + + + def test_bad_address(self): + # Make sure proper exception is raised when connecting to a bogus + # address. + self.assertRaises(IOError, + # SF patch 809915: In Sep 2003, VeriSign started + # highjacking invalid .com and .net addresses to + # boost traffic to their own site. This test + # started failing then. One hopes the .invalid + # domain will be spared to serve its defined + # purpose. + # urllib2.urlopen, "http://www.sadflkjsasadf.com/") + urllib2.urlopen, "http://www.python.invalid./") + + def test_main(): # We will NOT depend on the network resource flag # (Lib/test/regrtest.py -u network) since all tests here are only @@ -288,6 +484,7 @@ #test_support.requires("network") test_support.run_unittest(ProxyAuthTests) + test_support.run_unittest(TestUrlopen) if __name__ == "__main__": test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_urllib2net.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_urllib2net.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_urllib2net.py Wed Apr 30 15:57:13 2008 @@ -17,27 +17,14 @@ for i in range(3): try: return urllib2.urlopen(host, *args, **kwargs) - except urllib2.URLError as last_exc: + except urllib2.URLError as e: + last_exc = e continue except: raise raise last_exc -class URLTimeoutTest(unittest.TestCase): - - TIMEOUT = 10.0 - - def setUp(self): - socket.setdefaulttimeout(self.TIMEOUT) - - def tearDown(self): - socket.setdefaulttimeout(None) - - def testURLread(self): - f = _urlopen_with_retry("http://www.python.org/") - x = f.read() - class AuthTests(unittest.TestCase): """Tests urllib2 authentication features.""" @@ -97,68 +84,6 @@ response.close() self.assert_(fileobject.closed) -class urlopenNetworkTests(unittest.TestCase): - """Tests urllib2.urlopen using the network. - - These tests are not exhaustive. Assuming that testing using files does a - good job overall of some of the basic interface features. There are no - tests exercising the optional 'data' and 'proxies' arguments. No tests - for transparent redirection have been written. - - setUp is not used for always constructing a connection to - http://www.python.org/ since there a few tests that don't use that address - and making a connection is expensive enough to warrant minimizing unneeded - connections. - - """ - - def test_basic(self): - # Simple test expected to pass. - open_url = _urlopen_with_retry("http://www.python.org/") - for attr in ("read", "close", "info", "geturl"): - self.assert_(hasattr(open_url, attr), "object returned from " - "urlopen lacks the %s attribute" % attr) - try: - self.assert_(open_url.read(), "calling 'read' failed") - finally: - open_url.close() - - def test_info(self): - # Test 'info'. - open_url = _urlopen_with_retry("http://www.python.org/") - try: - info_obj = open_url.info() - finally: - open_url.close() - self.assert_(isinstance(info_obj, mimetools.Message), - "object returned by 'info' is not an instance of " - "mimetools.Message") - self.assertEqual(info_obj.getsubtype(), "html") - - def test_geturl(self): - # Make sure same URL as opened is returned by geturl. - URL = "http://www.python.org/" - open_url = _urlopen_with_retry(URL) - try: - gotten_url = open_url.geturl() - finally: - open_url.close() - self.assertEqual(gotten_url, URL) - - def test_bad_address(self): - # Make sure proper exception is raised when connecting to a bogus - # address. - self.assertRaises(IOError, - # SF patch 809915: In Sep 2003, VeriSign started - # highjacking invalid .com and .net addresses to - # boost traffic to their own site. This test - # started failing then. One hopes the .invalid - # domain will be spared to serve its defined - # purpose. - # urllib2.urlopen, "http://www.sadflkjsasadf.com/") - urllib2.urlopen, "http://www.python.invalid./") - - class OtherNetworkTests(unittest.TestCase): def setUp(self): if 0: # for debugging @@ -166,13 +91,6 @@ logger = logging.getLogger("test_urllib2net") logger.addHandler(logging.StreamHandler()) - def test_range (self): - req = urllib2.Request("http://www.python.org", - headers={'Range': 'bytes=20-39'}) - result = _urlopen_with_retry(req) - data = result.read() - self.assertEqual(len(data), 20) - # XXX The rest of these tests aren't very good -- they don't check much. # They do sometimes catch some major disasters, though. @@ -200,16 +118,6 @@ finally: os.remove(TESTFN) - def test_http(self): - urls = [ - 'http://www.espn.com/', # redirect - 'http://www.python.org/Spanish/Inquistion/', - ('http://www.python.org/cgi-bin/faqw.py', - 'query=pythonistas&querytype=simple&casefold=yes&req=search', None), - 'http://www.python.org/', - ] - self._test_urls(urls, self._extra_handlers()) - # XXX Following test depends on machine configurations that are internal # to CNRI. Need to set up a public server with the right authentication # configuration for test purposes. @@ -277,6 +185,7 @@ return handlers + class TimeoutTest(unittest.TestCase): def test_http_basic(self): u = _urlopen_with_retry("http://www.python.org") @@ -310,13 +219,13 @@ socket.setdefaulttimeout(60) try: u = _urlopen_with_retry(self.FTP_HOST, timeout=None) - self.assertEqual(u.fp.fp._sock.gettimeout(), 60) + self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60) finally: socket.setdefaulttimeout(prev) def test_ftp_NoneNodefault(self): u = _urlopen_with_retry(self.FTP_HOST, timeout=None) - self.assertTrue(u.fp.fp._sock.gettimeout() is None) + self.assertTrue(u.fp.fp.raw._sock.gettimeout() is None) def test_ftp_Value(self): u = _urlopen_with_retry(self.FTP_HOST, timeout=60) @@ -325,9 +234,7 @@ def test_main(): test_support.requires("network") - test_support.run_unittest(URLTimeoutTest, - urlopenNetworkTests, - AuthTests, + test_support.run_unittest(AuthTests, OtherNetworkTests, CloseSocketTest, TimeoutTest, Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_urllibnet.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_urllibnet.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_urllibnet.py Wed Apr 30 15:57:13 2008 @@ -9,6 +9,22 @@ import os import mimetools + +def _open_with_retry(func, host, *args, **kwargs): + # Connecting to remote hosts is flaky. Make it more robust + # by retrying the connection several times. + last_exc = None + for i in range(3): + try: + return func(host, *args, **kwargs) + except IOError as err: + last_exc = err + continue + except: + raise + raise last_exc + + class URLTimeoutTest(unittest.TestCase): TIMEOUT = 10.0 @@ -20,7 +36,7 @@ socket.setdefaulttimeout(None) def testURLread(self): - f = urllib.urlopen("http://www.python.org/") + f = _open_with_retry(urllib.urlopen, "http://www.python.org/") x = f.read() class urlopenNetworkTests(unittest.TestCase): @@ -38,9 +54,12 @@ """ + def urlopen(self, *args): + return _open_with_retry(urllib.urlopen, *args) + def test_basic(self): # Simple test expected to pass. - open_url = urllib.urlopen("http://www.python.org/") + open_url = self.urlopen("http://www.python.org/") for attr in ("read", "readline", "readlines", "fileno", "close", "info", "geturl"): self.assert_(hasattr(open_url, attr), "object returned from " @@ -52,7 +71,7 @@ def test_readlines(self): # Test both readline and readlines. - open_url = urllib.urlopen("http://www.python.org/") + open_url = self.urlopen("http://www.python.org/") try: self.assert_(isinstance(open_url.readline(), bytes), "readline did not return bytes") @@ -63,7 +82,7 @@ def test_info(self): # Test 'info'. - open_url = urllib.urlopen("http://www.python.org/") + open_url = self.urlopen("http://www.python.org/") try: info_obj = open_url.info() finally: @@ -76,7 +95,7 @@ def test_geturl(self): # Make sure same URL as opened is returned by geturl. URL = "http://www.python.org/" - open_url = urllib.urlopen(URL) + open_url = self.urlopen(URL) try: gotten_url = open_url.geturl() finally: @@ -100,9 +119,12 @@ # test can't pass on Windows. return # Make sure fd returned by fileno is valid. - open_url = urllib.urlopen("http://www.python.org/") + open_url = self.urlopen("http://www.python.org/") fd = open_url.fileno() + # XXX(nnorwitz): There is currently no way to pass errors, encoding, + # etc to fdopen. :-( FILE = os.fdopen(fd) + FILE._errors = 'ignore' try: self.assert_(FILE.read(), "reading from file created using fd " "returned by fileno failed") @@ -125,12 +147,15 @@ class urlretrieveNetworkTests(unittest.TestCase): """Tests urllib.urlretrieve using the network.""" + def urlretrieve(self, *args): + return _open_with_retry(urllib.urlretrieve, *args) + def test_basic(self): # Test basic functionality. - file_location,info = urllib.urlretrieve("http://www.python.org/") + file_location,info = self.urlretrieve("http://www.python.org/") self.assert_(os.path.exists(file_location), "file location returned by" " urlretrieve is not a valid path") - FILE = open(file_location) + FILE = open(file_location, errors='ignore') try: self.assert_(FILE.read(), "reading from the file location returned" " by urlretrieve failed") @@ -140,11 +165,11 @@ def test_specified_path(self): # Make sure that specifying the location of the file to write to works. - file_location,info = urllib.urlretrieve("http://www.python.org/", - test_support.TESTFN) + file_location,info = self.urlretrieve("http://www.python.org/", + test_support.TESTFN) self.assertEqual(file_location, test_support.TESTFN) self.assert_(os.path.exists(file_location)) - FILE = open(file_location) + FILE = open(file_location, errors='ignore') try: self.assert_(FILE.read(), "reading from temporary file failed") finally: @@ -153,7 +178,7 @@ def test_header(self): # Make sure header returned as 2nd value from urlretrieve is good. - file_location, header = urllib.urlretrieve("http://www.python.org/") + file_location, header = self.urlretrieve("http://www.python.org/") os.unlink(file_location) self.assert_(isinstance(header, mimetools.Message), "header is not an instance of mimetools.Message") Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_userdict.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_userdict.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_userdict.py Wed Apr 30 15:57:13 2008 @@ -1,8 +1,7 @@ # Check every path through every method of UserDict -import unittest from test import test_support, mapping_tests -import UserDict +import collections d0 = {} d1 = {"one": 1} @@ -12,36 +11,36 @@ d5 = {"one": 1, "two": 1} class UserDictTest(mapping_tests.TestHashMappingProtocol): - type2test = UserDict.IterableUserDict + type2test = collections.UserDict def test_all(self): # Test constructors - u = UserDict.UserDict() - u0 = UserDict.UserDict(d0) - u1 = UserDict.UserDict(d1) - u2 = UserDict.IterableUserDict(d2) - - uu = UserDict.UserDict(u) - uu0 = UserDict.UserDict(u0) - uu1 = UserDict.UserDict(u1) - uu2 = UserDict.UserDict(u2) + u = collections.UserDict() + u0 = collections.UserDict(d0) + u1 = collections.UserDict(d1) + u2 = collections.UserDict(d2) + + uu = collections.UserDict(u) + uu0 = collections.UserDict(u0) + uu1 = collections.UserDict(u1) + uu2 = collections.UserDict(u2) # keyword arg constructor - self.assertEqual(UserDict.UserDict(one=1, two=2), d2) + self.assertEqual(collections.UserDict(one=1, two=2), d2) # item sequence constructor - self.assertEqual(UserDict.UserDict([('one',1), ('two',2)]), d2) - self.assertEqual(UserDict.UserDict(dict=[('one',1), ('two',2)]), d2) + self.assertEqual(collections.UserDict([('one',1), ('two',2)]), d2) + self.assertEqual(collections.UserDict(dict=[('one',1), ('two',2)]), d2) # both together - self.assertEqual(UserDict.UserDict([('one',1), ('two',2)], two=3, three=5), d3) + self.assertEqual(collections.UserDict([('one',1), ('two',2)], two=3, three=5), d3) # alternate constructor - self.assertEqual(UserDict.UserDict.fromkeys('one two'.split()), d4) - self.assertEqual(UserDict.UserDict().fromkeys('one two'.split()), d4) - self.assertEqual(UserDict.UserDict.fromkeys('one two'.split(), 1), d5) - self.assertEqual(UserDict.UserDict().fromkeys('one two'.split(), 1), d5) + self.assertEqual(collections.UserDict.fromkeys('one two'.split()), d4) + self.assertEqual(collections.UserDict().fromkeys('one two'.split()), d4) + self.assertEqual(collections.UserDict.fromkeys('one two'.split(), 1), d5) + self.assertEqual(collections.UserDict().fromkeys('one two'.split(), 1), d5) self.assert_(u1.fromkeys('one two'.split()) is not u1) - self.assert_(isinstance(u1.fromkeys('one two'.split()), UserDict.UserDict)) - self.assert_(isinstance(u2.fromkeys('one two'.split()), UserDict.IterableUserDict)) + self.assert_(isinstance(u1.fromkeys('one two'.split()), collections.UserDict)) + self.assert_(isinstance(u2.fromkeys('one two'.split()), collections.UserDict)) # Test __repr__ self.assertEqual(str(u0), str(d0)) @@ -59,7 +58,7 @@ self.assertRaises(KeyError, u1.__getitem__, "two") # Test __setitem__ - u3 = UserDict.UserDict(u2) + u3 = collections.UserDict(u2) u3["two"] = 2 u3["three"] = 3 @@ -74,11 +73,11 @@ # Test copy() u2a = u2.copy() self.assertEqual(u2a, u2) - u2b = UserDict.UserDict(x=42, y=23) + u2b = collections.UserDict(x=42, y=23) u2c = u2b.copy() # making a copy of a UserDict is special cased self.assertEqual(u2b, u2c) - class MyUserDict(UserDict.UserDict): + class MyUserDict(collections.UserDict): def display(self): print(self) m2 = MyUserDict(u2) @@ -101,15 +100,9 @@ self.assertEqual(i in u0, i in d0) # Test update - t = UserDict.UserDict() + t = collections.UserDict() t.update(u2) self.assertEqual(t, u2) - class Items: - def items(self): - return (("x", 42), ("y", 23)) - t = UserDict.UserDict() - t.update(Items()) - self.assertEqual(t, {"x": 42, "y": 23}) # Test get for i in u2.keys(): @@ -127,13 +120,13 @@ self.assertEqual(set(ikeys), set(keys)) # Test setdefault - t = UserDict.UserDict() + t = collections.UserDict() self.assertEqual(t.setdefault("x", 42), 42) self.assert_("x" in t) self.assertEqual(t.setdefault("x", 23), 42) # Test pop - t = UserDict.UserDict(x=42) + t = collections.UserDict(x=42) self.assertEqual(t.pop("x"), 42) self.assertRaises(KeyError, t.pop, "x") self.assertEqual(t.pop("x", 1), 1) @@ -141,19 +134,19 @@ self.assertEqual(t.pop("x", 1), 42) # Test popitem - t = UserDict.UserDict(x=42) + t = collections.UserDict(x=42) self.assertEqual(t.popitem(), ("x", 42)) self.assertRaises(KeyError, t.popitem) def test_missing(self): # Make sure UserDict doesn't have a __missing__ method - self.assertEqual(hasattr(UserDict, "__missing__"), False) + self.assertEqual(hasattr(collections.UserDict, "__missing__"), False) # Test several cases: # (D) subclass defines __missing__ method returning a value # (E) subclass defines __missing__ method raising RuntimeError # (F) subclass sets __missing__ instance variable (no effect) # (G) subclass doesn't define __missing__ at a all - class D(UserDict.UserDict): + class D(collections.UserDict): def __missing__(self, key): return 42 d = D({1: 2, 3: 4}) @@ -162,7 +155,7 @@ self.assert_(2 not in d) self.assert_(2 not in d.keys()) self.assertEqual(d[2], 42) - class E(UserDict.UserDict): + class E(collections.UserDict): def __missing__(self, key): raise RuntimeError(key) e = E() @@ -172,11 +165,11 @@ self.assertEqual(err.args, (42,)) else: self.fail("e[42] didn't raise RuntimeError") - class F(UserDict.UserDict): + class F(collections.UserDict): def __init__(self): # An instance variable __missing__ should have no effect self.__missing__ = lambda key: None - UserDict.UserDict.__init__(self) + collections.UserDict.__init__(self) f = F() try: f[42] @@ -184,7 +177,7 @@ self.assertEqual(err.args, (42,)) else: self.fail("f[42] didn't raise KeyError") - class G(UserDict.UserDict): + class G(collections.UserDict): pass g = G() try: @@ -194,150 +187,11 @@ else: self.fail("g[42] didn't raise KeyError") -########################## -# Test Dict Mixin -class SeqDict(UserDict.DictMixin): - """Dictionary lookalike implemented with lists. - - Used to test and demonstrate DictMixin - """ - def __init__(self, other=None, **kwargs): - self.keylist = [] - self.valuelist = [] - if other is not None: - for (key, value) in other: - self[key] = value - for (key, value) in kwargs.items(): - self[key] = value - def __getitem__(self, key): - try: - i = self.keylist.index(key) - except ValueError: - raise KeyError - return self.valuelist[i] - def __setitem__(self, key, value): - try: - i = self.keylist.index(key) - self.valuelist[i] = value - except ValueError: - self.keylist.append(key) - self.valuelist.append(value) - def __delitem__(self, key): - try: - i = self.keylist.index(key) - except ValueError: - raise KeyError - self.keylist.pop(i) - self.valuelist.pop(i) - def keys(self): - return list(self.keylist) - def copy(self): - d = self.__class__() - for key, value in self.items(): - d[key] = value - return d - @classmethod - def fromkeys(cls, keys, value=None): - d = cls() - for key in keys: - d[key] = value - return d - -class UserDictMixinTest(mapping_tests.TestMappingProtocol): - type2test = SeqDict - - def test_all(self): - ## Setup test and verify working of the test class - - # check init - s = SeqDict() - - # exercise setitem - s[10] = 'ten' - s[20] = 'twenty' - s[30] = 'thirty' - - # exercise delitem - del s[20] - # check getitem and setitem - self.assertEqual(s[10], 'ten') - # check keys() and delitem - self.assertEqual(s.keys(), [10, 30]) - - ## Now, test the DictMixin methods one by one - - # __contains__ - self.assert_(10 in s) - self.assert_(20 not in s) - - # __iter__ - self.assertEqual([k for k in s], [10, 30]) - - # __len__ - self.assertEqual(len(s), 2) - - # iteritems - self.assertEqual(list(s.items()), [(10,'ten'), (30, 'thirty')]) - - # iterkeys - self.assertEqual(list(s.keys()), [10, 30]) - - # itervalues - self.assertEqual(list(s.values()), ['ten', 'thirty']) - - # values - self.assertEqual(s.values(), ['ten', 'thirty']) - - # items - self.assertEqual(s.items(), [(10,'ten'), (30, 'thirty')]) - - # get - self.assertEqual(s.get(10), 'ten') - self.assertEqual(s.get(15,'fifteen'), 'fifteen') - self.assertEqual(s.get(15), None) - - # setdefault - self.assertEqual(s.setdefault(40, 'forty'), 'forty') - self.assertEqual(s.setdefault(10, 'null'), 'ten') - del s[40] - - # pop - self.assertEqual(s.pop(10), 'ten') - self.assert_(10 not in s) - s[10] = 'ten' - self.assertEqual(s.pop("x", 1), 1) - s["x"] = 42 - self.assertEqual(s.pop("x", 1), 42) - - # popitem - k, v = s.popitem() - self.assert_(k not in s) - s[k] = v - - # clear - s.clear() - self.assertEqual(len(s), 0) - - # empty popitem - self.assertRaises(KeyError, s.popitem) - - # update - s.update({10: 'ten', 20:'twenty'}) - self.assertEqual(s[10], 'ten') - self.assertEqual(s[20], 'twenty') - - # cmp - self.assertEqual(s, {10: 'ten', 20:'twenty'}) - t = SeqDict() - t[20] = 'twenty' - t[10] = 'ten' - self.assertEqual(s, t) def test_main(): test_support.run_unittest( UserDictTest, - UserDictMixinTest ) if __name__ == "__main__": Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_userlist.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_userlist.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_userlist.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,6 @@ # Check every path through every method of UserList -from UserList import UserList -import unittest +from collections import UserList from test import test_support, list_tests class UserListTest(list_tests.CommonTest): Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_userstring.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_userstring.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_userstring.py Wed Apr 30 15:57:13 2008 @@ -2,11 +2,10 @@ # UserString is a wrapper around the native builtin string type. # UserString instances should behave similar to builtin string objects. -import unittest import string from test import test_support, string_tests -from UserString import UserString, MutableString +from collections import UserString class UserStringTest( string_tests.CommonTest, @@ -42,99 +41,9 @@ # we don't fix the arguments, because UserString can't cope with it getattr(object, methodname)(*args) -class MutableStringTest(UserStringTest): - type2test = MutableString - - # MutableStrings can be hashed => deactivate test - def test_hash(self): - pass - - def test_setitem(self): - s = self.type2test("foo") - self.assertRaises(IndexError, s.__setitem__, -4, "bar") - self.assertRaises(IndexError, s.__setitem__, 3, "bar") - s[-1] = "bar" - self.assertEqual(s, "fobar") - s[0] = "bar" - self.assertEqual(s, "barobar") - - def test_delitem(self): - s = self.type2test("foo") - self.assertRaises(IndexError, s.__delitem__, -4) - self.assertRaises(IndexError, s.__delitem__, 3) - del s[-1] - self.assertEqual(s, "fo") - del s[0] - self.assertEqual(s, "o") - del s[0] - self.assertEqual(s, "") - - def test_setslice(self): - s = self.type2test("foo") - s[:] = "bar" - self.assertEqual(s, "bar") - s[1:2] = "foo" - self.assertEqual(s, "bfoor") - s[1:-1] = UserString("a") - self.assertEqual(s, "bar") - s[0:10] = 42 - self.assertEqual(s, "42") - - def test_delslice(self): - s = self.type2test("foobar") - del s[3:10] - self.assertEqual(s, "foo") - del s[-1:10] - self.assertEqual(s, "fo") - - def test_extended_set_del_slice(self): - indices = (0, None, 1, 3, 19, 100, -1, -2, -31, -100) - orig = string.ascii_letters + string.digits - for start in indices: - for stop in indices: - # Use indices[1:] when MutableString can handle real - # extended slices - for step in (None, 1, -1): - s = self.type2test(orig) - L = list(orig) - # Make sure we have a slice of exactly the right length, - # but with (hopefully) different data. - data = L[start:stop:step] - data.reverse() - L[start:stop:step] = data - s[start:stop:step] = "".join(data) - self.assertEquals(s, "".join(L)) - - del L[start:stop:step] - del s[start:stop:step] - self.assertEquals(s, "".join(L)) - - def test_immutable(self): - s = self.type2test("foobar") - s2 = s.immutable() - self.assertEqual(s, s2) - self.assert_(isinstance(s2, UserString)) - - def test_iadd(self): - s = self.type2test("foo") - s += "bar" - self.assertEqual(s, "foobar") - s += UserString("baz") - self.assertEqual(s, "foobarbaz") - s += 42 - self.assertEqual(s, "foobarbaz42") - - def test_imul(self): - s = self.type2test("foo") - s *= 1 - self.assertEqual(s, "foo") - s *= 2 - self.assertEqual(s, "foofoo") - s *= -1 - self.assertEqual(s, "") def test_main(): - test_support.run_unittest(UserStringTest, MutableStringTest) + test_support.run_unittest(UserStringTest) if __name__ == "__main__": test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_uu.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_uu.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_uu.py Wed Apr 30 15:57:13 2008 @@ -121,6 +121,7 @@ def test_encode(self): fin = fout = None try: + test_support.unlink(self.tmpin) fin = open(self.tmpin, 'wb') fin.write(plaintext) fin.close() @@ -150,6 +151,7 @@ def test_decode(self): f = None try: + test_support.unlink(self.tmpin) f = open(self.tmpin, 'wb') f.write(encodedtextwrapped(0o644, self.tmpout)) f.close() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_warnings.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_warnings.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_warnings.py Wed Apr 30 15:57:13 2008 @@ -1,4 +1,4 @@ -import warnings +from contextlib import contextmanager import linecache import os from io import StringIO @@ -8,112 +8,359 @@ from test import warning_tests -class TestModule(unittest.TestCase): - def setUp(self): - self.ignored = [w[2].__name__ for w in warnings.filters - if w[0]=='ignore' and w[1] is None and w[3] is None] +import warnings as original_warnings - def test_warn_default_category(self): - with test_support.catch_warning() as w: - for i in range(4): - text = 'multi %d' %i # Different text on each call - warnings.warn(text) - self.assertEqual(str(w.message), text) - self.assert_(w.category is UserWarning) +sys.modules['_warnings'] = 0 +del sys.modules['warnings'] + +import warnings as py_warnings + +del sys.modules['_warnings'] +del sys.modules['warnings'] + +import warnings as c_warnings + +sys.modules['warnings'] = original_warnings + + + at contextmanager +def warnings_state(module): + """Use a specific warnings implementation in warning_tests.""" + global __warningregistry__ + for to_clear in (sys, warning_tests): + try: + to_clear.__warningregistry__.clear() + except AttributeError: + pass + try: + __warningregistry__.clear() + except NameError: + pass + original_warnings = warning_tests.warnings + try: + warning_tests.warnings = module + yield + finally: + warning_tests.warnings = original_warnings - def test_warn_specific_category(self): - with test_support.catch_warning() as w: - text = 'None' - for category in [DeprecationWarning, FutureWarning, - PendingDeprecationWarning, RuntimeWarning, - SyntaxWarning, UserWarning, Warning]: - if category.__name__ in self.ignored: - text = 'filtered out' + category.__name__ - warnings.warn(text, category) - self.assertNotEqual(w.message, text) + +class BaseTest(unittest.TestCase): + + """Basic bookkeeping required for testing.""" + + def setUp(self): + # The __warningregistry__ needs to be in a pristine state for tests + # to work properly. + if '__warningregistry__' in globals(): + del globals()['__warningregistry__'] + if hasattr(warning_tests, '__warningregistry__'): + del warning_tests.__warningregistry__ + if hasattr(sys, '__warningregistry__'): + del sys.__warningregistry__ + # The 'warnings' module must be explicitly set so that the proper + # interaction between _warnings and 'warnings' can be controlled. + sys.modules['warnings'] = self.module + super(BaseTest, self).setUp() + + def tearDown(self): + sys.modules['warnings'] = original_warnings + super(BaseTest, self).tearDown() + + +class FilterTests(object): + + """Testing the filtering functionality.""" + + def test_error(self): + with test_support.catch_warning(self.module) as w: + self.module.resetwarnings() + self.module.filterwarnings("error", category=UserWarning) + self.assertRaises(UserWarning, self.module.warn, + "FilterTests.test_error") + + def test_ignore(self): + with test_support.catch_warning(self.module) as w: + self.module.resetwarnings() + self.module.filterwarnings("ignore", category=UserWarning) + self.module.warn("FilterTests.test_ignore", UserWarning) + self.assert_(not w.message) + + def test_always(self): + with test_support.catch_warning(self.module) as w: + self.module.resetwarnings() + self.module.filterwarnings("always", category=UserWarning) + message = "FilterTests.test_always" + self.module.warn(message, UserWarning) + self.assert_(message, w.message) + w.message = None # Reset. + self.module.warn(message, UserWarning) + self.assert_(w.message, message) + + def test_default(self): + with test_support.catch_warning(self.module) as w: + self.module.resetwarnings() + self.module.filterwarnings("default", category=UserWarning) + message = UserWarning("FilterTests.test_default") + for x in range(2): + self.module.warn(message, UserWarning) + if x == 0: + self.assertEquals(w.message, message) + w.reset() + elif x == 1: + self.assert_(not w.message, "unexpected warning: " + str(w)) else: - text = 'unfiltered %s' % category.__name__ - warnings.warn(text, category) - self.assertEqual(str(w.message), text) - self.assert_(w.category is category) + raise ValueError("loop variant unhandled") + + def test_module(self): + with test_support.catch_warning(self.module) as w: + self.module.resetwarnings() + self.module.filterwarnings("module", category=UserWarning) + message = UserWarning("FilterTests.test_module") + self.module.warn(message, UserWarning) + self.assertEquals(w.message, message) + w.reset() + self.module.warn(message, UserWarning) + self.assert_(not w.message, "unexpected message: " + str(w)) + + def test_once(self): + with test_support.catch_warning(self.module) as w: + self.module.resetwarnings() + self.module.filterwarnings("once", category=UserWarning) + message = UserWarning("FilterTests.test_once") + self.module.warn_explicit(message, UserWarning, "test_warnings.py", + 42) + self.assertEquals(w.message, message) + w.reset() + self.module.warn_explicit(message, UserWarning, "test_warnings.py", + 13) + self.assert_(not w.message) + self.module.warn_explicit(message, UserWarning, "test_warnings2.py", + 42) + self.assert_(not w.message) + + def test_inheritance(self): + with test_support.catch_warning(self.module) as w: + self.module.resetwarnings() + self.module.filterwarnings("error", category=Warning) + self.assertRaises(UserWarning, self.module.warn, + "FilterTests.test_inheritance", UserWarning) + + def test_ordering(self): + with test_support.catch_warning(self.module) as w: + self.module.resetwarnings() + self.module.filterwarnings("ignore", category=UserWarning) + self.module.filterwarnings("error", category=UserWarning, + append=True) + w.reset() + try: + self.module.warn("FilterTests.test_ordering", UserWarning) + except UserWarning: + self.fail("order handling for actions failed") + self.assert_(not w.message) - def test_filtering(self): + def test_filterwarnings(self): # Test filterwarnings(). # Implicitly also tests resetwarnings(). - with test_support.catch_warning() as w: - warnings.filterwarnings("error", "", Warning, "", 0) - self.assertRaises(UserWarning, warnings.warn, 'convert to error') + with test_support.catch_warning(self.module) as w: + self.module.filterwarnings("error", "", Warning, "", 0) + self.assertRaises(UserWarning, self.module.warn, 'convert to error') - warnings.resetwarnings() + self.module.resetwarnings() text = 'handle normally' - warnings.warn(text) + self.module.warn(text) self.assertEqual(str(w.message), text) self.assert_(w.category is UserWarning) - warnings.filterwarnings("ignore", "", Warning, "", 0) + self.module.filterwarnings("ignore", "", Warning, "", 0) text = 'filtered out' - warnings.warn(text) + self.module.warn(text) self.assertNotEqual(str(w.message), text) - warnings.resetwarnings() - warnings.filterwarnings("error", "hex*", Warning, "", 0) - self.assertRaises(UserWarning, warnings.warn, 'hex/oct') + self.module.resetwarnings() + self.module.filterwarnings("error", "hex*", Warning, "", 0) + self.assertRaises(UserWarning, self.module.warn, 'hex/oct') text = 'nonmatching text' - warnings.warn(text) + self.module.warn(text) self.assertEqual(str(w.message), text) self.assert_(w.category is UserWarning) - def test_options(self): - # Uses the private _setoption() function to test the parsing - # of command-line warning arguments - with test_support.catch_warning(): - self.assertRaises(warnings._OptionError, - warnings._setoption, '1:2:3:4:5:6') - self.assertRaises(warnings._OptionError, - warnings._setoption, 'bogus::Warning') - self.assertRaises(warnings._OptionError, - warnings._setoption, 'ignore:2::4:-5') - warnings._setoption('error::Warning::0') - self.assertRaises(UserWarning, warnings.warn, 'convert to error') +class CFilterTests(BaseTest, FilterTests): + module = c_warnings + +class PyFilterTests(BaseTest, FilterTests): + module = py_warnings + + +class WarnTests(unittest.TestCase): + + """Test warnings.warn() and warnings.warn_explicit().""" + + def test_message(self): + with test_support.catch_warning(self.module) as w: + for i in range(4): + text = 'multi %d' %i # Different text on each call. + self.module.warn(text) + self.assertEqual(str(w.message), text) + self.assert_(w.category is UserWarning) def test_filename(self): - with test_support.catch_warning() as w: - warning_tests.inner("spam1") - self.assertEqual(os.path.basename(w.filename), "warning_tests.py") - warning_tests.outer("spam2") - self.assertEqual(os.path.basename(w.filename), "warning_tests.py") + with warnings_state(self.module): + with test_support.catch_warning(self.module) as w: + warning_tests.inner("spam1") + self.assertEqual(os.path.basename(w.filename), "warning_tests.py") + warning_tests.outer("spam2") + self.assertEqual(os.path.basename(w.filename), "warning_tests.py") def test_stacklevel(self): # Test stacklevel argument # make sure all messages are different, so the warning won't be skipped - with test_support.catch_warning() as w: - warning_tests.inner("spam3", stacklevel=1) - self.assertEqual(os.path.basename(w.filename), "warning_tests.py") - warning_tests.outer("spam4", stacklevel=1) - self.assertEqual(os.path.basename(w.filename), "warning_tests.py") - - warning_tests.inner("spam5", stacklevel=2) - self.assertEqual(os.path.basename(w.filename), "test_warnings.py") - warning_tests.outer("spam6", stacklevel=2) - self.assertEqual(os.path.basename(w.filename), "warning_tests.py") + with warnings_state(self.module): + with test_support.catch_warning(self.module) as w: + warning_tests.inner("spam3", stacklevel=1) + self.assertEqual(os.path.basename(w.filename), "warning_tests.py") + warning_tests.outer("spam4", stacklevel=1) + self.assertEqual(os.path.basename(w.filename), "warning_tests.py") + + warning_tests.inner("spam5", stacklevel=2) + self.assertEqual(os.path.basename(w.filename), "test_warnings.py") + warning_tests.outer("spam6", stacklevel=2) + self.assertEqual(os.path.basename(w.filename), "warning_tests.py") + + warning_tests.inner("spam7", stacklevel=9999) + self.assertEqual(os.path.basename(w.filename), "sys") + - warning_tests.inner("spam7", stacklevel=9999) - self.assertEqual(os.path.basename(w.filename), "sys") +class CWarnTests(BaseTest, WarnTests): + module = c_warnings + +class PyWarnTests(BaseTest, WarnTests): + module = py_warnings + + +class WCmdLineTests(unittest.TestCase): + + def test_improper_input(self): + # Uses the private _setoption() function to test the parsing + # of command-line warning arguments + with test_support.catch_warning(self.module): + self.assertRaises(self.module._OptionError, + self.module._setoption, '1:2:3:4:5:6') + self.assertRaises(self.module._OptionError, + self.module._setoption, 'bogus::Warning') + self.assertRaises(self.module._OptionError, + self.module._setoption, 'ignore:2::4:-5') + self.module._setoption('error::Warning::0') + self.assertRaises(UserWarning, self.module.warn, 'convert to error') + +class CWCmdLineTests(BaseTest, WCmdLineTests): + module = c_warnings + +class PyWCmdLineTests(BaseTest, WCmdLineTests): + module = py_warnings + + +class _WarningsTests(BaseTest): + + """Tests specific to the _warnings module.""" + + module = c_warnings + + def test_filter(self): + # Everything should function even if 'filters' is not in warnings. + with test_support.catch_warning(self.module) as w: + self.module.filterwarnings("error", "", Warning, "", 0) + self.assertRaises(UserWarning, self.module.warn, + 'convert to error') + del self.module.filters + self.assertRaises(UserWarning, self.module.warn, + 'convert to error') + + def test_onceregistry(self): + # Replacing or removing the onceregistry should be okay. + global __warningregistry__ + message = UserWarning('onceregistry test') + try: + original_registry = self.module.onceregistry + __warningregistry__ = {} + with test_support.catch_warning(self.module) as w: + self.module.resetwarnings() + self.module.filterwarnings("once", category=UserWarning) + self.module.warn_explicit(message, UserWarning, "file", 42) + self.failUnlessEqual(w.message, message) + w.reset() + self.module.warn_explicit(message, UserWarning, "file", 42) + self.assert_(not w.message) + # Test the resetting of onceregistry. + self.module.onceregistry = {} + __warningregistry__ = {} + self.module.warn('onceregistry test') + self.failUnlessEqual(w.message.args, message.args) + # Removal of onceregistry is okay. + w.reset() + del self.module.onceregistry + __warningregistry__ = {} + self.module.warn_explicit(message, UserWarning, "file", 42) + self.failUnless(not w.message) + finally: + self.module.onceregistry = original_registry + + def test_showwarning_missing(self): + # Test that showwarning() missing is okay. + text = 'del showwarning test' + with test_support.catch_warning(self.module): + self.module.filterwarnings("always", category=UserWarning) + del self.module.showwarning + with test_support.captured_output('stderr') as stream: + self.module.warn(text) + result = stream.getvalue() + self.failUnless(text in result) + + def test_show_warning_output(self): + # With showarning() missing, make sure that output is okay. + text = 'test show_warning' + with test_support.catch_warning(self.module): + self.module.filterwarnings("always", category=UserWarning) + del self.module.showwarning + with test_support.captured_output('stderr') as stream: + warning_tests.inner(text) + result = stream.getvalue() + self.failUnlessEqual(result.count('\n'), 2, + "Too many newlines in %r" % result) + first_line, second_line = result.split('\n', 1) + expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py' + first_line_parts = first_line.rsplit(':', 3) + path, line, warning_class, message = first_line_parts + line = int(line) + self.failUnlessEqual(expected_file, path) + self.failUnlessEqual(warning_class, ' ' + UserWarning.__name__) + self.failUnlessEqual(message, ' ' + text) + expected_line = ' ' + linecache.getline(path, line).strip() + '\n' + assert expected_line + self.failUnlessEqual(second_line, expected_line) class WarningsDisplayTests(unittest.TestCase): + """Test the displaying of warnings and the ability to overload functions + related to displaying warnings.""" + def test_formatwarning(self): message = "msg" category = Warning file_name = os.path.splitext(warning_tests.__file__)[0] + '.py' line_num = 3 file_line = linecache.getline(file_name, line_num).strip() - expect = "%s:%s: %s: %s\n %s\n" % (file_name, line_num, category.__name__, - message, file_line) - self.failUnlessEqual(warnings.formatwarning(message, category, - file_name, line_num), - expect) + format = "%s:%s: %s: %s\n %s\n" + expect = format % (file_name, line_num, category.__name__, message, + file_line) + self.failUnlessEqual(expect, self.module.formatwarning(message, + category, file_name, line_num)) + # Test the 'line' argument. + file_line += " for the win!" + expect = format % (file_name, line_num, category.__name__, message, + file_line) + self.failUnlessEqual(expect, self.module.formatwarning(message, + category, file_name, line_num, file_line)) def test_showwarning(self): file_name = os.path.splitext(warning_tests.__file__)[0] + '.py' @@ -122,22 +369,39 @@ message = 'msg' category = Warning file_object = StringIO() - expect = warnings.formatwarning(message, category, file_name, line_num) - warnings.showwarning(message, category, file_name, line_num, + expect = self.module.formatwarning(message, category, file_name, + line_num) + self.module.showwarning(message, category, file_name, line_num, file_object) self.failUnlessEqual(file_object.getvalue(), expect) + # Test 'line' argument. + expected_file_line += "for the win!" + expect = self.module.formatwarning(message, category, file_name, + line_num, expected_file_line) + file_object = StringIO() + self.module.showwarning(message, category, file_name, line_num, + file_object, expected_file_line) + self.failUnlessEqual(expect, file_object.getvalue()) + +class CWarningsDisplayTests(BaseTest, WarningsDisplayTests): + module = c_warnings + +class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests): + module = py_warnings + + +def test_main(): + py_warnings.onceregistry.clear() + c_warnings.onceregistry.clear() + test_support.run_unittest(CFilterTests, + PyFilterTests, + CWarnTests, + PyWarnTests, + CWCmdLineTests, PyWCmdLineTests, + _WarningsTests, + CWarningsDisplayTests, PyWarningsDisplayTests, + ) -def test_main(verbose=None): - # Obscure hack so that this test passes after reloads or repeated calls - # to test_main (regrtest -R). - if '__warningregistry__' in globals(): - del globals()['__warningregistry__'] - if hasattr(warning_tests, '__warningregistry__'): - del warning_tests.__warningregistry__ - if hasattr(sys, '__warningregistry__'): - del sys.__warningregistry__ - test_support.run_unittest(TestModule, WarningsDisplayTests) - if __name__ == "__main__": - test_main(verbose=True) + test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_wave.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_wave.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_wave.py Wed Apr 30 15:57:13 2008 @@ -1,32 +1,45 @@ -from test.test_support import TestFailed, TESTFN +from test.test_support import TESTFN, run_unittest import os import wave - -def check(t, msg=None): - if not t: - raise TestFailed(msg) +import unittest nchannels = 2 sampwidth = 2 framerate = 8000 nframes = 100 -f = wave.open(TESTFN, 'wb') -f.setnchannels(nchannels) -f.setsampwidth(sampwidth) -f.setframerate(framerate) -f.setnframes(nframes) -output = b'\0' * nframes * nchannels * sampwidth -f.writeframes(output) -f.close() - -f = wave.open(TESTFN, 'rb') -check(nchannels == f.getnchannels(), "nchannels") -check(sampwidth == f.getsampwidth(), "sampwidth") -check(framerate == f.getframerate(), "framerate") -check(nframes == f.getnframes(), "nframes") -input = f.readframes(nframes) -check(input == output, "data") -f.close() +class TestWave(unittest.TestCase): + + def setUp(self): + self.f = None + + def tearDown(self): + if self.f is not None: + self.f.close() + try: + os.remove(TESTFN) + except OSError: + pass + + def test_it(self): + self.f = wave.open(TESTFN, 'wb') + self.f.setnchannels(nchannels) + self.f.setsampwidth(sampwidth) + self.f.setframerate(framerate) + self.f.setnframes(nframes) + output = b'\0' * nframes * nchannels * sampwidth + self.f.writeframes(output) + self.f.close() + + self.f = wave.open(TESTFN, 'rb') + self.assertEqual(nchannels, self.f.getnchannels()) + self.assertEqual(sampwidth, self.f.getsampwidth()) + self.assertEqual(framerate, self.f.getframerate()) + self.assertEqual(nframes, self.f.getnframes()) + self.assertEqual(self.f.readframes(nframes), output) + +def test_main(): + run_unittest(TestWave) -os.remove(TESTFN) +if __name__ == '__main__': + test_main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_weakref.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_weakref.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_weakref.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,7 @@ import gc import sys import unittest -import UserList +import collections import weakref from test import test_support @@ -157,7 +157,7 @@ o = C() self.check_proxy(o, weakref.proxy(o)) - L = UserList.UserList() + L = collections.UserList() p = weakref.proxy(L) self.failIf(p, "proxy for empty UserList should be false") p.append(12) @@ -171,11 +171,11 @@ p[1] = 5 self.assertEqual(L[1], 5) self.assertEqual(p[1], 5) - L2 = UserList.UserList(L) + L2 = collections.UserList(L) p2 = weakref.proxy(L2) self.assertEqual(p, p2) ## self.assertEqual(repr(L2), repr(p2)) - L3 = UserList.UserList(range(10)) + L3 = collections.UserList(range(10)) p3 = weakref.proxy(L3) self.assertEqual(L3[:], p3[:]) self.assertEqual(L3[5:], p3[5:]) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_whichdb.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_whichdb.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_whichdb.py Wed Apr 30 15:57:13 2008 @@ -8,7 +8,6 @@ import unittest import whichdb import anydbm -import tempfile import glob from test.test_anydbm import delete_files, dbm_iterator Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_winsound.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_winsound.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_winsound.py Wed Apr 30 15:57:13 2008 @@ -9,6 +9,13 @@ class BeepTest(unittest.TestCase): + # As with PlaySoundTest, incorporate the _have_soundcard() check + # into our test methods. If there's no audio device present, + # winsound.Beep returns 0 and GetLastError() returns 127, which + # is: ERROR_PROC_NOT_FOUND ("The specified procedure could not + # be found"). (FWIW, virtual/Hyper-V systems fall under this + # scenario as they have no sound devices whatsoever (not even + # a legacy Beep device).) def test_errors(self): self.assertRaises(TypeError, winsound.Beep) @@ -16,12 +23,27 @@ self.assertRaises(ValueError, winsound.Beep, 32768, 75) def test_extremes(self): - winsound.Beep(37, 75) - winsound.Beep(32767, 75) + self._beep(37, 75) + self._beep(32767, 75) def test_increasingfrequency(self): for i in range(100, 2000, 100): - winsound.Beep(i, 75) + self._beep(i, 75) + + def _beep(self, *args): + # these tests used to use _have_soundcard(), but it's quite + # possible to have a soundcard, and yet have the beep driver + # disabled. So basically, we have no way of knowing whether + # a beep should be produced or not, so currently if these + # tests fail we're ignoring them + # + # XXX the right fix for this is to define something like + # _have_enabled_beep_driver() and use that instead of the + # try/except below + try: + winsound.Beep(*args) + except RuntimeError: + pass class MessageBeepTest(unittest.TestCase): Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_wsgiref.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_wsgiref.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_wsgiref.py Wed Apr 30 15:57:13 2008 @@ -157,7 +157,7 @@ self.assertEqual( err.splitlines()[-2], "AssertionError: Headers (('Content-Type', 'text/plain')) must" - " be of type list: " + " be of type list: " ) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_xml_etree.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_xml_etree.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_xml_etree.py Wed Apr 30 15:57:13 2008 @@ -2,7 +2,8 @@ # all included components work as they should. For a more extensive # test suite, see the selftest script in the ElementTree distribution. -import doctest, sys +import doctest +import sys from test import test_support Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_xml_etree_c.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_xml_etree_c.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_xml_etree_c.py Wed Apr 30 15:57:13 2008 @@ -1,6 +1,7 @@ # xml.etree test for cElementTree -import doctest, sys +import doctest +import sys from test import test_support Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_xmlrpc.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_xmlrpc.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_xmlrpc.py Wed Apr 30 15:57:13 2008 @@ -26,10 +26,6 @@ (2005, 2, 10, 11, 41, 23, 0, 1, -1)), 'datetime3': xmlrpclib.DateTime( datetime.datetime(2005, 2, 10, 11, 41, 23)), - 'datetime4': xmlrpclib.DateTime( - datetime.date(2005, 2, 10)), - 'datetime5': xmlrpclib.DateTime( - datetime.time(11, 41, 23)), }] class XMLRPCTestCase(unittest.TestCase): @@ -53,34 +49,25 @@ (newdt,), m = xmlrpclib.loads(s, use_datetime=0) self.assertEquals(newdt, xmlrpclib.DateTime('20050210T11:41:23')) - def test_dump_bare_date(self): - # This checks that an unwrapped datetime.date object can be handled - # by the marshalling code. This can't be done via test_dump_load() - # since the unmarshaller produces a datetime object - d = datetime.datetime(2005, 2, 10, 11, 41, 23).date() - s = xmlrpclib.dumps((d,)) - (newd,), m = xmlrpclib.loads(s, use_datetime=1) - self.assertEquals(newd.date(), d) - self.assertEquals(newd.time(), datetime.time(0, 0, 0)) + def test_datetime_before_1900(self): + # same as before but with an date before 1900 + dt = datetime.datetime(1, 2, 10, 11, 41, 23) + s = xmlrpclib.dumps((dt,)) + (newdt,), m = xmlrpclib.loads(s, use_datetime=1) + self.assertEquals(newdt, dt) self.assertEquals(m, None) (newdt,), m = xmlrpclib.loads(s, use_datetime=0) - self.assertEquals(newdt, xmlrpclib.DateTime('20050210T00:00:00')) + self.assertEquals(newdt, xmlrpclib.DateTime('00010210T11:41:23')) - def test_dump_bare_time(self): - # This checks that an unwrapped datetime.time object can be handled - # by the marshalling code. This can't be done via test_dump_load() - # since the unmarshaller produces a datetime object - t = datetime.datetime(2005, 2, 10, 11, 41, 23).time() - s = xmlrpclib.dumps((t,)) - (newt,), m = xmlrpclib.loads(s, use_datetime=1) - today = datetime.datetime.now().date().strftime("%Y%m%d") - self.assertEquals(newt.time(), t) - self.assertEquals(newt.date(), datetime.datetime.now().date()) - self.assertEquals(m, None) - - (newdt,), m = xmlrpclib.loads(s, use_datetime=0) - self.assertEquals(newdt, xmlrpclib.DateTime('%sT11:41:23'%today)) + def test_cmp_datetime_DateTime(self): + now = datetime.datetime.now() + dt = xmlrpclib.DateTime(now.timetuple()) + self.assert_(dt == now) + self.assert_(now == dt) + then = now + datetime.timedelta(seconds=4) + self.assert_(then >= dt) + self.assert_(dt < then) def test_bug_1164912 (self): d = xmlrpclib.DateTime() @@ -201,21 +188,6 @@ t = xmlrpclib.DateTime(d) self.assertEqual(str(t), '20070102T03:04:05') - def test_datetime_date(self): - d = datetime.date(2007,9,8) - t = xmlrpclib.DateTime(d) - self.assertEqual(str(t), '20070908T00:00:00') - - def test_datetime_time(self): - d = datetime.time(13,17,19) - # allow for date rollover by checking today's or tomorrow's dates - dd1 = datetime.datetime.now().date() - dd2 = dd1 + datetime.timedelta(days=1) - vals = (dd1.strftime('%Y%m%dT13:17:19'), - dd2.strftime('%Y%m%dT13:17:19')) - t = xmlrpclib.DateTime(d) - self.assertEqual(str(t) in vals, True) - def test_repr(self): d = datetime.datetime(2007,1,2,3,4,5) t = xmlrpclib.DateTime(d) @@ -261,6 +233,9 @@ PORT = None +# The evt is set twice. First when the server is ready to serve. +# Second when the server has been shutdown. The user must clear +# the event after it has been set the first time to catch the second set. def http_server(evt, numrequests): class TestInstanceClass: def div(self, x, y): @@ -274,9 +249,17 @@ '''This is my function''' return True + class MyXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer): + def get_request(self): + # Ensure the socket is always non-blocking. On Linux, socket + # attributes are not inherited like they are on *BSD and Windows. + s, port = self.socket.accept() + s.setblocking(True) + return s, port + try: - serv = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 0), - logRequests=False, bind_and_activate=False) + serv = MyXMLRPCServer(("localhost", 0), + logRequests=False, bind_and_activate=False) serv.server_bind() global PORT PORT = serv.socket.getsockname()[1] @@ -287,6 +270,7 @@ serv.register_function(lambda x,y: x+y, 'add') serv.register_function(my_function) serv.register_instance(TestInstanceClass()) + evt.set() # handle up to 'numrequests' requests while numrequests > 0: @@ -300,15 +284,24 @@ PORT = None evt.set() -def stop_serving(): - global PORT - if PORT is None: - return - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.connect(('localhost', int(PORT))) - sock.send(b"") - sock.close() +# This function prevents errors like: +# +def is_unavailable_exception(e): + '''Returns True if the given ProtocolError is the product of a server-side + exception caused by the 'temporarily unavailable' response sometimes + given by operations on non-blocking sockets.''' + + # sometimes we get a -1 error code and/or empty headers + try: + if e.errcode == -1 or e.headers is None: + return True + exc_mess = e.headers.get('X-exception') + except AttributeError: + # Ignore socket.errors here. + exc_mess = str(e) + if exc_mess and 'temporarily unavailable' in exc_mess.lower(): + return True class SimpleServerTestCase(unittest.TestCase): def setUp(self): @@ -320,13 +313,9 @@ serv_args = (self.evt, 1) threading.Thread(target=http_server, args=serv_args).start() - # wait for port to be assigned to server - n = 1000 - while n > 0 and PORT is None: - time.sleep(0.001) - n -= 1 - - time.sleep(0.5) + # wait for the server to be ready + self.evt.wait() + self.evt.clear() def tearDown(self): # wait on the server thread to terminate @@ -343,9 +332,11 @@ try: p = xmlrpclib.ServerProxy('http://localhost:%d' % PORT) self.assertEqual(p.pow(6,8), 6**8) - except xmlrpclib.ProtocolError as e: - # protocol error; provide additional information in test output - self.fail("%s\n%s" % (e, e.headers)) + except (xmlrpclib.ProtocolError, socket.error) as e: + # ignore failures due to non-blocking socket 'unavailable' errors + if not is_unavailable_exception(e): + # protocol error; provide additional information in test output + self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) # [ch] The test 404 is causing lots of false alarms. def XXXtest_404(self): @@ -367,9 +358,12 @@ 'system.listMethods', 'system.methodHelp', 'system.methodSignature', 'system.multicall']) self.assertEqual(set(meth), expected_methods) - except xmlrpclib.ProtocolError as e: - # protocol error; provide additional information in test output - self.fail("%s\n%s" % (e, e.headers)) + except (xmlrpclib.ProtocolError, socket.error) as e: + # ignore failures due to non-blocking socket 'unavailable' errors + if not is_unavailable_exception(e): + # protocol error; provide additional information in test output + self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) + def test_introspection2(self): try: @@ -377,9 +371,11 @@ p = xmlrpclib.ServerProxy('http://localhost:%d' % PORT) divhelp = p.system.methodHelp('div') self.assertEqual(divhelp, 'This is the div function') - except xmlrpclib.ProtocolError as e: - # protocol error; provide additional information in test output - self.fail("%s\n%s" % (e, e.headers)) + except (xmlrpclib.ProtocolError, socket.error) as e: + # ignore failures due to non-blocking socket 'unavailable' errors + if not is_unavailable_exception(e): + # protocol error; provide additional information in test output + self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_introspection3(self): try: @@ -387,11 +383,11 @@ p = xmlrpclib.ServerProxy('http://localhost:%d' % PORT) myfunction = p.system.methodHelp('my_function') self.assertEqual(myfunction, 'This is my function') - except xmlrpclib.ProtocolError as e: + except (xmlrpclib.ProtocolError, socket.error) as e: # ignore failures due to non-blocking socket 'unavailable' errors if not is_unavailable_exception(e): # protocol error; provide additional information in test output - self.fail("%s\n%s" % (e, e.headers)) + self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_introspection4(self): # the SimpleXMLRPCServer doesn't support signatures, but @@ -400,9 +396,11 @@ p = xmlrpclib.ServerProxy('http://localhost:%d' % PORT) divsig = p.system.methodSignature('div') self.assertEqual(divsig, 'signatures not supported') - except xmlrpclib.ProtocolError as e: - # protocol error; provide additional information in test output - self.fail("%s\n%s" % (e, e.headers)) + except (xmlrpclib.ProtocolError, socket.error) as e: + # ignore failures due to non-blocking socket 'unavailable' errors + if not is_unavailable_exception(e): + # protocol error; provide additional information in test output + self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_multicall(self): try: @@ -415,9 +413,11 @@ self.assertEqual(add_result, 2+3) self.assertEqual(pow_result, 6**8) self.assertEqual(div_result, 127//42) - except xmlrpclib.ProtocolError as e: - # protocol error; provide additional information in test output - self.fail("%s\n%s" % (e, e.headers)) + except (xmlrpclib.ProtocolError, socket.error) as e: + # ignore failures due to non-blocking socket 'unavailable' errors + if not is_unavailable_exception(e): + # protocol error; provide additional information in test output + self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_non_existing_multicall(self): try: @@ -427,18 +427,28 @@ result = multicall() # result.results contains; - # [{'faultCode': 1, 'faultString': ':' + # [{'faultCode': 1, 'faultString': ':' # 'method "this_is_not_exists" is not supported'>}] self.assertEqual(result.results[0]['faultCode'], 1) self.assertEqual(result.results[0]['faultString'], - ':method "this_is_not_exists" ' + ':method "this_is_not_exists" ' 'is not supported') - except xmlrpclib.ProtocolError as e: + except (xmlrpclib.ProtocolError, socket.error) as e: # ignore failures due to non-blocking socket 'unavailable' errors if not is_unavailable_exception(e): # protocol error; provide additional information in test output - self.fail("%s\n%s" % (e, e.headers)) + self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) + + def test_dotted_attribute(self): + # Raises an AttributeError because private methods are not allowed. + self.assertRaises(AttributeError, + SimpleXMLRPCServer.resolve_dotted_attribute, str, '__add') + + self.assert_(SimpleXMLRPCServer.resolve_dotted_attribute(str, 'title')) + # Get the test to run faster by sending a request with test_simple1. + # This avoids waiting for the socket timeout. + self.test_simple1() # This is a contrived way to make a failure occur on the server side # in order to test the _send_traceback_header flag on the server @@ -457,13 +467,9 @@ serv_args = (self.evt, 1) threading.Thread(target=http_server, args=serv_args).start() - # wait for port to be assigned to server - n = 1000 - while n > 0 and PORT is None: - time.sleep(0.001) - n -= 1 - - time.sleep(0.5) + # wait for the server to be ready + self.evt.wait() + self.evt.clear() def tearDown(self): # wait on the server thread to terminate @@ -485,9 +491,11 @@ try: p = xmlrpclib.ServerProxy('http://localhost:%d' % PORT) self.assertEqual(p.pow(6,8), 6**8) - except xmlrpclib.ProtocolError as e: - # protocol error; provide additional information in test output - self.fail("%s\n%s" % (e, e.headers)) + except (xmlrpclib.ProtocolError, socket.error) as e: + # ignore failures due to non-blocking socket 'unavailable' errors + if not is_unavailable_exception(e): + # protocol error; provide additional information in test output + self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_fail_no_info(self): # use the broken message class @@ -496,10 +504,12 @@ try: p = xmlrpclib.ServerProxy('http://localhost:%d' % PORT) p.pow(6,8) - except xmlrpclib.ProtocolError as e: - # The two server-side error headers shouldn't be sent back in this case - self.assertTrue(e.headers.get("X-exception") is None) - self.assertTrue(e.headers.get("X-traceback") is None) + except (xmlrpclib.ProtocolError, socket.error) as e: + # ignore failures due to non-blocking socket 'unavailable' errors + if not is_unavailable_exception(e) and hasattr(e, "headers"): + # The two server-side error headers shouldn't be sent back in this case + self.assertTrue(e.headers.get("X-exception") is None) + self.assertTrue(e.headers.get("X-traceback") is None) else: self.fail('ProtocolError not raised') @@ -514,11 +524,13 @@ try: p = xmlrpclib.ServerProxy('http://localhost:%d' % PORT) p.pow(6,8) - except xmlrpclib.ProtocolError as e: - # We should get error info in the response - expected_err = "invalid literal for int() with base 10: 'I am broken'" - self.assertEqual(e.headers.get("x-exception"), expected_err) - self.assertTrue(e.headers.get("x-traceback") is not None) + except (xmlrpclib.ProtocolError, socket.error) as e: + # ignore failures due to non-blocking socket 'unavailable' errors + if not is_unavailable_exception(e) and hasattr(e, "headers"): + # We should get error info in the response + expected_err = "invalid literal for int() with base 10: 'I am broken'" + self.assertEqual(e.headers.get("x-exception"), expected_err) + self.assertTrue(e.headers.get("x-traceback") is not None) else: self.fail('ProtocolError not raised') Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_xmlrpc_net.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_xmlrpc_net.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_xmlrpc_net.py Wed Apr 30 15:57:13 2008 @@ -1,5 +1,8 @@ #!/usr/bin/env python +import errno +import socket +import sys import unittest from test import test_support @@ -11,7 +14,12 @@ # Get the current time from xmlrpc.com. This code exercises # the minimal HTTP functionality in xmlrpclib. server = xmlrpclib.ServerProxy("http://time.xmlrpc.com/RPC2") - t0 = server.currentTime.getCurrentTime() + try: + t0 = server.currentTime.getCurrentTime() + except socket.error as e: + print(" test_current_time: skipping test, got error: %s" % e, + file=sys.stderr) + return # Perform a minimal sanity check on the result, just to be sure # the request means what we think it means. Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_zipfile.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_zipfile.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_zipfile.py Wed Apr 30 15:57:13 2008 @@ -309,6 +309,7 @@ correctfile = os.path.join(os.getcwd(), fpath[1:]) else: correctfile = os.path.join(os.getcwd(), fpath) + correctfile = os.path.normpath(correctfile) self.assertEqual(writtenfile, correctfile) Modified: python/branches/py3k-ctypes-pep3118/Lib/test/test_zlib.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/test_zlib.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/test/test_zlib.py Wed Apr 30 15:57:13 2008 @@ -1,6 +1,7 @@ import unittest from test import test_support import zlib +import binascii import random @@ -38,6 +39,21 @@ self.assertEqual(zlib.crc32(b"penguin"), zlib.crc32(b"penguin", 0)) self.assertEqual(zlib.adler32(b"penguin"),zlib.adler32(b"penguin",1)) + def test_crc32_adler32_unsigned(self): + foo = 'abcdefghijklmnop' + # explicitly test signed behavior + self.assertEqual(zlib.crc32(foo), 2486878355) + self.assertEqual(zlib.crc32('spam'), 1138425661) + self.assertEqual(zlib.adler32(foo+foo), 3573550353) + self.assertEqual(zlib.adler32('spam'), 72286642) + + def test_same_as_binascii_crc32(self): + foo = 'abcdefghijklmnop' + crc = 2486878355 + self.assertEqual(binascii.crc32(foo), crc) + self.assertEqual(zlib.crc32(foo), crc) + self.assertEqual(binascii.crc32('spam'), zlib.crc32('spam')) + class ExceptionTestCase(unittest.TestCase): @@ -59,6 +75,11 @@ # verify failure on building decompress object with bad params self.assertRaises(ValueError, zlib.decompressobj, 0) + def test_decompressobj_badflush(self): + # verify failure on calling decompressobj.flush with bad params + self.assertRaises(ValueError, zlib.decompressobj().flush, 0) + self.assertRaises(ValueError, zlib.decompressobj().flush, -1) + class CompressTestCase(unittest.TestCase): Deleted: python/branches/py3k-ctypes-pep3118/Lib/test/testall.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/test/testall.py Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,4 +0,0 @@ -# Backward compatibility -- you should use regrtest instead of this module. -import sys, regrtest -sys.argv[1:] = ["-vv"] -regrtest.main() Modified: python/branches/py3k-ctypes-pep3118/Lib/test/testtar.tar ============================================================================== Binary files. No diff available. Modified: python/branches/py3k-ctypes-pep3118/Lib/threading.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/threading.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/threading.py Wed Apr 30 15:57:13 2008 @@ -391,6 +391,9 @@ # shutdown and thus raises an exception about trying to perform some # operation on/with a NoneType __exc_info = _sys.exc_info + # Keep sys.exc_clear too to clear the exception just before + # allowing .join() to return. + #XXX __exc_clear = _sys.exc_clear def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None): @@ -403,7 +406,7 @@ self._args = args self._kwargs = kwargs self._daemonic = self._set_daemon() - self._started = False + self._started = Event() self._stopped = False self._block = Condition(Lock()) self._initialized = True @@ -418,7 +421,7 @@ def __repr__(self): assert self._initialized, "Thread.__init__() was not called" status = "initial" - if self._started: + if self._started.isSet(): status = "started" if self._stopped: status = "stopped" @@ -429,7 +432,8 @@ def start(self): if not self._initialized: raise RuntimeError("thread.__init__() not called") - if self._started: + + if self._started.isSet(): raise RuntimeError("thread already started") if __debug__: self._note("%s.start(): starting thread", self) @@ -437,12 +441,16 @@ _limbo[self] = self _active_limbo_lock.release() _start_new_thread(self._bootstrap, ()) - self._started = True - _sleep(0.000001) # 1 usec, to let the thread run (Solaris hack) + self._started.wait() def run(self): - if self._target: - self._target(*self._args, **self._kwargs) + try: + if self._target: + self._target(*self._args, **self._kwargs) + finally: + # Avoid a refcycle if the thread is running a function with + # an argument that has a member that points to the thread. + del self._target, self._args, self._kwargs def _bootstrap(self): # Wrapper around the real bootstrap code that ignores @@ -450,11 +458,11 @@ # happen when a daemon thread wakes up at an unfortunate # moment, finds the world around it destroyed, and raises some # random exception *** while trying to report the exception in - # __bootstrap_inner() below ***. Those random exceptions + # _bootstrap_inner() below ***. Those random exceptions # don't help anybody, and they confuse users, so we suppress # them. We suppress them only when it appears that the world # indeed has already been destroyed, so that exceptions in - # __bootstrap_inner() during normal business hours are properly + # _bootstrap_inner() during normal business hours are properly # reported. Also, we only suppress them for daemonic threads; # if a non-daemonic encounters this, something else is wrong. try: @@ -466,29 +474,29 @@ def _bootstrap_inner(self): try: - self._started = True + self._started.set() _active_limbo_lock.acquire() _active[_get_ident()] = self del _limbo[self] _active_limbo_lock.release() if __debug__: - self._note("%s.__bootstrap(): thread started", self) + self._note("%s._bootstrap(): thread started", self) if _trace_hook: - self._note("%s.__bootstrap(): registering trace hook", self) + self._note("%s._bootstrap(): registering trace hook", self) _sys.settrace(_trace_hook) if _profile_hook: - self._note("%s.__bootstrap(): registering profile hook", self) + self._note("%s._bootstrap(): registering profile hook", self) _sys.setprofile(_profile_hook) try: self.run() except SystemExit: if __debug__: - self._note("%s.__bootstrap(): raised SystemExit", self) + self._note("%s._bootstrap(): raised SystemExit", self) except: if __debug__: - self._note("%s.__bootstrap(): unhandled exception", self) + self._note("%s._bootstrap(): unhandled exception", self) # If sys.stderr is no more (most likely from interpreter # shutdown) use self._stderr. Otherwise still use sys (as in # _sys) in case sys.stderr was redefined since the creation of @@ -521,7 +529,14 @@ del exc_type, exc_value, exc_tb else: if __debug__: - self._note("%s.__bootstrap(): normal return", self) + self._note("%s._bootstrap(): normal return", self) + finally: + # Prevent a race in + # test_threading.test_no_refcycle_through_target when + # the exception keeps the target alive past when we + # assert that it's dead. + #XXX self.__exc_clear() + pass finally: with _active_limbo_lock: self._stop() @@ -562,20 +577,21 @@ # since it isn't if dummy_threading is *not* being used then don't # hide the exception. - _active_limbo_lock.acquire() try: - try: + with _active_limbo_lock: del _active[_get_ident()] - except KeyError: - if 'dummy_threading' not in _sys.modules: - raise - finally: - _active_limbo_lock.release() + # There must not be any python code between the previous line + # and after the lock is released. Otherwise a tracing function + # could try to acquire the lock again in the same thread, (in + # currentThread()), and would block. + except KeyError: + if 'dummy_threading' not in _sys.modules: + raise def join(self, timeout=None): if not self._initialized: raise RuntimeError("Thread.__init__() not called") - if not self._started: + if not self._started.isSet(): raise RuntimeError("cannot join thread before it is started") if self is currentThread(): raise RuntimeError("cannot join current thread") @@ -616,7 +632,7 @@ def isAlive(self): assert self._initialized, "Thread.__init__() not called" - return self._started and not self._stopped + return self._started.isSet() and not self._stopped def isDaemon(self): assert self._initialized, "Thread.__init__() not called" @@ -625,7 +641,7 @@ def setDaemon(self, daemonic): if not self._initialized: raise RuntimeError("Thread.__init__() not called") - if self._started: + if self._started.isSet(): raise RuntimeError("cannot set daemon status of active thread"); self._daemonic = daemonic @@ -667,7 +683,7 @@ def __init__(self): Thread.__init__(self, name="MainThread") - self._started = True + self._started.set() _active_limbo_lock.acquire() _active[_get_ident()] = self _active_limbo_lock.release() @@ -713,7 +729,8 @@ # instance is immortal, that's bad, so release this resource. del self._block - self._started = True + + self._started.set() _active_limbo_lock.acquire() _active[_get_ident()] = self _active_limbo_lock.release() Modified: python/branches/py3k-ctypes-pep3118/Lib/token.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/token.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/token.py Wed Apr 30 15:57:13 2008 @@ -72,6 +72,7 @@ for _name, _value in list(globals().items()): if type(_value) is type(0): tok_name[_value] = _name +del _name, _value def ISTERMINAL(x): Modified: python/branches/py3k-ctypes-pep3118/Lib/tokenize.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/tokenize.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/tokenize.py Wed Apr 30 15:57:13 2008 @@ -1,8 +1,11 @@ """Tokenization help for Python programs. -generate_tokens(readline) is a generator that breaks a stream of -text into Python tokens. It accepts a readline-like method which is called -repeatedly to get the next line of input (or "" for EOF). It generates +tokenize(readline) is a generator that breaks a stream of +bytes into Python tokens. It decodes the bytes according to +PEP-0263 for determining source file encoding. + +It accepts a readline-like method which is called +repeatedly to get the next line of input (or b"" for EOF). It generates 5-tuples with these members: the token type (see token.py) @@ -13,32 +16,32 @@ It is designed to match the working of the Python tokenizer exactly, except that it produces COMMENT tokens for comments and gives type OP for all -operators - -Older entry points - tokenize_loop(readline, tokeneater) - tokenize(readline, tokeneater=printtoken) -are the same, except instead of generating tokens, tokeneater is a callback -function to which the 5 fields described above are passed as 5 arguments, -each time a new token is found.""" +operators. Aditionally, all token lists start with an ENCODING token +which tells you which encoding was used to decode the bytes stream.""" __author__ = 'Ka-Ping Yee ' -__credits__ = \ - 'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro, Raymond Hettinger' +__credits__ = ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, ' + 'Skip Montanaro, Raymond Hettinger, Trent Nelson, ' + 'Michael Foord') -import string, re +import re, string, sys from token import * +from codecs import lookup +from itertools import chain, repeat +cookie_re = re.compile("coding[:=]\s*([-\w.]+)") import token __all__ = [x for x in dir(token) if x[0] != '_'] + ["COMMENT", "tokenize", - "generate_tokens", "NL", "untokenize"] + "detect_encoding", "NL", "untokenize", "ENCODING"] del token COMMENT = N_TOKENS tok_name[COMMENT] = 'COMMENT' NL = N_TOKENS + 1 tok_name[NL] = 'NL' -N_TOKENS += 2 +ENCODING = N_TOKENS + 2 +tok_name[ENCODING] = 'ENCODING' +N_TOKENS += 3 def group(*choices): return '(' + '|'.join(choices) + ')' def any(*choices): return group(*choices) + '*' @@ -132,33 +135,6 @@ class StopTokenizing(Exception): pass -def printtoken(type, token, startrowcol, endrowcol, line): # for testing - (srow, scol), (erow, ecol) = startrowcol, endrowcol - print("%d,%d-%d,%d:\t%s\t%s" % \ - (srow, scol, erow, ecol, tok_name[type], repr(token))) - -def tokenize(readline, tokeneater=printtoken): - """ - The tokenize() function accepts two parameters: one representing the - input stream, and one providing an output mechanism for tokenize(). - - The first parameter, readline, must be a callable object which provides - the same interface as the readline() method of built-in file objects. - Each call to the function should return one line of input as a string. - - The second parameter, tokeneater, must also be a callable object. It is - called once for each token, with five arguments, corresponding to the - tuples generated by generate_tokens(). - """ - try: - tokenize_loop(readline, tokeneater) - except StopTokenizing: - pass - -# backwards compatible interface -def tokenize_loop(readline, tokeneater): - for token_info in generate_tokens(readline): - tokeneater(*token_info) class Untokenizer: @@ -166,6 +142,7 @@ self.tokens = [] self.prev_row = 1 self.prev_col = 0 + self.encoding = None def add_whitespace(self, start): row, col = start @@ -180,6 +157,9 @@ self.compat(t, iterable) break tok_type, token, start, end, line = t + if tok_type == ENCODING: + self.encoding = token + continue self.add_whitespace(start) self.tokens.append(token) self.prev_row, self.prev_col = end @@ -193,16 +173,29 @@ indents = [] toks_append = self.tokens.append toknum, tokval = token + if toknum in (NAME, NUMBER): tokval += ' ' if toknum in (NEWLINE, NL): startline = True + prevstring = False for tok in iterable: toknum, tokval = tok[:2] + if toknum == ENCODING: + self.encoding = tokval + continue if toknum in (NAME, NUMBER): tokval += ' ' + # Insert a space between two consecutive strings + if toknum == STRING: + if prevstring: + tokval = ' ' + tokval + prevstring = True + else: + prevstring = False + if toknum == INDENT: indents.append(tokval) continue @@ -216,8 +209,11 @@ startline = False toks_append(tokval) + def untokenize(iterable): """Transform tokens back into Python source code. + It returns a bytes object, encoded using the ENCODING + token, which is the first token sequence output by tokenize. Each element returned by the iterable must be a token sequence with at least two elements, a token number and token value. If @@ -227,24 +223,89 @@ Untokenized source will match input source exactly Round-trip invariant for limited intput: - # Output text will tokenize the back to the input - t1 = [tok[:2] for tok in generate_tokens(f.readline)] + # Output bytes will tokenize the back to the input + t1 = [tok[:2] for tok in tokenize(f.readline)] newcode = untokenize(t1) - readline = iter(newcode.splitlines(1)).__next__ - t2 = [tok[:2] for tokin generate_tokens(readline)] + readline = BytesIO(newcode).readline + t2 = [tok[:2] for tok in tokenize(readline)] assert t1 == t2 """ ut = Untokenizer() - return ut.untokenize(iterable) + out = ut.untokenize(iterable) + if ut.encoding is not None: + out = out.encode(ut.encoding) + return out -def generate_tokens(readline): + +def detect_encoding(readline): + """ + The detect_encoding() function is used to detect the encoding that should + be used to decode a Python source file. It requires one argment, readline, + in the same way as the tokenize() generator. + + It will call readline a maximum of twice, and return the encoding used + (as a string) and a list of any lines (left as bytes) it has read + in. + + It detects the encoding from the presence of a utf-8 bom or an encoding + cookie as specified in pep-0263. If both a bom and a cookie are present, + but disagree, a SyntaxError will be raised. + + If no encoding is specified, then the default of 'utf-8' will be returned. """ - The generate_tokens() generator requires one argment, readline, which + utf8_bom = b'\xef\xbb\xbf' + bom_found = False + encoding = None + def read_or_stop(): + try: + return readline() + except StopIteration: + return b'' + + def find_cookie(line): + try: + line_string = line.decode('ascii') + except UnicodeDecodeError: + pass + else: + matches = cookie_re.findall(line_string) + if matches: + encoding = matches[0] + if bom_found and lookup(encoding).name != 'utf-8': + # This behaviour mimics the Python interpreter + raise SyntaxError('encoding problem: utf-8') + return encoding + + first = read_or_stop() + if first.startswith(utf8_bom): + bom_found = True + first = first[3:] + if not first: + return 'utf-8', [] + + encoding = find_cookie(first) + if encoding: + return encoding, [first] + + second = read_or_stop() + if not second: + return 'utf-8', [first] + + encoding = find_cookie(second) + if encoding: + return encoding, [first, second] + + return 'utf-8', [first, second] + + +def tokenize(readline): + """ + The tokenize() generator requires one argment, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function - should return one line of input as a string. Alternately, readline + should return one line of input as bytes. Alternately, readline can be a callable function terminating with StopIteration: - readline = open(myfile).__next__ # Example of alternate readline + readline = open(myfile, 'rb').__next__ # Example of alternate readline The generator produces 5-tuples with these members: the token type; the token string; a 2-tuple (srow, scol) of ints specifying the row and @@ -252,18 +313,38 @@ ints specifying the row and column where the token ends in the source; and the line on which the token was found. The line passed is the logical line; continuation lines are included. + + The first token sequence will always be an ENCODING token + which tells you which encoding was used to decode the bytes stream. """ + encoding, consumed = detect_encoding(readline) + def readline_generator(): + while True: + try: + yield readline() + except StopIteration: + return + chained = chain(consumed, readline_generator()) + return _tokenize(chained.__next__, encoding) + + +def _tokenize(readline, encoding): lnum = parenlev = continued = 0 namechars, numchars = string.ascii_letters + '_', '0123456789' contstr, needcont = '', 0 contline = None indents = [0] + if encoding is not None: + yield (ENCODING, encoding, (0, 0), (0, 0), '') while 1: # loop over lines in stream try: line = readline() except StopIteration: - line = '' + line = b'' + + if encoding is not None: + line = line.decode(encoding) lnum = lnum + 1 pos, max = 0, len(line) @@ -385,7 +466,8 @@ yield (DEDENT, '', (lnum, 0), (lnum, 0), '') yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '') -if __name__ == '__main__': # testing - import sys - if len(sys.argv) > 1: tokenize(open(sys.argv[1]).readline) - else: tokenize(sys.stdin.readline) + +# An undocumented, backwards compatible, API for all the places in the standard +# library that expect to be able to use tokenize with strings +def generate_tokens(readline): + return _tokenize(readline, None) Modified: python/branches/py3k-ctypes-pep3118/Lib/trace.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/trace.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/trace.py Wed Apr 30 15:57:13 2008 @@ -53,6 +53,7 @@ import re import sys import threading +import time import token import tokenize import types @@ -94,6 +95,8 @@ with '>>>>>> '. -s, --summary Write a brief summary on stdout for each file. (Can only be used with --count or --report.) +-g, --timing Prefix each line with the time since the program started. + Only used while tracing. Filters, may be repeated multiple times: --ignore-module= Ignore the given module(s) and its submodules @@ -246,19 +249,15 @@ if self.calledfuncs: print() print("functions called:") - calls = self.calledfuncs.keys() - calls.sort() - for filename, modulename, funcname in calls: + for filename, modulename, funcname in sorted(calls.keys()): print(("filename: %s, modulename: %s, funcname: %s" % (filename, modulename, funcname))) if self.callers: print() print("calling relationships:") - calls = self.callers.keys() - calls.sort() lastfile = lastcfile = "" - for ((pfile, pmod, pfunc), (cfile, cmod, cfunc)) in calls: + for ((pfile, pmod, pfunc), (cfile, cmod, cfunc)) in sorted(self.callers.keys()): if pfile != lastfile: print() print("***", pfile, "***") @@ -315,10 +314,8 @@ sums[modulename] = n_lines, percent, modulename, filename if summary and sums: - mods = sums.keys() - mods.sort() print("lines cov% module (path)") - for m in mods: + for m in sorted(sums.keys()): n_lines, percent, modulename, filename = sums[m] print("%5d %3d%% %s (%s)" % sums[m]) @@ -431,7 +428,8 @@ class Trace: def __init__(self, count=1, trace=1, countfuncs=0, countcallers=0, - ignoremods=(), ignoredirs=(), infile=None, outfile=None): + ignoremods=(), ignoredirs=(), infile=None, outfile=None, + timing=False): """ @param count true iff it should count number of times each line is executed @@ -447,6 +445,7 @@ @param infile file from which to read stored counts to be added into the results @param outfile file in which to write the results + @param timing true iff timing information be displayed """ self.infile = infile self.outfile = outfile @@ -459,6 +458,9 @@ self._calledfuncs = {} self._callers = {} self._caller_cache = {} + self.start_time = None + if timing: + self.start_time = time.time() if countcallers: self.globaltrace = self.globaltrace_trackcallers elif countfuncs: @@ -609,6 +611,8 @@ key = filename, lineno self.counts[key] = self.counts.get(key, 0) + 1 + if self.start_time: + print('%.2f' % (time.time() - self.start_time), end=' ') bname = os.path.basename(filename) print("%s(%d): %s" % (bname, lineno, linecache.getline(filename, lineno)), end=' ') @@ -620,6 +624,8 @@ filename = frame.f_code.co_filename lineno = frame.f_lineno + if self.start_time: + print('%.2f' % (time.time() - self.start_time), end=' ') bname = os.path.basename(filename) print("%s(%d): %s" % (bname, lineno, linecache.getline(filename, lineno)), end=' ') @@ -649,13 +655,13 @@ if argv is None: argv = sys.argv try: - opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:lT", + opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:lTg", ["help", "version", "trace", "count", "report", "no-report", "summary", "file=", "missing", "ignore-module=", "ignore-dir=", "coverdir=", "listfuncs", - "trackcalls"]) + "trackcalls", "timing"]) except getopt.error as msg: sys.stderr.write("%s: %s\n" % (sys.argv[0], msg)) @@ -675,6 +681,7 @@ summary = 0 listfuncs = False countcallers = False + timing = False for opt, val in opts: if opt == "--help": @@ -693,6 +700,10 @@ listfuncs = True continue + if opt == "-g" or opt == "--timing": + timing = True + continue + if opt == "-t" or opt == "--trace": trace = 1 continue @@ -775,7 +786,7 @@ t = Trace(count, trace, countfuncs=listfuncs, countcallers=countcallers, ignoremods=ignore_modules, ignoredirs=ignore_dirs, infile=counts_file, - outfile=counts_file) + outfile=counts_file, timing=timing) try: fp = open(progname) try: Modified: python/branches/py3k-ctypes-pep3118/Lib/types.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/types.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/types.py Wed Apr 30 15:57:13 2008 @@ -34,16 +34,8 @@ FrameType = type(tb.tb_frame) tb = None; del tb -# Extension types defined in a C helper module. XXX There may be no -# equivalent in implementations other than CPython, so it seems better to -# leave them undefined then to set them to e.g. None. -try: - import _types -except ImportError: - pass -else: - GetSetDescriptorType = type(_types.Helper.getter) - MemberDescriptorType = type(_types.Helper.member) - del _types +# For Jython, the following two types are identical +GetSetDescriptorType = type(FunctionType.__code__) +MemberDescriptorType = type(FunctionType.__globals__) del sys, _f, _g, _C, # Not for export Modified: python/branches/py3k-ctypes-pep3118/Lib/unittest.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/unittest.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/unittest.py Wed Apr 30 15:57:13 2008 @@ -504,6 +504,15 @@ # Locating and loading tests ############################################################################## +def CmpToKey(mycmp): + 'Convert a cmp= function into a key= function' + class K(object): + def __init__(self, obj, *args): + self.obj = obj + def __lt__(self, other): + return mycmp(self.obj, other.obj) == -1 + return K + class TestLoader: """This class is responsible for loading tests according to various criteria and returning them wrapped in a TestSuite @@ -598,7 +607,7 @@ and hasattr(getattr(testCaseClass, attrname), '__call__') testFnNames = list(filter(isTestMethod, dir(testCaseClass))) if self.sortTestMethodsUsing: - testFnNames.sort(self.sortTestMethodsUsing) + testFnNames.sort(key=CmpToKey(self.sortTestMethodsUsing)) return testFnNames Modified: python/branches/py3k-ctypes-pep3118/Lib/urllib.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/urllib.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/urllib.py Wed Apr 30 15:57:13 2008 @@ -360,7 +360,8 @@ # According to RFC 2616, "2xx" code indicates that the client's # request was successfully received, understood, and accepted. if (200 <= response.status < 300): - return addinfourl(response.fp, response.msg, "http:" + url) + return addinfourl(response.fp, response.msg, "http:" + url, + response.status) else: return self.http_error( url, response.fp, Modified: python/branches/py3k-ctypes-pep3118/Lib/urllib2.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/urllib2.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/urllib2.py Wed Apr 30 15:57:13 2008 @@ -157,7 +157,7 @@ # file object. If this happens, the simplest workaround is to # not initialize the base classes. if fp is not None: - self.__super_init(fp, hdrs, url) + self.__super_init(fp, hdrs, url, code) def __str__(self): return 'HTTP Error %s: %s' % (self.code, self.msg) @@ -531,8 +531,11 @@ # do the same. # be conciliant with URIs containing a space newurl = newurl.replace(' ', '%20') + newheaders = dict((k,v) for k,v in req.headers.items() + if k.lower() not in ("content-length", "content-type") + ) return Request(newurl, - headers=req.headers, + headers=newheaders, origin_req_host=req.get_origin_req_host(), unverifiable=True) else: @@ -774,7 +777,10 @@ # XXX this allows for multiple auth-schemes, but will stupidly pick # the last one with a realm specified. - rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', re.I) + # allow for double- and single-quoted realm values + # (single quotes are a violation of the RFC, but appear in the wild) + rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+' + 'realm=(["\'])(.*?)\\2', re.I) # XXX could pre-emptively send auth info already accepted (RFC 2617, # end of section 2, and section 1.2 immediately after "credentials" @@ -794,7 +800,7 @@ if authreq: mo = AbstractBasicAuthHandler.rx.search(authreq) if mo: - scheme, realm = mo.groups() + scheme, quote, realm = mo.groups() if scheme.lower() == 'basic': return self.retry_http_basic_auth(host, req, realm) Modified: python/branches/py3k-ctypes-pep3118/Lib/warnings.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/warnings.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/warnings.py Wed Apr 30 15:57:13 2008 @@ -3,143 +3,30 @@ # Note: function level imports should *not* be used # in this module as it may cause import lock deadlock. # See bug 683658. -import sys import linecache +import sys +import types __all__ = ["warn", "showwarning", "formatwarning", "filterwarnings", "resetwarnings"] -# filters contains a sequence of filter 5-tuples -# The components of the 5-tuple are: -# - an action: error, ignore, always, default, module, or once -# - a compiled regex that must match the warning message -# - a class representing the warning category -# - a compiled regex that must match the module that is being warned -# - a line number for the line being warning, or 0 to mean any line -# If either if the compiled regexs are None, match anything. -filters = [] -defaultaction = "default" -onceregistry = {} - -def warn(message, category=None, stacklevel=1): - """Issue a warning, or maybe ignore it or raise an exception.""" - # Check if message is already a Warning object - if isinstance(message, Warning): - category = message.__class__ - # Check category argument - if category is None: - category = UserWarning - assert issubclass(category, Warning) - # Get context information - try: - caller = sys._getframe(stacklevel) - except ValueError: - globals = sys.__dict__ - lineno = 1 - else: - globals = caller.f_globals - lineno = caller.f_lineno - if '__name__' in globals: - module = globals['__name__'] - else: - module = "" - filename = globals.get('__file__') - if filename: - fnl = filename.lower() - if fnl.endswith((".pyc", ".pyo")): - filename = filename[:-1] - else: - if module == "__main__": - try: - filename = sys.argv[0] - except AttributeError: - # embedded interpreters don't have sys.argv, see bug #839151 - filename = '__main__' - if not filename: - filename = module - registry = globals.setdefault("__warningregistry__", {}) - warn_explicit(message, category, filename, lineno, module, registry, - globals) - -def warn_explicit(message, category, filename, lineno, - module=None, registry=None, module_globals=None): - if module is None: - module = filename or "" - if module[-3:].lower() == ".py": - module = module[:-3] # XXX What about leading pathname? - if registry is None: - registry = {} - if isinstance(message, Warning): - text = str(message) - category = message.__class__ - else: - text = message - message = category(message) - key = (text, category, lineno) - # Quick test for common case - if registry.get(key): - return - # Search the filters - for item in filters: - action, msg, cat, mod, ln = item - if ((msg is None or msg.match(text)) and - issubclass(category, cat) and - (mod is None or mod.match(module)) and - (ln == 0 or lineno == ln)): - break - else: - action = defaultaction - # Early exit actions - if action == "ignore": - registry[key] = 1 - return - - # Prime the linecache for formatting, in case the - # "file" is actually in a zipfile or something. - linecache.getlines(filename, module_globals) - - if action == "error": - raise message - # Other actions - if action == "once": - registry[key] = 1 - oncekey = (text, category) - if onceregistry.get(oncekey): - return - onceregistry[oncekey] = 1 - elif action == "always": - pass - elif action == "module": - registry[key] = 1 - altkey = (text, category, 0) - if registry.get(altkey): - return - registry[altkey] = 1 - elif action == "default": - registry[key] = 1 - else: - # Unrecognized actions are errors - raise RuntimeError( - "Unrecognized action (%r) in warnings.filters:\n %s" % - (action, item)) - # Print message and context - showwarning(message, category, filename, lineno) -def showwarning(message, category, filename, lineno, file=None): +def showwarning(message, category, filename, lineno, file=None, line=None): """Hook to write a warning to a file; replace if you like.""" if file is None: file = sys.stderr try: - file.write(formatwarning(message, category, filename, lineno)) + file.write(formatwarning(message, category, filename, lineno, line)) except IOError: pass # the file (probably stderr) is invalid - this warning gets lost. -def formatwarning(message, category, filename, lineno): +def formatwarning(message, category, filename, lineno, line=None): """Function to format a warning the standard way.""" s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message) - line = linecache.getline(filename, lineno).strip() + line = linecache.getline(filename, lineno) if line is None else line if line: - s = s + " " + line + "\n" + line = line.strip() + s += " %s\n" % line return s def filterwarnings(action, message="", category=Warning, module="", lineno=0, @@ -257,7 +144,145 @@ raise _OptionError("invalid warning category: %r" % (category,)) return cat + +# Code typically replaced by _warnings +def warn(message, category=None, stacklevel=1): + """Issue a warning, or maybe ignore it or raise an exception.""" + # Check if message is already a Warning object + if isinstance(message, Warning): + category = message.__class__ + # Check category argument + if category is None: + category = UserWarning + assert issubclass(category, Warning) + # Get context information + try: + caller = sys._getframe(stacklevel) + except ValueError: + globals = sys.__dict__ + lineno = 1 + else: + globals = caller.f_globals + lineno = caller.f_lineno + if '__name__' in globals: + module = globals['__name__'] + else: + module = "" + filename = globals.get('__file__') + if filename: + fnl = filename.lower() + if fnl.endswith((".pyc", ".pyo")): + filename = filename[:-1] + else: + if module == "__main__": + try: + filename = sys.argv[0] + except AttributeError: + # embedded interpreters don't have sys.argv, see bug #839151 + filename = '__main__' + if not filename: + filename = module + registry = globals.setdefault("__warningregistry__", {}) + warn_explicit(message, category, filename, lineno, module, registry, + globals) + +def warn_explicit(message, category, filename, lineno, + module=None, registry=None, module_globals=None): + if module is None: + module = filename or "" + if module[-3:].lower() == ".py": + module = module[:-3] # XXX What about leading pathname? + if registry is None: + registry = {} + if isinstance(message, Warning): + text = str(message) + category = message.__class__ + else: + text = message + message = category(message) + key = (text, category, lineno) + # Quick test for common case + if registry.get(key): + return + # Search the filters + for item in filters: + action, msg, cat, mod, ln = item + if ((msg is None or msg.match(text)) and + issubclass(category, cat) and + (mod is None or mod.match(module)) and + (ln == 0 or lineno == ln)): + break + else: + action = defaultaction + # Early exit actions + if action == "ignore": + registry[key] = 1 + return + + # Prime the linecache for formatting, in case the + # "file" is actually in a zipfile or something. + linecache.getlines(filename, module_globals) + + if action == "error": + raise message + # Other actions + if action == "once": + registry[key] = 1 + oncekey = (text, category) + if onceregistry.get(oncekey): + return + onceregistry[oncekey] = 1 + elif action == "always": + pass + elif action == "module": + registry[key] = 1 + altkey = (text, category, 0) + if registry.get(altkey): + return + registry[altkey] = 1 + elif action == "default": + registry[key] = 1 + else: + # Unrecognized actions are errors + raise RuntimeError( + "Unrecognized action (%r) in warnings.filters:\n %s" % + (action, item)) + # Print message and context + showwarning(message, category, filename, lineno) + + +# filters contains a sequence of filter 5-tuples +# The components of the 5-tuple are: +# - an action: error, ignore, always, default, module, or once +# - a compiled regex that must match the warning message +# - a class representing the warning category +# - a compiled regex that must match the module that is being warned +# - a line number for the line being warning, or 0 to mean any line +# If either if the compiled regexs are None, match anything. +_warnings_defaults = False +try: + from _warnings import (filters, default_action, once_registry, + warn, warn_explicit) + defaultaction = default_action + onceregistry = once_registry + _warnings_defaults = True +except ImportError: + filters = [] + defaultaction = "default" + onceregistry = {} + + # Module initialization _processoptions(sys.warnoptions) -simplefilter("ignore", category=PendingDeprecationWarning, append=1) -simplefilter("ignore", category=ImportWarning, append=1) +if not _warnings_defaults: + simplefilter("ignore", category=PendingDeprecationWarning, append=1) + simplefilter("ignore", category=ImportWarning, append=1) + bytes_warning = sys.flags.bytes_warning + if bytes_warning > 1: + bytes_action = "error" + elif bytes_warning: + bytes_action = "default" + else: + bytes_action = "ignore" + simplefilter(bytes_action, category=BytesWarning, append=1) +del _warnings_defaults Modified: python/branches/py3k-ctypes-pep3118/Lib/weakref.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/weakref.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/weakref.py Wed Apr 30 15:57:13 2008 @@ -9,7 +9,7 @@ # they are called this instead of "ref" to avoid name collisions with # the module-global ref() function imported from _weakref. -import UserDict +import collections from _weakref import ( getweakrefcount, @@ -20,15 +20,17 @@ ProxyType, ReferenceType) +from _weakrefset import WeakSet ProxyTypes = (ProxyType, CallableProxyType) __all__ = ["ref", "proxy", "getweakrefcount", "getweakrefs", "WeakKeyDictionary", "ReferenceType", "ProxyType", - "CallableProxyType", "ProxyTypes", "WeakValueDictionary"] + "CallableProxyType", "ProxyTypes", "WeakValueDictionary", + "WeakSet"] -class WeakValueDictionary(UserDict.UserDict): +class WeakValueDictionary(collections.MutableMapping): """Mapping class that references values weakly. Entries in the dictionary will be discarded when no strong @@ -46,7 +48,8 @@ if self is not None: del self.data[wr.key] self._remove = remove - UserDict.UserDict.__init__(self, *args, **kw) + self.data = d = {} + d.update(*args, **kw) def __getitem__(self, key): o = self.data[key]() @@ -55,6 +58,12 @@ else: return o + def __delitem__(self, key): + del self.data[key] + + def __len__(self): + return sum(wr() is not None for wr in self.data.values()) + def __contains__(self, key): try: o = self.data[key]() @@ -207,7 +216,7 @@ super().__init__(ob, callback) -class WeakKeyDictionary(UserDict.UserDict): +class WeakKeyDictionary(collections.MutableMapping): """ Mapping class that references keys weakly. Entries in the dictionary will be discarded when there is no @@ -233,6 +242,9 @@ def __getitem__(self, key): return self.data[ref(key)] + def __len__(self): + return len(self.data) + def __repr__(self): return "" % id(self) @@ -337,108 +349,3 @@ d[ref(key, self._remove)] = value if len(kwargs): self.update(kwargs) - - -class WeakSet: - def __init__(self, data=None): - self.data = set() - def _remove(item, selfref=ref(self)): - self = selfref() - if self is not None: - self.data.discard(item) - self._remove = _remove - if data is not None: - self.update(data) - - def __iter__(self): - for itemref in self.data: - item = itemref() - if item is not None: - yield item - - def __contains__(self, item): - return ref(item) in self.data - - def __reduce__(self): - return (self.__class__, (list(self),), - getattr(self, '__dict__', None)) - - def add(self, item): - self.data.add(ref(item, self._remove)) - - def clear(self): - self.data.clear() - - def copy(self): - return self.__class__(self) - - def pop(self): - while True: - itemref = self.data.pop() - item = itemref() - if item is not None: - return item - - def remove(self, item): - self.data.remove(ref(item)) - - def discard(self, item): - self.data.discard(ref(item)) - - def update(self, other): - if isinstance(other, self.__class__): - self.data.update(other.data) - else: - for element in other: - self.add(element) - __ior__ = update - - # Helper functions for simple delegating methods. - def _apply(self, other, method): - if not isinstance(other, self.__class__): - other = self.__class__(other) - newdata = method(other.data) - newset = self.__class__() - newset.data = newdata - return newset - - def _apply_mutate(self, other, method): - if not isinstance(other, self.__class__): - other = self.__class__(other) - method(other) - - def difference(self, other): - return self._apply(other, self.data.difference) - __sub__ = difference - - def difference_update(self, other): - self._apply_mutate(self, self.data.difference_update) - __isub__ = difference_update - - def intersection(self, other): - return self._apply(other, self.data.intersection) - __and__ = intersection - - def intersection_update(self, other): - self._apply_mutate(self, self.data.intersection_update) - __iand__ = intersection_update - - def issubset(self, other): - return self.data.issubset(ref(item) for item in other) - __lt__ = issubset - - def issuperset(self, other): - return self.data.issuperset(ref(item) for item in other) - __gt__ = issuperset - - def symmetric_difference(self, other): - return self._apply(other, self.data.symmetric_difference) - __xor__ = symmetric_difference - - def symmetric_difference_update(self, other): - self._apply_mutate(other, self.data.symmetric_difference_update) - __ixor__ = symmetric_difference_update - - def union(self, other): - self._apply_mutate(other, self.data.union) - __or__ = union Modified: python/branches/py3k-ctypes-pep3118/Lib/xml/dom/minidom.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/xml/dom/minidom.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/xml/dom/minidom.py Wed Apr 30 15:57:13 2008 @@ -204,6 +204,8 @@ L.append(child) if child.nodeType == Node.ELEMENT_NODE: child.normalize() + if L: + L[-1].nextSibling = None self.childNodes[:] = L def cloneNode(self, deep): Modified: python/branches/py3k-ctypes-pep3118/Lib/xml/sax/expatreader.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/xml/sax/expatreader.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/xml/sax/expatreader.py Wed Apr 30 15:57:13 2008 @@ -107,7 +107,7 @@ xmlreader.IncrementalParser.parse(self, source) def prepareParser(self, source): - if source.getSystemId() != None: + if source.getSystemId() is not None: self._parser.SetBase(source.getSystemId()) # Redefined setContentHandler to allow changing handlers during parsing Modified: python/branches/py3k-ctypes-pep3118/Lib/xmlrpclib.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/xmlrpclib.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/xmlrpclib.py Wed Apr 30 15:57:13 2008 @@ -287,6 +287,20 @@ # @param value The time, given as an ISO 8601 string, a time # tuple, or a integer time value. +def _strftime(value): + if datetime: + if isinstance(value, datetime.datetime): + return "%04d%02d%02dT%02d:%02d:%02d" % ( + value.year, value.month, value.day, + value.hour, value.minute, value.second) + + if not isinstance(value, (tuple, time.struct_time)): + if value == 0: + value = time.time() + value = time.localtime(value) + + return "%04d%02d%02dT%02d:%02d:%02d" % value[:6] + class DateTime: """DateTime wrapper for an ISO 8601 string or time tuple or localtime integer value to generate 'dateTime.iso8601' XML-RPC @@ -294,33 +308,62 @@ """ def __init__(self, value=0): - if not isinstance(value, str): - if datetime and isinstance(value, datetime.datetime): - self.value = value.strftime("%Y%m%dT%H:%M:%S") - return - if datetime and isinstance(value, datetime.date): - self.value = value.strftime("%Y%m%dT%H:%M:%S") - return - if datetime and isinstance(value, datetime.time): - today = datetime.datetime.now().strftime("%Y%m%d") - self.value = value.strftime(today+"T%H:%M:%S") - return - if not isinstance(value, (tuple, time.struct_time)): - if value == 0: - value = time.time() - value = time.localtime(value) - value = time.strftime("%Y%m%dT%H:%M:%S", value) - self.value = value + if isinstance(value, str): + self.value = value + else: + self.value = _strftime(value) - def __eq__(self, other): + def make_comparable(self, other): if isinstance(other, DateTime): - other = other.value - return self.value == other + s = self.value + o = other.value + elif datetime and isinstance(other, datetime.datetime): + s = self.value + o = other.strftime("%Y%m%dT%H:%M:%S") + elif isinstance(other, (str, unicode)): + s = self.value + o = other + elif hasattr(other, "timetuple"): + s = self.timetuple() + o = other.timetuple() + else: + otype = (hasattr(other, "__class__") + and other.__class__.__name__ + or type(other)) + raise TypeError("Can't compare %s and %s" % + (self.__class__.__name__, otype)) + return s, o + + def __lt__(self, other): + s, o = self.make_comparable(other) + return s < o + + def __le__(self, other): + s, o = self.make_comparable(other) + return s <= o + + def __gt__(self, other): + s, o = self.make_comparable(other) + return s > o + + def __ge__(self, other): + s, o = self.make_comparable(other) + return s >= o + + def __eq__(self, other): + s, o = self.make_comparable(other) + return s == o def __ne__(self, other): - if isinstance(other, DateTime): - other = other.value - return self.value != other + s, o = self.make_comparable(other) + return s != o + + def timetuple(self): + return time.strptime(self.value, "%Y%m%dT%H:%M:%S") + + def __cmp__(self, other): + s, o = self.make_comparable(other) + return cmp(s, o) ## # Get date/time value. @@ -665,23 +708,10 @@ if datetime: def dump_datetime(self, value, write): write("") - write(value.strftime("%Y%m%dT%H:%M:%S")) + write(_strftime(value)) write("\n") dispatch[datetime.datetime] = dump_datetime - def dump_date(self, value, write): - write("") - write(value.strftime("%Y%m%dT00:00:00")) - write("\n") - dispatch[datetime.date] = dump_date - - def dump_time(self, value, write): - write("") - write(datetime.datetime.now().date().strftime("%Y%m%dT")) - write(value.strftime("%H:%M:%S")) - write("\n") - dispatch[datetime.time] = dump_time - def dump_instance(self, value, write): # check for special wrappers if value.__class__ in WRAPPERS: Modified: python/branches/py3k-ctypes-pep3118/Lib/zipfile.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Lib/zipfile.py (original) +++ python/branches/py3k-ctypes-pep3118/Lib/zipfile.py Wed Apr 30 15:57:13 2008 @@ -8,8 +8,10 @@ try: import zlib # We may need its compression method + crc32 = zlib.crc32 except ImportError: zlib = None + crc32 = binascii.crc32 __all__ = ["BadZipfile", "error", "ZIP_STORED", "ZIP_DEFLATED", "is_zipfile", "ZipInfo", "ZipFile", "PyZipFile", "LargeZipFile" ] @@ -36,13 +38,13 @@ # Here are some struct module formats for reading headers structEndArchive = "<4s4H2LH" # 9 items, end of archive, 22 bytes stringEndArchive = b"PK\005\006" # magic number for end of archive record -structCentralDir = "<4s4B4HlLL5HLL"# 19 items, central directory, 46 bytes +structCentralDir = "<4s4B4HLLL5HLL"# 19 items, central directory, 46 bytes stringCentralDir = b"PK\001\002" # magic number for central directory -structFileHeader = "<4s2B4HlLL2H" # 12 items, file header record, 30 bytes +structFileHeader = "<4s2B4HLLL2H" # 12 items, file header record, 30 bytes stringFileHeader = b"PK\003\004" # magic number for file header -structEndArchive64Locator = "<4slql" # 4 items, locate Zip64 header, 20 bytes +structEndArchive64Locator = "<4sLQL" # 4 items, locate Zip64 header, 20 bytes stringEndArchive64Locator = b"PK\x06\x07" # magic token for locator header -structEndArchive64 = "<4sqhhllqqqq" # 10 items, end of archive (Zip64), 56 bytes +structEndArchive64 = "<4sQHHLLQQQQ" # 10 items, end of archive (Zip64), 56 bytes stringEndArchive64 = b"PK\x06\x06" # magic token for Zip64 header @@ -140,7 +142,7 @@ endrec = list(endrec) endrec.append("") # Append the archive comment endrec.append(filesize - 22) # Append the record start offset - if endrec[-4] == -1 or endrec[-4] == 0xffffffff: + if endrec[-4] == 0xffffffff: return _EndRecData64(fpin, -22, endrec) return endrec # Search the last END_BLOCK bytes of the file for the record signature. @@ -160,7 +162,7 @@ # Append the archive comment and start offset endrec.append(comment) endrec.append(filesize - END_BLOCK + start) - if endrec[-4] == -1 or endrec[-4] == 0xffffffff: + if endrec[-4] == 0xffffffff: return _EndRecData64(fpin, - END_BLOCK + start, endrec) return endrec return # Error, return None @@ -247,7 +249,7 @@ if file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT: # File is larger than what fits into a 4 byte integer, # fall back to the ZIP64 extension - fmt = '= 24: - counts = unpack(' ZIP64_LIMIT: extra.append(zinfo.header_offset) - header_offset = -1 # struct "l" format: 32 one bits + header_offset = 0xffffffff # -1 32 bit else: header_offset = zinfo.header_offset @@ -1055,7 +1058,7 @@ if extra: # Append a ZIP64 field to the extra's extra_data = struct.pack( - ', generating ctlgen.py. import sys -import os from bgenlocations import TOOLBOXDIR, BGENDIR sys.path.append(BGENDIR) Modified: python/branches/py3k-ctypes-pep3118/Mac/Modules/dlg/dlgscan.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Modules/dlg/dlgscan.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Modules/dlg/dlgscan.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,6 @@ # Scan an Apple header file, generating a Python file of generator calls. import sys -import os from bgenlocations import TOOLBOXDIR, BGENDIR sys.path.append(BGENDIR) Modified: python/branches/py3k-ctypes-pep3118/Mac/Modules/drag/dragscan.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Modules/drag/dragscan.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Modules/drag/dragscan.py Wed Apr 30 15:57:13 2008 @@ -1,6 +1,5 @@ # Scan , generating draggen.py. import sys -import os from bgenlocations import TOOLBOXDIR, BGENDIR, INCLUDEDIR sys.path.append(BGENDIR) Modified: python/branches/py3k-ctypes-pep3118/Mac/Modules/evt/evtscan.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Modules/evt/evtscan.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Modules/evt/evtscan.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,6 @@ # Scan an Apple header file, generating a Python file of generator calls. import sys -import os from bgenlocations import TOOLBOXDIR, BGENDIR sys.path.append(BGENDIR) from scantools import Scanner Modified: python/branches/py3k-ctypes-pep3118/Mac/Modules/file/filescan.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Modules/file/filescan.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Modules/file/filescan.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,6 @@ # Scan an Apple header file, generating a Python file of generator calls. import sys -import os from bgenlocations import TOOLBOXDIR, BGENDIR sys.path.append(BGENDIR) from scantools import Scanner_OSX Modified: python/branches/py3k-ctypes-pep3118/Mac/Modules/fm/fmscan.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Modules/fm/fmscan.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Modules/fm/fmscan.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,6 @@ # Scan an Apple header file, generating a Python file of generator calls. import sys -import os from bgenlocations import TOOLBOXDIR, BGENDIR sys.path.append(BGENDIR) from scantools import Scanner Modified: python/branches/py3k-ctypes-pep3118/Mac/Modules/folder/folderscan.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Modules/folder/folderscan.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Modules/folder/folderscan.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,6 @@ # Scan an Apple header file, generating a Python file of generator calls. import sys -import os from bgenlocations import TOOLBOXDIR, BGENDIR sys.path.append(BGENDIR) from scantools import Scanner_OSX Modified: python/branches/py3k-ctypes-pep3118/Mac/Modules/help/helpscan.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Modules/help/helpscan.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Modules/help/helpscan.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,6 @@ # Scan an Apple header file, generating a Python file of generator calls. import sys -import os from bgenlocations import TOOLBOXDIR, BGENDIR sys.path.append(BGENDIR) from scantools import Scanner Modified: python/branches/py3k-ctypes-pep3118/Mac/Modules/ibcarbon/IBCarbonscan.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Modules/ibcarbon/IBCarbonscan.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Modules/ibcarbon/IBCarbonscan.py Wed Apr 30 15:57:13 2008 @@ -1,8 +1,6 @@ # IBCarbonscan.py import sys -import os -import string from bgenlocations import TOOLBOXDIR, BGENDIR sys.path.append(BGENDIR) Modified: python/branches/py3k-ctypes-pep3118/Mac/Modules/icn/icnscan.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Modules/icn/icnscan.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Modules/icn/icnscan.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,6 @@ # Scan an Apple header file, generating a Python file of generator calls. import sys -import os from bgenlocations import TOOLBOXDIR, BGENDIR sys.path.append(BGENDIR) from scantools import Scanner Modified: python/branches/py3k-ctypes-pep3118/Mac/Modules/launch/launchscan.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Modules/launch/launchscan.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Modules/launch/launchscan.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,6 @@ # Scan an Apple header file, generating a Python file of generator calls. import sys -import os from bgenlocations import TOOLBOXDIR, BGENDIR sys.path.append(BGENDIR) from scantools import Scanner Modified: python/branches/py3k-ctypes-pep3118/Mac/Modules/list/listscan.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Modules/list/listscan.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Modules/list/listscan.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,6 @@ # Scan an Apple header file, generating a Python file of generator calls. import sys -import os from bgenlocations import TOOLBOXDIR, BGENDIR sys.path.append(BGENDIR) from scantools import Scanner Modified: python/branches/py3k-ctypes-pep3118/Mac/Modules/menu/menuscan.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Modules/menu/menuscan.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Modules/menu/menuscan.py Wed Apr 30 15:57:13 2008 @@ -1,6 +1,5 @@ # Scan , generating menugen.py. import sys -import os from bgenlocations import TOOLBOXDIR, BGENDIR sys.path.append(BGENDIR) Modified: python/branches/py3k-ctypes-pep3118/Mac/Modules/mlte/mltescan.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Modules/mlte/mltescan.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Modules/mlte/mltescan.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,6 @@ # Scan an Apple header file, generating a Python file of generator calls. import sys -import os from bgenlocations import TOOLBOXDIR, BGENDIR sys.path.append(BGENDIR) from scantools import Scanner_OSX Modified: python/branches/py3k-ctypes-pep3118/Mac/Modules/osa/osascan.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Modules/osa/osascan.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Modules/osa/osascan.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,6 @@ # Scan an Apple header file, generating a Python file of generator calls. import sys -import os from bgenlocations import TOOLBOXDIR, BGENDIR sys.path.append(BGENDIR) from scantools import Scanner Modified: python/branches/py3k-ctypes-pep3118/Mac/Modules/qd/qdscan.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Modules/qd/qdscan.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Modules/qd/qdscan.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,6 @@ # Scan an Apple header file, generating a Python file of generator calls. import sys -import os from bgenlocations import TOOLBOXDIR, BGENDIR sys.path.append(BGENDIR) Modified: python/branches/py3k-ctypes-pep3118/Mac/Modules/qdoffs/qdoffsscan.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Modules/qdoffs/qdoffsscan.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Modules/qdoffs/qdoffsscan.py Wed Apr 30 15:57:13 2008 @@ -1,6 +1,5 @@ # Scan an Apple header file, generating a Python file of generator calls. import sys -import os from bgenlocations import TOOLBOXDIR, BGENDIR sys.path.append(BGENDIR) Modified: python/branches/py3k-ctypes-pep3118/Mac/Modules/qt/qtscan.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Modules/qt/qtscan.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Modules/qt/qtscan.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,6 @@ # Scan an Apple header file, generating a Python file of generator calls. import sys -import os from bgenlocations import TOOLBOXDIR, BGENDIR sys.path.append(BGENDIR) from scantools import Scanner Modified: python/branches/py3k-ctypes-pep3118/Mac/Modules/res/resscan.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Modules/res/resscan.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Modules/res/resscan.py Wed Apr 30 15:57:13 2008 @@ -3,8 +3,6 @@ # (Should learn how to tell the compiler to compile it as well.) import sys -import os -import string import MacOS from bgenlocations import TOOLBOXDIR, BGENDIR Modified: python/branches/py3k-ctypes-pep3118/Mac/Modules/scrap/scrapscan.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Modules/scrap/scrapscan.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Modules/scrap/scrapscan.py Wed Apr 30 15:57:13 2008 @@ -4,7 +4,6 @@ # generates a boilerplate to be edited by hand. import sys -import os from bgenlocations import TOOLBOXDIR, BGENDIR sys.path.append(BGENDIR) from scantools import Scanner Modified: python/branches/py3k-ctypes-pep3118/Mac/Modules/snd/sndscan.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Modules/snd/sndscan.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Modules/snd/sndscan.py Wed Apr 30 15:57:13 2008 @@ -3,7 +3,6 @@ # (Should learn how to tell the compiler to compile it as well.) import sys -import os from bgenlocations import TOOLBOXDIR, BGENDIR sys.path.append(BGENDIR) Modified: python/branches/py3k-ctypes-pep3118/Mac/Modules/te/tescan.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Modules/te/tescan.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Modules/te/tescan.py Wed Apr 30 15:57:13 2008 @@ -1,7 +1,6 @@ # Scan an Apple header file, generating a Python file of generator calls. import sys -import os from bgenlocations import TOOLBOXDIR, BGENDIR sys.path.append(BGENDIR) from scantools import Scanner Modified: python/branches/py3k-ctypes-pep3118/Mac/Modules/win/winscan.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Modules/win/winscan.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Modules/win/winscan.py Wed Apr 30 15:57:13 2008 @@ -1,6 +1,5 @@ # Scan an Apple header file, generating a Python file of generator calls. import sys -import os from bgenlocations import TOOLBOXDIR, BGENDIR sys.path.append(BGENDIR) Modified: python/branches/py3k-ctypes-pep3118/Mac/Tools/Doc/HelpIndexingTool/Standard_Suite.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Tools/Doc/HelpIndexingTool/Standard_Suite.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Tools/Doc/HelpIndexingTool/Standard_Suite.py Wed Apr 30 15:57:13 2008 @@ -103,7 +103,7 @@ _subcode = 'crel' aetools.keysubst(_arguments, self._argmap_make) - if _no_object != None: raise TypeError('No direct arg expected') + if _no_object is not None: raise TypeError('No direct arg expected') _reply, _arguments, _attributes = self.send(_code, _subcode, Modified: python/branches/py3k-ctypes-pep3118/Mac/Tools/Doc/setup.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/Tools/Doc/setup.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/Tools/Doc/setup.py Wed Apr 30 15:57:13 2008 @@ -174,10 +174,10 @@ ('root', 'root')) # import pdb ; pdb.set_trace() build_cmd = self.get_finalized_command('build') - if self.build_dest == None: + if self.build_dest is None: build_cmd = self.get_finalized_command('build') self.build_dest = build_cmd.build_dest - if self.install_doc == None: + if self.install_doc is None: self.install_doc = os.path.join(self.prefix, DESTDIR) print('INSTALL', self.build_dest, '->', self.install_doc) Modified: python/branches/py3k-ctypes-pep3118/Mac/scripts/buildpkg.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Mac/scripts/buildpkg.py (original) +++ python/branches/py3k-ctypes-pep3118/Mac/scripts/buildpkg.py Wed Apr 30 15:57:13 2008 @@ -183,7 +183,7 @@ # set folder attributes self.sourceFolder = root - if resources == None: + if resources is None: self.resourceFolder = root else: self.resourceFolder = resources Modified: python/branches/py3k-ctypes-pep3118/Makefile.pre.in ============================================================================== --- python/branches/py3k-ctypes-pep3118/Makefile.pre.in (original) +++ python/branches/py3k-ctypes-pep3118/Makefile.pre.in Wed Apr 30 15:57:13 2008 @@ -175,6 +175,10 @@ PYTHON= python$(EXE) BUILDPYTHON= python$(BUILDEXE) +# The task to run while instrument when building the profile-opt target +PROFILE_TASK= Tools/pybench/pybench.py -n 2 --with-gc --with-syscheck +#PROFILE_TASK= Lib/test/regrtest.py + # === Definitions added by makesetup === @@ -244,6 +248,7 @@ ########################################################################## # Python PYTHON_OBJS= \ + Python/_warnings.o \ Python/Python-ast.o \ Python/asdl.o \ Python/ast.o \ @@ -271,6 +276,7 @@ Python/peephole.o \ Python/pyarena.o \ Python/pyfpe.o \ + Python/pymath.o \ Python/pystate.o \ Python/pythonrun.o \ Python/structmember.o \ @@ -331,7 +337,6 @@ ########################################################################## # objects that get linked into the Python library LIBRARY_OBJS= \ - Modules/_typesmodule.o \ Modules/getbuildinfo.o \ $(PARSER_OBJS) \ $(OBJECT_OBJS) \ @@ -347,6 +352,27 @@ all: build_all build_all: $(BUILDPYTHON) oldsharedmods sharedmods +# Compile a binary with gcc profile guided optimization. +profile-opt: + @echo "Building with support for profile generation:" + $(MAKE) clean + $(MAKE) build_all_generate_profile + @echo "Running benchmark to generate profile data:" + $(MAKE) profile-removal + $(MAKE) run_profile_task + @echo "Rebuilding with profile guided optimizations:" + $(MAKE) clean + $(MAKE) build_all_use_profile + +build_all_generate_profile: + $(MAKE) all CFLAGS="$(CFLAGS) -fprofile-generate" LIBS="$(LIBS) -lgcov" + +run_profile_task: + ./$(BUILDPYTHON) $(PROFILE_TASK) + +build_all_use_profile: + $(MAKE) all CFLAGS="$(CFLAGS) -fprofile-use" + # Build the interpreter $(BUILDPYTHON): Modules/python.o $(LIBRARY) $(LDLIBRARY) $(LINKCC) $(LDFLAGS) $(LINKFORSHARED) -o $@ \ @@ -369,7 +395,6 @@ $(LIBRARY): $(LIBRARY_OBJS) -rm -f $@ $(AR) cr $@ Modules/getbuildinfo.o - $(AR) cr $@ Modules/_typesmodule.o $(AR) cr $@ $(PARSER_OBJS) $(AR) cr $@ $(OBJECT_OBJS) $(AR) cr $@ $(PYTHON_OBJS) @@ -517,29 +542,28 @@ Objects/unicodectype.o: $(srcdir)/Objects/unicodectype.c \ $(srcdir)/Objects/unicodetype_db.h -BYTESTR_DEPS = Include/bytes_methods.h \ - $(srcdir)/Objects/stringlib/fastsearch.h \ - $(srcdir)/Objects/stringlib/count.h \ - $(srcdir)/Objects/stringlib/find.h \ - $(srcdir)/Objects/stringlib/partition.h \ - $(srcdir)/Objects/stringlib/ctype.h \ - $(srcdir)/Objects/stringlib/transmogrify.h +BYTESTR_DEPS = \ + $(srcdir)/Include/bytes_methods.h \ + $(srcdir)/Objects/stringlib/count.h \ + $(srcdir)/Objects/stringlib/ctype.h \ + $(srcdir)/Objects/stringlib/eq.h \ + $(srcdir)/Objects/stringlib/fastsearch.h \ + $(srcdir)/Objects/stringlib/find.h \ + $(srcdir)/Objects/stringlib/partition.h \ + $(srcdir)/Objects/stringlib/stringdefs.h \ + $(srcdir)/Objects/stringlib/string_format.h \ + $(srcdir)/Objects/stringlib/transmogrify.h \ + $(srcdir)/Objects/stringlib/unicodedefs.h \ Objects/stringobject.o: $(srcdir)/Objects/stringobject.c $(BYTESTR_DEPS) Objects/bytesobject.o: $(srcdir)/Objects/bytesobject.c $(BYTESTR_DEPS) Objects/unicodeobject.o: $(srcdir)/Objects/unicodeobject.c \ - $(srcdir)/Objects/stringlib/string_format.h \ - $(srcdir)/Objects/stringlib/unicodedefs.h \ - $(srcdir)/Objects/stringlib/fastsearch.h \ - $(srcdir)/Objects/stringlib/count.h \ - $(srcdir)/Objects/stringlib/find.h \ - $(srcdir)/Objects/stringlib/partition.h + $(BYTESTR_DEPS) Python/formatter_unicode.o: $(srcdir)/Python/formatter_unicode.c \ - $(srcdir)/Objects/stringlib/formatter.h - + $(BYTESTR_DEPS) ############################################################################ @@ -599,6 +623,7 @@ Include/pydebug.h \ Include/pyerrors.h \ Include/pyfpe.h \ + Include/pymath.h \ Include/pygetopt.h \ Include/pymem.h \ Include/pyport.h \ @@ -619,6 +644,7 @@ Include/tupleobject.h \ Include/ucnhash.h \ Include/unicodeobject.h \ + Include/warnings.h \ Include/weakrefobject.h \ pyconfig.h \ $(PARSER_HEADERS) @@ -646,7 +672,7 @@ testall: all platform -find $(srcdir)/Lib -name '*.py[co]' -print | xargs rm -f - $(TESTPYTHON) Lib/compileall.py + $(TESTPYTHON) $(srcdir)/Lib/compileall.py -find $(srcdir)/Lib -name '*.py[co]' -print | xargs rm -f -$(TESTPYTHON) $(TESTPROG) $(TESTOPTS) -uall $(TESTPYTHON) $(TESTPROG) $(TESTOPTS) -uall @@ -688,7 +714,15 @@ $(TESTPYTHON) $(TESTPROG) $(MEMTESTOPTS) # Install everything -install: @FRAMEWORKINSTALLFIRST@ altinstall bininstall maninstall @FRAMEWORKINSTALLLAST@ +fullinstall: @FRAMEWORKINSTALLFIRST@ altinstall bininstall maninstall @FRAMEWORKINSTALLLAST@ + +# "make install" is an alias for "make altinstall" since we never want to +# overwrite Python 2.x. +install: altinstall + echo "* Note: not installed as 'python'." + echo "* Use 'make fullinstall' to install as 'python'." + echo "* However, 'make fulinstall' is discouraged," + echo "* as it will clobber your Python 2.x installation." # Install almost everything without disturbing previous versions altinstall: @FRAMEWORKALTINSTALLFIRST@ altbininstall libinstall inclinstall libainstall \ @@ -785,6 +819,7 @@ email email/mime email/test email/test/data \ sqlite3 sqlite3/test \ logging bsddb bsddb/test csv wsgiref \ + lib2to3 lib2to3/fixes lib2to3/pgen2 \ ctypes ctypes/test ctypes/macholib idlelib idlelib/Icons \ distutils distutils/command distutils/tests $(XMLLIBSUBDIRS) \ setuptools setuptools/command setuptools/tests setuptools.egg-info \ @@ -861,6 +896,8 @@ ./$(BUILDPYTHON) -Wi -t -O $(DESTDIR)$(LIBDEST)/compileall.py \ -d $(LIBDEST)/site-packages -f \ -x badsyntax $(DESTDIR)$(LIBDEST)/site-packages + -PYTHONPATH=$(DESTDIR)$(LIBDEST) $(RUNSHARED) \ + ./$(BUILDPYTHON) -Wi -t -c "import lib2to3.pygram" # Create the PLATDIR source directory, if one wasn't distributed.. $(srcdir)/Lib/$(PLATDIR): @@ -1043,7 +1080,7 @@ # Run reindent on the library reindent: - ./python$(EXEEXT) $(srcdir)/Tools/scripts/reindent.py -r $(srcdir)/Lib + ./$(BUILDPYTHON) $(srcdir)/Tools/scripts/reindent.py -r $(srcdir)/Lib # Rerun configure with the same options as it was run last time, # provided the config.status script exists @@ -1092,7 +1129,10 @@ find $(srcdir)/build -name 'fficonfig.h' -exec rm -f {} ';' || true find $(srcdir)/build -name 'fficonfig.py' -exec rm -f {} ';' || true -clobber: clean rmtestturds docclean +profile-removal: + find . -name '*.gc??' -exec rm -f {} ';' + +clobber: clean profile-removal -rm -f $(BUILDPYTHON) $(PGEN) $(LIBRARY) $(LDLIBRARY) $(DLLLIBRARY) \ tags TAGS \ config.cache config.log pyconfig.h Modules/config.c @@ -1152,6 +1192,10 @@ -o -name MANIFEST \ -o -print +# Perform some verification checks on any modified files. +check: + ./$(BUILDPYTHON) $(srcdir)/Tools/scripts/patchcheck.py + # Dependencies Python/thread.o: @THREADHEADERS@ Modified: python/branches/py3k-ctypes-pep3118/Misc/ACKS ============================================================================== --- python/branches/py3k-ctypes-pep3118/Misc/ACKS (original) +++ python/branches/py3k-ctypes-pep3118/Misc/ACKS Wed Apr 30 15:57:13 2008 @@ -1,14 +1,13 @@ -Acknowledgements ----------------- + This list is not complete and not in any useful order, but I would like to thank everybody who contributed in any way, with code, hints, bug reports, ideas, moral support, endorsement, or even complaints.... -Without you I would've stopped working on Python long ago! +Without you, I would've stopped working on Python long ago! --Guido -PS: In the standard Python distribution this file is encoded in Latin-1. +PS: In the standard Python distribution, this file is encoded in Latin-1. David Abrahams Jim Ahlstrom @@ -17,15 +16,15 @@ Kevin Altis Mark Anacker Anders Andersen -Erik Anders?n John Anderson +Erik Anders?n Oliver Andrich Ross Andrus Jason Asbahr David Ascher -Peter ?strand Chris AtLee John Aycock +Jan-Hein B"uhrman Donovan Baarda Attila Babo Alfonso Baciero @@ -33,6 +32,7 @@ Stig Bakken Greg Ball Luigi Ballabio +Jeff Balogh Michael J. Barber Chris Barker Quentin Barnes @@ -47,13 +47,12 @@ Samuel L. Bayer Donald Beaudry David Beazley -Neal Becker Robin Becker +Neal Becker Bill Bedford Reimer Behrends Ben Bell Thomas Bellman -Juan M. Bello Rivas Alexander Belopolsky Andrew Bennetts Andy Bensky @@ -87,13 +86,12 @@ Dave Brennan Tom Bridgman Richard Brodie -Gary S. Brown Daniel Brotsky +Gary S. Brown Oleg Broytmann Dave Brueck Stan Bubrouski Erik de Bueger -Jan-Hein B"uhrman Dick Bulterman Bill Bumgarner Jimmy Burgett @@ -114,9 +112,9 @@ Octavian Cerna Hye-Shik Chang Jeffrey Chang -Brad Chapman -Greg Chapman Mitch Chapman +Greg Chapman +Brad Chapman David Chaum Nicolas Chauvat Michael Chermside @@ -147,8 +145,8 @@ Christopher A. Craig Laura Creighton Drew Csillag -Tom Culliton John Cugini +Tom Culliton Andrew Dalke Lars Damerow Eric Daniel @@ -164,13 +162,11 @@ Mark Dickinson Yves Dionne Daniel Dittmar -Walter D?rwald Jaromir Dolecek Ismail Donmez Dima Dorfman Cesar Douady Dean Draayer -Fred L. Drake, Jr. John DuBois Paul Dubois Quinn Dunkan @@ -179,7 +175,9 @@ Andy Dustman Gary Duzan Eugene Dvurechenski +Josip Dzolonga Maxim Dzumanenko +Walter D?rwald Hans Eckardt Grant Edwards John Ehresman @@ -194,8 +192,8 @@ Ben Escoto Andy Eskilsson Stefan Esser -Carey Evans Stephen D Evans +Carey Evans Tim Everett Paul Everitt David Everly @@ -213,7 +211,7 @@ Frederik Fix Matt Fleming Hern?n Mart?nez Foffani -Amaury Forgeot d'Arc +Michael Foord Doug Fort John Fouhy Martin Franklin @@ -251,14 +249,14 @@ Eddy De Greef Duncan Grisby Dag Gruneau -Thomas G?ttler Michael Guravage Lars Gust?bel +Thomas G?ttler Barry Haddow -V?clav Haisman Paul ten Hagen Rasmus Hahn Peter Haight +V?clav Haisman Bob Halley Jesse Hallio Jun Hamano @@ -270,13 +268,13 @@ Lynda Hardman Derek Harland Jason Harper -Gerhard H?ring Larry Hastings Shane Hathaway Rycharde Hawkes Jochen Hayek Christian Heimes Thomas Heller +Malte Helmert Lance Finn Helsten Jonathan Hendry James Henstridge @@ -318,15 +316,15 @@ Greg Humphreys Eric Huss Jeremy Hylton +Gerhard H?ring Mihai Ibanescu -Juan David Ib??ez Palomar Lars Immisch Tony Ingraldi John Interrante Bob Ippolito Atsuo Ishimoto -Ben Jackson Paul Jackson +Ben Jackson David Jacobs Kevin Jacobs Kjetil Jacobsen @@ -344,8 +342,9 @@ Richard Jones Irmen de Jong Lucas de Jonge -Jens B. Jorgensen John Jorgensen +Jens B. Jorgensen +Fred L. Drake, Jr. Andreas Jung Tattoo Mabonzo K. Bob Kahn @@ -355,12 +354,14 @@ Jacob Kaplan-Moss Lou Kates Sebastien Keim -Randall Kern Robert Kern +Randall Kern Magnus Kessler Lawrence Kesteloot Vivek Khera Mads Kiilerich +Taek Joo Kim +Paul Kippes Steve Kirsch Ron Klatchko Bastian Kleineidam @@ -378,7 +379,6 @@ Hannu Krosing Andrew Kuchling Vladimir Kushnir -Arnaud Mazin Cameron Laird Tino Lange Andrew Langmead @@ -389,28 +389,28 @@ Simon Law Chris Lawrence Brian Leair -Christopher Lee -Inyeol Lee John J. Lee +Inyeol Lee Thomas Lee +Christopher Lee Luc Lefebvre Kip Lehman Joerg Lehmann Luke Kenneth Casson Leighton Marc-Andre Lemburg John Lenton +Christopher Tur Lesniewski-Laas Mark Levinson William Lewis Robert van Liere Shawn Ligocki Martin Ligr Christopher Lindblad -Eric Lindvall Bjorn Lindqvist Per Lindqvist +Eric Lindvall Nick Lockwood Stephanie Lockwood -Martin von L?wis Anne Lord Tom Loredo Jason Lowe @@ -421,7 +421,7 @@ Mark Lutz Jim Lynch Mikael Lyngvig -Alan McIntyre +Martin von L?wis Andrew I MacIntyre Tim MacKenzie Nick Maclaren @@ -429,6 +429,7 @@ Grzegorz Makarewicz Ken Manheimer Vladimir Marangozov +David Marek Doug Marien Alex Martelli Anthony Martin @@ -437,14 +438,14 @@ Nick Mathewson Graham Matthews Dieter Maurer +Arnaud Mazin +Chris McDonough Greg McFarlane +Alan McIntyre Michael McLay Gordon McMillan -Damien Miller -Jay T. Miller -Chris McDonough -Andrew McNamara Caolan McNamara +Andrew McNamara Craig McPheeters Lambert Meertens Bill van Melle @@ -452,23 +453,25 @@ Mike Meyer Steven Miale Trent Mick -Chad Miller Damien Miller +Chad Miller +Jay T. Miller Roman Milner -Dom Mitchell Dustin J. Mitchell +Dom Mitchell Doug Moen -Paul Moore The Dragon De Monsyne Skip Montanaro +Paul Moore James A Morrison -Sape Mullender Sjoerd Mullender +Sape Mullender Michael Muller John Nagle Takahiro Nakayama Travers Naran Fredrik Nehr +Trent Nelson Tony Nelson Chad Netzer Max Neunh?ffer @@ -494,24 +497,24 @@ Douglas Orr Denis S. Otkidach Russel Owen +Ondrej Palkovsky Mike Pall Todd R. Palmer +Juan David Ib??ez Palomar Jan Palus +M. Papillon Peter Parente Alexandre Parenteau Dan Parisien Harri Pasanen Randy Pausch -Ondrej Palkovsky -M. Papillon -Marcel van der Peijl Samuele Pedroni +Marcel van der Peijl Steven Pemberton -Eduardo P?rez -Fernando P?rez Mark Perrego Trevor Perrin Tim Peters +Benjamin Peterson Chris Petrilli Bjorn Pettersen Geoff Philbrick @@ -519,12 +522,15 @@ Adrian Phillips Christopher J. Phoenix Neale Pickett -Jean-Fran?ois Pi?ronne +Jim St. Pierre Dan Pierson Martijn Pieters Fran?ois Pinard Zach Pincus Michael Piotrowski +Antoine Pitrou +Jean-Fran?ois Pi?ronne +Guilherme Polo Michael Pomraning Iustin Pop John Popplewell @@ -532,6 +538,8 @@ Paul Prescod Donovan Preston Steve Purcell +Fernando P?rez +Eduardo P?rez Brian Quinlan Anders Qvist Burton Radons @@ -553,24 +561,25 @@ Armin Rigo Nicholas Riley Jean-Claude Rimbault +Juan M. Bello Rivas Anthony Roach Mark Roberts -Andy Robinson Jim Robinson +Andy Robinson Kevin Rodgers +Giampaolo Rodola Mike Romberg Case Roole Timothy Roscoe -Craig Rowland Jim Roskind -Erik van Blokland Just van Rossum Hugo van Rossum Saskia van Rossum Donald Wallace Rouse II Liam Routt -Sam Ruby +Craig Rowland Paul Rubin +Sam Ruby Audun S. Runde Jeff Rush Sam Rushing @@ -594,14 +603,15 @@ Stefan Schwarzer Dietmar Schwertberger Federico Schwindt -Barry Scott Steven Scott +Barry Scott Nick Seidenman ??iga Seilnach Fred Sells Jiwon Seo Jerry Seutter Denis Severson +Ian Seyer Ha Shao Bruce Sherwood Pete Shinners @@ -617,6 +627,7 @@ George Sipe J. Sipprell Kragen Sitaker +Eric V. Smith Christopher Smith Gregory P. Smith Rafal Smotrzyk @@ -628,7 +639,6 @@ Noah Spurrier Nathan Srebro RajGopal Srinivasan -Jim St. Pierre Quentin Stafford-Fraser Frank Stajano Oliver Steele @@ -651,8 +661,8 @@ William Tanksley Christian Tanzer Steven Taschuk -Amy Taylor Monty Taylor +Amy Taylor Tobias Thelen Robin Thomas Eric Tiedemann @@ -668,11 +678,10 @@ John Tromp Jason Trowbridge Anthony Tuininga -Christopher Tur Lesniewski-Laas Stephen Turner Bill Tutt -Eren T?rkay Doobee R. Tzeck +Eren T?rkay Lionel Ulmer Roger Upole Michael Urman @@ -708,14 +717,15 @@ Cliff Wells Rickard Westman Jeff Wheeler +Christopher White Mats Wichmann Truida Wiedijk Felix Wiemann Gerry Wiener Bryce "Zooko" Wilcox-O'Hearn -Gerald S. Williams John Williams Sue Williams +Gerald S. Williams Frank Willison Greg V. Wilson Jody Winston @@ -725,6 +735,7 @@ Jean-Claude Wippler Lars Wirzenius Stefan Witzel +David Wolever Klaus-Juergen Wolf Dan Wolfe Richard Wolff @@ -744,3 +755,5 @@ Mike Zarnstorff Siebren van der Zee Uwe Zessin +Amaury Forgeot d'Arc +Peter ?strand Modified: python/branches/py3k-ctypes-pep3118/Misc/HISTORY ============================================================================== --- python/branches/py3k-ctypes-pep3118/Misc/HISTORY (original) +++ python/branches/py3k-ctypes-pep3118/Misc/HISTORY Wed Apr 30 15:57:13 2008 @@ -3,11 +3,2150 @@ This file contains the release messages for previous Python releases. As you read on you go back to the dark ages of Python's history. +(Note: news about 2.5c2 and later 2.5 releases is in the Misc/NEWS +file of the release25-maint branch.) ====================================================================== +What's New in Python 2.5 release candidate 1? +============================================= + +*Release date: 17-AUG-2006* + +Core and builtins +----------------- + +- Unicode objects will no longer raise an exception when being + compared equal or unequal to a string and a UnicodeDecodeError + exception occurs, e.g. as result of a decoding failure. + + Instead, the equal (==) and unequal (!=) comparison operators will + now issue a UnicodeWarning and interpret the two objects as + unequal. The UnicodeWarning can be filtered as desired using + the warning framework, e.g. silenced completely, turned into an + exception, logged, etc. + + Note that compare operators other than equal and unequal will still + raise UnicodeDecodeError exceptions as they've always done. + +- Fix segfault when doing string formatting on subclasses of long. + +- Fix bug related to __len__ functions using values > 2**32 on 64-bit machines + with new-style classes. + +- Fix bug related to __len__ functions returning negative values with + classic classes. + +- Patch #1538606, Fix __index__() clipping. There were some problems + discovered with the API and how integers that didn't fit into Py_ssize_t + were handled. This patch attempts to provide enough alternatives + to effectively use __index__. + +- Bug #1536021: __hash__ may now return long int; the final hash + value is obtained by invoking hash on the long int. + +- Bug #1536786: buffer comparison could emit a RuntimeWarning. + +- Bug #1535165: fixed a segfault in input() and raw_input() when + sys.stdin is closed. + +- On Windows, the PyErr_Warn function is now exported from + the Python dll again. + +- Bug #1191458: tracing over for loops now produces a line event + on each iteration. Fixing this problem required changing the .pyc + magic number. This means that .pyc files generated before 2.5c1 + will be regenerated. + +- Bug #1333982: string/number constants were inappropriately stored + in the byte code and co_consts even if they were not used, ie + immediately popped off the stack. + +- Fixed a reference-counting problem in property(). + + +Library +------- + +- Fix a bug in the ``compiler`` package that caused invalid code to be + generated for generator expressions. + +- The distutils version has been changed to 2.5.0. The change to + keep it programmatically in sync with the Python version running + the code (introduced in 2.5b3) has been reverted. It will continue + to be maintained manually as static string literal. + +- If the Python part of a ctypes callback function returns None, + and this cannot be converted to the required C type, an exception is + printed with PyErr_WriteUnraisable. Before this change, the C + callback returned arbitrary values to the calling code. + +- The __repr__ method of a NULL ctypes.py_object() no longer raises + an exception. + +- uuid.UUID now has a bytes_le attribute. This returns the UUID in + little-endian byte order for Windows. In addition, uuid.py gained some + workarounds for clocks with low resolution, to stop the code yielding + duplicate UUIDs. + +- Patch #1540892: site.py Quitter() class attempts to close sys.stdin + before raising SystemExit, allowing IDLE to honor quit() and exit(). + +- Bug #1224621: make tabnanny recognize IndentationErrors raised by tokenize. + +- Patch #1536071: trace.py should now find the full module name of a + file correctly even on Windows. + +- logging's atexit hook now runs even if the rest of the module has + already been cleaned up. + +- Bug #1112549, fix DoS attack on cgi.FieldStorage. + +- Bug #1531405, format_exception no longer raises an exception if + str(exception) raised an exception. + +- Fix a bug in the ``compiler`` package that caused invalid code to be + generated for nested functions. + + +Extension Modules +----------------- + +- Patch #1511317: don't crash on invalid hostname (alias) info. + +- Patch #1535500: fix segfault in BZ2File.writelines and make sure it + raises the correct exceptions. + +- Patch # 1536908: enable building ctypes on OpenBSD/AMD64. The + '-no-stack-protector' compiler flag for OpenBSD has been removed. + +- Patch #1532975 was applied, which fixes Bug #1533481: ctypes now + uses the _as_parameter_ attribute when objects are passed to foreign + function calls. The ctypes version number was changed to 1.0.1. + +- Bug #1530559, struct.pack raises TypeError where it used to convert. + Passing float arguments to struct.pack when integers are expected + now triggers a DeprecationWarning. + + +Tests +----- + +- test_socketserver should now work on cygwin and not fail sporadically + on other platforms. + +- test_mailbox should now work on cygwin versions 2006-08-10 and later. + +- Bug #1535182: really test the xreadlines() method of bz2 objects. + +- test_threading now skips testing alternate thread stack sizes on + platforms that don't support changing thread stack size. + + +Documentation +------------- + +- Patch #1534922: unittest docs were corrected and enhanced. + + +Build +----- + +- Bug #1535502, build _hashlib on Windows, and use masm assembler + code in OpenSSL. + +- Bug #1534738, win32 debug version of _msi should be _msi_d.pyd. + +- Bug #1530448, ctypes build failure on Solaris 10 was fixed. + + +C API +----- + +- New API for Unicode rich comparisons: PyUnicode_RichCompare() + +- Bug #1069160. Internal correctness changes were made to + ``PyThreadState_SetAsyncExc()``. A test case was added, and + the documentation was changed to state that the return value + is always 1 (normal) or 0 (if the specified thread wasn't found). + + +What's New in Python 2.5 beta 3? +================================ + +*Release date: 03-AUG-2006* + +Core and builtins +----------------- + +- _PyWeakref_GetWeakrefCount() now returns a Py_ssize_t; it previously + returned a long (see PEP 353). + +- Bug #1515471: string.replace() accepts character buffers again. + +- Add PyErr_WarnEx() so C code can pass the stacklevel to warnings.warn(). + This provides the proper warning for struct.pack(). + PyErr_Warn() is now deprecated in favor of PyErr_WarnEx(). + +- Patch #1531113: Fix augmented assignment with yield expressions. + Also fix a SystemError when trying to assign to yield expressions. + +- Bug #1529871: The speed enhancement patch #921466 broke Python's compliance + with PEP 302. This was fixed by adding an ``imp.NullImporter`` type that is + used in ``sys.path_importer_cache`` to cache non-directory paths and avoid + excessive filesystem operations during imports. + +- Bug #1521947: When checking for overflow, ``PyOS_strtol()`` used some + operations on signed longs that are formally undefined by C. + Unfortunately, at least one compiler now cares about that, so complicated + the code to make that compiler happy again. + +- Bug #1524310: Properly report errors from FindNextFile in os.listdir. + +- Patch #1232023: Stop including current directory in search + path on Windows. + +- Fix some potential crashes found with failmalloc. + +- Fix warnings reported by Klocwork's static analysis tool. + +- Bug #1512814, Fix incorrect lineno's when code within a function + had more than 255 blank lines. + +- Patch #1521179: Python now accepts the standard options ``--help`` and + ``--version`` as well as ``/?`` on Windows. + +- Bug #1520864: unpacking singleton tuples in a 'for' loop (for x, in) works + again. Fixing this problem required changing the .pyc magic number. + This means that .pyc files generated before 2.5b3 will be regenerated. + +- Bug #1524317: Compiling Python ``--without-threads`` failed. + The Python core compiles again, and, in a build without threads, the + new ``sys._current_frames()`` returns a dictionary with one entry, + mapping the faux "thread id" 0 to the current frame. + +- Bug #1525447: build on MacOS X on a case-sensitive filesystem. + + +Library +------- + +- Fix #1693149. Now you can pass several modules separated by + comma to trace.py in the same --ignore-module option. + +- Correction of patch #1455898: In the mbcs decoder, set final=False + for stream decoder, but final=True for the decode function. + +- os.urandom no longer masks unrelated exceptions like SystemExit or + KeyboardInterrupt. + +- Bug #1525866: Don't copy directory stat times in + shutil.copytree on Windows + +- Bug #1002398: The documentation for os.path.sameopenfile now correctly + refers to file descriptors, not file objects. + +- The renaming of the xml package to xmlcore, and the import hackery done + to make it appear at both names, has been removed. Bug #1511497, + #1513611, and probably others. + +- Bug #1441397: The compiler module now recognizes module and function + docstrings correctly as it did in Python 2.4. + +- Bug #1529297: The rewrite of doctest for Python 2.4 unintentionally + lost that tests are sorted by name before being run. This rarely + matters for well-written tests, but can create baffling symptoms if + side effects from one test to the next affect outcomes. ``DocTestFinder`` + has been changed to sort the list of tests it returns. + +- The distutils version has been changed to 2.5.0, and is now kept + in sync with sys.version_info[:3]. + +- Bug #978833: Really close underlying socket in _socketobject.close. + +- Bug #1459963: urllib and urllib2 now normalize HTTP header names with + title(). + +- Patch #1525766: In pkgutil.walk_packages, correctly pass the onerror callback + to recursive calls and call it with the failing package name. + +- Bug #1525817: Don't truncate short lines in IDLE's tool tips. + +- Patch #1515343: Fix printing of deprecated string exceptions with a + value in the traceback module. + +- Resync optparse with Optik 1.5.3: minor tweaks for/to tests. + +- Patch #1524429: Use repr() instead of backticks in Tkinter again. + +- Bug #1520914: Change time.strftime() to accept a zero for any position in its + argument tuple. For arguments where zero is illegal, the value is forced to + the minimum value that is correct. This is to support an undocumented but + common way people used to fill in inconsequential information in the time + tuple pre-2.4. + +- Patch #1220874: Update the binhex module for Mach-O. + +- The email package has improved RFC 2231 support, specifically for + recognizing the difference between encoded (name*0*=) and non-encoded + (name*0=) parameter continuations. This may change the types of + values returned from email.message.Message.get_param() and friends. + Specifically in some cases where non-encoded continuations were used, + get_param() used to return a 3-tuple of (None, None, string) whereas now it + will just return the string (since non-encoded continuations don't have + charset and language parts). + + Also, whereas % values were decoded in all parameter continuations, they are + now only decoded in encoded parameter parts. + +- Bug #1517990: IDLE keybindings on MacOS X now work correctly + +- Bug #1517996: IDLE now longer shows the default Tk menu when a + path browser, class browser or debugger is the frontmost window on MacOS X + +- Patch #1520294: Support for getset and member descriptors in types.py, + inspect.py, and pydoc.py. Specifically, this allows for querying the type + of an object against these built-in types and more importantly, for getting + their docstrings printed in the interactive interpreter's help() function. + + +Extension Modules +----------------- + +- Patch #1519025 and bug #926423: If a KeyboardInterrupt occurs during + a socket operation on a socket with a timeout, the exception will be + caught correctly. Previously, the exception was not caught. + +- Patch #1529514: The _ctypes extension is now compiled on more + openbsd target platforms. + +- The ``__reduce__()`` method of the new ``collections.defaultdict`` had + a memory leak, affecting pickles and deep copies. + +- Bug #1471938: Fix curses module build problem on Solaris 8; patch by + Paul Eggert. + +- Patch #1448199: Release interpreter lock in _winreg.ConnectRegistry. + +- Patch #1521817: Index range checking on ctypes arrays containing + exactly one element enabled again. This allows iterating over these + arrays, without the need to check the array size before. + +- Bug #1521375: When the code in ctypes.util.find_library was + run with root privileges, it could overwrite or delete + /dev/null in certain cases; this is now fixed. + +- Bug #1467450: On Mac OS X 10.3, RTLD_GLOBAL is now used as the + default mode for loading shared libraries in ctypes. + +- Because of a misspelled preprocessor symbol, ctypes was always + compiled without thread support; this is now fixed. + +- pybsddb Bug #1527939: bsddb module DBEnv dbremove and dbrename + methods now allow their database parameter to be None as the + sleepycat API allows. + +- Bug #1526460: Fix socketmodule compile on NetBSD as it has a different + bluetooth API compared with Linux and FreeBSD. + +Tests +----- + +- Bug #1501330: Change test_ossaudiodev to be much more tolerant in terms of + how long the test file should take to play. Now accepts taking 2.93 secs + (exact time) +/- 10% instead of the hard-coded 3.1 sec. + +- Patch #1529686: The standard tests ``test_defaultdict``, ``test_iterlen``, + ``test_uuid`` and ``test_email_codecs`` didn't actually run any tests when + run via ``regrtest.py``. Now they do. + +Build +----- + +- Bug #1439538: Drop usage of test -e in configure as it is not portable. + +Mac +--- + +- PythonLauncher now works correctly when the path to the script contains + characters that are treated specially by the shell (such as quotes). + +- Bug #1527397: PythonLauncher now launches scripts with the working directory + set to the directory that contains the script instead of the user home + directory. That latter was an implementation accident and not what users + expect. + + +What's New in Python 2.5 beta 2? +================================ + +*Release date: 11-JUL-2006* + +Core and builtins +----------------- + +- Bug #1441486: The literal representation of -(sys.maxint - 1) + again evaluates to a int object, not a long. + +- Bug #1501934: The scope of global variables that are locally assigned + using augmented assignment is now correctly determined. + +- Bug #927248: Recursive method-wrapper objects can now safely + be released. + +- Bug #1417699: Reject locale-specific decimal point in float() + and atof(). + +- Bug #1511381: codec_getstreamcodec() in codec.c is corrected to + omit a default "error" argument for NULL pointer. This allows + the parser to take a codec from cjkcodecs again. + +- Bug #1519018: 'as' is now validated properly in import statements. + +- On 64 bit systems, int literals that use less than 64 bits are + now ints rather than longs. + +- Bug #1512814, Fix incorrect lineno's when code at module scope + started after line 256. + +- New function ``sys._current_frames()`` returns a dict mapping thread + id to topmost thread stack frame. This is for expert use, and is + especially useful for debugging application deadlocks. The functionality + was previously available in Fazal Majid's ``threadframe`` extension + module, but it wasn't possible to do this in a wholly threadsafe way from + an extension. + +Library +------- + +- Bug #1257728: Mention Cygwin in distutils error message about a missing + VS 2003. + +- Patch #1519566: Update turtle demo, make begin_fill idempotent. + +- Bug #1508010: msvccompiler now requires the DISTUTILS_USE_SDK + environment variable to be set in order to the SDK environment + for finding the compiler, include files, etc. + +- Bug #1515998: Properly generate logical ids for files in bdist_msi. + +- warnings.py now ignores ImportWarning by default + +- string.Template() now correctly handles tuple-values. Previously, + multi-value tuples would raise an exception and single-value tuples would + be treated as the value they contain, instead. + +- Bug #822974: Honor timeout in telnetlib.{expect,read_until} + even if some data are received. + +- Bug #1267547: Put proper recursive setup.py call into the + spec file generated by bdist_rpm. + +- Bug #1514693: Update turtle's heading when switching between + degrees and radians. + +- Reimplement turtle.circle using a polyline, to allow correct + filling of arcs. + +- Bug #1514703: Only setup canvas window in turtle when the canvas + is created. + +- Bug #1513223: .close() of a _socketobj now releases the underlying + socket again, which then gets closed as it becomes unreferenced. + +- Bug #1504333: Make sgmllib support angle brackets in quoted + attribute values. + +- Bug #853506: Fix IPv6 address parsing in unquoted attributes in + sgmllib ('[' and ']' were not accepted). + +- Fix a bug in the turtle module's end_fill function. + +- Bug #1510580: The 'warnings' module improperly required that a Warning + category be either a types.ClassType and a subclass of Warning. The proper + check is just that it is a subclass with Warning as the documentation states. + +- The compiler module now correctly compiles the new try-except-finally + statement (bug #1509132). + +- The wsgiref package is now installed properly on Unix. + +- A bug was fixed in logging.config.fileConfig() which caused a crash on + shutdown when fileConfig() was called multiple times. + +- The sqlite3 module did cut off data from the SQLite database at the first + null character before sending it to a custom converter. This has been fixed + now. + +Extension Modules +----------------- + +- #1494314: Fix a regression with high-numbered sockets in 2.4.3. This + means that select() on sockets > FD_SETSIZE (typically 1024) work again. + The patch makes sockets use poll() internally where available. + +- Assigning None to pointer type fields in ctypes structures possible + overwrote the wrong fields, this is fixed now. + +- Fixed a segfault in _ctypes when ctypes.wintypes were imported + on non-Windows platforms. + +- Bug #1518190: The ctypes.c_void_p constructor now accepts any + integer or long, without range checking. + +- Patch #1517790: It is now possible to use custom objects in the ctypes + foreign function argtypes sequence as long as they provide a from_param + method, no longer is it required that the object is a ctypes type. + +- The '_ctypes' extension module now works when Python is configured + with the --without-threads option. + +- Bug #1513646: os.access on Windows now correctly determines write + access, again. + +- Bug #1512695: cPickle.loads could crash if it was interrupted with + a KeyboardInterrupt. + +- Bug #1296433: parsing XML with a non-default encoding and + a CharacterDataHandler could crash the interpreter in pyexpat. + +- Patch #1516912: improve Modules support for OpenVMS. + +Build +----- + +- Automate Windows build process for the Win64 SSL module. + +- 'configure' now detects the zlib library the same way as distutils. + Previously, the slight difference could cause compilation errors of the + 'zlib' module on systems with more than one version of zlib. + +- The MSI compileall step was fixed to also support a TARGETDIR + with spaces in it. + +- Bug #1517388: sqlite3.dll is now installed on Windows independent + of Tcl/Tk. + +- Bug #1513032: 'make install' failed on FreeBSD 5.3 due to lib-old + trying to be installed even though it's empty. + +Tests +----- + +- Call os.waitpid() at the end of tests that spawn child processes in order + to minimize resources (zombies). + +Documentation +------------- + +- Cover ImportWarning, PendingDeprecationWarning and simplefilter() in the + documentation for the warnings module. + +- Patch #1509163: MS Toolkit Compiler no longer available. + +- Patch #1504046: Add documentation for xml.etree. + + +What's New in Python 2.5 beta 1? +================================ + +*Release date: 20-JUN-2006* + +Core and builtins +----------------- + +- Patch #1507676: Error messages returned by invalid abstract object operations + (such as iterating over an integer) have been improved and now include the + type of the offending object to help with debugging. + +- Bug #992017: A classic class that defined a __coerce__() method that returned + its arguments swapped would infinitely recurse and segfault the interpreter. + +- Fix the socket tests so they can be run concurrently. + +- Removed 5 integers from C frame objects (PyFrameObject). + f_nlocals, f_ncells, f_nfreevars, f_stack_size, f_restricted. + +- Bug #532646: object.__call__() will continue looking for the __call__ + attribute on objects until one without one is found. This leads to recursion + when you take a class and set its __call__ attribute to an instance of the + class. Originally fixed for classic classes, but this fix is for new-style. + Removes the infinite_rec_3 crasher. + +- The string and unicode methods startswith() and endswith() now accept + a tuple of prefixes/suffixes to look for. Implements RFE #1491485. + +- Buffer objects, at the C level, never used the char buffer + implementation even when the char buffer for the wrapped object was + explicitly requested (originally returned the read or write buffer). + Now a TypeError is raised if the char buffer is not present but is + requested. + +- Patch #1346214: Statements like "if 0: suite" are now again optimized + away like they were in Python 2.4. + +- Builtin exceptions are now full-blown new-style classes instead of + instances pretending to be classes, which speeds up exception handling + by about 80% in comparison to 2.5a2. + +- Patch #1494554: Update unicodedata.numeric and unicode.isnumeric to + Unicode 4.1. + +- Patch #921466: sys.path_importer_cache is now used to cache valid and + invalid file paths for the built-in import machinery which leads to + fewer open calls on startup. + +- Patch #1442927: ``long(str, base)`` is now up to 6x faster for non-power- + of-2 bases. The largest speedup is for inputs with about 1000 decimal + digits. Conversion from non-power-of-2 bases remains quadratic-time in + the number of input digits (it was and remains linear-time for bases + 2, 4, 8, 16 and 32). + +- Bug #1334662: ``int(string, base)`` could deliver a wrong answer + when ``base`` was not 2, 4, 8, 10, 16 or 32, and ``string`` represented + an integer close to ``sys.maxint``. This was repaired by patch + #1335972, which also gives a nice speedup. + +- Patch #1337051: reduced size of frame objects. + +- PyErr_NewException now accepts a tuple of base classes as its + "base" parameter. + +- Patch #876206: function call speedup by retaining allocated frame + objects. + +- Bug #1462152: file() now checks more thoroughly for invalid mode + strings and removes a possible "U" before passing the mode to the + C library function. + +- Patch #1488312, Fix memory alignment problem on SPARC in unicode + +- Bug #1487966: Fix SystemError with conditional expression in assignment + +- WindowsError now has two error code attributes: errno, which carries + the error values from errno.h, and winerror, which carries the error + values from winerror.h. Previous versions put the winerror.h values + (from GetLastError()) into the errno attribute. + +- Patch #1475845: Raise IndentationError for unexpected indent. + +- Patch #1479181: split open() and file() from being aliases for each other. + +- Patch #1497053 & bug #1275608: Exceptions occurring in ``__eq__()`` + methods were always silently ignored by dictionaries when comparing keys. + They are now passed through (except when using the C API function + ``PyDict_GetItem()``, whose semantics did not change). + +- Bug #1456209: In some obscure cases it was possible for a class with a + custom ``__eq__()`` method to confuse dict internals when class instances + were used as a dict's keys and the ``__eq__()`` method mutated the dict. + No, you don't have any code that did this ;-) + +Extension Modules +----------------- + +- Bug #1295808: expat symbols should be namespaced in pyexpat + +- Patch #1462338: Upgrade pyexpat to expat 2.0.0 + +- Change binascii.hexlify to accept a read-only buffer instead of only a char + buffer and actually follow its documentation. + +- Fixed a potentially invalid memory access of CJKCodecs' shift-jis decoder. + +- Patch #1478788 (modified version): The functional extension module has + been renamed to _functools and a functools Python wrapper module added. + This provides a home for additional function related utilities that are + not specifically about functional programming. See PEP 309. + +- Patch #1493701: performance enhancements for struct module. + +- Patch #1490224: time.altzone is now set correctly on Cygwin. + +- Patch #1435422: zlib's compress and decompress objects now have a + copy() method. + +- Patch #1454481: thread stack size is now tunable at runtime for thread + enabled builds on Windows and systems with Posix threads support. + +- On Win32, os.listdir now supports arbitrarily-long Unicode path names + (up to the system limit of 32K characters). + +- Use Win32 API to implement os.{access,chdir,chmod,mkdir,remove,rename,rmdir,utime}. + As a result, these functions now raise WindowsError instead of OSError. + +- ``time.clock()`` on Win64 should use the high-performance Windows + ``QueryPerformanceCounter()`` now (as was already the case on 32-bit + Windows platforms). + +- Calling Tk_Init twice is refused if the first call failed as that + may deadlock. + +- bsddb: added the DB_ARCH_REMOVE flag and fixed db.DBEnv.log_archive() to + accept it without potentially using an uninitialized pointer. + +- bsddb: added support for the DBEnv.log_stat() and DBEnv.lsn_reset() methods + assuming BerkeleyDB >= 4.0 and 4.4 respectively. [pybsddb project SF + patch numbers 1494885 and 1494902] + +- bsddb: added an interface for the BerkeleyDB >= 4.3 DBSequence class. + [pybsddb project SF patch number 1466734] + +- bsddb: fix DBCursor.pget() bug with keyword argument names when no data + parameter is supplied. [SF pybsddb bug #1477863] + +- bsddb: the __len__ method of a DB object has been fixed to return correct + results. It could previously incorrectly return 0 in some cases. + Fixes SF bug 1493322 (pybsddb bug 1184012). + +- bsddb: the bsddb.dbtables Modify method now raises the proper error and + aborts the db transaction safely when a modifier callback fails. + Fixes SF python patch/bug #1408584. + +- bsddb: multithreaded DB access using the simple bsddb module interface + now works reliably. It has been updated to use automatic BerkeleyDB + deadlock detection and the bsddb.dbutils.DeadlockWrap wrapper to retry + database calls that would previously deadlock. [SF python bug #775414] + +- Patch #1446489: add support for the ZIP64 extensions to zipfile. + +- Patch #1506645: add Python wrappers for the curses functions + is_term_resized, resize_term and resizeterm. + +Library +------- + +- Patch #815924: Restore ability to pass type= and icon= in tkMessageBox + functions. + +- Patch #812986: Update turtle output even if not tracing. + +- Patch #1494750: Destroy master after deleting children in + Tkinter.BaseWidget. + +- Patch #1096231: Add ``default`` argument to Tkinter.Wm.wm_iconbitmap. + +- Patch #763580: Add name and value arguments to Tkinter variable + classes. + +- Bug #1117556: SimpleHTTPServer now tries to find and use the system's + mime.types file for determining MIME types. + +- Bug #1339007: Shelf objects now don't raise an exception in their + __del__ method when initialization failed. + +- Patch #1455898: The MBCS codec now supports the incremental mode for + double-byte encodings. + +- ``difflib``'s ``SequenceMatcher.get_matching_blocks()`` was changed to + guarantee that adjacent triples in the return list always describe + non-adjacent blocks. Previously, a pair of matching blocks could end + up being described by multiple adjacent triples that formed a partition + of the matching pair. + +- Bug #1498146: fix optparse to handle Unicode strings in option help, + description, and epilog. + +- Bug #1366250: minor optparse documentation error. + +- Bug #1361643: fix textwrap.dedent() so it handles tabs appropriately; + clarify docs. + +- The wsgiref package has been added to the standard library. + +- The functions update_wrapper() and wraps() have been added to the functools + module. These make it easier to copy relevant metadata from the original + function when writing wrapper functions. + +- The optional ``isprivate`` argument to ``doctest.testmod()``, and the + ``doctest.is_private()`` function, both deprecated in 2.4, were removed. + +- Patch #1359618: Speed up charmap encoder by using a trie structure + for lookup. + +- The functions in the ``pprint`` module now sort dictionaries by key + before computing the display. Before 2.5, ``pprint`` sorted a dictionary + if and only if its display required more than one line, although that + wasn't documented. The new behavior increases predictability; e.g., + using ``pprint.pprint(a_dict)`` in a doctest is now reliable. + +- Patch #1497027: try HTTP digest auth before basic auth in urllib2 + (thanks for J. J. Lee). + +- Patch #1496206: improve urllib2 handling of passwords with respect to + default HTTP and HTTPS ports. + +- Patch #1080727: add "encoding" parameter to doctest.DocFileSuite. + +- Patch #1281707: speed up gzip.readline. + +- Patch #1180296: Two new functions were added to the locale module: + format_string() to get the effect of "format % items" but locale-aware, + and currency() to format a monetary number with currency sign. + +- Patch #1486962: Several bugs in the turtle Tk demo module were fixed + and several features added, such as speed and geometry control. + +- Patch #1488881: add support for external file objects in bz2 compressed + tarfiles. + +- Patch #721464: pdb.Pdb instances can now be given explicit stdin and + stdout arguments, making it possible to redirect input and output + for remote debugging. + +- Patch #1484695: Update the tarfile module to version 0.8. This fixes + a couple of issues, notably handling of long file names using the + GNU LONGNAME extension. + +- Patch #1478292. ``doctest.register_optionflag(name)`` shouldn't create a + new flag when ``name`` is already the name of an option flag. + +- Bug #1385040: don't allow "def foo(a=1, b): pass" in the compiler + package. + +- Patch #1472854: make the rlcompleter.Completer class usable on non- + UNIX platforms. + +- Patch #1470846: fix urllib2 ProxyBasicAuthHandler. + +- Bug #1472827: correctly escape newlines and tabs in attribute values in + the saxutils.XMLGenerator class. + + +Build +----- + +- Bug #1502728: Correctly link against librt library on HP-UX. + +- OpenBSD 3.9 is supported now. + +- Patch #1492356: Port to Windows CE. + +- Bug/Patch #1481770: Use .so extension for shared libraries on HP-UX for ia64. + +- Patch #1471883: Add --enable-universalsdk. + +C API +----- + +Tests +----- + +Tools +----- + +Documentation +------------- + + + +What's New in Python 2.5 alpha 2? +================================= + +*Release date: 27-APR-2006* + +Core and builtins +----------------- + +- Bug #1465834: 'bdist_wininst preinstall script support' was fixed + by converting these apis from macros into exported functions again: + + PyParser_SimpleParseFile PyParser_SimpleParseString PyRun_AnyFile + PyRun_AnyFileEx PyRun_AnyFileFlags PyRun_File PyRun_FileEx + PyRun_FileFlags PyRun_InteractiveLoop PyRun_InteractiveOne + PyRun_SimpleFile PyRun_SimpleFileEx PyRun_SimpleString + PyRun_String Py_CompileString + +- Under COUNT_ALLOCS, types are not necessarily immortal anymore. + +- All uses of PyStructSequence_InitType have been changed to initialize + the type objects only once, even if the interpreter is initialized + multiple times. + +- Bug #1454485, array.array('u') could crash the interpreter. This was + due to PyArgs_ParseTuple(args, 'u#', ...) trying to convert buffers (strings) + to unicode when it didn't make sense. 'u#' now requires a unicode string. + +- Py_UNICODE is unsigned. It was always documented as unsigned, but + due to a bug had a signed value in previous versions. + +- Patch #837242: ``id()`` of any Python object always gives a positive + number now, which might be a long integer. ``PyLong_FromVoidPtr`` and + ``PyLong_AsVoidPtr`` have been changed accordingly. Note that it has + never been correct to implement a ``__hash()__`` method that returns the + ``id()`` of an object: + + def __hash__(self): + return id(self) # WRONG + + because a hash result must be a (short) Python int but it was always + possible for ``id()`` to return a Python long. However, because ``id()`` + could return negative values before, on a 32-bit box an ``id()`` result + was always usable as a hash value before this patch. That's no longer + necessarily so. + +- Python on OS X 10.3 and above now uses dlopen() (via dynload_shlib.c) + to load extension modules and now provides the dl module. As a result, + sys.setdlopenflags() now works correctly on these systems. (SF patch + #1454844) + +- Patch #1463867: enhanced garbage collection to allow cleanup of cycles + involving generators that have paused outside of any ``try`` or ``with`` + blocks. (In 2.5a1, a paused generator that was part of a reference + cycle could not be garbage collected, regardless of whether it was + paused in a ``try`` or ``with`` block.) + +Extension Modules +----------------- + +- Patch #1191065: Fix preprocessor problems on systems where recvfrom + is a macro. + +- Bug #1467952: os.listdir() now correctly raises an error if readdir() + fails with an error condition. + +- Fixed bsddb.db.DBError derived exceptions so they can be unpickled. + +- Bug #1117761: bsddb.*open() no longer raises an exception when using + the cachesize parameter. + +- Bug #1149413: bsddb.*open() no longer raises an exception when using + a temporary db (file=None) with the 'n' flag to truncate on open. + +- Bug #1332852: bsddb module minimum BerkeleyDB version raised to 3.3 + as older versions cause excessive test failures. + +- Patch #1062014: AF_UNIX sockets under Linux have a special + abstract namespace that is now fully supported. + +Library +------- + +- Bug #1223937: subprocess.CalledProcessError reports the exit status + of the process using the returncode attribute, instead of + abusing errno. + +- Patch #1475231: ``doctest`` has a new ``SKIP`` option, which causes + a doctest to be skipped (the code is not run, and the expected output + or exception is ignored). + +- Fixed contextlib.nested to cope with exceptions being raised and + caught inside exit handlers. + +- Updated optparse module to Optik 1.5.1 (allow numeric constants in + hex, octal, or binary; add ``append_const`` action; keep going if + gettext cannot be imported; added ``OptionParser.destroy()`` method; + added ``epilog`` for better help generation). + +- Bug #1473760: ``tempfile.TemporaryFile()`` could hang on Windows, when + called from a thread spawned as a side effect of importing a module. + +- The pydoc module now supports documenting packages contained in + .zip or .egg files. + +- The pkgutil module now has several new utility functions, such + as ``walk_packages()`` to support working with packages that are either + in the filesystem or zip files. + +- The mailbox module can now modify and delete messages from + mailboxes, in addition to simply reading them. Thanks to Gregory + K. Johnson for writing the code, and to the 2005 Google Summer of + Code for funding his work. + +- The ``__del__`` method of class ``local`` in module ``_threading_local`` + returned before accomplishing any of its intended cleanup. + +- Patch #790710: Add breakpoint command lists in pdb. + +- Patch #1063914: Add Tkinter.Misc.clipboard_get(). + +- Patch #1191700: Adjust column alignment in bdb breakpoint lists. + +- SimpleXMLRPCServer relied on the fcntl module, which is unavailable on + Windows. Bug #1469163. + +- The warnings, linecache, inspect, traceback, site, and doctest modules + were updated to work correctly with modules imported from zipfiles or + via other PEP 302 __loader__ objects. + +- Patch #1467770: Reduce usage of subprocess._active to processes which + the application hasn't waited on. + +- Patch #1462222: Fix Tix.Grid. + +- Fix exception when doing glob.glob('anything*/') + +- The pstats.Stats class accepts an optional stream keyword argument to + direct output to an alternate file-like object. + +Build +----- + +- The Makefile now has a reindent target, which runs reindent.py on + the library. + +- Patch #1470875: Building Python with MS Free Compiler + +- Patch #1161914: Add a python-config script. + +- Patch #1324762:Remove ccpython.cc; replace --with-cxx with + --with-cxx-main. Link with C++ compiler only if --with-cxx-main was + specified. (Can be overridden by explicitly setting LINKCC.) Decouple + CXX from --with-cxx-main, see description in README. + +- Patch #1429775: Link extension modules with the shared libpython. + +- Fixed a libffi build problem on MIPS systems. + +- ``PyString_FromFormat``, ``PyErr_Format``, and ``PyString_FromFormatV`` + now accept formats "%u" for unsigned ints, "%lu" for unsigned longs, + and "%zu" for unsigned integers of type ``size_t``. + +Tests +----- + +- test_contextlib now checks contextlib.nested can cope with exceptions + being raised and caught inside exit handlers. + +- test_cmd_line now checks operation of the -m and -c command switches + +- The test_contextlib test in 2.5a1 wasn't actually run unless you ran + it separately and by hand. It also wasn't cleaning up its changes to + the current Decimal context. + +- regrtest.py now has a -M option to run tests that test the new limits of + containers, on 64-bit architectures. Running these tests is only sensible + on 64-bit machines with more than two gigabytes of memory. The argument + passed is the maximum amount of memory for the tests to use. + +Tools +----- + +- Added the Python benchmark suite pybench to the Tools/ directory; + contributed by Marc-Andre Lemburg. + +Documentation +------------- + +- Patch #1473132: Improve docs for ``tp_clear`` and ``tp_traverse``. + +- PEP 343: Added Context Types section to the library reference + and attempted to bring other PEP 343 related documentation into + line with the implementation and/or python-dev discussions. + +- Bug #1337990: clarified that ``doctest`` does not support examples + requiring both expected output and an exception. + + +What's New in Python 2.5 alpha 1? +================================= + +*Release date: 05-APR-2006* + +Core and builtins +----------------- + +- PEP 338: -m command line switch now delegates to runpy.run_module + allowing it to support modules in packages and zipfiles + +- On Windows, .DLL is not an accepted file name extension for + extension modules anymore; extensions are only found if they + end in .PYD. + +- Bug #1421664: sys.stderr.encoding is now set to the same value as + sys.stdout.encoding. + +- __import__ accepts keyword arguments. + +- Patch #1460496: round() now accepts keyword arguments. + +- Fixed bug #1459029 - unicode reprs were double-escaped. + +- Patch #1396919: The system scope threads are reenabled on FreeBSD + 5.4 and later versions. + +- Bug #1115379: Compiling a Unicode string with an encoding declaration + now gives a SyntaxError. + +- Previously, Python code had no easy way to access the contents of a + cell object. Now, a ``cell_contents`` attribute has been added + (closes patch #1170323). + +- Patch #1123430: Python's small-object allocator now returns an arena to + the system ``free()`` when all memory within an arena becomes unused + again. Prior to Python 2.5, arenas (256KB chunks of memory) were never + freed. Some applications will see a drop in virtual memory size now, + especially long-running applications that, from time to time, temporarily + use a large number of small objects. Note that when Python returns an + arena to the platform C's ``free()``, there's no guarantee that the + platform C library will in turn return that memory to the operating system. + The effect of the patch is to stop making that impossible, and in tests it + appears to be effective at least on Microsoft C and gcc-based systems. + Thanks to Evan Jones for hard work and patience. + +- Patch #1434038: property() now uses the getter's docstring if there is + no "doc" argument given. This makes it possible to legitimately use + property() as a decorator to produce a read-only property. + +- PEP 357, patch 1436368: add an __index__ method to int/long and a matching + nb_index slot to the PyNumberMethods struct. The slot is consulted instead + of requiring an int or long in slicing and a few other contexts, enabling + other objects (e.g. Numeric Python's integers) to be used as slice indices. + +- Fixed various bugs reported by Coverity's Prevent tool. + +- PEP 352, patch #1104669: Make exceptions new-style objects. Introduced the + new exception base class, BaseException, which has a new message attribute. + KeyboardInterrupt and SystemExit to directly inherit from BaseException now. + Raising a string exception now raises a DeprecationWarning. + +- Patch #1438387, PEP 328: relative and absolute imports. Imports can now be + explicitly relative, using 'from .module import name' to mean 'from the same + package as this module is in. Imports without dots still default to the + old relative-then-absolute, unless 'from __future__ import + absolute_import' is used. + +- Properly check if 'warnings' raises an exception (usually when a filter set + to "error" is triggered) when raising a warning for raising string + exceptions. + +- CO_GENERATOR_ALLOWED is no longer defined. This behavior is the default. + The name was removed from Include/code.h. + +- PEP 308: conditional expressions were added: (x if cond else y). + +- Patch 1433928: + - The copy module now "copies" function objects (as atomic objects). + - dict.__getitem__ now looks for a __missing__ hook before raising + KeyError. + +- PEP 343: with statement implemented. Needs ``from __future__ import + with_statement``. Use of 'with' as a variable will generate a warning. + Use of 'as' as a variable will also generate a warning (unless it's + part of an import statement). + The following objects have __context__ methods: + - The built-in file type. + - The thread.LockType type. + - The following types defined by the threading module: + Lock, RLock, Condition, Semaphore, BoundedSemaphore. + - The decimal.Context class. + +- Fix the encodings package codec search function to only search + inside its own package. Fixes problem reported in patch #1433198. + + Note: Codec packages should implement and register their own + codec search function. PEP 100 has the details. + +- PEP 353: Using ``Py_ssize_t`` as the index type. + +- ``PYMALLOC_DEBUG`` builds now add ``4*sizeof(size_t)`` bytes of debugging + info to each allocated block, since the ``Py_ssize_t`` changes (PEP 353) + now allow Python to make use of memory blocks exceeding 2**32 bytes for + some purposes on 64-bit boxes. A ``PYMALLOC_DEBUG`` build was limited + to 4-byte allocations before. + +- Patch #1400181, fix unicode string formatting to not use the locale. + This is how string objects work. u'%f' could use , instead of . + for the decimal point. Now both strings and unicode always use periods. + +- Bug #1244610, #1392915, fix build problem on OpenBSD 3.7 and 3.8. + configure would break checking curses.h. + +- Bug #959576: The pwd module is now builtin. This allows Python to be + built on UNIX platforms without $HOME set. + +- Bug #1072182, fix some potential problems if characters are signed. + +- Bug #889500, fix line number on SyntaxWarning for global declarations. + +- Bug #1378022, UTF-8 files with a leading BOM crashed the interpreter. + +- Support for converting hex strings to floats no longer works. + This was not portable. float('0x3') now raises a ValueError. + +- Patch #1382163: Expose Subversion revision number to Python. New C API + function Py_GetBuildNumber(). New attribute sys.subversion. Build number + is now displayed in interactive prompt banner. + +- Implementation of PEP 341 - Unification of try/except and try/finally. + "except" clauses can now be written together with a "finally" clause in + one try statement instead of two nested ones. Patch #1355913. + +- Bug #1379994: Builtin unicode_escape and raw_unicode_escape codec + now encodes backslash correctly. + +- Patch #1350409: Work around signal handling bug in Visual Studio 2005. + +- Bug #1281408: Py_BuildValue now works correctly even with unsigned longs + and long longs. + +- SF Bug #1350188, "setdlopenflags" leads to crash upon "import" + It was possible for dlerror() to return a NULL pointer, so + it will now use a default error message in this case. + +- Replaced most Unicode charmap codecs with new ones using the + new Unicode translate string feature in the builtin charmap + codec; the codecs were created from the mapping tables available + at ftp.unicode.org and contain a few updates (e.g. the Mac OS + encodings now include a mapping for the Apple logo) + +- Added a few more codecs for Mac OS encodings + +- Sped up some Unicode operations. + +- A new AST parser implementation was completed. The abstract + syntax tree is available for read-only (non-compile) access + to Python code; an _ast module was added. + +- SF bug #1167751: fix incorrect code being produced for generator expressions. + The following code now raises a SyntaxError: foo(a = i for i in range(10)) + +- SF Bug #976608: fix SystemError when mtime of an imported file is -1. + +- SF Bug #887946: fix segfault when redirecting stdin from a directory. + Provide a warning when a directory is passed on the command line. + +- Fix segfault with invalid coding. + +- SF bug #772896: unknown encoding results in MemoryError. + +- All iterators now have a Boolean value of True. Formerly, some iterators + supported a __len__() method which evaluated to False when the iterator + was empty. + +- On 64-bit platforms, when __len__() returns a value that cannot be + represented as a C int, raise OverflowError. + +- test__locale is skipped on OS X < 10.4 (only partial locale support is + present). + +- SF bug #893549: parsing keyword arguments was broken with a few format + codes. + +- Changes donated by Elemental Security to make it work on AIX 5.3 + with IBM's 64-bit compiler (SF patch #1284289). This also closes SF + bug #105470: test_pwd fails on 64bit system (Opteron). + +- Changes donated by Elemental Security to make it work on HP-UX 11 on + Itanium2 with HP's 64-bit compiler (SF patch #1225212). + +- Disallow keyword arguments for type constructors that don't use them + (fixes bug #1119418). + +- Forward UnicodeDecodeError into SyntaxError for source encoding errors. + +- SF bug #900092: When tracing (e.g. for hotshot), restore 'return' events for + exceptions that cause a function to exit. + +- The implementation of set() and frozenset() was revised to use its + own internal data structure. Memory consumption is reduced by 1/3 + and there are modest speed-ups as well. The API is unchanged. + +- SF bug #1238681: freed pointer is used in longobject.c:long_pow(). + +- SF bug #1229429: PyObject_CallMethod failed to decrement some + reference counts in some error exit cases. + +- SF bug #1185883: Python's small-object memory allocator took over + a block managed by the platform C library whenever a realloc specified + a small new size. However, there's no portable way to know then how + much of the address space following the pointer is valid, so there's no + portable way to copy data from the C-managed block into Python's + small-object space without risking a memory fault. Python's small-object + realloc now leaves such blocks under the control of the platform C + realloc. + +- SF bug #1232517: An overflow error was not detected properly when + attempting to convert a large float to an int in os.utime(). + +- SF bug #1224347: hex longs now print with lowercase letters just + like their int counterparts. + +- SF bug #1163563: the original fix for bug #1010677 ("thread Module + Breaks PyGILState_Ensure()") broke badly in the case of multiple + interpreter states; back out that fix and do a better job (see + http://mail.python.org/pipermail/python-dev/2005-June/054258.html + for a longer write-up of the problem). + +- SF patch #1180995: marshal now uses a binary format by default when + serializing floats. + +- SF patch #1181301: on platforms that appear to use IEEE 754 floats, + the routines that promise to produce IEEE 754 binary representations + of floats now simply copy bytes around. + +- bug #967182: disallow opening files with 'wU' or 'aU' as specified by PEP + 278. + +- patch #1109424: int, long, float, complex, and unicode now check for the + proper magic slot for type conversions when subclassed. Previously the + magic slot was ignored during conversion. Semantics now match the way + subclasses of str always behaved. int/long/float, conversion of an instance + to the base class has been moved to the proper nb_* magic slot and out of + PyNumber_*(). + Thanks Walter D???rwald. + +- Descriptors defined in C with a PyGetSetDef structure, where the setter is + NULL, now raise an AttributeError when attempting to set or delete the + attribute. Previously a TypeError was raised, but this was inconsistent + with the equivalent pure-Python implementation. + +- It is now safe to call PyGILState_Release() before + PyEval_InitThreads() (note that if there is reason to believe there + are multiple threads around you still must call PyEval_InitThreads() + before using the Python API; this fix is for extension modules that + have no way of knowing if Python is multi-threaded yet). + +- Typing Ctrl-C whilst raw_input() was waiting in a build with threads + disabled caused a crash. + +- Bug #1165306: instancemethod_new allowed the creation of a method + with im_class == im_self == NULL, which caused a crash when called. + +- Move exception finalisation later in the shutdown process - this + fixes the crash seen in bug #1165761 + +- Added two new builtins, any() and all(). + +- Defining a class with empty parentheses is now allowed + (e.g., ``class C(): pass`` is no longer a syntax error). + Patch #1176012 added support to the 'parser' module and 'compiler' package + (thanks to logistix for that added support). + +- Patch #1115086: Support PY_LONGLONG in structmember. + +- Bug #1155938: new style classes did not check that __init__() was + returning None. + +- Patch #802188: Report characters after line continuation character + ('\') with a specific error message. + +- Bug #723201: Raise a TypeError for passing bad objects to 'L' format. + +- Bug #1124295: the __name__ attribute of file objects was + inadvertently made inaccessible in restricted mode. + +- Bug #1074011: closing sys.std{out,err} now causes a flush() and + an ferror() call. + +- min() and max() now support key= arguments with the same meaning as in + list.sort(). + +- The peephole optimizer now performs simple constant folding in expressions: + (2+3) --> (5). + +- set and frozenset objects can now be marshalled. SF #1098985. + +- Bug #1077106: Poor argument checking could cause memory corruption + in calls to os.read(). + +- The parser did not complain about future statements in illegal + positions. It once again reports a syntax error if a future + statement occurs after anything other than a doc string. + +- Change the %s format specifier for str objects so that it returns a + unicode instance if the argument is not an instance of basestring and + calling __str__ on the argument returns a unicode instance. + +- Patch #1413181: changed ``PyThreadState_Delete()`` to forget about the + current thread state when the auto-GIL-state machinery knows about + it (since the thread state is being deleted, continuing to remember it + can't help, but can hurt if another thread happens to get created with + the same thread id). + +Extension Modules +----------------- + +- Patch #1380952: fix SSL objects timing out on consecutive read()s + +- Patch #1309579: wait3 and wait4 were added to the posix module. + +- Patch #1231053: The audioop module now supports encoding/decoding of alaw. + In addition, the existing ulaw code was updated. + +- RFE #567972: Socket objects' family, type and proto properties are + now exposed via new attributes. + +- Everything under lib-old was removed. This includes the following modules: + Para, addpack, cmp, cmpcache, codehack, dircmp, dump, find, fmt, grep, + lockfile, newdir, ni, packmail, poly, rand, statcache, tb, tzparse, + util, whatsound, whrandom, zmod + +- The following modules were removed: regsub, reconvert, regex, regex_syntax. + +- re and sre were swapped, so help(re) provides full help. importing sre + is deprecated. The undocumented re.engine variable no longer exists. + +- Bug #1448490: Fixed a bug that ISO-2022 codecs could not handle + SS2 (single-shift 2) escape sequences correctly. + +- The unicodedata module was updated to the 4.1 version of the Unicode + database. The 3.2 version is still available as unicodedata.db_3_2_0 + for applications that require this specific version (such as IDNA). + +- The timing module is no longer built by default. It was deprecated + in PEP 4 in Python 2.0 or earlier. + +- Patch 1433928: Added a new type, defaultdict, to the collections module. + This uses the new __missing__ hook behavior added to dict (see above). + +- Bug #854823: socketmodule now builds on Sun platforms even when + INET_ADDRSTRLEN is not defined. + +- Patch #1393157: os.startfile() now has an optional argument to specify + a "command verb" to invoke on the file. + +- Bug #876637, prevent stack corruption when socket descriptor + is larger than FD_SETSIZE. + +- Patch #1407135, bug #1424041: harmonize mmap behavior of anonymous memory. + mmap.mmap(-1, size) now returns anonymous memory in both Unix and Windows. + mmap.mmap(0, size) should not be used on Windows for anonymous memory. + +- Patch #1422385: The nis module now supports access to domains other + than the system default domain. + +- Use Win32 API to implement os.stat/fstat. As a result, subsecond timestamps + are reported, the limit on path name lengths is removed, and stat reports + WindowsError now (instead of OSError). + +- Add bsddb.db.DBEnv.set_tx_timestamp allowing time based database recovery. + +- Bug #1413192, fix seg fault in bsddb if a transaction was deleted + before the env. + +- Patch #1103116: Basic AF_NETLINK support. + +- Bug #1402308, (possible) segfault when using mmap.mmap(-1, ...) + +- Bug #1400822, _curses over{lay,write} doesn't work when passing 6 ints. + Also fix ungetmouse() which did not accept arguments properly. + The code now conforms to the documented signature. + +- Bug #1400115, Fix segfault when calling curses.panel.userptr() + without prior setting of the userptr. + +- Fix 64-bit problems in bsddb. + +- Patch #1365916: fix some unsafe 64-bit mmap methods. + +- Bug #1290333: Added a workaround for cjkcodecs' _codecs_cn build + problem on AIX. + +- Bug #869197: os.setgroups rejects long integer arguments + +- Bug #1346533, select.poll() doesn't raise an error if timeout > sys.maxint + +- Bug #1344508, Fix UNIX mmap leaking file descriptors + +- Patch #1338314, Bug #1336623: fix tarfile so it can extract + REGTYPE directories from tarfiles written by old programs. + +- Patch #1407992, fixes broken bsddb module db associate when using + BerkeleyDB 3.3, 4.0 or 4.1. + +- Get bsddb module to build with BerkeleyDB version 4.4 + +- Get bsddb module to build with BerkeleyDB version 3.2 + +- Patch #1309009, Fix segfault in pyexpat when the XML document is in latin_1, + but Python incorrectly assumes it is in UTF-8 format + +- Fix parse errors in the readline module when compiling without threads. + +- Patch #1288833: Removed thread lock from socket.getaddrinfo on + FreeBSD 5.3 and later versions which got thread-safe getaddrinfo(3). + +- Patches #1298449 and #1298499: Add some missing checks for error + returns in cStringIO.c. + +- Patch #1297028: fix segfault if call type on MultibyteCodec, + MultibyteStreamReader, or MultibyteStreamWriter + +- Fix memory leak in posix.access(). + +- Patch #1213831: Fix typo in unicodedata._getcode. + +- Bug #1007046: os.startfile() did not accept unicode strings encoded in + the file system encoding. + +- Patch #756021: Special-case socket.inet_aton('255.255.255.255') for + platforms that don't have inet_aton(). + +- Bug #1215928: Fix bz2.BZ2File.seek() for 64-bit file offsets. + +- Bug #1191043: Fix bz2.BZ2File.(x)readlines for files containing one + line without newlines. + +- Bug #728515: mmap.resize() now resizes the file on Unix as it did + on Windows. + +- Patch #1180695: Add nanosecond stat resolution, and st_gen, + st_birthtime for FreeBSD. + +- Patch #1231069: The fcntl.ioctl function now uses the 'I' code for + the request code argument, which results in more C-like behaviour + for large or negative values. + +- Bug #1234979: For the argument of thread.Lock.acquire, the Windows + implementation treated all integer values except 1 as false. + +- Bug #1194181: bz2.BZ2File didn't handle mode 'U' correctly. + +- Patch #1212117: os.stat().st_flags is now accessible as a attribute + if available on the platform. + +- Patch #1103951: Expose O_SHLOCK and O_EXLOCK in the posix module if + available on the platform. + +- Bug #1166660: The readline module could segfault if hook functions + were set in a different thread than that which called readline. + +- collections.deque objects now support a remove() method. + +- operator.itemgetter() and operator.attrgetter() now support retrieving + multiple fields. This provides direct support for sorting on multiple + keys (primary, secondary, etc). + +- os.access now supports Unicode path names on non-Win32 systems. + +- Patches #925152, #1118602: Avoid reading after the end of the buffer + in pyexpat.GetInputContext. + +- Patches #749830, #1144555: allow UNIX mmap size to default to current + file size. + +- Added functional.partial(). See PEP309. + +- Patch #1093585: raise a ValueError for negative history items in readline. + {remove_history,replace_history} + +- The spwd module has been added, allowing access to the shadow password + database. + +- stat_float_times is now True. + +- array.array objects are now picklable. + +- the cPickle module no longer accepts the deprecated None option in the + args tuple returned by __reduce__(). + +- itertools.islice() now accepts None for the start and step arguments. + This allows islice() to work more readily with slices: + islice(s.start, s.stop, s.step) + +- datetime.datetime() now has a strptime class method which can be used to + create datetime object using a string and format. + +- Patch #1117961: Replace the MD5 implementation from RSA Data Security Inc + with the implementation from http://sourceforge.net/projects/libmd5-rfc/. + +Library +------- + +- Patch #1388073: Numerous __-prefixed attributes of unittest.TestCase have + been renamed to have only a single underscore prefix. This was done to + make subclassing easier. + +- PEP 338: new module runpy defines a run_module function to support + executing modules which provide access to source code or a code object + via the PEP 302 import mechanisms. + +- The email module's parsedate_tz function now sets the daylight savings + flag to -1 (unknown) since it can't tell from the date whether it should + be set. + +- Patch #624325: urlparse.urlparse() and urlparse.urlsplit() results + now sport attributes that provide access to the parts of the result. + +- Patch #1462498: sgmllib now handles entity and character references + in attribute values. + +- Added the sqlite3 package. This is based on pysqlite2.1.3, and provides + a DB-API interface in the standard library. You'll need sqlite 3.0.8 or + later to build this - if you have an earlier version, the C extension + module will not be built. + +- Bug #1460340: ``random.sample(dict)`` failed in various ways. Dicts + aren't officially supported here, and trying to use them will probably + raise an exception some day. But dicts have been allowed, and "mostly + worked", so support for them won't go away without warning. + +- Bug #1445068: getpass.getpass() can now be given an explicit stream + argument to specify where to write the prompt. + +- Patch #1462313, bug #1443328: the pickle modules now can handle classes + that have __private names in their __slots__. + +- Bug #1250170: mimetools now handles socket.gethostname() failures gracefully. + +- patch #1457316: "setup.py upload" now supports --identity to select the + key to be used for signing the uploaded code. + +- Queue.Queue objects now support .task_done() and .join() methods + to make it easier to monitor when daemon threads have completed + processing all enqueued tasks. Patch #1455676. + +- popen2.Popen objects now preserve the command in a .cmd attribute. + +- Added the ctypes ffi package. + +- email 4.0 package now integrated. This is largely the same as the email 3.0 + package that was included in Python 2.3, except that PEP 8 module names are + now used (e.g. mail.message instead of email.Message). The MIME classes + have been moved to a subpackage (e.g. email.mime.text instead of + email.MIMEText). The old names are still supported for now. Several + deprecated Message methods have been removed and lots of bugs have been + fixed. More details can be found in the email package documentation. + +- Patches #1436130/#1443155: codecs.lookup() now returns a CodecInfo object + (a subclass of tuple) that provides incremental decoders and encoders + (a way to use stateful codecs without the stream API). Python functions + codecs.getincrementaldecoder() and codecs.getincrementalencoder() as well + as C functions PyCodec_IncrementalEncoder() and PyCodec_IncrementalDecoder() + have been added. + +- Patch #1359365: Calling next() on a closed StringIO.String object raises + a ValueError instead of a StopIteration now (like file and cString.String do). + cStringIO.StringIO.isatty() will raise a ValueError now if close() has been + called before (like file and StringIO.StringIO do). + +- A regrtest option -w was added to re-run failed tests in verbose mode. + +- Patch #1446372: quit and exit can now be called from the interactive + interpreter to exit. + +- The function get_count() has been added to the gc module, and gc.collect() + grew an optional 'generation' argument. + +- A library msilib to generate Windows Installer files, and a distutils + command bdist_msi have been added. + +- PEP 343: new module contextlib.py defines decorator @contextmanager + and helpful context managers nested() and closing(). + +- The compiler package now supports future imports after the module docstring. + +- Bug #1413790: zipfile now sanitizes absolute archive names that are + not allowed by the specs. + +- Patch #1215184: FileInput now can be given an opening hook which can + be used to control how files are opened. + +- Patch #1212287: fileinput.input() now has a mode parameter for + specifying the file mode input files should be opened with. + +- Patch #1215184: fileinput now has a fileno() function for getting the + current file number. + +- Patch #1349274: gettext.install() now optionally installs additional + translation functions other than _() in the builtin namespace. + +- Patch #1337756: fileinput now accepts Unicode filenames. + +- Patch #1373643: The chunk module can now read chunks larger than + two gigabytes. + +- Patch #1417555: SimpleHTTPServer now returns Last-Modified headers. + +- Bug #1430298: It is now possible to send a mail with an empty + return address using smtplib. + +- Bug #1432260: The names of lambda functions are now properly displayed + in pydoc. + +- Patch #1412872: zipfile now sets the creator system to 3 (Unix) + unless the system is Win32. + +- Patch #1349118: urllib now supports user:pass@ style proxy + specifications, raises IOErrors when proxies for unsupported protocols + are defined, and uses the https proxy on https redirections. + +- Bug #902075: urllib2 now supports 'host:port' style proxy specifications. + +- Bug #1407902: Add support for sftp:// URIs to urlparse. + +- Bug #1371247: Update Windows locale identifiers in locale.py. + +- Bug #1394565: SimpleHTTPServer now doesn't choke on query parameters + any more. + +- Bug #1403410: The warnings module now doesn't get confused + when it can't find out the module name it generates a warning for. + +- Patch #1177307: Added a new codec utf_8_sig for UTF-8 with a BOM signature. + +- Patch #1157027: cookielib mishandles RFC 2109 cookies in Netscape mode + +- Patch #1117398: cookielib.LWPCookieJar and .MozillaCookieJar now raise + LoadError as documented, instead of IOError. For compatibility, + LoadError subclasses IOError. + +- Added the hashlib module. It provides secure hash functions for MD5 and + SHA1, 224, 256, 384, and 512. Note that recent developments make the + historic MD5 and SHA1 unsuitable for cryptographic-strength applications. + In + Ronald L. Rivest offered this advice for Python: + + "The consensus of researchers in this area (at least as + expressed at the NIST Hash Function Workshop 10/31/05), + is that SHA-256 is a good choice for the time being, but + that research should continue, and other alternatives may + arise from this research. The larger SHA's also seem OK." + +- Added a subset of Fredrik Lundh's ElementTree package. Available + modules are xml.etree.ElementTree, xml.etree.ElementPath, and + xml.etree.ElementInclude, from ElementTree 1.2.6. + +- Patch #1162825: Support non-ASCII characters in IDLE window titles. + +- Bug #1365984: urllib now opens "data:" URLs again. + +- Patch #1314396: prevent deadlock for threading.Thread.join() when an exception + is raised within the method itself on a previous call (e.g., passing in an + illegal argument) + +- Bug #1340337: change time.strptime() to always return ValueError when there + is an error in the format string. + +- Patch #754022: Greatly enhanced webbrowser.py (by Oleg Broytmann). + +- Bug #729103: pydoc.py: Fix docother() method to accept additional + "parent" argument. + +- Patch #1300515: xdrlib.py: Fix pack_fstring() to really use null bytes + for padding. + +- Bug #1296004: httplib.py: Limit maximal amount of data read from the + socket to avoid a MemoryError on Windows. + +- Patch #1166948: locale.py: Prefer LC_ALL, LC_CTYPE and LANG over LANGUAGE + to get the correct encoding. + +- Patch #1166938: locale.py: Parse LANGUAGE as a colon separated list of + languages. + +- Patch #1268314: Cache lines in StreamReader.readlines for performance. + +- Bug #1290505: Fix clearing the regex cache for time.strptime(). + +- Bug #1167128: Fix size of a symlink in a tarfile to be 0. + +- Patch #810023: Fix off-by-one bug in urllib.urlretrieve reporthook + functionality. + +- Bug #1163178: Make IDNA return an empty string when the input is empty. + +- Patch #848017: Make Cookie more RFC-compliant. Use CRLF as default output + separator and do not output trailing semicolon. + +- Patch #1062060: urllib.urlretrieve() now raises a new exception, named + ContentTooShortException, when the actually downloaded size does not + match the Content-Length header. + +- Bug #1121494: distutils.dir_utils.mkpath now accepts Unicode strings. + +- Bug #1178484: Return complete lines from codec stream readers + even if there is an exception in later lines, resulting in + correct line numbers for decoding errors in source code. + +- Bug #1192315: Disallow negative arguments to clear() in pdb. + +- Patch #827386: Support absolute source paths in msvccompiler.py. + +- Patch #1105730: Apply the new implementation of commonprefix in posixpath + to ntpath, macpath, os2emxpath and riscospath. + +- Fix a problem in Tkinter introduced by SF patch #869468: delete bogus + __hasattr__ and __delattr__ methods on class Tk that were breaking + Tkdnd. + +- Bug #1015140: disambiguated the term "article id" in nntplib docs and + docstrings to either "article number" or "message id". + +- Bug #1238170: threading.Thread.__init__ no longer has "kwargs={}" as a + parameter, but uses the usual "kwargs=None". + +- textwrap now processes text chunks at O(n) speed instead of O(n**2). + Patch #1209527 (Contributed by Connelly). + +- urllib2 has now an attribute 'httpresponses' mapping from HTTP status code + to W3C name (404 -> 'Not Found'). RFE #1216944. + +- Bug #1177468: Don't cache the /dev/urandom file descriptor for os.urandom, + as this can cause problems with apps closing all file descriptors. + +- Bug #839151: Fix an attempt to access sys.argv in the warnings module; + it can be missing in embedded interpreters + +- Bug #1155638: Fix a bug which affected HTTP 0.9 responses in httplib. + +- Bug #1100201: Cross-site scripting was possible on BaseHTTPServer via + error messages. + +- Bug #1108948: Cookie.py produced invalid JavaScript code. + +- The tokenize module now detects and reports indentation errors. + Bug #1224621. + +- The tokenize module has a new untokenize() function to support a full + roundtrip from lexed tokens back to Python source code. In addition, + the generate_tokens() function now accepts a callable argument that + terminates by raising StopIteration. + +- Bug #1196315: fix weakref.WeakValueDictionary constructor. + +- Bug #1213894: os.path.realpath didn't resolve symlinks that were the first + component of the path. + +- Patch #1120353: The xmlrpclib module provides better, more transparent, + support for datetime.{datetime,date,time} objects. With use_datetime set + to True, applications shouldn't have to fiddle with the DateTime wrapper + class at all. + +- distutils.commands.upload was added to support uploading distribution + files to PyPI. + +- distutils.commands.register now encodes the data as UTF-8 before posting + them to PyPI. + +- decimal operator and comparison methods now return NotImplemented + instead of raising a TypeError when interacting with other types. This + allows other classes to implement __radd__ style methods and have them + work as expected. + +- Bug #1163325: Decimal infinities failed to hash. Attempting to + hash a NaN raised an InvalidOperation instead of a TypeError. + +- Patch #918101: Add tarfile open mode r|* for auto-detection of the + stream compression; add, for symmetry reasons, r:* as a synonym of r. + +- Patch #1043890: Add extractall method to tarfile. + +- Patch #1075887: Don't require MSVC in distutils if there is nothing + to build. + +- Patch #1103407: Properly deal with tarfile iterators when untarring + symbolic links on Windows. + +- Patch #645894: Use getrusage for computing the time consumption in + profile.py if available. + +- Patch #1046831: Use get_python_version where appropriate in sysconfig.py. + +- Patch #1117454: Remove code to special-case cookies without values + in LWPCookieJar. + +- Patch #1117339: Add cookielib special name tests. + +- Patch #1112812: Make bsddb/__init__.py more friendly for modulefinder. + +- Patch #1110248: SYNC_FLUSH the zlib buffer for GZipFile.flush. + +- Patch #1107973: Allow to iterate over the lines of a tarfile.ExFileObject. + +- Patch #1104111: Alter setup.py --help and --help-commands. + +- Patch #1121234: Properly cleanup _exit and tkerror commands. + +- Patch #1049151: xdrlib now unpacks booleans as True or False. + +- Fixed bug in a NameError bug in cookielib. Patch #1116583. + +- Applied a security fix to SimpleXMLRPCserver (PSF-2005-001). This + disables recursive traversal through instance attributes, which can + be exploited in various ways. + +- Bug #1222790: in SimpleXMLRPCServer, set the reuse-address and close-on-exec + flags on the HTTP listening socket. + +- Bug #792570: SimpleXMLRPCServer had problems if the request grew too large. + Fixed by reading the HTTP body in chunks instead of one big socket.read(). + +- Patches #893642, #1039083: add allow_none, encoding arguments to + constructors of SimpleXMLRPCServer and CGIXMLRPCRequestHandler. + +- Bug #1110478: Revert os.environ.update to do putenv again. + +- Bug #1103844: fix distutils.install.dump_dirs() with negated options. + +- os.{SEEK_SET, SEEK_CUR, SEEK_END} have been added for convenience. + +- Enhancements to the csv module: + + + Dialects are now validated by the underlying C code, better + reflecting its capabilities, and improving its compliance with + PEP 305. + + Dialect parameter parsing has been re-implemented to improve error + reporting. + + quotechar=None and quoting=QUOTE_NONE now work the way PEP 305 + dictates. + + the parser now removes the escapechar prefix from escaped characters. + + when quoting=QUOTE_NONNUMERIC, the writer now tests for numeric + types, rather than any object that can be represented as a numeric. + + when quoting=QUOTE_NONNUMERIC, the reader now casts unquoted fields + to floats. + + reader now allows \r characters to be quoted (previously it only allowed + \n to be quoted). + + writer doublequote handling improved. + + Dialect classes passed to the module are no longer instantiated by + the module before being parsed (the former validation scheme required + this, but the mechanism was unreliable). + + The dialect registry now contains instances of the internal + C-coded dialect type, rather than references to python objects. + + the internal c-coded dialect type is now immutable. + + register_dialect now accepts the same keyword dialect specifications + as the reader and writer, allowing the user to register dialects + without first creating a dialect class. + + a configurable limit to the size of parsed fields has been added - + previously, an unmatched quote character could result in the entire + file being read into the field buffer before an error was reported. + + A new module method csv.field_size_limit() has been added that sets + the parser field size limit (returning the former limit). The initial + limit is 128kB. + + A line_num attribute has been added to the reader object, which tracks + the number of lines read from the source iterator. This is not + the same as the number of records returned, as records can span + multiple lines. + + reader and writer objects were not being registered with the cyclic-GC. + This has been fixed. + +- _DummyThread objects in the threading module now delete self.__block that is + inherited from _Thread since it uses up a lock allocated by 'thread'. The + lock primitives tend to be limited in number and thus should not be wasted on + a _DummyThread object. Fixes bug #1089632. + +- The imghdr module now detects Exif files. + +- StringIO.truncate() now correctly adjusts the size attribute. + (Bug #951915). + +- locale.py now uses an updated locale alias table (built using + Tools/i18n/makelocalealias.py, a tool to parse the X11 locale + alias file); the encoding lookup was enhanced to use Python's + encoding alias table. + +- moved deprecated modules to Lib/lib-old: whrandom, tzparse, statcache. + +- the pickle module no longer accepts the deprecated None option in the + args tuple returned by __reduce__(). + +- optparse now optionally imports gettext. This allows its use in setup.py. + +- the pickle module no longer uses the deprecated bin parameter. + +- the shelve module no longer uses the deprecated binary parameter. + +- the pstats module no longer uses the deprecated ignore() method. + +- the filecmp module no longer uses the deprecated use_statcache argument. + +- unittest.TestCase.run() and unittest.TestSuite.run() can now be successfully + extended or overridden by subclasses. Formerly, the subclassed method would + be ignored by the rest of the module. (Bug #1078905). + +- heapq.nsmallest() and heapq.nlargest() now support key= arguments with + the same meaning as in list.sort(). + +- Bug #1076985: ``codecs.StreamReader.readline()`` now calls ``read()`` only + once when a size argument is given. This prevents a buffer overflow in the + tokenizer with very long source lines. + +- Bug #1083110: ``zlib.decompress.flush()`` would segfault if called + immediately after creating the object, without any intervening + ``.decompress()`` calls. + +- The reconvert.quote function can now emit triple-quoted strings. The + reconvert module now has some simple documentation. + +- ``UserString.MutableString`` now supports negative indices in + ``__setitem__`` and ``__delitem__`` + +- Bug #1149508: ``textwrap`` now handles hyphenated numbers (eg. "2004-03-05") + correctly. + +- Partial fixes for SF bugs #1163244 and #1175396: If a chunk read by + ``codecs.StreamReader.readline()`` has a trailing "\r", read one more + character even if the user has passed a size parameter to get a proper + line ending. Remove the special handling of a "\r\n" that has been split + between two lines. + +- Bug #1251300: On UCS-4 builds the "unicode-internal" codec will now complain + about illegal code points. The codec now supports PEP 293 style error + handlers. + +- Bug #1235646: ``codecs.StreamRecoder.next()`` now reencodes the data it reads + from the input stream, so that the output is a byte string in the correct + encoding instead of a unicode string. + +- Bug #1202493: Fixing SRE parser to handle '{}' as perl does, rather than + considering it exactly like a '*'. + +- Bug #1245379: Add "unicode-1-1-utf-7" as an alias for "utf-7" to + ``encodings.aliases``. + +- ` uu.encode()`` and ``uu.decode()`` now support unicode filenames. + +- Patch #1413711: Certain patterns of differences were making difflib + touch the recursion limit. + +- Bug #947906: An object oriented interface has been added to the calendar + module. It's possible to generate HTML calendar now and the module can be + called as a script (e.g. via ``python -mcalendar``). Localized month and + weekday names can be ouput (even if an exotic encoding is used) using + special classes that use unicode. + +Build +----- + +- Fix test_float, test_long, and test_struct failures on Tru64 with gcc + by using -mieee gcc option. + +- Patch #1432345: Make python compile on DragonFly. + +- Build support for Win64-AMD64 was added. + +- Patch #1428494: Prefer linking against ncursesw over ncurses library. + +- Patch #881820: look for openpty and forkpty also in libbsd. + +- The sources of zlib are now part of the Python distribution (zlib 1.2.3). + The zlib module is now builtin on Windows. + +- Use -xcode=pic32 for CCSHARED on Solaris with SunPro. + +- Bug #1189330: configure did not correctly determine the necessary + value of LINKCC if python was built with GCC 4.0. + +- Upgrade Windows build to zlib 1.2.3 which eliminates a potential security + vulnerability in zlib 1.2.1 and 1.2.2. + +- EXTRA_CFLAGS has been introduced as an environment variable to hold compiler + flags that change binary compatibility. Changes were also made to + distutils.sysconfig to also use the environment variable when used during + compilation of the interpreter and of C extensions through distutils. + +- SF patch 1171735: Darwin 8's headers are anal about POSIX compliance, + and linking has changed (prebinding is now deprecated, and libcc_dynamic + no longer exists). This configure patch makes things right. + +- Bug #1158607: Build with --disable-unicode again. + +- spwdmodule.c is built only if either HAVE_GETSPNAM or HAVE_HAVE_GETSPENT is + defined. Discovered as a result of not being able to build on OS X. + +- setup.py now uses the directories specified in LDFLAGS using the -L option + and in CPPFLAGS using the -I option for adding library and include + directories, respectively, for compiling extension modules against. This has + led to the core being compiled using the values in CPPFLAGS. It also removes + the need for the special-casing of both DarwinPorts and Fink for darwin since + the proper directories can be specified in LDFLAGS (``-L/sw/lib`` for Fink, + ``-L/opt/local/lib`` for DarwinPorts) and CPPFLAGS (``-I/sw/include`` for + Fink, ``-I/opt/local/include`` for DarwinPorts). + +- Test in configure.in that checks for tzset no longer dependent on tm->tm_zone + to exist in the struct (not required by either ISO C nor the UNIX 2 spec). + Tests for sanity in tzname when HAVE_TZNAME defined were also defined. + Closes bug #1096244. Thanks Gregory Bond. + +C API +----- + +- ``PyMem_{Del, DEL}`` and ``PyMem_{Free, FREE}`` no longer map to + ``PyObject_{Free, FREE}``. They map to the system ``free()`` now. If memory + is obtained via the ``PyObject_`` family, it must be released via the + ``PyObject_`` family, and likewise for the ``PyMem_`` family. This has + always been officially true, but when Python's small-object allocator was + introduced, an attempt was made to cater to a few extension modules + discovered at the time that obtained memory via ``PyObject_New`` but + released it via ``PyMem_DEL``. It's years later, and if such code still + exists it will fail now (probably with segfaults, but calling wrong + low-level memory management functions can yield many symptoms). + +- Added a C API for set and frozenset objects. + +- Removed PyRange_New(). + +- Patch #1313939: PyUnicode_DecodeCharmap() accepts a unicode string as the + mapping argument now. This string is used as a mapping table. Byte values + greater than the length of the string and 0xFFFE are treated as undefined + mappings. + + +Tests +----- + +- In test_os, st_?time is now truncated before comparing it with ST_?TIME. + +- Patch #1276356: New resource "urlfetch" is implemented. This enables + even impatient people to run tests that require remote files. + + +Documentation +------------- + +- Bug #1402224: Add warning to dl docs about crashes. + +- Bug #1396471: Document that Windows' ftell() can return invalid + values for text files with UNIX-style line endings. + +- Bug #1274828: Document os.path.splitunc(). + +- Bug #1190204: Clarify which directories are searched by site.py. + +- Bug #1193849: Clarify os.path.expanduser() documentation. + +- Bug #1243192: re.UNICODE and re.LOCALE affect \d, \D, \s and \S. + +- Bug #755617: Document the effects of os.chown() on Windows. + +- Patch #1180012: The documentation for modulefinder is now in the library reference. + +- Patch #1213031: Document that os.chown() accepts argument values of -1. + +- Bug #1190563: Document os.waitpid() return value with WNOHANG flag. + +- Bug #1175022: Correct the example code for property(). + +- Document the IterableUserDict class in the UserDict module. + Closes bug #1166582. + +- Remove all latent references for "Macintosh" that referred to semantics for + Mac OS 9 and change to reflect the state for OS X. + Closes patch #1095802. Thanks Jack Jansen. + +Mac +--- + + +New platforms +------------- + +- FreeBSD 7 support is added. + + +Tools/Demos +----------- + +- Created Misc/Vim/vim_syntax.py to auto-generate a python.vim file in that + directory for syntax highlighting in Vim. Vim directory was added and placed + vimrc to it (was previous up a level). + +- Added two new files to Tools/scripts: pysource.py, which recursively + finds Python source files, and findnocoding.py, which finds Python + source files that need an encoding declaration. + Patch #784089, credits to Oleg Broytmann. + +- Bug #1072853: pindent.py used an uninitialized variable. + +- Patch #1177597: Correct Complex.__init__. + +- Fixed a display glitch in Pynche, which could cause the right arrow to + wiggle over by a pixel. + + What's New in Python 2.4 final? =============================== Modified: python/branches/py3k-ctypes-pep3118/Misc/NEWS ============================================================================== --- python/branches/py3k-ctypes-pep3118/Misc/NEWS (original) +++ python/branches/py3k-ctypes-pep3118/Misc/NEWS Wed Apr 30 15:57:13 2008 @@ -4,7 +4,7 @@ (editors: check NEWS.help for information about editing NEWS using ReST.) -What's New in Python 3.0a3? +What's New in Python 3.0a5? =========================== *Release date: XX-XXX-2008* @@ -12,7 +12,157 @@ Core and Builtins ----------------- -- map() and itertools.imap() no longer accept None for the first argument. +- Fix misbehaviour of PyLong_FromSsize_t on systems where sizeof(size_t) > + sizeof(long). + +- Issue #2221: Corrected a SystemError "error return without exception set", + when the code executed by exec() raises an exception, and sys.stdout.flush() + also raises an error. + +- Bug #2565: The repr() of type objects now calls them 'class', + not 'type' - whether they are builtin types or not. + +- The command line processing was converted to pass Unicode strings + through as unmodified as possible; as a consequence, the C API + related to command line arguments was changed to use wchar_t. + +- All backslashes in raw strings are interpreted literally. This means that + '\u' and '\U' escapes are not treated specially. + +Extension Modules +----------------- + +Library +------- + +- Issue #2682: ctypes callback functions now longer contain a cyclic + reference to themselves. + +- Issue #2058: Remove the buf attribute and add __slots__ to the TarInfo + class in order to reduce tarfile's memory usage. + +- Bug #2606: Avoid calling .sort() on a dict_keys object. + +- The bundled libffi copy is now in sync with the recently released + libffi3.0.5 version, apart from some small changes to + Modules/_ctypes/libffi/configure.ac. + +Build +----- + +- Issue #1496032: On alpha, use -mieee when gcc is the compiler. + +- "make install" is now an alias for "make altinstall", to prevent + accidentally overwriting a Python 2.x installation. + Use "make fullinstall" to force Python 3.0 to be installed as + "python". + +- Issue #2544: On HP-UX systems, use 'gcc -shared' for linking when + gcc is used as compiler. + +What's New in Python 3.0a4? +=========================== + +*Release date: 02-Apr-2008* + +Core and Builtins +----------------- + +- Bug #2301: Don't try decoding the source code into the original + encoding for syntax errors. + +Extension Modules +----------------- + +- The dl module was removed, use the ctypes module instead. + +- Use wchar_t functions in _locale module. + +Library +------- + +- The class distutils.commands.build_py.build_py_2to3 can be used + as a build_py replacement to automatically run 2to3 on modules + that are going to be installed. + +- A new pickle protocol (protocol 3) is added with explicit support + for bytes. This is the default protocol. It intentionally cannot + be unpickled by Python 2.x. + +- When a pickle written by Python 2.x contains an (8-bit) str + instance, this is now decoded to a (Unicode) str instance. The + encoding used to do this defaults to ASCII, but can be overridden + via two new keyword arguments to the Unpickler class. Previously + this would create bytes instances, which is usually wrong: str + instances are often used to pickle attribute names etc., and text is + more common than binary data anyway. + +- Default to ASCII as the locale.getpreferredencoding, if the POSIX + system doesn't support CODESET and LANG isn't set or doesn't + allow deduction of an encoding. + +- Issue #1202: zlib.crc32 and zlib.adler32 now return an unsigned value. + +- Issue #719888: Updated tokenize to use a bytes API. generate_tokens has been + renamed tokenize and now works with bytes rather than strings. A new + detect_encoding function has been added for determining source file encoding + according to PEP-0263. Token sequences returned by tokenize always start + with an ENCODING token which specifies the encoding used to decode the file. + This token is used to encode the output of untokenize back to bytes. + +What's New in Python 3.0a3? +=========================== + +*Release date: 29-Feb-2008* + +Core and Builtins +----------------- + +- Issue #2282: io.TextIOWrapper was not overriding seekable() from io.IOBase. + +- Issue #2115: Important speedup in setting __slot__ attributes. Also + prevent a possible crash: an Abstract Base Class would try to access a slot + on a registered virtual subclass. + +- Fixed repr() and str() of complex numbers with infinity or nan as real or + imaginary part. + +- Clear all free list during a gc.collect() of the highest generation in order + to allow pymalloc to free more arenas. Python may give back memory to the + OS earlier. + +- Issue #2045: Fix an infinite recursion triggered when printing a subclass of + collections.defaultdict, if its default_factory is set to a bound method. + +- Fixed a minor memory leak in dictobject.c. The content of the free + list was not freed on interpreter shutdown. + +- Limit free list of method and builtin function objects to 256 entries + each. + +- Patch #1953: Added ``sys._compact_freelists()`` and the C API functions + ``PyInt_CompactFreeList`` and ``PyFloat_CompactFreeList`` + to compact the internal free lists of pre-allocted ints and floats. + +- Bug #1983: Fixed return type of fork(), fork1() and forkpty() calls. + Python expected the return type int but the fork familie returns pi_t. + +- Issue #1678380: Fix a bug that identifies 0j and -0j when they appear + in the same code unit. + +- Issue #2025 : Add tuple.count() and tuple.index() methods to comply with + the collections.Sequence API. + +- Fixed multiple reinitialization of the Python interpreter. The small int + list in longobject.c has caused a seg fault during the third finalization. + +- Issue #1973: bytes.fromhex('') raises SystemError + +- Issue #1771: remove cmp parameter from sorted() and list.sort() + +- Issue #1969: split and rsplit in bytearray are inconsistent + +- map() and no longer accepts None for the first argument. Use zip() instead. - Issue #1769: Now int("- 1") is not allowed any more. @@ -42,32 +192,57 @@ gc module; gc.DEBUG_COLLECTABLE or gc.DEBUG_UNCOLLECTABLE are now enough to print the corresponding list of objects considered by the garbage collector. -- Issue #1580: New free format floating point representation based on - "Floating-Point Printer Sample Code", by Robert G. Burger. For example - repr(11./5) now returns '2.2' instead of '2.2000000000000002'. - - Issue #1573: Improper use of the keyword-only syntax makes the parser crash. - Issue #1564: The set implementation should special-case PyUnicode instead of PyString. +- Patch #1031213: Decode source line in SyntaxErrors back to its + original source encoding. + +- inspect.getsource() includes the decorators again. + +- Bug #1713: posixpath.ismount() claims symlink to a mountpoint is a + mountpoint. + +- Fix utf-8-sig incremental decoder, which didn't recognise a BOM when the + first chunk fed to the decoder started with a BOM, but was longer than 3 + bytes. + Extension Modules ----------------- +- Code for itertools ifilter(), imap(), and izip() moved to bultins and + renamed to filter(), map(), and zip(). Also, renamed izip_longest() + to zip_longest() and ifilterfalse() to filterfalse(). + - Issue #1762972: Readded the reload() function as imp.reload() +- Bug #2111: mmap segfaults when trying to write a block opened with PROT_READ + +- #2063: correct order of utime and stime in os.times() result on Windows. + Library ------- +- Weakref dictionaries now inherit from MutableMapping. + XXX their API still needs to be modernized (i.e. eliminate the iter methods). + +- Created new UserDict class in collections module. This one inherits from and + complies with the MutableMapping ABC. Also, moved UserString and UserList + to the collections module. The MutableUserString class was removed. + +- Removed UserDict.DictMixin. Replaced all its uses with + collections.MutableMapping. + - Issue #1703: getpass() should flush after writing prompt. - Issue #1585: IDLE uses non-existent xrange() function. - Issue #1578: Problems in win_getpass. - Build ----- @@ -392,6 +567,9 @@ Tests ----- +- Removed test.testall as test.regrtest replaces it. + + Documentation ------------- Deleted: python/branches/py3k-ctypes-pep3118/Misc/RPM/python-2.6.spec ============================================================================== --- python/branches/py3k-ctypes-pep3118/Misc/RPM/python-2.6.spec Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,385 +0,0 @@ -########################## -# User-modifiable configs -########################## - -# Is the resulting package and the installed binary named "python" or -# "python2"? -#WARNING: Commenting out doesn't work. Last line is what's used. -%define config_binsuffix none -%define config_binsuffix 2.6 - -# Build tkinter? "auto" enables it if /usr/bin/wish exists. -#WARNING: Commenting out doesn't work. Last line is what's used. -%define config_tkinter no -%define config_tkinter yes -%define config_tkinter auto - -# Use pymalloc? The last line (commented or not) determines wether -# pymalloc is used. -#WARNING: Commenting out doesn't work. Last line is what's used. -%define config_pymalloc no -%define config_pymalloc yes - -# Enable IPV6? -#WARNING: Commenting out doesn't work. Last line is what's used. -%define config_ipv6 yes -%define config_ipv6 no - -# Location of the HTML directory. -%define config_htmldir /var/www/html/python - -################################# -# End of user-modifiable configs -################################# - -%define name python -%define version 2.6a1 -%define libvers 2.6 -%define release 1pydotorg -%define __prefix /usr - -# kludge to get around rpm define weirdness -%define ipv6 %(if [ "%{config_ipv6}" = yes ]; then echo --enable-ipv6; else echo --disable-ipv6; fi) -%define pymalloc %(if [ "%{config_pymalloc}" = yes ]; then echo --with-pymalloc; else echo --without-pymalloc; fi) -%define binsuffix %(if [ "%{config_binsuffix}" = none ]; then echo ; else echo "%{config_binsuffix}"; fi) -%define include_tkinter %(if [ \\( "%{config_tkinter}" = auto -a -f /usr/bin/wish \\) -o "%{config_tkinter}" = yes ]; then echo 1; else echo 0; fi) -%define libdirname %(( uname -m | egrep -q '_64$' && [ -d /usr/lib64 ] && echo lib64 ) || echo lib) - -# detect if documentation is available -%define include_docs %(if [ -f "%{_sourcedir}/html-%{version}.tar.bz2" ]; then echo 1; else echo 0; fi) - -Summary: An interpreted, interactive, object-oriented programming language. -Name: %{name}%{binsuffix} -Version: %{version} -Release: %{release} -Copyright: Modified CNRI Open Source License -Group: Development/Languages -Source: Python-%{version}.tar.bz2 -%if %{include_docs} -Source1: html-%{version}.tar.bz2 -%endif -BuildRoot: %{_tmppath}/%{name}-%{version}-root -BuildPrereq: expat-devel -BuildPrereq: db4-devel -BuildPrereq: gdbm-devel -BuildPrereq: sqlite-devel -Prefix: %{__prefix} -Packager: Sean Reifschneider - -%description -Python is an interpreted, interactive, object-oriented programming -language. It incorporates modules, exceptions, dynamic typing, very high -level dynamic data types, and classes. Python combines remarkable power -with very clear syntax. It has interfaces to many system calls and -libraries, as well as to various window systems, and is extensible in C or -C++. It is also usable as an extension language for applications that need -a programmable interface. Finally, Python is portable: it runs on many -brands of UNIX, on PCs under Windows, MS-DOS, and OS/2, and on the -Mac. - -%package devel -Summary: The libraries and header files needed for Python extension development. -Prereq: python%{binsuffix} = %{PACKAGE_VERSION} -Group: Development/Libraries - -%description devel -The Python programming language's interpreter can be extended with -dynamically loaded extensions and can be embedded in other programs. -This package contains the header files and libraries needed to do -these types of tasks. - -Install python-devel if you want to develop Python extensions. The -python package will also need to be installed. You'll probably also -want to install the python-docs package, which contains Python -documentation. - -%if %{include_tkinter} -%package tkinter -Summary: A graphical user interface for the Python scripting language. -Group: Development/Languages -Prereq: python%{binsuffix} = %{PACKAGE_VERSION}-%{release} - -%description tkinter -The Tkinter (Tk interface) program is an graphical user interface for -the Python scripting language. - -You should install the tkinter package if you'd like to use a graphical -user interface for Python programming. -%endif - -%package tools -Summary: A collection of development tools included with Python. -Group: Development/Tools -Prereq: python%{binsuffix} = %{PACKAGE_VERSION}-%{release} - -%description tools -The Python package includes several development tools that are used -to build python programs. This package contains a selection of those -tools, including the IDLE Python IDE. - -Install python-tools if you want to use these tools to develop -Python programs. You will also need to install the python and -tkinter packages. - -%if %{include_docs} -%package docs -Summary: Python-related documentation. -Group: Development/Documentation - -%description docs -Documentation relating to the Python programming language in HTML and info -formats. -%endif - -%changelog -* Mon Dec 20 2004 Sean Reifschneider [2.4-2pydotorg] -- Changing the idle wrapper so that it passes arguments to idle. - -* Tue Oct 19 2004 Sean Reifschneider [2.4b1-1pydotorg] -- Updating to 2.4. - -* Thu Jul 22 2004 Sean Reifschneider [2.3.4-3pydotorg] -- Paul Tiemann fixes for %{prefix}. -- Adding permission changes for directory as suggested by reimeika.ca -- Adding code to detect when it should be using lib64. -- Adding a define for the location of /var/www/html for docs. - -* Thu May 27 2004 Sean Reifschneider [2.3.4-2pydotorg] -- Including changes from Ian Holsman to build under Red Hat 7.3. -- Fixing some problems with the /usr/local path change. - -* Sat Mar 27 2004 Sean Reifschneider [2.3.2-3pydotorg] -- Being more agressive about finding the paths to fix for - #!/usr/local/bin/python. - -* Sat Feb 07 2004 Sean Reifschneider [2.3.3-2pydotorg] -- Adding code to remove "#!/usr/local/bin/python" from particular files and - causing the RPM build to terminate if there are any unexpected files - which have that line in them. - -* Mon Oct 13 2003 Sean Reifschneider [2.3.2-1pydotorg] -- Adding code to detect wether documentation is available to build. - -* Fri Sep 19 2003 Sean Reifschneider [2.3.1-1pydotorg] -- Updating to the 2.3.1 release. - -* Mon Feb 24 2003 Sean Reifschneider [2.3b1-1pydotorg] -- Updating to 2.3b1 release. - -* Mon Feb 17 2003 Sean Reifschneider [2.3a1-1] -- Updating to 2.3 release. - -* Sun Dec 23 2001 Sean Reifschneider -[Release 2.2-2] -- Added -docs package. -- Added "auto" config_tkinter setting which only enables tk if - /usr/bin/wish exists. - -* Sat Dec 22 2001 Sean Reifschneider -[Release 2.2-1] -- Updated to 2.2. -- Changed the extension to "2" from "2.2". - -* Tue Nov 18 2001 Sean Reifschneider -[Release 2.2c1-1] -- Updated to 2.2c1. - -* Thu Nov 1 2001 Sean Reifschneider -[Release 2.2b1-3] -- Changed the way the sed for fixing the #! in pydoc works. - -* Wed Oct 24 2001 Sean Reifschneider -[Release 2.2b1-2] -- Fixed missing "email" package, thanks to anonymous report on sourceforge. -- Fixed missing "compiler" package. - -* Mon Oct 22 2001 Sean Reifschneider -[Release 2.2b1-1] -- Updated to 2.2b1. - -* Mon Oct 9 2001 Sean Reifschneider -[Release 2.2a4-4] -- otto at balinor.mat.unimi.it mentioned that the license file is missing. - -* Sun Sep 30 2001 Sean Reifschneider -[Release 2.2a4-3] -- Ignacio Vazquez-Abrams pointed out that I had a spruious double-quote in - the spec files. Thanks. - -* Wed Jul 25 2001 Sean Reifschneider -[Release 2.2a1-1] -- Updated to 2.2a1 release. -- Changed idle and pydoc to use binsuffix macro - -####### -# PREP -####### -%prep -%setup -n Python-%{version} - -######## -# BUILD -######## -%build -./configure --enable-unicode=ucs4 %{ipv6} %{pymalloc} --prefix=%{__prefix} -make - -########## -# INSTALL -########## -%install -# set the install path -echo '[install_scripts]' >setup.cfg -echo 'install_dir='"${RPM_BUILD_ROOT}%{__prefix}/bin" >>setup.cfg - -[ -d "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != "/" ] && rm -rf $RPM_BUILD_ROOT -mkdir -p $RPM_BUILD_ROOT%{__prefix}/%{libdirname}/python%{libvers}/lib-dynload -make prefix=$RPM_BUILD_ROOT%{__prefix} install - -# REPLACE PATH IN PYDOC -if [ ! -z "%{binsuffix}" ] -then - ( - cd $RPM_BUILD_ROOT%{__prefix}/bin - mv pydoc pydoc.old - sed 's|#!.*|#!%{__prefix}/bin/env python'%{binsuffix}'|' \ - pydoc.old >pydoc - chmod 755 pydoc - rm -f pydoc.old - ) -fi - -# add the binsuffix -if [ ! -z "%{binsuffix}" ] -then - ( cd $RPM_BUILD_ROOT%{__prefix}/bin; rm -f python[0-9a-zA-Z]*; - mv -f python python"%{binsuffix}" ) - ( cd $RPM_BUILD_ROOT%{__prefix}/man/man1; mv python.1 python%{binsuffix}.1 ) - ( cd $RPM_BUILD_ROOT%{__prefix}/bin; mv -f pydoc pydoc"%{binsuffix}" ) - ( cd $RPM_BUILD_ROOT%{__prefix}/bin; mv -f idle idle"%{binsuffix}" ) -fi - -######## -# Tools -echo '#!%{__prefix}/bin/env python%{binsuffix}' >${RPM_BUILD_ROOT}%{__prefix}/bin/idle%{binsuffix} -echo 'import os, sys' >>${RPM_BUILD_ROOT}%{__prefix}/bin/idle%{binsuffix} -echo 'os.execvp("%{__prefix}/bin/python%{binsuffix}", ["%{__prefix}/bin/python%{binsuffix}", "%{__prefix}/lib/python%{libvers}/idlelib/idle.py"] + sys.argv[1:])' >>${RPM_BUILD_ROOT}%{__prefix}/bin/idle%{binsuffix} -echo 'print "Failed to exec Idle"' >>${RPM_BUILD_ROOT}%{__prefix}/bin/idle%{binsuffix} -echo 'sys.exit(1)' >>${RPM_BUILD_ROOT}%{__prefix}/bin/idle%{binsuffix} -chmod 755 $RPM_BUILD_ROOT%{__prefix}/bin/idle%{binsuffix} -cp -a Tools $RPM_BUILD_ROOT%{__prefix}/%{libdirname}/python%{libvers} - -# MAKE FILE LISTS -rm -f mainpkg.files -find "$RPM_BUILD_ROOT""%{__prefix}"/%{libdirname}/python%{libvers}/lib-dynload -type f | - sed "s|^${RPM_BUILD_ROOT}|/|" | - grep -v -e '_tkinter.so$' >mainpkg.files -find "$RPM_BUILD_ROOT""%{__prefix}"/bin -type f | - sed "s|^${RPM_BUILD_ROOT}|/|" | - grep -v -e '/bin/idle%{binsuffix}$' >>mainpkg.files - -rm -f tools.files -find "$RPM_BUILD_ROOT""%{__prefix}"/%{libdirname}/python%{libvers}/idlelib \ - "$RPM_BUILD_ROOT""%{__prefix}"/%{libdirname}/python%{libvers}/Tools -type f | - sed "s|^${RPM_BUILD_ROOT}|/|" >tools.files -echo "%{__prefix}"/bin/idle%{binsuffix} >>tools.files - -###### -# Docs -%if %{include_docs} -mkdir -p "$RPM_BUILD_ROOT"%{config_htmldir} -( - cd "$RPM_BUILD_ROOT"%{config_htmldir} - bunzip2 < %{SOURCE1} | tar x -) -%endif - -# fix the #! line in installed files -find "$RPM_BUILD_ROOT" -type f -print0 | - xargs -0 grep -l /usr/local/bin/python | while read file -do - FIXFILE="$file" - sed 's|^#!.*python|#!%{__prefix}/bin/env python'"%{binsuffix}"'|' \ - "$FIXFILE" >/tmp/fix-python-path.$$ - cat /tmp/fix-python-path.$$ >"$FIXFILE" - rm -f /tmp/fix-python-path.$$ -done - -# check to see if there are any straggling #! lines -find "$RPM_BUILD_ROOT" -type f | xargs egrep -n '^#! */usr/local/bin/python' \ - | grep ':1:#!' >/tmp/python-rpm-files.$$ || true -if [ -s /tmp/python-rpm-files.$$ ] -then - echo '*****************************************************' - cat /tmp/python-rpm-files.$$ - cat <<@EOF - ***************************************************** - There are still files referencing /usr/local/bin/python in the - install directory. They are listed above. Please fix the .spec - file and try again. If you are an end-user, you probably want - to report this to jafo-rpms at tummy.com as well. - ***************************************************** - at EOF - rm -f /tmp/python-rpm-files.$$ - exit 1 -fi -rm -f /tmp/python-rpm-files.$$ - -######## -# CLEAN -######## -%clean -[ -n "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && rm -rf $RPM_BUILD_ROOT -rm -f mainpkg.files tools.files - -######## -# FILES -######## -%files -f mainpkg.files -%defattr(-,root,root) -%doc Misc/README Misc/cheatsheet Misc/Porting -%doc LICENSE Misc/ACKS Misc/HISTORY Misc/NEWS -%{__prefix}/man/man1/python%{binsuffix}.1* - -%attr(755,root,root) %dir %{__prefix}/include/python%{libvers} -%attr(755,root,root) %dir %{__prefix}/%{libdirname}/python%{libvers}/ -%{__prefix}/%{libdirname}/python%{libvers}/*.txt -%{__prefix}/%{libdirname}/python%{libvers}/*.py* -%{__prefix}/%{libdirname}/python%{libvers}/pdb.doc -%{__prefix}/%{libdirname}/python%{libvers}/profile.doc -%{__prefix}/%{libdirname}/python%{libvers}/curses -%{__prefix}/%{libdirname}/python%{libvers}/distutils -%{__prefix}/%{libdirname}/python%{libvers}/encodings -%{__prefix}/%{libdirname}/python%{libvers}/plat-linux2 -%{__prefix}/%{libdirname}/python%{libvers}/site-packages -%{__prefix}/%{libdirname}/python%{libvers}/test -%{__prefix}/%{libdirname}/python%{libvers}/xml -%{__prefix}/%{libdirname}/python%{libvers}/email -%{__prefix}/%{libdirname}/python%{libvers}/email/mime -%{__prefix}/%{libdirname}/python%{libvers}/sqlite3 -%{__prefix}/%{libdirname}/python%{libvers}/compiler -%{__prefix}/%{libdirname}/python%{libvers}/bsddb -%{__prefix}/%{libdirname}/python%{libvers}/hotshot -%{__prefix}/%{libdirname}/python%{libvers}/logging -%{__prefix}/%{libdirname}/python%{libvers}/lib-old - -%files devel -%defattr(-,root,root) -%{__prefix}/include/python%{libvers}/*.h -%{__prefix}/%{libdirname}/python%{libvers}/config - -%files -f tools.files tools -%defattr(-,root,root) - -%if %{include_tkinter} -%files tkinter -%defattr(-,root,root) -%{__prefix}/%{libdirname}/python%{libvers}/lib-tk -%{__prefix}/%{libdirname}/python%{libvers}/lib-dynload/_tkinter.so* -%endif - -%if %{include_docs} -%files docs -%defattr(-,root,root) -%{config_htmldir}/* -%endif Modified: python/branches/py3k-ctypes-pep3118/Misc/Vim/python.vim ============================================================================== --- python/branches/py3k-ctypes-pep3118/Misc/Vim/python.vim (original) +++ python/branches/py3k-ctypes-pep3118/Misc/Vim/python.vim Wed Apr 30 15:57:13 2008 @@ -1,4 +1,4 @@ -" Auto-generated Vim syntax file for Python +" Auto-generated Vim syntax file for Python (trunk: r60376M). " " To use: copy or symlink to ~/.vim/syntax/python.vim @@ -63,7 +63,7 @@ if exists("python_highlight_builtins") syn keyword pythonBuiltin Ellipsis False None NotImplemented True __debug__ - syn keyword pythonBuiltin __import__ abs all any basestring bool + syn keyword pythonBuiltin __import__ abs all any bool syn keyword pythonBuiltin buffer callable chr classmethod cmp syn keyword pythonBuiltin complex copyright credits delattr dict syn keyword pythonBuiltin dir divmod enumerate eval exec exit @@ -73,7 +73,8 @@ syn keyword pythonBuiltin max min object oct open ord pow property quit syn keyword pythonBuiltin range reload repr reversed round syn keyword pythonBuiltin set setattr slice sorted staticmethod str sum - syn keyword pythonBuiltin super tuple type unichr unicode vars zip + syn keyword pythonBuiltin super trunc tuple type unicode vars + syn keyword pythonBuiltin zip endif Modified: python/branches/py3k-ctypes-pep3118/Misc/Vim/syntax_test.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Misc/Vim/syntax_test.py (original) +++ python/branches/py3k-ctypes-pep3118/Misc/Vim/syntax_test.py Wed Apr 30 15:57:13 2008 @@ -4,9 +4,8 @@ Not necessarily sensical or comprehensive (assume that if one exception is highlighted that all are, for instance). -Highlighting extraneous whitespace at the end of the line is not represented -here as all trailing whitespace is automatically removed from .py files in the -repository. +Extraneous trailing whitespace can't be tested because of svn pre-commit hook +checks for such things. """ # Comment Modified: python/branches/py3k-ctypes-pep3118/Misc/Vim/vim_syntax.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Misc/Vim/vim_syntax.py (original) +++ python/branches/py3k-ctypes-pep3118/Misc/Vim/vim_syntax.py Wed Apr 30 15:57:13 2008 @@ -6,8 +6,9 @@ import exceptions import builtins from string import Template +from sys import subversion -comment_header = '''" Auto-generated Vim syntax file for Python. +comment_header = '''" Auto-generated Vim syntax file for Python (%s: r%s). " " To use: copy or symlink to ~/.vim/syntax/python.vim''' @@ -162,7 +163,7 @@ def main(file_path): with open(file_path, 'w') as FILE: # Comment for file - print>>FILE, comment_header + print>>FILE, comment_header % subversion[1:] print>>FILE, '' # Statements at start of file print>>FILE, statement_header Modified: python/branches/py3k-ctypes-pep3118/Misc/build.sh ============================================================================== --- python/branches/py3k-ctypes-pep3118/Misc/build.sh (original) +++ python/branches/py3k-ctypes-pep3118/Misc/build.sh Wed Apr 30 15:57:13 2008 @@ -67,7 +67,7 @@ # Note: test_XXX (none currently) really leak, but are disabled # so we don't send spam. Any test which really leaks should only # be listed here if there are also test cases under Lib/test/leakers. -LEAKY_TESTS="test_(cmd_line|popen2|socket|threading_local|urllib2_localnet)" +LEAKY_TESTS="test_(asynchat|cmd_line|popen2|socket|smtplib|sys|threadsignals|urllib2_localnet)" # These tests always fail, so skip them so we don't get false positives. _ALWAYS_SKIP="" @@ -92,6 +92,24 @@ echo "
  • $1 ($time seconds)
  • " >> $RESULT_FILE } +place_summary_first() { + testf=$1 + sed -n '/^[0-9][0-9]* tests OK\./,$p' < $testf \ + | egrep -v '\[[0-9]+ refs\]' > $testf.tmp + echo "" >> $testf.tmp + cat $testf >> $testf.tmp + mv $testf.tmp $testf +} + +count_failures () { + testf=$1 + n=`grep -ic " failed:" $testf` + if [ $n -eq 1 ] ; then + n=`grep " failed:" $testf | sed -e 's/ .*//'` + fi + echo $n +} + mail_on_failure() { if [ "$NUM_FAILURES" != "0" ]; then dest=$FAILURE_MAILTO @@ -99,7 +117,17 @@ if [ "$FAILURE_CC" != "" ]; then dest="$dest -c $FAILURE_CC" fi - mutt -s "$FAILURE_SUBJECT $1 ($NUM_FAILURES)" $dest < $2 + if [ "x$3" != "x" ] ; then + (echo "More important issues:" + echo "----------------------" + egrep -v "$3" < $2 + echo "" + echo "Less important issues:" + echo "----------------------" + egrep "$3" < $2) + else + cat $2 + fi | mutt -s "$FAILURE_SUBJECT $1 ($NUM_FAILURES)" $dest fi } @@ -176,15 +204,17 @@ ## make and run basic tests F=make-test.out start=`current_time` - $PYTHON $REGRTEST_ARGS $ALWAYS_SKIP >& build/$F - NUM_FAILURES=`grep -ic " failed:" build/$F` + $PYTHON $REGRTEST_ARGS -u urlfetch >& build/$F + NUM_FAILURES=`count_failures build/$F` + place_summary_first build/$F update_status "Testing basics ($NUM_FAILURES failures)" "$F" $start mail_on_failure "basics" build/$F F=make-test-opt.out start=`current_time` - $PYTHON -O $REGRTEST_ARGS $ALWAYS_SKIP >& build/$F - NUM_FAILURES=`grep -ic " failed:" build/$F` + $PYTHON -O $REGRTEST_ARGS -u urlfetch >& build/$F + NUM_FAILURES=`count_failures build/$F` + place_summary_first build/$F update_status "Testing opt ($NUM_FAILURES failures)" "$F" $start mail_on_failure "opt" build/$F @@ -193,10 +223,12 @@ start=`current_time` ## ensure that the reflog exists so the grep doesn't fail touch $REFLOG - $PYTHON $REGRTEST_ARGS -R 4:3:$REFLOG -u network $LEAKY_SKIPS >& build/$F - NUM_FAILURES=`egrep -vc "($LEAKY_TESTS|sum=0)" $REFLOG` + $PYTHON $REGRTEST_ARGS -R 4:3:$REFLOG -u network,urlfetch $LEAKY_SKIPS >& build/$F + LEAK_PAT="($LEAKY_TESTS|sum=0)" + NUM_FAILURES=`egrep -vc "$LEAK_PAT" $REFLOG` + place_summary_first build/$F update_status "Testing refleaks ($NUM_FAILURES failures)" "$F" $start - mail_on_failure "refleak" $REFLOG + mail_on_failure "refleak" $REFLOG "$LEAK_PAT" ## now try to run all the tests F=make-testall.out @@ -204,7 +236,8 @@ ## skip curses when running from cron since there's no terminal ## skip sound since it's not setup on the PSF box (/dev/dsp) $PYTHON $REGRTEST_ARGS -uall -x test_curses test_linuxaudiodev test_ossaudiodev $_ALWAYS_SKIP >& build/$F - NUM_FAILURES=`grep -ic " failed:" build/$F` + NUM_FAILURES=`count_failures build/$F` + place_summary_first build/$F update_status "Testing all except curses and sound ($NUM_FAILURES failures)" "$F" $start mail_on_failure "all" build/$F fi Modified: python/branches/py3k-ctypes-pep3118/Misc/cheatsheet ============================================================================== --- python/branches/py3k-ctypes-pep3118/Misc/cheatsheet (original) +++ python/branches/py3k-ctypes-pep3118/Misc/cheatsheet Wed Apr 30 15:57:13 2008 @@ -561,8 +561,8 @@ i Signed integer decimal. o Unsigned octal. u Unsigned decimal. -x Unsigned hexidecimal (lowercase). -X Unsigned hexidecimal (uppercase). +x Unsigned hexadecimal (lowercase). +X Unsigned hexadecimal (uppercase). e Floating point exponential format (lowercase). E Floating point exponential format (uppercase). f Floating point decimal format. Modified: python/branches/py3k-ctypes-pep3118/Misc/developers.txt ============================================================================== --- python/branches/py3k-ctypes-pep3118/Misc/developers.txt (original) +++ python/branches/py3k-ctypes-pep3118/Misc/developers.txt Wed Apr 30 15:57:13 2008 @@ -17,6 +17,26 @@ Permissions History ------------------- +- Jeroen Ruigrok van der Werven was given SVN access on 12 April 2008 + by Georg Brandl, for documentation work. + +- Josiah Carlson was given SVN access on 26 March 2008 by Georg Brandl, + for work on asyncore/asynchat. + +- Benjamin Peterson was given SVN access on 25 March 2008 by Georg + Brandl, for bug triage work. + +- Jerry Seutter was given SVN access on 20 March 2008 by BAC, for + general contributions to Python. + +- Jeff Rush was given SVN access on 18 March 2008 by AMK, for Distutils work. + +- David Wolever was given SVN access on 17 March 2008 by MvL, + for 2to3 work. + +- Trent Nelson was given SVN access on 17 March 2008 by MvL, + for general contributions to Python. + - Mark Dickinson was given SVN access on 6 January 2008 by Facundo Batista for his work on mathemathics and number related issues. Modified: python/branches/py3k-ctypes-pep3118/Misc/python-mode.el ============================================================================== --- python/branches/py3k-ctypes-pep3118/Misc/python-mode.el (original) +++ python/branches/py3k-ctypes-pep3118/Misc/python-mode.el Wed Apr 30 15:57:13 2008 @@ -2,7 +2,8 @@ ;; Copyright (C) 1992,1993,1994 Tim Peters -;; Author: 1995-2002 Barry A. Warsaw +;; Author: 2003-2007 http://sf.net/projects/python-mode +;; 1995-2002 Barry A. Warsaw ;; 1992-1994 Tim Peters ;; Maintainer: python-mode at python.org ;; Created: Feb 1992 @@ -19,19 +20,38 @@ ;;; Commentary: -;; This is a major mode for editing Python programs. It was developed -;; by Tim Peters after an original idea by Michael A. Guravage. Tim -;; subsequently left the net; in 1995, Barry Warsaw inherited the mode -;; and is the current maintainer. Tim's now back but disavows all -;; responsibility for the mode. Smart Tim :-) +;; This is a major mode for editing Python programs. It was developed by Tim +;; Peters after an original idea by Michael A. Guravage. Tim subsequently +;; left the net and in 1995, Barry Warsaw inherited the mode. Tim's now back +;; but disavows all responsibility for the mode. In fact, we suspect he +;; doesn't even use Emacs any more. In 2003, python-mode.el was moved to its +;; own SourceForge project apart from the Python project, and now is +;; maintained by the volunteers at the python-mode at python.org mailing list. -;; pdbtrack support contributed by Ken Manheimer, April 2001. +;; pdbtrack support contributed by Ken Manheimer, April 2001. Skip Montanaro +;; has also contributed significantly to python-mode's development. ;; Please use the SourceForge Python project to submit bugs or ;; patches: ;; ;; http://sourceforge.net/projects/python +;; INSTALLATION: + +;; To install, just drop this file into a directory on your load-path and +;; byte-compile it. To set up Emacs to automatically edit files ending in +;; ".py" using python-mode add the following to your ~/.emacs file (GNU +;; Emacs) or ~/.xemacs/init.el file (XEmacs): +;; (setq auto-mode-alist (cons '("\\.py$" . python-mode) auto-mode-alist)) +;; (setq interpreter-mode-alist (cons '("python" . python-mode) +;; interpreter-mode-alist)) +;; (autoload 'python-mode "python-mode" "Python editing mode." t) +;; +;; In XEmacs syntax highlighting should be enabled automatically. In GNU +;; Emacs you may have to add these lines to your ~/.emacs file: +;; (global-font-lock-mode t) +;; (setq font-lock-maximum-decoration t) + ;; FOR MORE INFORMATION: ;; There is some information on python-mode.el at @@ -60,6 +80,7 @@ (require 'custom) (require 'cl) (require 'compile) +(require 'ansi-color) ;; user definable variables @@ -70,34 +91,41 @@ :group 'languages :prefix "py-") +(defcustom py-tab-always-indent t + "*Non-nil means TAB in Python mode should always reindent the current line, +regardless of where in the line point is when the TAB command is used." + :type 'boolean + :group 'python) + (defcustom py-python-command "python" "*Shell command used to start Python interpreter." :type 'string :group 'python) -(defcustom py-jpython-command "jpython" - "*Shell command used to start the JPython interpreter." +(make-obsolete-variable 'py-jpython-command 'py-jython-command) +(defcustom py-jython-command "jython" + "*Shell command used to start the Jython interpreter." :type 'string :group 'python - :tag "JPython Command") + :tag "Jython Command") (defcustom py-default-interpreter 'cpython "*Which Python interpreter is used by default. -The value for this variable can be either `cpython' or `jpython'. +The value for this variable can be either `cpython' or `jython'. When the value is `cpython', the variables `py-python-command' and `py-python-command-args' are consulted to determine the interpreter and arguments to use. -When the value is `jpython', the variables `py-jpython-command' and -`py-jpython-command-args' are consulted to determine the interpreter +When the value is `jython', the variables `py-jython-command' and +`py-jython-command-args' are consulted to determine the interpreter and arguments to use. Note that this variable is consulted only the first time that a Python mode buffer is visited during an Emacs session. After that, use \\[py-toggle-shells] to change the interpreter shell." :type '(choice (const :tag "Python (a.k.a. CPython)" cpython) - (const :tag "JPython" jpython)) + (const :tag "Jython" jython)) :group 'python) (defcustom py-python-command-args '("-i") @@ -105,11 +133,12 @@ :type '(repeat string) :group 'python) -(defcustom py-jpython-command-args '("-i") - "*List of string arguments to be used when starting a JPython shell." +(make-obsolete-variable 'py-jpython-command-args 'py-jython-command-args) +(defcustom py-jython-command-args '("-i") + "*List of string arguments to be used when starting a Jython shell." :type '(repeat string) :group 'python - :tag "JPython Command Args") + :tag "Jython Command Args") (defcustom py-indent-offset 4 "*Amount of offset per level of indentation. @@ -248,7 +277,7 @@ :type 'function :group 'python) -(defcustom py-imenu-show-method-args-p nil +(defcustom py-imenu-show-method-args-p nil "*Controls echoing of arguments of functions & methods in the Imenu buffer. When non-nil, arguments are printed." :type 'boolean @@ -275,19 +304,20 @@ 20000 "Maximum number of characters to search for a Java-ish import statement. When `python-mode' tries to calculate the shell to use (either a -CPython or a JPython shell), it looks at the so-called `shebang' line +CPython or a Jython shell), it looks at the so-called `shebang' line -- i.e. #! line. If that's not available, it looks at some of the file heading imports to see if they look Java-like." :type 'integer :group 'python ) -(defcustom py-jpython-packages +(make-obsolete-variable 'py-jpython-packages 'py-jython-packages) +(defcustom py-jython-packages '("java" "javax" "org" "com") - "Imported packages that imply `jpython-mode'." + "Imported packages that imply `jython-mode'." :type '(repeat string) :group 'python) - + ;; Not customizable (defvar py-master-file nil "If non-nil, execute the named file instead of the buffer's file. @@ -317,16 +347,39 @@ :tag "Pychecker Command Args") (defvar py-shell-alist - '(("jpython" . 'jpython) - ("jython" . 'jpython) + '(("jython" . 'jython) ("python" . 'cpython)) "*Alist of interpreters and python shells. Used by `py-choose-shell' to select the appropriate python interpreter mode for a file.") +(defcustom py-shell-input-prompt-1-regexp "^>>> " + "*A regular expression to match the input prompt of the shell." + :type 'string + :group 'python) + +(defcustom py-shell-input-prompt-2-regexp "^[.][.][.] " + "*A regular expression to match the input prompt of the shell after the + first line of input." + :type 'string + :group 'python) + +(defcustom py-shell-switch-buffers-on-execute t + "*Controls switching to the Python buffer where commands are + executed. When non-nil the buffer switches to the Python buffer, if + not no switching occurs." + :type 'boolean + :group 'python) + ;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT +(defvar py-line-number-offset 0 + "When an exception occurs as a result of py-execute-region, a +subsequent py-up-exception needs the line number where the region +started, in order to jump to the correct file line. This variable is +set in py-execute-region and used in py-jump-to-exception.") + (defconst py-emacs-features (let (features) features) @@ -339,9 +392,31 @@ "Face for pseudo keywords in Python mode, like self, True, False, Ellipsis.") (make-face 'py-pseudo-keyword-face) +;; PEP 318 decorators +(defvar py-decorators-face 'py-decorators-face + "Face method decorators.") +(make-face 'py-decorators-face) + +;; Face for builtins +(defvar py-builtins-face 'py-builtins-face + "Face for builtins like TypeError, object, open, and exec.") +(make-face 'py-builtins-face) + +;; XXX, TODO, and FIXME comments and such +(defvar py-XXX-tag-face 'py-XXX-tag-face + "Face for XXX, TODO, and FIXME tags") +(make-face 'py-XXX-tag-face) + (defun py-font-lock-mode-hook () (or (face-differs-from-default-p 'py-pseudo-keyword-face) - (copy-face 'font-lock-keyword-face 'py-pseudo-keyword-face))) + (copy-face 'font-lock-keyword-face 'py-pseudo-keyword-face)) + (or (face-differs-from-default-p 'py-builtins-face) + (copy-face 'font-lock-keyword-face 'py-builtins-face)) + (or (face-differs-from-default-p 'py-decorators-face) + (copy-face 'py-pseudo-keyword-face 'py-decorators-face)) + (or (face-differs-from-default-p 'py-XXX-tag-face) + (copy-face 'font-lock-comment-face 'py-XXX-tag-face)) + ) (add-hook 'font-lock-mode-hook 'py-font-lock-mode-hook) (defvar python-font-lock-keywords @@ -352,7 +427,7 @@ "from" "global" "if" "import" "in" "is" "lambda" "not" "or" "pass" "print" "raise" - "return" "while" "yield" + "return" "while" "with" "yield" ) "\\|")) (kw2 (mapconcat 'identity @@ -391,26 +466,52 @@ "super" "tuple" "type" "unichr" "unicode" "vars" "zip") "\\|")) + (kw4 (mapconcat 'identity + ;; Exceptions and warnings + '("ArithmeticError" "AssertionError" + "AttributeError" "DeprecationWarning" "EOFError" + "EnvironmentError" "Exception" + "FloatingPointError" "FutureWarning" "IOError" + "ImportError" "IndentationError" "IndexError" + "KeyError" "KeyboardInterrupt" "LookupError" + "MemoryError" "NameError" "NotImplemented" + "NotImplementedError" "OSError" "OverflowError" + "OverflowWarning" "PendingDeprecationWarning" + "ReferenceError" "RuntimeError" "RuntimeWarning" + "StandardError" "StopIteration" "SyntaxError" + "SyntaxWarning" "SystemError" "SystemExit" + "TabError" "TypeError" "UnboundLocalError" + "UnicodeDecodeError" "UnicodeEncodeError" + "UnicodeError" "UnicodeTranslateError" + "UserWarning" "ValueError" "Warning" + "ZeroDivisionError") + "\\|")) ) (list + '("^[ \t]*\\(@.+\\)" 1 'py-decorators-face) ;; keywords - (cons (concat "\\b\\(" kw1 "\\)\\b[ \n\t(]") 1) + (cons (concat "\\<\\(" kw1 "\\)\\>[ \n\t(]") 1) ;; builtins when they don't appear as object attributes - (cons (concat "\\(\\b\\|[.]\\)\\(" kw3 "\\)\\b[ \n\t(]") 2) + (list (concat "\\([^. \t]\\|^\\)[ \t]*\\<\\(" kw3 "\\)\\>[ \n\t(]") 2 + 'py-builtins-face) ;; block introducing keywords with immediately following colons. ;; Yes "except" is in both lists. - (cons (concat "\\b\\(" kw2 "\\)[ \n\t(]") 1) - ;; `as' but only in "import foo as bar" - '("[ \t]*\\(\\bfrom\\b.*\\)?\\bimport\\b.*\\b\\(as\\)\\b" . 2) + (cons (concat "\\<\\(" kw2 "\\)[ \n\t(]") 1) + ;; Exceptions + (list (concat "\\<\\(" kw4 "\\)[ \n\t:,(]") 1 'py-builtins-face) + ;; `as' but only in "import foo as bar" or "with foo as bar" + '("[ \t]*\\(\\.*\\)?\\.*\\<\\(as\\)\\>" . 2) + '("[ \t]*\\.*\\<\\(as\\)\\>" . 1) ;; classes - '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)" - 1 font-lock-type-face) + '("\\" 1 py-pseudo-keyword-face) + ;; XXX, TODO, and FIXME tags + '("XXX\\|TODO\\|FIXME" 0 py-XXX-tag-face t) )) "Additional expressions to highlight in Python mode.") (put 'python-mode 'font-lock-defaults '(python-font-lock-keywords)) @@ -421,13 +522,7 @@ Currently-active file is at the head of the list.") (defvar py-pdbtrack-is-tracking-p nil) -(defvar py-pdbtrack-last-grubbed-buffer nil - "Record of the last buffer used when the source path was invalid. -This buffer is consulted before the buffer-list history for satisfying -`py-pdbtrack-grub-for-buffer', since it's the most often the likely -prospect as debugging continues.") -(make-variable-buffer-local 'py-pdbtrack-last-grubbed-buffer) (defvar py-pychecker-history nil) @@ -461,7 +556,7 @@ "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*" "\\\\$") "Regular expression matching Python backslash continuation lines.") - + (defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)" "Regular expression matching a blank or comment line.") @@ -474,7 +569,7 @@ "\\|") "\\)") "Regular expression matching statements to be dedented one level.") - + (defconst py-block-closing-keywords-re "\\(return\\|raise\\|break\\|continue\\|pass\\)" "Regular expression matching keywords which typically close a block.") @@ -495,30 +590,17 @@ "\\)") "Regular expression matching lines not to dedent after.") -(defconst py-defun-start-re - "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=" - ;; If you change this, you probably have to change py-current-defun - ;; as well. This is only used by py-current-defun to find the name - ;; for add-log.el. - "Regular expression matching a function, method, or variable assignment.") - -(defconst py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)" - ;; If you change this, you probably have to change py-current-defun - ;; as well. This is only used by py-current-defun to find the name - ;; for add-log.el. - "Regular expression for finding a class name.") - -(defconst py-traceback-line-re +(defvar py-traceback-line-re "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)" "Regular expression that describes tracebacks.") -;; pdbtrack contants +;; pdbtrack constants (defconst py-pdbtrack-stack-entry-regexp ; "^> \\([^(]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_]+\\)()" "^> \\(.*\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_]+\\)()" "Regular expression pdbtrack uses to find a stack trace entry.") -(defconst py-pdbtrack-input-prompt "\n[(<]*pdb[>)]+ " +(defconst py-pdbtrack-input-prompt "\n[(<]*[Pp]db[>)]+ " "Regular expression pdbtrack uses to recognize a pdb prompt.") (defconst py-pdbtrack-track-range 10000 @@ -536,8 +618,9 @@ (defvar python-mode-hook nil "*Hook called by `python-mode'.") -(defvar jpython-mode-hook nil - "*Hook called by `jpython-mode'. `jpython-mode' also calls +(make-obsolete-variable 'jpython-mode-hook 'jython-mode-hook) +(defvar jython-mode-hook nil + "*Hook called by `jython-mode'. `jython-mode' also calls `python-mode-hook'.") (defvar py-shell-hook nil @@ -560,8 +643,6 @@ (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right) (define-key py-mode-map "\C-c<" 'py-shift-region-left) (define-key py-mode-map "\C-c>" 'py-shift-region-right) - ;; paragraph and string filling - (define-key py-mode-map "\eq" 'py-fill-paragraph) ;; subprocess commands (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer) (define-key py-mode-map "\C-c\C-m" 'py-execute-import-or-reload) @@ -624,7 +705,7 @@ ;; expect RET to do a `py-newline-and-indent' and any Emacsers who ;; dislike this are probably knowledgeable enough to do a rebind. ;; However, we do *not* change C-j since many Emacsers have already - ;; swapped RET and C-j and they don't want C-j bound to `newline' to + ;; swapped RET and C-j and they don't want C-j bound to `newline' to ;; change. (define-key py-mode-map "\C-m" 'py-newline-and-indent) ) @@ -740,8 +821,8 @@ (cond ((eq position 'bol) (beginning-of-line)) ((eq position 'eol) (end-of-line)) - ((eq position 'bod) (py-beginning-of-def-or-class)) - ((eq position 'eod) (py-end-of-def-or-class)) + ((eq position 'bod) (py-beginning-of-def-or-class 'either)) + ((eq position 'eod) (py-end-of-def-or-class 'either)) ;; Kind of funny, I know, but useful for py-up-exception. ((eq position 'bob) (beginning-of-buffer)) ((eq position 'eob) (end-of-buffer)) @@ -849,7 +930,7 @@ (defvar py-imenu-method-regexp (concat ; <> - "\\(" ; + "\\(" ; "^[ \t]*" ; new line and maybe whitespace "\\(def[ \t]+" ; function definitions start with def "\\([a-zA-Z0-9_]+\\)" ; name is here @@ -885,7 +966,7 @@ ;; it. (defvar py-imenu-generic-expression (cons - (concat + (concat py-imenu-class-regexp "\\|" ; or... py-imenu-method-regexp @@ -954,7 +1035,7 @@ looking-p def-name prev-name cur-indent def-pos - (class-paren (first py-imenu-generic-parens)) + (class-paren (first py-imenu-generic-parens)) (def-paren (second py-imenu-generic-parens))) (setq looking-p (re-search-forward py-imenu-generic-regexp (point-max) t)) @@ -1009,7 +1090,7 @@ (cons save-elmt sub-method-alist)) index-alist)))) ;; found less indented expression, we're done. - (t + (t (setq looking-p nil) (re-search-backward py-imenu-generic-regexp (point-min) t))) ;; end-cond @@ -1023,7 +1104,7 @@ (defun py-choose-shell-by-shebang () - "Choose CPython or JPython mode by looking at #! on the first line. + "Choose CPython or Jython mode by looking at #! on the first line. Returns the appropriate mode function. Used by `py-choose-shell', and similar to but distinct from `set-auto-mode', though it uses `auto-mode-interpreter-regexp' (if available)." @@ -1047,10 +1128,10 @@ (defun py-choose-shell-by-import () - "Choose CPython or JPython mode based imports. -If a file imports any packages in `py-jpython-packages', within + "Choose CPython or Jython mode based imports. +If a file imports any packages in `py-jython-packages', within `py-import-check-point-max' characters from the start of the file, -return `jpython', otherwise return nil." +return `jython', otherwise return nil." (let (mode) (save-excursion (goto-char (point-min)) @@ -1058,14 +1139,14 @@ (search-forward-regexp "^\\(\\(from\\)\\|\\(import\\)\\) \\([^ \t\n.]+\\)" py-import-check-point-max t)) - (setq mode (and (member (match-string 4) py-jpython-packages) - 'jpython + (setq mode (and (member (match-string 4) py-jython-packages) + 'jython )))) mode)) (defun py-choose-shell () - "Choose CPython or JPython mode. Returns the appropriate mode function. + "Choose CPython or Jython mode. Returns the appropriate mode function. This does the following: - look for an interpreter with `py-choose-shell-by-shebang' - examine imports using `py-choose-shell-by-import' @@ -1114,6 +1195,7 @@ (make-local-variable 'indent-region-function) (make-local-variable 'indent-line-function) (make-local-variable 'add-log-current-defun-function) + (make-local-variable 'fill-paragraph-function) ;; (set-syntax-table py-mode-syntax-table) (setq major-mode 'python-mode @@ -1132,6 +1214,8 @@ indent-line-function 'py-indent-line ;; tell add-log.el how to find the current function/method/variable add-log-current-defun-function 'py-current-defun + + fill-paragraph-function 'py-fill-paragraph ) (use-local-map py-mode-map) ;; add the menu @@ -1171,17 +1255,18 @@ (py-toggle-shells (py-choose-shell)))) -(defun jpython-mode () - "Major mode for editing JPython/Jython files. +(make-obsolete 'jpython-mode 'jython-mode) +(defun jython-mode () + "Major mode for editing Jython/Jython files. This is a simple wrapper around `python-mode'. -It runs `jpython-mode-hook' then calls `python-mode.' +It runs `jython-mode-hook' then calls `python-mode.' It is added to `interpreter-mode-alist' and `py-choose-shell'. " (interactive) (python-mode) - (py-toggle-shells 'jpython) - (when jpython-mode-hook - (run-hooks 'jpython-mode-hook))) + (py-toggle-shells 'jython) + (when jython-mode-hook + (run-hooks 'jython-mode-hook))) ;; It's handy to add recognition of Python files to the @@ -1189,16 +1274,16 @@ ;; can specify different `derived-modes' based on the #! line, but ;; with the latter, we can't. So we just won't add them if they're ;; already added. -(let ((modes '(("jpython" . jpython-mode) - ("jython" . jpython-mode) +;;;###autoload +(let ((modes '(("jython" . jython-mode) ("python" . python-mode)))) (while modes (when (not (assoc (car modes) interpreter-mode-alist)) (push (car modes) interpreter-mode-alist)) (setq modes (cdr modes)))) - +;;;###autoload (when (not (or (rassq 'python-mode auto-mode-alist) - (rassq 'jpython-mode auto-mode-alist))) + (rassq 'jython-mode auto-mode-alist))) (push '("\\.py$" . python-mode) auto-mode-alist)) @@ -1283,12 +1368,13 @@ (defun py-comint-output-filter-function (string) "Watch output for Python prompt and exec next file waiting in queue. This function is appropriate for `comint-output-filter-functions'." - ;; TBD: this should probably use split-string - (when (and (or (string-equal string ">>> ") - (and (>= (length string) 5) - (string-equal (substring string -5) "\n>>> "))) - py-file-queue) - (pop-to-buffer (current-buffer)) + ;;remove ansi terminal escape sequences from string, not sure why they are + ;;still around... + (setq string (ansi-color-filter-apply string)) + (when (and (string-match py-shell-input-prompt-1-regexp string) + py-file-queue) + (if py-shell-switch-buffers-on-execute + (pop-to-buffer (current-buffer))) (py-safe (delete-file (car py-file-queue))) (setq py-file-queue (cdr py-file-queue)) (if py-file-queue @@ -1344,7 +1430,7 @@ (- procmark py-pdbtrack-track-range)) procmark)) - target target_fname target_lineno) + target target_fname target_lineno target_buffer) (if (not (string-match (concat py-pdbtrack-input-prompt "$") block)) (py-pdbtrack-overlay-arrow nil) @@ -1372,8 +1458,7 @@ We look first to visit the file indicated in the trace. Failing that, we look for the most recently visited python-mode buffer -with the same name or having -having the named function. +with the same name or having the named function. If we're unable find the source code we return a string describing the problem as best as we can determine." @@ -1417,11 +1502,10 @@ (defun py-pdbtrack-grub-for-buffer (funcname lineno) "Find most recent buffer itself named or having function funcname. -We first check the last buffer this function found, if any, then walk -throught the buffer-list history for python-mode buffers that are +We walk the buffer-list history for python-mode buffers that are named for funcname or define a function funcname." (let ((buffers (buffer-list)) - curbuf + buf got) (while (and buffers (not got)) (setq buf (car buffers) @@ -1436,7 +1520,7 @@ (buffer-substring (point-min) (point-max)))))) (setq got buf))) - (setq py-pdbtrack-last-grubbed-buffer got))) + got)) (defun py-postprocess-output-buffer (buf) "Highlight exceptions found in BUF. @@ -1466,7 +1550,7 @@ (defconst py-output-buffer "*Python Output*") (make-variable-buffer-local 'py-output-buffer) -;; for toggling between CPython and JPython +;; for toggling between CPython and Jython (defvar py-which-shell nil) (defvar py-which-args py-python-command-args) (defvar py-which-bufname "Python") @@ -1475,14 +1559,14 @@ (make-variable-buffer-local 'py-which-bufname) (defun py-toggle-shells (arg) - "Toggles between the CPython and JPython shells. + "Toggles between the CPython and Jython shells. With positive argument ARG (interactively \\[universal-argument]), -uses the CPython shell, with negative ARG uses the JPython shell, and +uses the CPython shell, with negative ARG uses the Jython shell, and with a zero argument, toggles the shell. Programmatically, ARG can also be one of the symbols `cpython' or -`jpython', equivalent to positive arg and negative arg respectively." +`jython', equivalent to positive arg and negative arg respectively." (interactive "P") ;; default is to toggle (if (null arg) @@ -1495,7 +1579,7 @@ (setq arg -1) (setq arg 1))) ((equal arg 'cpython) (setq arg 1)) - ((equal arg 'jpython) (setq arg -1))) + ((equal arg 'jython) (setq arg -1))) (let (msg) (cond ((< 0 arg) @@ -1503,14 +1587,16 @@ (setq py-which-shell py-python-command py-which-args py-python-command-args py-which-bufname "Python" - msg "CPython" - mode-name "Python")) + msg "CPython") + (if (string-equal py-which-bufname "Jython") + (setq mode-name "Python"))) ((> 0 arg) - (setq py-which-shell py-jpython-command - py-which-args py-jpython-command-args - py-which-bufname "JPython" - msg "JPython" - mode-name "JPython")) + (setq py-which-shell py-jython-command + py-which-args py-jython-command-args + py-which-bufname "Jython" + msg "Jython") + (if (string-equal py-which-bufname "Python") + (setq mode-name "Jython"))) ) (message "Using the %s shell" msg) (setq py-output-buffer (format "*%s Output*" py-which-bufname)))) @@ -1532,9 +1618,9 @@ programmatically, or when running in Emacs 19.34 or older. Note: You can toggle between using the CPython interpreter and the -JPython interpreter by hitting \\[py-toggle-shells]. This toggles +Jython interpreter by hitting \\[py-toggle-shells]. This toggles buffer local variables which control whether all your subshell -interactions happen to the `*JPython*' or `*Python*' buffers (the +interactions happen to the `*Jython*' or `*Python*' buffers (the latter is the name used for the CPython buffer). Warning: Don't use an interactive Python if you change sys.ps1 or @@ -1568,10 +1654,14 @@ (concat (mapconcat 'identity py-which-args " ") " ") )))) - (switch-to-buffer-other-window - (apply 'make-comint py-which-bufname py-which-shell nil args)) + (if (not (equal (buffer-name) "*Python*")) + (switch-to-buffer-other-window + (apply 'make-comint py-which-bufname py-which-shell nil args)) + (apply 'make-comint py-which-bufname py-which-shell nil args)) (make-local-variable 'comint-prompt-regexp) - (setq comint-prompt-regexp "^>>> \\|^[.][.][.] \\|^(pdb) ") + (setq comint-prompt-regexp (concat py-shell-input-prompt-1-regexp "\\|" + py-shell-input-prompt-2-regexp "\\|" + "^([Pp]db) ")) (add-hook 'comint-output-filter-functions 'py-comint-output-filter-function) ;; pdbtrack @@ -1642,11 +1732,13 @@ (setq start (point)) (or (< start end) (error "Region is empty")) + (setq py-line-number-offset (count-lines 1 start)) (let ((needs-if (/= (py-point 'bol) (py-point 'boi)))) (set-buffer buf) (python-mode) (when needs-if - (insert "if 1:\n")) + (insert "if 1:\n") + (setq py-line-number-offset (- py-line-number-offset 1))) (insert-buffer-substring cur start end) ;; Set the shell either to the #! line command, or to the ;; py-which-shell buffer local variable. @@ -1683,8 +1775,9 @@ (setq py-exception-buffer (cons file (current-buffer)))) (t ;; TBD: a horrible hack, but why create new Custom variables? - (let ((cmd (concat shell (if (string-equal py-which-bufname "JPython") - " -" "")))) + (let ((cmd (concat py-which-shell (if (string-equal py-which-bufname + "Jython") + " -" "")))) ;; otherwise either run it synchronously in a subprocess (save-excursion (set-buffer buf) @@ -1718,12 +1811,14 @@ See the `\\[py-execute-region]' docs for an account of some subtleties, including the use of the optional ASYNC argument." (interactive "P") - (if py-master-file - (let* ((filename (expand-file-name py-master-file)) - (buffer (or (get-file-buffer filename) - (find-file-noselect filename)))) - (set-buffer buffer))) - (py-execute-region (point-min) (point-max) async)) + (let ((old-buffer (current-buffer))) + (if py-master-file + (let* ((filename (expand-file-name py-master-file)) + (buffer (or (get-file-buffer filename) + (find-file-noselect filename)))) + (set-buffer buffer))) + (py-execute-region (point-min) (point-max) async) + (pop-to-buffer old-buffer))) (defun py-execute-import-or-reload (&optional async) "Import the current buffer's file in a Python interpreter. @@ -1819,6 +1914,9 @@ (t (find-file (read-file-name "Exception file: " nil file t)))))) + ;; Fiddle about with line number + (setq line (+ py-line-number-offset line)) + (pop-to-buffer buffer) ;; Force Python mode (if (not (eq major-mode 'python-mode)) @@ -1999,16 +2097,29 @@ (interactive "P") (let* ((ci (current-indentation)) (move-to-indentation-p (<= (current-column) ci)) - (need (py-compute-indentation (not arg)))) - ;; see if we need to dedent - (if (py-outdent-p) - (setq need (- need py-indent-offset))) - (if (/= ci need) - (save-excursion - (beginning-of-line) - (delete-horizontal-space) - (indent-to need))) - (if move-to-indentation-p (back-to-indentation)))) + (need (py-compute-indentation (not arg))) + (cc (current-column))) + ;; dedent out a level if previous command was the same unless we're in + ;; column 1 + (if (and (equal last-command this-command) + (/= cc 0)) + (progn + (beginning-of-line) + (delete-horizontal-space) + (indent-to (* (/ (- cc 1) py-indent-offset) py-indent-offset))) + (progn + ;; see if we need to dedent + (if (py-outdent-p) + (setq need (- need py-indent-offset))) + (if (or py-tab-always-indent + move-to-indentation-p) + (progn (if (/= ci need) + (save-excursion + (beginning-of-line) + (delete-horizontal-space) + (indent-to need))) + (if move-to-indentation-p (back-to-indentation))) + (insert-tab)))))) (defun py-newline-and-indent () "Strives to act like the Emacs `newline-and-indent'. @@ -2052,39 +2163,23 @@ ((py-continuation-line-p) (let ((startpos (point)) (open-bracket-pos (py-nesting-level)) - endpos searching found state) + endpos searching found state cind cline) (if open-bracket-pos (progn - ;; align with first item in list; else a normal - ;; indent beyond the line with the open bracket - (goto-char (1+ open-bracket-pos)) ; just beyond bracket - ;; is the first list item on the same line? - (skip-chars-forward " \t") - (if (null (memq (following-char) '(?\n ?# ?\\))) - ; yes, so line up with it - (current-column) - ;; first list item on another line, or doesn't exist yet - (forward-line 1) - (while (and (< (point) startpos) - (looking-at "[ \t]*[#\n\\\\]")) ; skip noise - (forward-line 1)) - (if (and (< (point) startpos) - (/= startpos - (save-excursion - (goto-char (1+ open-bracket-pos)) - (forward-comment (point-max)) - (point)))) - ;; again mimic the first list item - (current-indentation) - ;; else they're about to enter the first item - (goto-char open-bracket-pos) - (setq placeholder (point)) - (py-goto-initial-line) - (py-goto-beginning-of-tqs - (save-excursion (nth 3 (parse-partial-sexp - placeholder (point))))) - (+ (current-indentation) py-indent-offset)))) - + (setq endpos (py-point 'bol)) + (py-goto-initial-line) + (setq cind (current-indentation)) + (setq cline cind) + (dolist (bp + (nth 9 (save-excursion + (parse-partial-sexp (point) endpos))) + cind) + (if (search-forward "\n" bp t) (setq cline cind)) + (goto-char (1+ bp)) + (skip-chars-forward " \t") + (setq cind (if (memq (following-char) '(?\n ?# ?\\)) + (+ cline py-indent-offset) + (current-column))))) ;; else on backslash continuation line (forward-line -1) (if (py-continuation-line-p) ; on at least 3rd line in block @@ -2832,7 +2927,7 @@ ;; ripped from cc-mode (defun py-forward-into-nomenclature (&optional arg) "Move forward to end of a nomenclature section or word. -With \\[universal-argument] (programmatically, optional argument ARG), +With \\[universal-argument] (programmatically, optional argument ARG), do it that many times. A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores." @@ -2886,6 +2981,11 @@ ;; Pychecker + +;; hack for FSF Emacs +(unless (fboundp 'read-shell-command) + (defalias 'read-shell-command 'read-string)) + (defun py-pychecker-run (command) "*Run pychecker (default on the file currently visited)." (interactive @@ -3410,7 +3510,7 @@ (defun py-statement-opens-block-p () "Return t iff the current statement opens a block. -I.e., iff it ends with a colon that is not in a comment. Point should +I.e., iff it ends with a colon that is not in a comment. Point should be at the start of a statement." (save-excursion (let ((start (point)) @@ -3494,8 +3594,8 @@ KEY is a regular expression describing a Python keyword. Skip blank lines and non-indenting comments. If the statement found starts with KEY, then stop, otherwise go back to first enclosing block starting -with KEY. If successful, leave point at the start of the KEY line and -return t. Otherwise, leav point at an undefined place and return nil." +with KEY. If successful, leave point at the start of the KEY line and +return t. Otherwise, leave point at an undefined place and return nil." ;; skip blanks and non-indenting # (py-goto-initial-line) (while (and @@ -3503,7 +3603,7 @@ (zerop (forward-line -1))) ; go back nil) (py-goto-initial-line) - (let* ((re (concat "[ \t]*" key "\\b")) + (let* ((re (concat "[ \t]*" key "\\>")) (case-fold-search nil) ; let* so looking-at sees this (found (looking-at re)) (dead nil)) @@ -3529,7 +3629,7 @@ `Keyword' is defined (essentially) as the regular expression ([a-z]+). Returns nil if none was found." (let ((case-fold-search nil)) - (if (looking-at "[ \t]*\\([a-z]+\\)\\b") + (if (looking-at "[ \t]*\\([a-z]+\\)\\>") (intern (buffer-substring (match-beginning 1) (match-end 1))) nil))) @@ -3537,14 +3637,49 @@ "Python value for `add-log-current-defun-function'. This tells add-log.el how to find the current function/method/variable." (save-excursion - (if (re-search-backward py-defun-start-re nil t) - (or (match-string 3) - (let ((method (match-string 2))) - (if (and (not (zerop (length (match-string 1)))) - (re-search-backward py-class-start-re nil t)) - (concat (match-string 1) "." method) - method))) - nil))) + + ;; Move back to start of the current statement. + + (py-goto-initial-line) + (back-to-indentation) + (while (and (or (looking-at py-blank-or-comment-re) + (py-in-literal)) + (not (bobp))) + (backward-to-indentation 1)) + (py-goto-initial-line) + + (let ((scopes "") + (sep "") + dead assignment) + + ;; Check for an assignment. If this assignment exists inside a + ;; def, it will be overwritten inside the while loop. If it + ;; exists at top lever or inside a class, it will be preserved. + + (when (looking-at "[ \t]*\\([a-zA-Z0-9_]+\\)[ \t]*=") + (setq scopes (buffer-substring (match-beginning 1) (match-end 1))) + (setq assignment t) + (setq sep ".")) + + ;; Prepend the name of each outer socpe (def or class). + + (while (not dead) + (if (and (py-go-up-tree-to-keyword "\\(class\\|def\\)") + (looking-at + "[ \t]*\\(class\\|def\\)[ \t]*\\([a-zA-Z0-9_]+\\)[ \t]*")) + (let ((name (buffer-substring (match-beginning 2) (match-end 2)))) + (if (and assignment (looking-at "[ \t]*def")) + (setq scopes name) + (setq scopes (concat name sep scopes)) + (setq sep ".")))) + (setq assignment nil) + (condition-case nil ; Terminate nicely at top level. + (py-goto-block-up 'no-mark) + (error (setq dead t)))) + (if (string= scopes "") + nil + scopes)))) + (defconst py-help-address "python-mode at python.org" @@ -3586,7 +3721,7 @@ "Dear Barry,") ;salutation (if enhancement-p nil (set-mark (point)) - (insert + (insert "Please replace this text with a sufficiently large code sample\n\ and an exact recipe so that I can reproduce your problem. Failure\n\ to do so may mean a greater delay in fixing your bug.\n\n") @@ -3606,7 +3741,7 @@ (add-hook 'comint-output-filter-functions 'py-pdbtrack-track-stack-file) ;; Add a designator to the minor mode strings -(or (assq 'py-pdbtrack-minor-mode-string minor-mode-alist) +(or (assq 'py-pdbtrack-is-tracking-p minor-mode-alist) (push '(py-pdbtrack-is-tracking-p py-pdbtrack-minor-mode-string) minor-mode-alist)) @@ -3745,20 +3880,35 @@ If point is inside a string, narrow to that string and fill. " (interactive "P") - (let* ((bod (py-point 'bod)) - (pps (parse-partial-sexp bod (point)))) - (cond - ;; are we inside a comment or on a line with only whitespace before - ;; the comment start? - ((or (nth 4 pps) - (save-excursion (beginning-of-line) (looking-at "[ \t]*#"))) - (py-fill-comment justify)) - ;; are we inside a string? - ((nth 3 pps) - (py-fill-string (nth 8 pps))) - ;; otherwise use the default - (t - (fill-paragraph justify))))) + ;; fill-paragraph will narrow incorrectly + (save-restriction + (widen) + (let* ((bod (py-point 'bod)) + (pps (parse-partial-sexp bod (point)))) + (cond + ;; are we inside a comment or on a line with only whitespace before + ;; the comment start? + ((or (nth 4 pps) + (save-excursion (beginning-of-line) (looking-at "[ \t]*#"))) + (py-fill-comment justify)) + ;; are we inside a string? + ((nth 3 pps) + (py-fill-string (nth 8 pps))) + ;; are we at the opening quote of a string, or in the indentation? + ((save-excursion + (forward-word 1) + (eq (py-in-literal) 'string)) + (save-excursion + (py-fill-string (py-point 'boi)))) + ;; are we at or after the closing quote of a string? + ((save-excursion + (backward-word 1) + (eq (py-in-literal) 'string)) + (save-excursion + (py-fill-string (py-point 'boi)))) + ;; otherwise use the default + (t + (fill-paragraph justify)))))) Modified: python/branches/py3k-ctypes-pep3118/Modules/Setup.dist ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/Setup.dist (original) +++ python/branches/py3k-ctypes-pep3118/Modules/Setup.dist Wed Apr 30 15:57:13 2008 @@ -295,14 +295,6 @@ #_curses_panel _curses_panel.c -lpanel -lncurses -# Generic (SunOS / SVR4) dynamic loading module. -# This is not needed for dynamic loading of Python modules -- -# it is a highly experimental and dangerous device for calling -# *arbitrary* C functions in *arbitrary* shared libraries: - -#dl dlmodule.c - - # Modules that provide persistent dictionary-like semantics. You will # probably want to arrange for at least one of them to be available on # your machine, though none are defined by default because of library Modified: python/branches/py3k-ctypes-pep3118/Modules/_bsddb.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_bsddb.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_bsddb.c Wed Apr 30 15:57:13 2008 @@ -312,10 +312,9 @@ "Py_buffer malloc failed"); return NULL; } - /* XXX(gps): PyBUF_LOCKDATA is desired to prevent other theads from - trashing the data buffer while we release the GIL during the db - operation. see http://bugs.python.org/issue1035 */ - if (PyObject_GetBuffer(obj, view, PyBUF_SIMPLE) == -1) { + /* We use PyBUF_LOCK to prevent other threads from trashing the data + buffer while we release the GIL. http://bugs.python.org/issue1035 */ + if (PyObject_GetBuffer(obj, view, PyBUF_LOCK) == -1) { PyMem_Free(view); return NULL; } @@ -904,7 +903,6 @@ } if (self->dbc != NULL) { - MYDB_BEGIN_ALLOW_THREADS; /* If the underlying database has been closed, we don't need to do anything. If the environment has been closed we need to leak, as BerkeleyDB will crash trying to access @@ -913,9 +911,14 @@ a database open. */ if (self->mydb->db && self->mydb->myenvobj && !self->mydb->myenvobj->closed) + /* test for: open db + no environment or non-closed environment */ + if (self->mydb->db && (!self->mydb->myenvobj || (self->mydb->myenvobj && + !self->mydb->myenvobj->closed))) { + MYDB_BEGIN_ALLOW_THREADS; err = self->dbc->c_close(self->dbc); + MYDB_END_ALLOW_THREADS; + } self->dbc = NULL; - MYDB_END_ALLOW_THREADS; } Py_XDECREF( self->mydb ); PyObject_Del(self); Modified: python/branches/py3k-ctypes-pep3118/Modules/_collectionsmodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_collectionsmodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_collectionsmodule.c Wed Apr 30 15:57:13 2008 @@ -1183,7 +1183,7 @@ {"__missing__", (PyCFunction)defdict_missing, METH_O, defdict_missing_doc}, {"copy", (PyCFunction)defdict_copy, METH_NOARGS, - defdict_copy_doc}, + defdict_copy_doc}, {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS, defdict_copy_doc}, {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS, @@ -1209,16 +1209,32 @@ defdict_repr(defdictobject *dd) { PyObject *baserepr; - PyObject *def; + PyObject *defrepr; PyObject *result; baserepr = PyDict_Type.tp_repr((PyObject *)dd); if (baserepr == NULL) return NULL; if (dd->default_factory == NULL) - def = Py_None; + defrepr = PyUnicode_FromString("None"); else - def = dd->default_factory; - result = PyUnicode_FromFormat("defaultdict(%R, %U)", def, baserepr); + { + int status = Py_ReprEnter(dd->default_factory); + if (status != 0) { + if (status < 0) + return NULL; + defrepr = PyUnicode_FromString("..."); + } + else + defrepr = PyObject_Repr(dd->default_factory); + Py_ReprLeave(dd->default_factory); + } + if (defrepr == NULL) { + Py_DECREF(baserepr); + return NULL; + } + result = PyUnicode_FromFormat("defaultdict(%U, %U)", + defrepr, baserepr); + Py_DECREF(defrepr); Py_DECREF(baserepr); return result; } Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/_ctypes.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/_ctypes.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/_ctypes.c Wed Apr 30 15:57:13 2008 @@ -99,6 +99,8 @@ * */ +#define PY_SSIZE_T_CLEAN + #include "Python.h" #include "structmember.h" @@ -121,8 +123,15 @@ #include "ctypes.h" PyObject *PyExc_ArgError; + +/* This dict maps ctypes types to POINTER types */ +PyObject *_pointer_type_cache; + static PyTypeObject Simple_Type; +/* a callable object used for unpickling */ +static PyObject *_unpickle; + char *conversion_mode_encoding = NULL; char *conversion_mode_errors = NULL; @@ -200,7 +209,7 @@ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ + 0, /* tp_new */ 0, /* tp_free */ }; @@ -740,6 +749,7 @@ stgdict->length = 1; stgdict->ffi_type_pointer = ffi_type_pointer; stgdict->paramfunc = PointerType_paramfunc; + stgdict->flags |= TYPEFLAG_ISPOINTER; proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */ if (proto && -1 == PointerType_SetProto(stgdict, proto)) { @@ -1202,6 +1212,9 @@ itemalign = itemdict->align; + if (itemdict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER)) + stgdict->flags |= TYPEFLAG_HASPOINTER; + stgdict->size = itemsize * length; stgdict->align = itemalign; stgdict->length = length; @@ -1298,7 +1311,7 @@ */ -static char *SIMPLE_TYPE_CHARS = "cbBhHiIlLdfuzZqQPXOvtg"; +static char *SIMPLE_TYPE_CHARS = "cbBhHiIlLdfuzZqQPXOv?g"; static PyObject * c_wchar_p_from_param(PyObject *type, PyObject *value) @@ -1593,9 +1606,9 @@ if (suffix == NULL) #ifdef WORDS_BIGENDIAN - suffix = PyUnicode_FromString("_le"); + suffix = PyUnicode_InternFromString("_le"); #else - suffix = PyUnicode_FromString("_be"); + suffix = PyUnicode_InternFromString("_be"); #endif newname = PyUnicode_Concat(name, suffix); @@ -1779,12 +1792,21 @@ switch (*proto_str) { case 'z': /* c_char_p */ ml = &c_char_p_method; + stgdict->flags |= TYPEFLAG_ISPOINTER; break; case 'Z': /* c_wchar_p */ ml = &c_wchar_p_method; + stgdict->flags |= TYPEFLAG_ISPOINTER; break; case 'P': /* c_void_p */ ml = &c_void_p_method; + stgdict->flags |= TYPEFLAG_ISPOINTER; + break; + case 'u': + case 'X': + case 'O': + ml = NULL; + stgdict->flags |= TYPEFLAG_ISPOINTER; break; default: ml = NULL; @@ -2011,7 +2033,7 @@ "class must define _flags_ which must be an integer"); return -1; } - stgdict->flags = PyLong_AS_LONG(ob); + stgdict->flags = PyLong_AS_LONG(ob) | TYPEFLAG_ISPOINTER; /* _argtypes_ is optional... */ ob = PyDict_GetItemString((PyObject *)stgdict, "_argtypes_"); @@ -2093,6 +2115,7 @@ argtypes would be a ctypes type). */ stgdict->format = alloc_format_string(NULL, "X{}"); + stgdict->flags |= TYPEFLAG_ISPOINTER; /* create the new instance (which is a class, since we are a metatype!) */ @@ -2242,7 +2265,7 @@ return 0; } ob = CData_GetContainer(target); - if (ob->b_objects == NULL || !PyDict_Check(ob->b_objects)) { + if (ob->b_objects == NULL || !PyDict_CheckExact(ob->b_objects)) { Py_XDECREF(ob->b_objects); ob->b_objects = keep; /* refcount consumed */ return 0; @@ -2349,6 +2372,45 @@ return -1; } +static PyObject * +CData_reduce(PyObject *_self, PyObject *args) +{ + CDataObject *self = (CDataObject *)_self; + + if (PyObject_stgdict(_self)->flags & (TYPEFLAG_ISPOINTER|TYPEFLAG_HASPOINTER)) { + PyErr_SetString(PyExc_ValueError, + "ctypes objects containing pointers cannot be pickled"); + return NULL; + } + return Py_BuildValue("O(O(NN))", + _unpickle, + Py_TYPE(_self), + PyObject_GetAttrString(_self, "__dict__"), + PyString_FromStringAndSize(self->b_ptr, self->b_size)); +} + +static PyObject * +CData_setstate(PyObject *_self, PyObject *args) +{ + void *data; + Py_ssize_t len; + int res; + PyObject *dict, *mydict; + CDataObject *self = (CDataObject *)_self; + if (!PyArg_ParseTuple(args, "Os#", &dict, &data, &len)) + return NULL; + if (len > self->b_size) + len = self->b_size; + memmove(self->b_ptr, data, len); + mydict = PyObject_GetAttrString(_self, "__dict__"); + res = PyDict_Update(mydict, dict); + Py_DECREF(mydict); + if (res == -1) + return NULL; + Py_INCREF(Py_None); + return Py_None; +} + /* * default __ctypes_from_outparam__ method returns self. */ @@ -2361,6 +2423,8 @@ static PyMethodDef CData_methods[] = { { "__ctypes_from_outparam__", CData_from_outparam, METH_NOARGS, }, + { "__reduce__", CData_reduce, METH_NOARGS, }, + { "__setstate__", CData_setstate, METH_VARARGS, }, { NULL, NULL }, }; @@ -3063,7 +3127,7 @@ char *name = NULL; PyObject *paramflags = NULL; GUID *iid = NULL; - int iid_len = 0; + Py_ssize_t iid_len = 0; if (!PyArg_ParseTuple(args, "is|Oz#", &index, &name, ¶mflags, &iid, &iid_len)) return NULL; @@ -3102,7 +3166,7 @@ CFuncPtrObject *self; PyObject *callable; StgDictObject *dict; - ffi_info *thunk; + CThunkObject *thunk; if (PyTuple_GET_SIZE(args) == 0) return GenericCData_new(type, args, kwds); @@ -3158,11 +3222,6 @@ return NULL; } - /*****************************************************************/ - /* The thunk keeps unowned references to callable and dict->argtypes - so we have to keep them alive somewhere else: callable is kept in self, - dict->argtypes is in the type's stgdict. - */ thunk = AllocFunctionCallback(callable, dict->argtypes, dict->restype, @@ -3171,27 +3230,22 @@ return NULL; self = (CFuncPtrObject *)GenericCData_new(type, args, kwds); - if (self == NULL) + if (self == NULL) { + Py_DECREF(thunk); return NULL; + } Py_INCREF(callable); self->callable = callable; self->thunk = thunk; - *(void **)self->b_ptr = *(void **)thunk; - - /* We store ourself in self->b_objects[0], because the whole instance - must be kept alive if stored in a structure field, for example. - Cycle GC to the rescue! And we have a unittest proving that this works - correctly... - */ - - Py_INCREF((PyObject *)self); /* for KeepRef */ - if (-1 == KeepRef((CDataObject *)self, 0, (PyObject *)self)) { + *(void **)self->b_ptr = (void *)thunk->pcl; + + Py_INCREF((PyObject *)thunk); /* for KeepRef */ + if (-1 == KeepRef((CDataObject *)self, 0, (PyObject *)thunk)) { Py_DECREF((PyObject *)self); return NULL; } - return (PyObject *)self; } @@ -3528,11 +3582,6 @@ pProc = *(void **)self->b_ptr; - if (pProc == NULL) { - PyErr_SetString(PyExc_ValueError, - "attempt to call NULL function pointer"); - return NULL; - } #ifdef MS_WIN32 if (self->index) { /* It's a COM method */ @@ -3645,6 +3694,7 @@ Py_VISIT(self->argtypes); Py_VISIT(self->converters); Py_VISIT(self->paramflags); + Py_VISIT(self->thunk); return CData_traverse((CDataObject *)self, visit, arg); } @@ -3658,13 +3708,7 @@ Py_CLEAR(self->argtypes); Py_CLEAR(self->converters); Py_CLEAR(self->paramflags); - - if (self->thunk) { - FreeClosure(self->thunk->pcl); - PyMem_Free(self->thunk); - self->thunk = NULL; - } - + Py_CLEAR(self->thunk); return CData_clear((CDataObject *)self); } @@ -4390,7 +4434,7 @@ } if (format == NULL) { - format = PyUnicode_FromString("%s(%r)"); + format = PyUnicode_InternFromString("%s(%r)"); if (format == NULL) return NULL; } @@ -4603,7 +4647,7 @@ { PyObject *value = NULL; - if (!PyArg_ParseTuple(args, "|O:POINTER", &value)) + if (!PyArg_UnpackTuple(args, "POINTER", 0, 1, &value)) return -1; if (value == NULL) return 0; @@ -5005,7 +5049,7 @@ } Py_XINCREF(obj->b_objects); result->b_objects = obj->b_objects; - if (result->b_objects && PyDict_Check(result->b_objects)) { + if (result->b_objects && PyDict_CheckExact(result->b_objects)) { PyObject *index; int rc; index = PyLong_FromVoidPtr((void *)src); @@ -5053,9 +5097,22 @@ if (!m) return; + _pointer_type_cache = PyDict_New(); + if (_pointer_type_cache == NULL) + return; + + PyModule_AddObject(m, "_pointer_type_cache", (PyObject *)_pointer_type_cache); + + _unpickle = PyObject_GetAttrString(m, "_unpickle"); + if (_unpickle == NULL) + return; + if (PyType_Ready(&PyCArg_Type) < 0) return; + if (PyType_Ready(&CThunk_Type) < 0) + return; + /* StgDict is derived from PyDict_Type */ StgDict_Type.tp_base = &PyDict_Type; if (PyType_Ready(&StgDict_Type) < 0) Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/_ctypes_test.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/_ctypes_test.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/_ctypes_test.c Wed Apr 30 15:57:13 2008 @@ -12,6 +12,15 @@ /* some functions handy for testing */ +EXPORT(void)testfunc_array(int values[4]) +{ + printf("testfunc_array %d %d %d %d\n", + values[0], + values[1], + values[2], + values[3]); +} + EXPORT(long double)testfunc_Ddd(double a, double b) { long double result = (long double)(a * b); @@ -398,7 +407,7 @@ return 0; } -PyMethodDef module_methods[] = { +static PyMethodDef module_methods[] = { /* {"get_last_tf_arg_s", get_last_tf_arg_s, METH_NOARGS}, {"get_last_tf_arg_u", get_last_tf_arg_u, METH_NOARGS}, */ Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/callbacks.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/callbacks.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/callbacks.c Wed Apr 30 15:57:13 2008 @@ -7,6 +7,73 @@ #endif #include "ctypes.h" +/**************************************************************/ + +static CThunkObject_dealloc(PyObject *_self) +{ + CThunkObject *self = (CThunkObject *)_self; + Py_XDECREF(self->converters); + Py_XDECREF(self->callable); + Py_XDECREF(self->restype); + if (self->pcl) + FreeClosure(self->pcl); + PyObject_Del(self); +} + +static int +CThunkObject_traverse(PyObject *_self, visitproc visit, void *arg) +{ + CThunkObject *self = (CThunkObject *)_self; + Py_VISIT(self->converters); + Py_VISIT(self->callable); + Py_VISIT(self->restype); + return 0; +} + +static int +CThunkObject_clear(PyObject *_self) +{ + CThunkObject *self = (CThunkObject *)_self; + Py_CLEAR(self->converters); + Py_CLEAR(self->callable); + Py_CLEAR(self->restype); + return 0; +} + +PyTypeObject CThunk_Type = { + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.CThunkObject", + sizeof(CThunkObject), /* tp_basicsize */ + sizeof(ffi_type), /* tp_itemsize */ + CThunkObject_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + "CThunkObject", /* tp_doc */ + CThunkObject_traverse, /* tp_traverse */ + CThunkObject_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ +}; + +/**************************************************************/ + static void PrintError(char *msg, ...) { @@ -244,32 +311,56 @@ void **args, void *userdata) { - ffi_info *p = userdata; + CThunkObject *p = (CThunkObject *)userdata; _CallPythonObject(resp, - p->restype, + p->ffi_restype, p->setfunc, p->callable, p->converters, args); } -ffi_info *AllocFunctionCallback(PyObject *callable, - PyObject *converters, - PyObject *restype, - int is_cdecl) +static CThunkObject* CThunkObject_new(Py_ssize_t nArgs) +{ + CThunkObject *p; + int i; + + p = PyObject_NewVar(CThunkObject, &CThunk_Type, nArgs); + if (p == NULL) { + PyErr_NoMemory(); + return NULL; + } + + p->pcl = NULL; + memset(&p->cif, 0, sizeof(p->cif)); + p->converters = NULL; + p->callable = NULL; + p->setfunc = NULL; + p->ffi_restype = NULL; + + for (i = 0; i < nArgs + 1; ++i) + p->atypes[i] = NULL; + return p; +} + +CThunkObject *AllocFunctionCallback(PyObject *callable, + PyObject *converters, + PyObject *restype, + int is_cdecl) { int result; - ffi_info *p; + CThunkObject *p; Py_ssize_t nArgs, i; ffi_abi cc; nArgs = PySequence_Size(converters); - p = (ffi_info *)PyMem_Malloc(sizeof(ffi_info) + sizeof(ffi_type) * (nArgs)); - if (p == NULL) { - PyErr_NoMemory(); + p = CThunkObject_new(nArgs); + if (p == NULL) return NULL; - } + + assert(CThunk_CheckExact((PyObject *)p)); + p->pcl = MallocClosure(); if (p->pcl == NULL) { PyErr_NoMemory(); @@ -285,9 +376,11 @@ } p->atypes[i] = NULL; + Py_INCREF(restype); + p->restype = restype; if (restype == Py_None) { p->setfunc = NULL; - p->restype = &ffi_type_void; + p->ffi_restype = &ffi_type_void; } else { StgDictObject *dict = PyType_stgdict(restype); if (dict == NULL || dict->setfunc == NULL) { @@ -296,7 +389,7 @@ goto error; } p->setfunc = dict->setfunc; - p->restype = &dict->ffi_type_pointer; + p->ffi_restype = &dict->ffi_type_pointer; } cc = FFI_DEFAULT_ABI; @@ -320,16 +413,14 @@ goto error; } + Py_INCREF(converters); p->converters = converters; + Py_INCREF(callable); p->callable = callable; return p; error: - if (p) { - if (p->pcl) - FreeClosure(p->pcl); - PyMem_Free(p); - } + Py_XDECREF(p); return NULL; } @@ -365,7 +456,7 @@ static PyObject *context; if (context == NULL) - context = PyUnicode_FromString("_ctypes.DllGetClassObject"); + context = PyUnicode_InternFromString("_ctypes.DllGetClassObject"); mod = PyImport_ImportModuleNoBlock("ctypes"); if (!mod) { @@ -444,7 +535,7 @@ static PyObject *context; if (context == NULL) - context = PyUnicode_FromString("_ctypes.DllCanUnloadNow"); + context = PyUnicode_InternFromString("_ctypes.DllCanUnloadNow"); mod = PyImport_ImportModuleNoBlock("ctypes"); if (!mod) { Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/callproc.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/callproc.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/callproc.c Wed Apr 30 15:57:13 2008 @@ -1568,8 +1568,100 @@ return Py_BuildValue("siN", dict->format, dict->ndim, shape); } +static PyObject * +unpickle(PyObject *self, PyObject *args) +{ + PyObject *typ; + PyObject *state; + PyObject *result; + PyObject *tmp; + + if (!PyArg_ParseTuple(args, "OO", &typ, &state)) + return NULL; + result = PyObject_CallMethod(typ, "__new__", "O", typ); + if (result == NULL) + return NULL; + tmp = PyObject_CallMethod(result, "__setstate__", "O", state); + if (tmp == NULL) { + Py_DECREF(result); + return NULL; + } + Py_DECREF(tmp); + return result; +} + +static PyObject * +POINTER(PyObject *self, PyObject *cls) +{ + PyObject *result; + PyTypeObject *typ; + PyObject *key; + char *buf; + + result = PyDict_GetItem(_pointer_type_cache, cls); + if (result) { + Py_INCREF(result); + return result; + } + if (PyUnicode_CheckExact(cls)) { + char *name = PyUnicode_AsString(cls); + buf = alloca(strlen(name) + 3 + 1); + sprintf(buf, "LP_%s", name); + result = PyObject_CallFunction((PyObject *)Py_TYPE(&Pointer_Type), + "s(O){}", + buf, + &Pointer_Type); + if (result == NULL) + return result; + key = PyLong_FromVoidPtr(result); + } else if (PyType_Check(cls)) { + typ = (PyTypeObject *)cls; + buf = alloca(strlen(typ->tp_name) + 3 + 1); + sprintf(buf, "LP_%s", typ->tp_name); + result = PyObject_CallFunction((PyObject *)Py_TYPE(&Pointer_Type), + "s(O){sO}", + buf, + &Pointer_Type, + "_type_", cls); + if (result == NULL) + return result; + Py_INCREF(cls); + key = cls; + } else { + PyErr_SetString(PyExc_TypeError, "must be a ctypes type"); + return NULL; + } + if (-1 == PyDict_SetItem(_pointer_type_cache, key, result)) { + Py_DECREF(result); + Py_DECREF(key); + return NULL; + } + Py_DECREF(key); + return result; +} + +static PyObject * +pointer(PyObject *self, PyObject *arg) +{ + PyObject *result; + PyObject *typ; + + typ = PyDict_GetItem(_pointer_type_cache, (PyObject *)Py_TYPE(arg)); + if (typ) + return PyObject_CallFunctionObjArgs(typ, arg, NULL); + typ = POINTER(NULL, (PyObject *)Py_TYPE(arg)); + if (typ == NULL) + return NULL; + result = PyObject_CallFunctionObjArgs(typ, arg, NULL); + Py_DECREF(typ); + return result; +} + PyMethodDef module_methods[] = { {"buffer_info", buffer_info, METH_O, "Return buffer interface information"}, + {"POINTER", POINTER, METH_O }, + {"pointer", pointer, METH_O }, + {"_unpickle", unpickle, METH_VARARGS }, {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"}, #ifdef CTYPES_UNICODE {"set_conversion_mode", set_conversion_mode, METH_VARARGS, set_conversion_mode_doc}, Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/cfield.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/cfield.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/cfield.c Wed Apr 30 15:57:13 2008 @@ -716,7 +716,7 @@ #endif static PyObject * -t_set(void *ptr, PyObject *value, Py_ssize_t size) +bool_set(void *ptr, PyObject *value, Py_ssize_t size) { switch (PyObject_IsTrue(value)) { case -1: @@ -731,7 +731,7 @@ } static PyObject * -t_get(void *ptr, Py_ssize_t size) +bool_get(void *ptr, Py_ssize_t size) { return PyBool_FromLong((long)*(BOOL_TYPE *)ptr); } @@ -1665,15 +1665,15 @@ { 'v', vBOOL_set, vBOOL_get, &ffi_type_sshort}, #endif #if SIZEOF__BOOL == 1 - { 't', t_set, t_get, &ffi_type_uchar}, /* Also fallback for no native _Bool support */ + { '?', bool_set, bool_get, &ffi_type_uchar}, /* Also fallback for no native _Bool support */ #elif SIZEOF__BOOL == SIZEOF_SHORT - { 't', t_set, t_get, &ffi_type_ushort}, + { '?', bool_set, bool_get, &ffi_type_ushort}, #elif SIZEOF__BOOL == SIZEOF_INT - { 't', t_set, t_get, &ffi_type_uint, I_set_sw, I_get_sw}, + { '?', bool_set, bool_get, &ffi_type_uint, I_set_sw, I_get_sw}, #elif SIZEOF__BOOL == SIZEOF_LONG - { 't', t_set, t_get, &ffi_type_ulong, L_set_sw, L_get_sw}, + { '?', bool_set, bool_get, &ffi_type_ulong, L_set_sw, L_get_sw}, #elif SIZEOF__BOOL == SIZEOF_LONG_LONG - { 't', t_set, t_get, &ffi_type_ulong, Q_set_sw, Q_get_sw}, + { '?', bool_set, bool_get, &ffi_type_ulong, Q_set_sw, Q_get_sw}, #endif /* SIZEOF__BOOL */ { 'O', O_set, O_get, &ffi_type_pointer}, { 0, NULL, NULL, NULL}, Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/ctypes.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/ctypes.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/ctypes.h Wed Apr 30 15:57:13 2008 @@ -53,14 +53,18 @@ }; typedef struct { + PyObject_VAR_HEAD ffi_closure *pcl; /* the C callable */ ffi_cif cif; PyObject *converters; PyObject *callable; + PyObject *restype; SETFUNC setfunc; - ffi_type *restype; + ffi_type *ffi_restype; ffi_type *atypes[1]; -} ffi_info; +} CThunkObject; +extern PyTypeObject CThunk_Type; +#define CThunk_CheckExact(v) ((v)->ob_type == &CThunk_Type) typedef struct { /* First part identical to tagCDataObject */ @@ -76,7 +80,7 @@ union value b_value; /* end of tagCDataObject, additional fields follow */ - ffi_info *thunk; + CThunkObject *thunk; PyObject *callable; /* These two fields will override the ones in the type's stgdict if @@ -147,10 +151,10 @@ extern PyMethodDef module_methods[]; -extern ffi_info *AllocFunctionCallback(PyObject *callable, - PyObject *converters, - PyObject *restype, - int stdcall); +extern CThunkObject *AllocFunctionCallback(PyObject *callable, + PyObject *converters, + PyObject *restype, + int stdcall); /* a table entry describing a predefined ctypes type */ struct fielddesc { char code; @@ -277,6 +281,9 @@ #define FUNCFLAG_HRESULT 0x2 #define FUNCFLAG_PYTHONAPI 0x4 +#define TYPEFLAG_ISPOINTER 0x100 +#define TYPEFLAG_HASPOINTER 0x200 + #define DICTFLAG_FINAL 0x1000 struct tagPyCArgObject { @@ -348,6 +355,7 @@ /* XXX better name needed! */ extern int IsSimpleSubType(PyObject *obj); +extern PyObject *_pointer_type_cache; #ifdef MS_WIN32 extern PyObject *ComError; Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/LICENSE ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/LICENSE (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/LICENSE Wed Apr 30 15:57:13 2008 @@ -1,4 +1,5 @@ -libffi - Copyright (c) 1996-2003 Red Hat, Inc. +libffi - Copyright (c) 1996-2008 Red Hat, Inc and others. +See source files for details. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the @@ -11,10 +12,10 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR -OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/README ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/README (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/README Wed Apr 30 15:57:13 2008 @@ -1,78 +1,67 @@ -This directory contains the libffi package, which is not part of GCC but -shipped with GCC as convenience. - Status ====== -libffi-2.00 has not been released yet! This is a development snapshot! - -libffi-1.20 was released on October 5, 1998. Check the libffi web -page for updates: . +libffi-3.0.5 was released on April 3, 2008. Check the libffi web +page for updates: . What is libffi? =============== Compilers for high level languages generate code that follow certain -conventions. These conventions are necessary, in part, for separate -compilation to work. One such convention is the "calling -convention". The "calling convention" is essentially a set of -assumptions made by the compiler about where function arguments will -be found on entry to a function. A "calling convention" also specifies -where the return value for a function is found. +conventions. These conventions are necessary, in part, for separate +compilation to work. One such convention is the "calling convention". +The "calling convention" is a set of assumptions made by the compiler +about where function arguments will be found on entry to a function. +A "calling convention" also specifies where the return value for a +function is found. Some programs may not know at the time of compilation what arguments -are to be passed to a function. For instance, an interpreter may be +are to be passed to a function. For instance, an interpreter may be told at run-time about the number and types of arguments used to call -a given function. Libffi can be used in such programs to provide a +a given function. Libffi can be used in such programs to provide a bridge from the interpreter program to compiled code. The libffi library provides a portable, high level programming -interface to various calling conventions. This allows a programmer to +interface to various calling conventions. This allows a programmer to call any function specified by a call interface description at run -time. +time. -Ffi stands for Foreign Function Interface. A foreign function +FFI stands for Foreign Function Interface. A foreign function interface is the popular name for the interface that allows code -written in one language to call code written in another language. The +written in one language to call code written in another language. The libffi library really only provides the lowest, machine dependent layer of a fully featured foreign function interface. A layer must exist above libffi that handles type conversions for values passed between the two languages. -Supported Platforms and Prerequisites -===================================== - -Libffi has been ported to: - - SunOS 4.1.3 & Solaris 2.x (SPARC-V8, SPARC-V9) - - Irix 5.3 & 6.2 (System V/o32 & n32) - - Intel x86 - Linux (System V ABI) - - Alpha - Linux and OSF/1 - - m68k - Linux (System V ABI) - - PowerPC - Linux (System V ABI, Darwin, AIX) +Supported Platforms +=================== - ARM - Linux (System V ABI) - -Libffi has been tested with the egcs 1.0.2 gcc compiler. Chances are -that other versions will work. Libffi has also been built and tested -with the SGI compiler tools. - -On PowerPC, the tests failed (see the note below). - -You must use GNU make to build libffi. SGI's make will not work. -Sun's probably won't either. - -If you port libffi to another platform, please let me know! I assume -that some will be easy (x86 NetBSD), and others will be more difficult -(HP). +Libffi has been ported to many different platforms, although this +release was only tested on: + arm oabi linux + arm eabi linux + hppa linux + mips o32 linux (little endian) + powerpc darwin + powerpc64 linux + sparc solaris + sparc64 solaris + x86 cygwin + x86 darwin + x86 freebsd + x86 linux + x86 openbsd + x86-64 darwin + x86-64 linux + x86-64 OS X + x86-64 freebsd + +Please send additional platform test results to +libffi-discuss at sourceware.org. Installing libffi ================= @@ -101,216 +90,17 @@ Configure has many other options. Use "configure --help" to see them all. Once configure has finished, type "make". Note that you must be using -GNU make. SGI's make will not work. Sun's probably won't either. -You can ftp GNU make from prep.ai.mit.edu:/pub/gnu. +GNU make. You can ftp GNU make from prep.ai.mit.edu:/pub/gnu. -To ensure that libffi is working as advertised, type "make test". +To ensure that libffi is working as advertised, type "make check". +This will require that you have DejaGNU installed. To install the library and header files, type "make install". -Using libffi -============ - - The Basics - ---------- - -Libffi assumes that you have a pointer to the function you wish to -call and that you know the number and types of arguments to pass it, -as well as the return type of the function. - -The first thing you must do is create an ffi_cif object that matches -the signature of the function you wish to call. The cif in ffi_cif -stands for Call InterFace. To prepare a call interface object, use the -following function: - -ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi, - unsigned int nargs, - ffi_type *rtype, ffi_type **atypes); - - CIF is a pointer to the call interface object you wish - to initialize. - - ABI is an enum that specifies the calling convention - to use for the call. FFI_DEFAULT_ABI defaults - to the system's native calling convention. Other - ABI's may be used with care. They are system - specific. - - NARGS is the number of arguments this function accepts. - libffi does not yet support vararg functions. - - RTYPE is a pointer to an ffi_type structure that represents - the return type of the function. Ffi_type objects - describe the types of values. libffi provides - ffi_type objects for many of the native C types: - signed int, unsigned int, signed char, unsigned char, - etc. There is also a pointer ffi_type object and - a void ffi_type. Use &ffi_type_void for functions that - don't return values. - - ATYPES is a vector of ffi_type pointers. ARGS must be NARGS long. - If NARGS is 0, this is ignored. - - -ffi_prep_cif will return a status code that you are responsible -for checking. It will be one of the following: - - FFI_OK - All is good. - - FFI_BAD_TYPEDEF - One of the ffi_type objects that ffi_prep_cif - came across is bad. - - -Before making the call, the VALUES vector should be initialized -with pointers to the appropriate argument values. - -To call the the function using the initialized ffi_cif, use the -ffi_call function: - -void ffi_call(ffi_cif *cif, void *fn, void *rvalue, void **avalues); - - CIF is a pointer to the ffi_cif initialized specifically - for this function. - - FN is a pointer to the function you want to call. - - RVALUE is a pointer to a chunk of memory that is to hold the - result of the function call. Currently, it must be - at least one word in size (except for the n32 version - under Irix 6.x, which must be a pointer to an 8 byte - aligned value (a long long). It must also be at least - word aligned (depending on the return type, and the - system's alignment requirements). If RTYPE is - &ffi_type_void, this is ignored. If RVALUE is NULL, - the return value is discarded. - - AVALUES is a vector of void* that point to the memory locations - holding the argument values for a call. - If NARGS is 0, this is ignored. - - -If you are expecting a return value from FN it will have been stored -at RVALUE. - - - - An Example - ---------- - -Here is a trivial example that calls puts() a few times. - - #include - #include - - int main() - { - ffi_cif cif; - ffi_type *args[1]; - void *values[1]; - char *s; - int rc; - - /* Initialize the argument info vectors */ - args[0] = &ffi_type_uint; - values[0] = &s; - - /* Initialize the cif */ - if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, - &ffi_type_uint, args) == FFI_OK) - { - s = "Hello World!"; - ffi_call(&cif, puts, &rc, values); - /* rc now holds the result of the call to puts */ - - /* values holds a pointer to the function's arg, so to - call puts() again all we need to do is change the - value of s */ - s = "This is cool!"; - ffi_call(&cif, puts, &rc, values); - } - - return 0; - } - - - - Aggregate Types - --------------- - -Although libffi has no special support for unions or bit-fields, it is -perfectly happy passing structures back and forth. You must first -describe the structure to libffi by creating a new ffi_type object -for it. Here is the definition of ffi_type: - - typedef struct _ffi_type - { - unsigned size; - short alignment; - short type; - struct _ffi_type **elements; - } ffi_type; - -All structures must have type set to FFI_TYPE_STRUCT. You may set -size and alignment to 0. These will be calculated and reset to the -appropriate values by ffi_prep_cif(). - -elements is a NULL terminated array of pointers to ffi_type objects -that describe the type of the structure elements. These may, in turn, -be structure elements. - -The following example initializes a ffi_type object representing the -tm struct from Linux's time.h: - - struct tm { - int tm_sec; - int tm_min; - int tm_hour; - int tm_mday; - int tm_mon; - int tm_year; - int tm_wday; - int tm_yday; - int tm_isdst; - /* Those are for future use. */ - long int __tm_gmtoff__; - __const char *__tm_zone__; - }; - - { - ffi_type tm_type; - ffi_type *tm_type_elements[12]; - int i; - - tm_type.size = tm_type.alignment = 0; - tm_type.elements = &tm_type_elements; - - for (i = 0; i < 9; i++) - tm_type_elements[i] = &ffi_type_sint; - - tm_type_elements[9] = &ffi_type_slong; - tm_type_elements[10] = &ffi_type_pointer; - tm_type_elements[11] = NULL; - - /* tm_type can now be used to represent tm argument types and - return types for ffi_prep_cif() */ - } - - - Platform Specific Notes ======================= - Intel x86 - --------- - -There are no known problems with the x86 port. - - Sun SPARC - SunOS 4.1.3 & Solaris 2.x - ------------------------------------- - -You must use GNU Make to build libffi on Sun platforms. - MIPS - Irix 5.3 & 6.x --------------------- @@ -339,13 +129,6 @@ You must use GNU Make to build libffi on SGI platforms. - ARM - System V ABI - ------------------ - -The ARM port was performed on a NetWinder running ARM Linux ELF -(2.0.31) and gcc 2.8.1. - - PowerPC System V ABI -------------------- @@ -372,18 +155,36 @@ arguments' test). -What's With The Crazy Comments? -=============================== - -You might notice a number of cryptic comments in the code, delimited -by /*@ and @*/. These are annotations read by the program LCLint, a -tool for statically checking C programs. You can read all about it at -. - - History ======= +3.0.5 Apr-3-08 + Fix libffi.pc file. + Fix #define ARM for IcedTea users. + Fix x86 closure bug. + +3.0.4 Feb-24-08 + Fix x86 OpenBSD configury. + +3.0.3 Feb-22-08 + Enable x86 OpenBSD thanks to Thomas Heller, and + x86-64 FreeBSD thanks to Bj??rn K??nig and Andreas Tobler. + Clean up test instruction in README. + +3.0.2 Feb-21-08 + Improved x86 FreeBSD support. + Thanks to Bj??rn K??nig. + +3.0.1 Feb-15-08 + Fix instruction cache flushing bug on MIPS. + Thanks to David Daney. + +3.0.0 Feb-15-08 + Many changes, mostly thanks to the GCC project. + Cygnus Solutions is now Red Hat. + + [10 years go by...] + 1.20 Oct-5-98 Raffaele Sena produces ARM port. @@ -467,34 +268,56 @@ Authors & Credits ================= -libffi was written by Anthony Green . +libffi was originally written by Anthony Green . + +The developers of the GNU Compiler Collection project have made +innumerable valuable contributions. See the ChangeLog file for +details. -Portions of libffi were derived from Gianni Mariani's free gencall -library for Silicon Graphics machines. +Some of the ideas behind libffi were inspired by Gianni Mariani's free +gencall library for Silicon Graphics machines. The closure mechanism was designed and implemented by Kresten Krab Thorup. -The Sparc port was derived from code contributed by the fine folks at -Visible Decisions Inc . Further enhancements were -made by Gordon Irlam at Cygnus Solutions . - -The Alpha port was written by Richard Henderson at Cygnus Solutions. - -Andreas Schwab ported libffi to m68k Linux and provided a number of -bug fixes. +Major processor architecture ports were contributed by the following +developers: -Geoffrey Keating ported libffi to the PowerPC. - -Raffaele Sena ported libffi to the ARM. +alpha Richard Henderson +arm Raffaele Sena +cris Simon Posnjak, Hans-Peter Nilsson +frv Anthony Green +ia64 Hans Boehm +m32r Kazuhiro Inaoka +m68k Andreas Schwab +mips Anthony Green, Casey Marshall +mips64 David Daney +pa Randolph Chung, Dave Anglin, Andreas Tobler +powerpc Geoffrey Keating, Andreas Tobler, + David Edelsohn, John Hornkvist +powerpc64 Jakub Jelinek +s390 Gerhard Tonn, Ulrich Weigand +sh Kaz Kojima +sh64 Kaz Kojima +sparc Anthony Green, Gordon Irlam +x86 Anthony Green, Jon Beniston +x86-64 Bo Thorsen Jesper Skov and Andrew Haley both did more than their fair share of stepping through the code and tracking down bugs. -Thanks also to Tom Tromey for bug fixes and configuration help. +Thanks also to Tom Tromey for bug fixes, documentation and +configuration help. Thanks to Jim Blandy, who provided some useful feedback on the libffi interface. +Andreas Tobler has done a tremendous amount of work on the testsuite. + +Alex Oliva solved the executable page problem for SElinux. + +The list above is almost certainly incomplete and inaccurate. I'm +happy to make corrections or additions upon request. + If you have a problem, or have found a bug, please send a note to -green at cygnus.com. +green at redhat.com. Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/aclocal.m4 ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/aclocal.m4 (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/aclocal.m4 Wed Apr 30 15:57:13 2008 @@ -1,92 +1,7516 @@ -# mmap(2) blacklisting. Some platforms provide the mmap library routine -# but don't support all of the features we need from it. -AC_DEFUN([AC_FUNC_MMAP_BLACKLIST], +# generated automatically by aclocal 1.10 -*- Autoconf -*- + +# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, +# 2005, 2006 Free Software Foundation, Inc. +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +m4_if(m4_PACKAGE_VERSION, [2.61],, +[m4_fatal([this file was generated for autoconf 2.61. +You have another version of autoconf. If you want to use that, +you should regenerate the build system entirely.], [63])]) + +# libtool.m4 - Configure libtool for the host system. -*-Autoconf-*- + +# serial 51 AC_PROG_LIBTOOL + + +# AC_PROVIDE_IFELSE(MACRO-NAME, IF-PROVIDED, IF-NOT-PROVIDED) +# ----------------------------------------------------------- +# If this macro is not defined by Autoconf, define it here. +m4_ifdef([AC_PROVIDE_IFELSE], + [], + [m4_define([AC_PROVIDE_IFELSE], + [m4_ifdef([AC_PROVIDE_$1], + [$2], [$3])])]) + + +# AC_PROG_LIBTOOL +# --------------- +AC_DEFUN([AC_PROG_LIBTOOL], +[AC_REQUIRE([_AC_PROG_LIBTOOL])dnl +dnl If AC_PROG_CXX has already been expanded, run AC_LIBTOOL_CXX +dnl immediately, otherwise, hook it in at the end of AC_PROG_CXX. + AC_PROVIDE_IFELSE([AC_PROG_CXX], + [AC_LIBTOOL_CXX], + [define([AC_PROG_CXX], defn([AC_PROG_CXX])[AC_LIBTOOL_CXX + ])]) +dnl And a similar setup for Fortran 77 support + AC_PROVIDE_IFELSE([AC_PROG_F77], + [AC_LIBTOOL_F77], + [define([AC_PROG_F77], defn([AC_PROG_F77])[AC_LIBTOOL_F77 +])]) + +dnl Quote A][M_PROG_GCJ so that aclocal doesn't bring it in needlessly. +dnl If either AC_PROG_GCJ or A][M_PROG_GCJ have already been expanded, run +dnl AC_LIBTOOL_GCJ immediately, otherwise, hook it in at the end of both. + AC_PROVIDE_IFELSE([AC_PROG_GCJ], + [AC_LIBTOOL_GCJ], + [AC_PROVIDE_IFELSE([A][M_PROG_GCJ], + [AC_LIBTOOL_GCJ], + [AC_PROVIDE_IFELSE([LT_AC_PROG_GCJ], + [AC_LIBTOOL_GCJ], + [ifdef([AC_PROG_GCJ], + [define([AC_PROG_GCJ], defn([AC_PROG_GCJ])[AC_LIBTOOL_GCJ])]) + ifdef([A][M_PROG_GCJ], + [define([A][M_PROG_GCJ], defn([A][M_PROG_GCJ])[AC_LIBTOOL_GCJ])]) + ifdef([LT_AC_PROG_GCJ], + [define([LT_AC_PROG_GCJ], + defn([LT_AC_PROG_GCJ])[AC_LIBTOOL_GCJ])])])]) +])])# AC_PROG_LIBTOOL + + +# _AC_PROG_LIBTOOL +# ---------------- +AC_DEFUN([_AC_PROG_LIBTOOL], +[AC_REQUIRE([AC_LIBTOOL_SETUP])dnl +AC_BEFORE([$0],[AC_LIBTOOL_CXX])dnl +AC_BEFORE([$0],[AC_LIBTOOL_F77])dnl +AC_BEFORE([$0],[AC_LIBTOOL_GCJ])dnl + +# This can be used to rebuild libtool when needed +LIBTOOL_DEPS="$ac_aux_dir/ltmain.sh" + +# Always use our own libtool. +LIBTOOL='$(SHELL) $(top_builddir)/libtool' +AC_SUBST(LIBTOOL)dnl + +# Prevent multiple expansion +define([AC_PROG_LIBTOOL], []) +])# _AC_PROG_LIBTOOL + + +# AC_LIBTOOL_SETUP +# ---------------- +AC_DEFUN([AC_LIBTOOL_SETUP], +[AC_PREREQ(2.50)dnl +AC_REQUIRE([AC_ENABLE_SHARED])dnl +AC_REQUIRE([AC_ENABLE_STATIC])dnl +AC_REQUIRE([AC_ENABLE_FAST_INSTALL])dnl +AC_REQUIRE([AC_CANONICAL_HOST])dnl +AC_REQUIRE([AC_CANONICAL_BUILD])dnl +AC_REQUIRE([AC_PROG_CC])dnl +AC_REQUIRE([AC_PROG_LD])dnl +AC_REQUIRE([AC_PROG_LD_RELOAD_FLAG])dnl +AC_REQUIRE([AC_PROG_NM])dnl + +AC_REQUIRE([AC_PROG_LN_S])dnl +AC_REQUIRE([AC_DEPLIBS_CHECK_METHOD])dnl +# Autoconf 2.13's AC_OBJEXT and AC_EXEEXT macros only works for C compilers! +AC_REQUIRE([AC_OBJEXT])dnl +AC_REQUIRE([AC_EXEEXT])dnl +dnl + +AC_LIBTOOL_SYS_MAX_CMD_LEN +AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE +AC_LIBTOOL_OBJDIR + +AC_REQUIRE([_LT_AC_SYS_COMPILER])dnl +_LT_AC_PROG_ECHO_BACKSLASH + +case $host_os in +aix3*) + # AIX sometimes has problems with the GCC collect2 program. For some + # reason, if we set the COLLECT_NAMES environment variable, the problems + # vanish in a puff of smoke. + if test "X${COLLECT_NAMES+set}" != Xset; then + COLLECT_NAMES= + export COLLECT_NAMES + fi + ;; +esac + +# Sed substitution that helps us do robust quoting. It backslashifies +# metacharacters that are still active within double-quoted strings. +Xsed='sed -e 1s/^X//' +[sed_quote_subst='s/\([\\"\\`$\\\\]\)/\\\1/g'] + +# Same as above, but do not quote variable references. +[double_quote_subst='s/\([\\"\\`\\\\]\)/\\\1/g'] + +# Sed substitution to delay expansion of an escaped shell variable in a +# double_quote_subst'ed string. +delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' + +# Sed substitution to avoid accidental globbing in evaled expressions +no_glob_subst='s/\*/\\\*/g' + +# Constants: +rm="rm -f" + +# Global variables: +default_ofile=libtool +can_build_shared=yes + +# All known linkers require a `.a' archive for static linking (except MSVC, +# which needs '.lib'). +libext=a +ltmain="$ac_aux_dir/ltmain.sh" +ofile="$default_ofile" +with_gnu_ld="$lt_cv_prog_gnu_ld" + +AC_CHECK_TOOL(AR, ar, false) +AC_CHECK_TOOL(RANLIB, ranlib, :) +AC_CHECK_TOOL(STRIP, strip, :) + +old_CC="$CC" +old_CFLAGS="$CFLAGS" + +# Set sane defaults for various variables +test -z "$AR" && AR=ar +test -z "$AR_FLAGS" && AR_FLAGS=cru +test -z "$AS" && AS=as +test -z "$CC" && CC=cc +test -z "$LTCC" && LTCC=$CC +test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS +test -z "$DLLTOOL" && DLLTOOL=dlltool +test -z "$LD" && LD=ld +test -z "$LN_S" && LN_S="ln -s" +test -z "$MAGIC_CMD" && MAGIC_CMD=file +test -z "$NM" && NM=nm +test -z "$SED" && SED=sed +test -z "$OBJDUMP" && OBJDUMP=objdump +test -z "$RANLIB" && RANLIB=: +test -z "$STRIP" && STRIP=: +test -z "$ac_objext" && ac_objext=o + +# Determine commands to create old-style static archives. +old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs' +old_postinstall_cmds='chmod 644 $oldlib' +old_postuninstall_cmds= + +if test -n "$RANLIB"; then + case $host_os in + openbsd*) + old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$oldlib" + ;; + *) + old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$oldlib" + ;; + esac + old_archive_cmds="$old_archive_cmds~\$RANLIB \$oldlib" +fi + +_LT_CC_BASENAME([$compiler]) + +# Only perform the check for file, if the check method requires it +case $deplibs_check_method in +file_magic*) + if test "$file_magic_cmd" = '$MAGIC_CMD'; then + AC_PATH_MAGIC + fi + ;; +esac + +AC_PROVIDE_IFELSE([AC_LIBTOOL_DLOPEN], enable_dlopen=yes, enable_dlopen=no) +AC_PROVIDE_IFELSE([AC_LIBTOOL_WIN32_DLL], +enable_win32_dll=yes, enable_win32_dll=no) + +AC_ARG_ENABLE([libtool-lock], + [AC_HELP_STRING([--disable-libtool-lock], + [avoid locking (might break parallel builds)])]) +test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes + +AC_ARG_WITH([pic], + [AC_HELP_STRING([--with-pic], + [try to use only PIC/non-PIC objects @<:@default=use both@:>@])], + [pic_mode="$withval"], + [pic_mode=default]) +test -z "$pic_mode" && pic_mode=default + +# Use C for the default configuration in the libtool script +tagname= +AC_LIBTOOL_LANG_C_CONFIG +_LT_AC_TAGCONFIG +])# AC_LIBTOOL_SETUP + + +# _LT_AC_SYS_COMPILER +# ------------------- +AC_DEFUN([_LT_AC_SYS_COMPILER], +[AC_REQUIRE([AC_PROG_CC])dnl + +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} + +# If no C compiler flags were specified, use CFLAGS. +LTCFLAGS=${LTCFLAGS-"$CFLAGS"} + +# Allow CC to be a program name with arguments. +compiler=$CC +])# _LT_AC_SYS_COMPILER + + +# _LT_CC_BASENAME(CC) +# ------------------- +# Calculate cc_basename. Skip known compiler wrappers and cross-prefix. +AC_DEFUN([_LT_CC_BASENAME], +[for cc_temp in $1""; do + case $cc_temp in + compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;; + distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;; + \-*) ;; + *) break;; + esac +done +cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"` +]) + + +# _LT_COMPILER_BOILERPLATE +# ------------------------ +# Check for compiler boilerplate output or warnings with +# the simple compiler test code. +AC_DEFUN([_LT_COMPILER_BOILERPLATE], +[AC_REQUIRE([LT_AC_PROG_SED])dnl +ac_outfile=conftest.$ac_objext +echo "$lt_simple_compile_test_code" >conftest.$ac_ext +eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_compiler_boilerplate=`cat conftest.err` +$rm conftest* +])# _LT_COMPILER_BOILERPLATE + + +# _LT_LINKER_BOILERPLATE +# ---------------------- +# Check for linker boilerplate output or warnings with +# the simple link test code. +AC_DEFUN([_LT_LINKER_BOILERPLATE], +[AC_REQUIRE([LT_AC_PROG_SED])dnl +ac_outfile=conftest.$ac_objext +echo "$lt_simple_link_test_code" >conftest.$ac_ext +eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_linker_boilerplate=`cat conftest.err` +$rm conftest* +])# _LT_LINKER_BOILERPLATE + + +# _LT_AC_SYS_LIBPATH_AIX +# ---------------------- +# Links a minimal program and checks the executable +# for the system default hardcoded library path. In most cases, +# this is /usr/lib:/lib, but when the MPI compilers are used +# the location of the communication and MPI libs are included too. +# If we don't find anything, use the default library path according +# to the aix ld manual. +AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX], +[AC_REQUIRE([LT_AC_PROG_SED])dnl +AC_LINK_IFELSE(AC_LANG_PROGRAM,[ +lt_aix_libpath_sed=' + /Import File Strings/,/^$/ { + /^0/ { + s/^0 *\(.*\)$/\1/ + p + } + }' +aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +# Check for a 64-bit object if we didn't find anything. +if test -z "$aix_libpath"; then + aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +fi],[]) +if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi +])# _LT_AC_SYS_LIBPATH_AIX + + +# _LT_AC_SHELL_INIT(ARG) +# ---------------------- +AC_DEFUN([_LT_AC_SHELL_INIT], +[ifdef([AC_DIVERSION_NOTICE], + [AC_DIVERT_PUSH(AC_DIVERSION_NOTICE)], + [AC_DIVERT_PUSH(NOTICE)]) +$1 +AC_DIVERT_POP +])# _LT_AC_SHELL_INIT + + +# _LT_AC_PROG_ECHO_BACKSLASH +# -------------------------- +# Add some code to the start of the generated configure script which +# will find an echo command which doesn't interpret backslashes. +AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH], +[_LT_AC_SHELL_INIT([ +# Check that we are running under the correct shell. +SHELL=${CONFIG_SHELL-/bin/sh} + +case X$ECHO in +X*--fallback-echo) + # Remove one level of quotation (which was required for Make). + ECHO=`echo "$ECHO" | sed 's,\\\\\[$]\\[$]0,'[$]0','` + ;; +esac + +echo=${ECHO-echo} +if test "X[$]1" = X--no-reexec; then + # Discard the --no-reexec flag, and continue. + shift +elif test "X[$]1" = X--fallback-echo; then + # Avoid inline document here, it may be left over + : +elif test "X`($echo '\t') 2>/dev/null`" = 'X\t' ; then + # Yippee, $echo works! + : +else + # Restart under the correct shell. + exec $SHELL "[$]0" --no-reexec ${1+"[$]@"} +fi + +if test "X[$]1" = X--fallback-echo; then + # used as fallback echo + shift + cat </dev/null 2>&1 && unset CDPATH + +if test -z "$ECHO"; then +if test "X${echo_test_string+set}" != Xset; then +# find a string as large as possible, as long as the shell can cope with it + for cmd in 'sed 50q "[$]0"' 'sed 20q "[$]0"' 'sed 10q "[$]0"' 'sed 2q "[$]0"' 'echo test'; do + # expected sizes: less than 2Kb, 1Kb, 512 bytes, 16 bytes, ... + if (echo_test_string=`eval $cmd`) 2>/dev/null && + echo_test_string=`eval $cmd` && + (test "X$echo_test_string" = "X$echo_test_string") 2>/dev/null + then + break + fi + done +fi + +if test "X`($echo '\t') 2>/dev/null`" = 'X\t' && + echo_testing_string=`($echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + : +else + # The Solaris, AIX, and Digital Unix default echo programs unquote + # backslashes. This makes it impossible to quote backslashes using + # echo "$something" | sed 's/\\/\\\\/g' + # + # So, first we look for a working echo in the user's PATH. + + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + for dir in $PATH /usr/ucb; do + IFS="$lt_save_ifs" + if (test -f $dir/echo || test -f $dir/echo$ac_exeext) && + test "X`($dir/echo '\t') 2>/dev/null`" = 'X\t' && + echo_testing_string=`($dir/echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + echo="$dir/echo" + break + fi + done + IFS="$lt_save_ifs" + + if test "X$echo" = Xecho; then + # We didn't find a better echo, so look for alternatives. + if test "X`(print -r '\t') 2>/dev/null`" = 'X\t' && + echo_testing_string=`(print -r "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + # This shell has a builtin print -r that does the trick. + echo='print -r' + elif (test -f /bin/ksh || test -f /bin/ksh$ac_exeext) && + test "X$CONFIG_SHELL" != X/bin/ksh; then + # If we have ksh, try running configure again with it. + ORIGINAL_CONFIG_SHELL=${CONFIG_SHELL-/bin/sh} + export ORIGINAL_CONFIG_SHELL + CONFIG_SHELL=/bin/ksh + export CONFIG_SHELL + exec $CONFIG_SHELL "[$]0" --no-reexec ${1+"[$]@"} + else + # Try using printf. + echo='printf %s\n' + if test "X`($echo '\t') 2>/dev/null`" = 'X\t' && + echo_testing_string=`($echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + # Cool, printf works + : + elif echo_testing_string=`($ORIGINAL_CONFIG_SHELL "[$]0" --fallback-echo '\t') 2>/dev/null` && + test "X$echo_testing_string" = 'X\t' && + echo_testing_string=`($ORIGINAL_CONFIG_SHELL "[$]0" --fallback-echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + CONFIG_SHELL=$ORIGINAL_CONFIG_SHELL + export CONFIG_SHELL + SHELL="$CONFIG_SHELL" + export SHELL + echo="$CONFIG_SHELL [$]0 --fallback-echo" + elif echo_testing_string=`($CONFIG_SHELL "[$]0" --fallback-echo '\t') 2>/dev/null` && + test "X$echo_testing_string" = 'X\t' && + echo_testing_string=`($CONFIG_SHELL "[$]0" --fallback-echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + echo="$CONFIG_SHELL [$]0 --fallback-echo" + else + # maybe with a smaller string... + prev=: + + for cmd in 'echo test' 'sed 2q "[$]0"' 'sed 10q "[$]0"' 'sed 20q "[$]0"' 'sed 50q "[$]0"'; do + if (test "X$echo_test_string" = "X`eval $cmd`") 2>/dev/null + then + break + fi + prev="$cmd" + done + + if test "$prev" != 'sed 50q "[$]0"'; then + echo_test_string=`eval $prev` + export echo_test_string + exec ${ORIGINAL_CONFIG_SHELL-${CONFIG_SHELL-/bin/sh}} "[$]0" ${1+"[$]@"} + else + # Oops. We lost completely, so just stick with echo. + echo=echo + fi + fi + fi + fi +fi +fi + +# Copy echo and quote the copy suitably for passing to libtool from +# the Makefile, instead of quoting the original, which is used later. +ECHO=$echo +if test "X$ECHO" = "X$CONFIG_SHELL [$]0 --fallback-echo"; then + ECHO="$CONFIG_SHELL \\\$\[$]0 --fallback-echo" +fi + +AC_SUBST(ECHO) +])])# _LT_AC_PROG_ECHO_BACKSLASH + + +# _LT_AC_LOCK +# ----------- +AC_DEFUN([_LT_AC_LOCK], +[AC_ARG_ENABLE([libtool-lock], + [AC_HELP_STRING([--disable-libtool-lock], + [avoid locking (might break parallel builds)])]) +test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes + +# Some flags need to be propagated to the compiler or linker for good +# libtool support. +case $host in +ia64-*-hpux*) + # Find out which ABI we are using. + echo 'int i;' > conftest.$ac_ext + if AC_TRY_EVAL(ac_compile); then + case `/usr/bin/file conftest.$ac_objext` in + *ELF-32*) + HPUX_IA64_MODE="32" + ;; + *ELF-64*) + HPUX_IA64_MODE="64" + ;; + esac + fi + rm -rf conftest* + ;; +*-*-irix6*) + # Find out which ABI we are using. + echo '[#]line __oline__ "configure"' > conftest.$ac_ext + if AC_TRY_EVAL(ac_compile); then + if test "$lt_cv_prog_gnu_ld" = yes; then + case `/usr/bin/file conftest.$ac_objext` in + *32-bit*) + LD="${LD-ld} -melf32bsmip" + ;; + *N32*) + LD="${LD-ld} -melf32bmipn32" + ;; + *64-bit*) + LD="${LD-ld} -melf64bmip" + ;; + esac + else + case `/usr/bin/file conftest.$ac_objext` in + *32-bit*) + LD="${LD-ld} -32" + ;; + *N32*) + LD="${LD-ld} -n32" + ;; + *64-bit*) + LD="${LD-ld} -64" + ;; + esac + fi + fi + rm -rf conftest* + ;; + +x86_64-*kfreebsd*-gnu|x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*| \ +s390*-*linux*|sparc*-*linux*) + # Find out which ABI we are using. + echo 'int i;' > conftest.$ac_ext + if AC_TRY_EVAL(ac_compile); then + case `/usr/bin/file conftest.o` in + *32-bit*) + case $host in + x86_64-*kfreebsd*-gnu) + LD="${LD-ld} -m elf_i386_fbsd" + ;; + x86_64-*linux*) + LD="${LD-ld} -m elf_i386" + ;; + ppc64-*linux*|powerpc64-*linux*) + LD="${LD-ld} -m elf32ppclinux" + ;; + s390x-*linux*) + LD="${LD-ld} -m elf_s390" + ;; + sparc64-*linux*) + LD="${LD-ld} -m elf32_sparc" + ;; + esac + ;; + *64-bit*) + libsuff=64 + case $host in + x86_64-*kfreebsd*-gnu) + LD="${LD-ld} -m elf_x86_64_fbsd" + ;; + x86_64-*linux*) + LD="${LD-ld} -m elf_x86_64" + ;; + ppc*-*linux*|powerpc*-*linux*) + LD="${LD-ld} -m elf64ppc" + ;; + s390*-*linux*) + LD="${LD-ld} -m elf64_s390" + ;; + sparc*-*linux*) + LD="${LD-ld} -m elf64_sparc" + ;; + esac + ;; + esac + fi + rm -rf conftest* + ;; + +*-*-sco3.2v5*) + # On SCO OpenServer 5, we need -belf to get full-featured binaries. + SAVE_CFLAGS="$CFLAGS" + CFLAGS="$CFLAGS -belf" + AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf, + [AC_LANG_PUSH(C) + AC_TRY_LINK([],[],[lt_cv_cc_needs_belf=yes],[lt_cv_cc_needs_belf=no]) + AC_LANG_POP]) + if test x"$lt_cv_cc_needs_belf" != x"yes"; then + # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf + CFLAGS="$SAVE_CFLAGS" + fi + ;; +sparc*-*solaris*) + # Find out which ABI we are using. + echo 'int i;' > conftest.$ac_ext + if AC_TRY_EVAL(ac_compile); then + case `/usr/bin/file conftest.o` in + *64-bit*) + case $lt_cv_prog_gnu_ld in + yes*) LD="${LD-ld} -m elf64_sparc" ;; + *) LD="${LD-ld} -64" ;; + esac + ;; + esac + fi + rm -rf conftest* + ;; + +AC_PROVIDE_IFELSE([AC_LIBTOOL_WIN32_DLL], +[*-*-cygwin* | *-*-mingw* | *-*-pw32*) + AC_CHECK_TOOL(DLLTOOL, dlltool, false) + AC_CHECK_TOOL(AS, as, false) + AC_CHECK_TOOL(OBJDUMP, objdump, false) + ;; + ]) +esac + +need_locks="$enable_libtool_lock" + +])# _LT_AC_LOCK + + +# AC_LIBTOOL_COMPILER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS, +# [OUTPUT-FILE], [ACTION-SUCCESS], [ACTION-FAILURE]) +# ---------------------------------------------------------------- +# Check whether the given compiler option works +AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION], +[AC_REQUIRE([LT_AC_PROG_SED]) +AC_CACHE_CHECK([$1], [$2], + [$2=no + ifelse([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4]) + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="$3" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&AS_MESSAGE_LOG_FD + echo "$as_me:__oline__: \$? = $ac_status" >&AS_MESSAGE_LOG_FD + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings other than the usual output. + $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then + $2=yes + fi + fi + $rm conftest* +]) + +if test x"[$]$2" = xyes; then + ifelse([$5], , :, [$5]) +else + ifelse([$6], , :, [$6]) +fi +])# AC_LIBTOOL_COMPILER_OPTION + + +# AC_LIBTOOL_LINKER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS, +# [ACTION-SUCCESS], [ACTION-FAILURE]) +# ------------------------------------------------------------ +# Check whether the given compiler option works +AC_DEFUN([AC_LIBTOOL_LINKER_OPTION], +[AC_REQUIRE([LT_AC_PROG_SED])dnl +AC_CACHE_CHECK([$1], [$2], + [$2=no + save_LDFLAGS="$LDFLAGS" + LDFLAGS="$LDFLAGS $3" + echo "$lt_simple_link_test_code" > conftest.$ac_ext + if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then + # The linker can only warn and ignore the option if not recognized + # So say no if there are warnings + if test -s conftest.err; then + # Append any errors to the config.log. + cat conftest.err 1>&AS_MESSAGE_LOG_FD + $echo "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if diff conftest.exp conftest.er2 >/dev/null; then + $2=yes + fi + else + $2=yes + fi + fi + $rm conftest* + LDFLAGS="$save_LDFLAGS" +]) + +if test x"[$]$2" = xyes; then + ifelse([$4], , :, [$4]) +else + ifelse([$5], , :, [$5]) +fi +])# AC_LIBTOOL_LINKER_OPTION + + +# AC_LIBTOOL_SYS_MAX_CMD_LEN +# -------------------------- +AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN], +[# find the maximum length of command line arguments +AC_MSG_CHECKING([the maximum length of command line arguments]) +AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl + i=0 + teststring="ABCD" + + case $build_os in + msdosdjgpp*) + # On DJGPP, this test can blow up pretty badly due to problems in libc + # (any single argument exceeding 2000 bytes causes a buffer overrun + # during glob expansion). Even if it were fixed, the result of this + # check would be larger than it should be. + lt_cv_sys_max_cmd_len=12288; # 12K is about right + ;; + + gnu*) + # Under GNU Hurd, this test is not required because there is + # no limit to the length of command line arguments. + # Libtool will interpret -1 as no limit whatsoever + lt_cv_sys_max_cmd_len=-1; + ;; + + cygwin* | mingw*) + # On Win9x/ME, this test blows up -- it succeeds, but takes + # about 5 minutes as the teststring grows exponentially. + # Worse, since 9x/ME are not pre-emptively multitasking, + # you end up with a "frozen" computer, even though with patience + # the test eventually succeeds (with a max line length of 256k). + # Instead, let's just punt: use the minimum linelength reported by + # all of the supported platforms: 8192 (on NT/2K/XP). + lt_cv_sys_max_cmd_len=8192; + ;; + + amigaos*) + # On AmigaOS with pdksh, this test takes hours, literally. + # So we just punt and use a minimum line length of 8192. + lt_cv_sys_max_cmd_len=8192; + ;; + + netbsd* | freebsd* | openbsd* | darwin* | dragonfly*) + # This has been around since 386BSD, at least. Likely further. + if test -x /sbin/sysctl; then + lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` + elif test -x /usr/sbin/sysctl; then + lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax` + else + lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs + fi + # And add a safety zone + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` + ;; + + interix*) + # We know the value 262144 and hardcode it with a safety zone (like BSD) + lt_cv_sys_max_cmd_len=196608 + ;; + + osf*) + # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure + # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not + # nice to cause kernel panics so lets avoid the loop below. + # First set a reasonable default. + lt_cv_sys_max_cmd_len=16384 + # + if test -x /sbin/sysconfig; then + case `/sbin/sysconfig -q proc exec_disable_arg_limit` in + *1*) lt_cv_sys_max_cmd_len=-1 ;; + esac + fi + ;; + sco3.2v5*) + lt_cv_sys_max_cmd_len=102400 + ;; + sysv5* | sco5v6* | sysv4.2uw2*) + kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null` + if test -n "$kargmax"; then + lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[[ ]]//'` + else + lt_cv_sys_max_cmd_len=32768 + fi + ;; + *) + lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null` + if test -n "$lt_cv_sys_max_cmd_len"; then + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` + else + SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}} + while (test "X"`$SHELL [$]0 --fallback-echo "X$teststring" 2>/dev/null` \ + = "XX$teststring") >/dev/null 2>&1 && + new_result=`expr "X$teststring" : ".*" 2>&1` && + lt_cv_sys_max_cmd_len=$new_result && + test $i != 17 # 1/2 MB should be enough + do + i=`expr $i + 1` + teststring=$teststring$teststring + done + teststring= + # Add a significant safety factor because C++ compilers can tack on massive + # amounts of additional arguments before passing them to the linker. + # It appears as though 1/2 is a usable value. + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` + fi + ;; + esac +]) +if test -n $lt_cv_sys_max_cmd_len ; then + AC_MSG_RESULT($lt_cv_sys_max_cmd_len) +else + AC_MSG_RESULT(none) +fi +])# AC_LIBTOOL_SYS_MAX_CMD_LEN + + +# _LT_AC_CHECK_DLFCN +# ------------------ +AC_DEFUN([_LT_AC_CHECK_DLFCN], +[AC_CHECK_HEADERS(dlfcn.h)dnl +])# _LT_AC_CHECK_DLFCN + + +# _LT_AC_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE, +# ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING) +# --------------------------------------------------------------------- +AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF], +[AC_REQUIRE([_LT_AC_CHECK_DLFCN])dnl +if test "$cross_compiling" = yes; then : + [$4] +else + lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 + lt_status=$lt_dlunknown + cat > conftest.$ac_ext < +#endif + +#include + +#ifdef RTLD_GLOBAL +# define LT_DLGLOBAL RTLD_GLOBAL +#else +# ifdef DL_GLOBAL +# define LT_DLGLOBAL DL_GLOBAL +# else +# define LT_DLGLOBAL 0 +# endif +#endif + +/* We may have to define LT_DLLAZY_OR_NOW in the command line if we + find out it does not work in some platform. */ +#ifndef LT_DLLAZY_OR_NOW +# ifdef RTLD_LAZY +# define LT_DLLAZY_OR_NOW RTLD_LAZY +# else +# ifdef DL_LAZY +# define LT_DLLAZY_OR_NOW DL_LAZY +# else +# ifdef RTLD_NOW +# define LT_DLLAZY_OR_NOW RTLD_NOW +# else +# ifdef DL_NOW +# define LT_DLLAZY_OR_NOW DL_NOW +# else +# define LT_DLLAZY_OR_NOW 0 +# endif +# endif +# endif +# endif +#endif + +#ifdef __cplusplus +extern "C" void exit (int); +#endif + +void fnord() { int i=42;} +int main () +{ + void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); + int status = $lt_dlunknown; + + if (self) + { + if (dlsym (self,"fnord")) status = $lt_dlno_uscore; + else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; + /* dlclose (self); */ + } + else + puts (dlerror ()); + + exit (status); +}] +EOF + if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext} 2>/dev/null; then + (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null + lt_status=$? + case x$lt_status in + x$lt_dlno_uscore) $1 ;; + x$lt_dlneed_uscore) $2 ;; + x$lt_dlunknown|x*) $3 ;; + esac + else : + # compilation failed + $3 + fi +fi +rm -fr conftest* +])# _LT_AC_TRY_DLOPEN_SELF + + +# AC_LIBTOOL_DLOPEN_SELF +# ---------------------- +AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF], +[AC_REQUIRE([_LT_AC_CHECK_DLFCN])dnl +if test "x$enable_dlopen" != xyes; then + enable_dlopen=unknown + enable_dlopen_self=unknown + enable_dlopen_self_static=unknown +else + lt_cv_dlopen=no + lt_cv_dlopen_libs= + + case $host_os in + beos*) + lt_cv_dlopen="load_add_on" + lt_cv_dlopen_libs= + lt_cv_dlopen_self=yes + ;; + + mingw* | pw32*) + lt_cv_dlopen="LoadLibrary" + lt_cv_dlopen_libs= + ;; + + cygwin*) + lt_cv_dlopen="dlopen" + lt_cv_dlopen_libs= + ;; + + darwin*) + # if libdl is installed we need to link against it + AC_CHECK_LIB([dl], [dlopen], + [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],[ + lt_cv_dlopen="dyld" + lt_cv_dlopen_libs= + lt_cv_dlopen_self=yes + ]) + ;; + + *) + AC_CHECK_FUNC([shl_load], + [lt_cv_dlopen="shl_load"], + [AC_CHECK_LIB([dld], [shl_load], + [lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-dld"], + [AC_CHECK_FUNC([dlopen], + [lt_cv_dlopen="dlopen"], + [AC_CHECK_LIB([dl], [dlopen], + [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"], + [AC_CHECK_LIB([svld], [dlopen], + [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"], + [AC_CHECK_LIB([dld], [dld_link], + [lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-dld"]) + ]) + ]) + ]) + ]) + ]) + ;; + esac + + if test "x$lt_cv_dlopen" != xno; then + enable_dlopen=yes + else + enable_dlopen=no + fi + + case $lt_cv_dlopen in + dlopen) + save_CPPFLAGS="$CPPFLAGS" + test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" + + save_LDFLAGS="$LDFLAGS" + wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" + + save_LIBS="$LIBS" + LIBS="$lt_cv_dlopen_libs $LIBS" + + AC_CACHE_CHECK([whether a program can dlopen itself], + lt_cv_dlopen_self, [dnl + _LT_AC_TRY_DLOPEN_SELF( + lt_cv_dlopen_self=yes, lt_cv_dlopen_self=yes, + lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross) + ]) + + if test "x$lt_cv_dlopen_self" = xyes; then + wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\" + AC_CACHE_CHECK([whether a statically linked program can dlopen itself], + lt_cv_dlopen_self_static, [dnl + _LT_AC_TRY_DLOPEN_SELF( + lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=yes, + lt_cv_dlopen_self_static=no, lt_cv_dlopen_self_static=cross) + ]) + fi + + CPPFLAGS="$save_CPPFLAGS" + LDFLAGS="$save_LDFLAGS" + LIBS="$save_LIBS" + ;; + esac + + case $lt_cv_dlopen_self in + yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; + *) enable_dlopen_self=unknown ;; + esac + + case $lt_cv_dlopen_self_static in + yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; + *) enable_dlopen_self_static=unknown ;; + esac +fi +])# AC_LIBTOOL_DLOPEN_SELF + + +# AC_LIBTOOL_PROG_CC_C_O([TAGNAME]) +# --------------------------------- +# Check to see if options -c and -o are simultaneously supported by compiler +AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O], +[AC_REQUIRE([LT_AC_PROG_SED])dnl +AC_REQUIRE([_LT_AC_SYS_COMPILER])dnl +AC_CACHE_CHECK([if $compiler supports -c -o file.$ac_objext], + [_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)], + [_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)=no + $rm -r conftest 2>/dev/null + mkdir conftest + cd conftest + mkdir out + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + lt_compiler_flag="-o out/conftest2.$ac_objext" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD) + (eval "$lt_compile" 2>out/conftest.err) + ac_status=$? + cat out/conftest.err >&AS_MESSAGE_LOG_FD + echo "$as_me:__oline__: \$? = $ac_status" >&AS_MESSAGE_LOG_FD + if (exit $ac_status) && test -s out/conftest2.$ac_objext + then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp + $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 + if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then + _LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes + fi + fi + chmod u+w . 2>&AS_MESSAGE_LOG_FD + $rm conftest* + # SGI C++ compiler will create directory out/ii_files/ for + # template instantiation + test -d out/ii_files && $rm out/ii_files/* && rmdir out/ii_files + $rm out/* && rmdir out + cd .. + rmdir conftest + $rm conftest* +]) +])# AC_LIBTOOL_PROG_CC_C_O + + +# AC_LIBTOOL_SYS_HARD_LINK_LOCKS([TAGNAME]) +# ----------------------------------------- +# Check to see if we can do hard links to lock some files if needed +AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS], +[AC_REQUIRE([_LT_AC_LOCK])dnl + +hard_links="nottested" +if test "$_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)" = no && test "$need_locks" != no; then + # do not overwrite the value of need_locks provided by the user + AC_MSG_CHECKING([if we can lock with hard links]) + hard_links=yes + $rm conftest* + ln conftest.a conftest.b 2>/dev/null && hard_links=no + touch conftest.a + ln conftest.a conftest.b 2>&5 || hard_links=no + ln conftest.a conftest.b 2>/dev/null && hard_links=no + AC_MSG_RESULT([$hard_links]) + if test "$hard_links" = no; then + AC_MSG_WARN([`$CC' does not support `-c -o', so `make -j' may be unsafe]) + need_locks=warn + fi +else + need_locks=no +fi +])# AC_LIBTOOL_SYS_HARD_LINK_LOCKS + + +# AC_LIBTOOL_OBJDIR +# ----------------- +AC_DEFUN([AC_LIBTOOL_OBJDIR], +[AC_CACHE_CHECK([for objdir], [lt_cv_objdir], +[rm -f .libs 2>/dev/null +mkdir .libs 2>/dev/null +if test -d .libs; then + lt_cv_objdir=.libs +else + # MS-DOS does not allow filenames that begin with a dot. + lt_cv_objdir=_libs +fi +rmdir .libs 2>/dev/null]) +objdir=$lt_cv_objdir +])# AC_LIBTOOL_OBJDIR + + +# AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH([TAGNAME]) +# ---------------------------------------------- +# Check hardcoding attributes. +AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH], +[AC_MSG_CHECKING([how to hardcode library paths into programs]) +_LT_AC_TAGVAR(hardcode_action, $1)= +if test -n "$_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)" || \ + test -n "$_LT_AC_TAGVAR(runpath_var, $1)" || \ + test "X$_LT_AC_TAGVAR(hardcode_automatic, $1)" = "Xyes" ; then + + # We can hardcode non-existant directories. + if test "$_LT_AC_TAGVAR(hardcode_direct, $1)" != no && + # If the only mechanism to avoid hardcoding is shlibpath_var, we + # have to relink, otherwise we might link with an installed library + # when we should be linking with a yet-to-be-installed one + ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, $1)" != no && + test "$_LT_AC_TAGVAR(hardcode_minus_L, $1)" != no; then + # Linking always hardcodes the temporary library directory. + _LT_AC_TAGVAR(hardcode_action, $1)=relink + else + # We can link without hardcoding, and we can hardcode nonexisting dirs. + _LT_AC_TAGVAR(hardcode_action, $1)=immediate + fi +else + # We cannot hardcode anything, or else we can only hardcode existing + # directories. + _LT_AC_TAGVAR(hardcode_action, $1)=unsupported +fi +AC_MSG_RESULT([$_LT_AC_TAGVAR(hardcode_action, $1)]) + +if test "$_LT_AC_TAGVAR(hardcode_action, $1)" = relink; then + # Fast installation is not supported + enable_fast_install=no +elif test "$shlibpath_overrides_runpath" = yes || + test "$enable_shared" = no; then + # Fast installation is not necessary + enable_fast_install=needless +fi +])# AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH + + +# AC_LIBTOOL_SYS_LIB_STRIP +# ------------------------ +AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP], +[striplib= +old_striplib= +AC_MSG_CHECKING([whether stripping libraries is possible]) +if test -n "$STRIP" && $STRIP -V 2>&1 | grep "GNU strip" >/dev/null; then + test -z "$old_striplib" && old_striplib="$STRIP --strip-debug" + test -z "$striplib" && striplib="$STRIP --strip-unneeded" + AC_MSG_RESULT([yes]) +else +# FIXME - insert some real tests, host_os isn't really good enough + case $host_os in + darwin*) + if test -n "$STRIP" ; then + striplib="$STRIP -x" + old_striplib="$STRIP -S" + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) +fi + ;; + *) + AC_MSG_RESULT([no]) + ;; + esac +fi +])# AC_LIBTOOL_SYS_LIB_STRIP + + +# AC_LIBTOOL_SYS_DYNAMIC_LINKER +# ----------------------------- +# PORTME Fill in your ld.so characteristics +AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER], +[AC_REQUIRE([LT_AC_PROG_SED])dnl +AC_MSG_CHECKING([dynamic linker characteristics]) +library_names_spec= +libname_spec='lib$name' +soname_spec= +shrext_cmds=".so" +postinstall_cmds= +postuninstall_cmds= +finish_cmds= +finish_eval= +shlibpath_var= +shlibpath_overrides_runpath=unknown +version_type=none +dynamic_linker="$host_os ld.so" +sys_lib_dlsearch_path_spec="/lib /usr/lib" +m4_if($1,[],[ +if test "$GCC" = yes; then + case $host_os in + darwin*) lt_awk_arg="/^libraries:/,/LR/" ;; + *) lt_awk_arg="/^libraries:/" ;; + esac + lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e "s,=/,/,g"` + if echo "$lt_search_path_spec" | grep ';' >/dev/null ; then + # if the path contains ";" then we assume it to be the separator + # otherwise default to the standard path separator (i.e. ":") - it is + # assumed that no part of a normal pathname contains ";" but that should + # okay in the real world where ";" in dirpaths is itself problematic. + lt_search_path_spec=`echo "$lt_search_path_spec" | $SED -e 's/;/ /g'` + else + lt_search_path_spec=`echo "$lt_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi + # Ok, now we have the path, separated by spaces, we can step through it + # and add multilib dir if necessary. + lt_tmp_lt_search_path_spec= + lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null` + for lt_sys_path in $lt_search_path_spec; do + if test -d "$lt_sys_path/$lt_multi_os_dir"; then + lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir" + else + test -d "$lt_sys_path" && \ + lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path" + fi + done + lt_search_path_spec=`echo $lt_tmp_lt_search_path_spec | awk ' +BEGIN {RS=" "; FS="/|\n";} { + lt_foo=""; + lt_count=0; + for (lt_i = NF; lt_i > 0; lt_i--) { + if ($lt_i != "" && $lt_i != ".") { + if ($lt_i == "..") { + lt_count++; + } else { + if (lt_count == 0) { + lt_foo="/" $lt_i lt_foo; + } else { + lt_count--; + } + } + } + } + if (lt_foo != "") { lt_freq[[lt_foo]]++; } + if (lt_freq[[lt_foo]] == 1) { print lt_foo; } +}'` + sys_lib_search_path_spec=`echo $lt_search_path_spec` +else + sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" +fi]) +need_lib_prefix=unknown +hardcode_into_libs=no + +# when you set need_version to no, make sure it does not cause -set_version +# flags to be left without arguments +need_version=unknown + +case $host_os in +aix3*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' + shlibpath_var=LIBPATH + + # AIX 3 has no versioning support, so we append a major version to the name. + soname_spec='${libname}${release}${shared_ext}$major' + ;; + +aix4* | aix5*) + version_type=linux + need_lib_prefix=no + need_version=no + hardcode_into_libs=yes + if test "$host_cpu" = ia64; then + # AIX 5 supports IA64 + library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + else + # With GCC up to 2.95.x, collect2 would create an import file + # for dependence libraries. The import file would start with + # the line `#! .'. This would cause the generated library to + # depend on `.', always an invalid library. This was fixed in + # development snapshots of GCC prior to 3.0. + case $host_os in + aix4 | aix4.[[01]] | aix4.[[01]].*) + if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' + echo ' yes ' + echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then + : + else + can_build_shared=no + fi + ;; + esac + # AIX (on Power*) has no versioning support, so currently we can not hardcode correct + # soname into executable. Probably we can add versioning support to + # collect2, so additional links can be useful in future. + if test "$aix_use_runtimelinking" = yes; then + # If using run time linking (on AIX 4.2 or later) use lib.so + # instead of lib.a to let people know that these are not + # typical AIX shared libraries. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + else + # We preserve .a as extension for shared libraries through AIX4.2 + # and later when we are not doing run time linking. + library_names_spec='${libname}${release}.a $libname.a' + soname_spec='${libname}${release}${shared_ext}$major' + fi + shlibpath_var=LIBPATH + fi + ;; + +amigaos*) + library_names_spec='$libname.ixlibrary $libname.a' + # Create ${libname}_ixlibrary.a entries in /sys/libs. + finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$echo "X$lib" | $Xsed -e '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; test $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' + ;; + +beos*) + library_names_spec='${libname}${shared_ext}' + dynamic_linker="$host_os ld.so" + shlibpath_var=LIBRARY_PATH + ;; + +bsdi[[45]]*) + version_type=linux + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" + sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" + # the default ld.so.conf also contains /usr/contrib/lib and + # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow + # libtool to hard-code these into programs + ;; + +cygwin* | mingw* | pw32*) + version_type=windows + shrext_cmds=".dll" + need_version=no + need_lib_prefix=no + + case $GCC,$host_os in + yes,cygwin* | yes,mingw* | yes,pw32*) + library_names_spec='$libname.dll.a' + # DLL is installed to $(libdir)/../bin by postinstall_cmds + postinstall_cmds='base_file=`basename \${file}`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname~ + chmod a+x \$dldir/$dlname' + postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ + dlpath=$dir/\$dldll~ + $rm \$dlpath' + shlibpath_overrides_runpath=yes + + case $host_os in + cygwin*) + # Cygwin DLLs use 'cyg' prefix rather than 'lib' + soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib" + ;; + mingw*) + # MinGW DLLs use traditional 'lib' prefix + soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"` + if echo "$sys_lib_search_path_spec" | [grep ';[c-zC-Z]:/' >/dev/null]; then + # It is most probably a Windows format PATH printed by + # mingw gcc, but we are running on Cygwin. Gcc prints its search + # path with ; separators, and with drive letters. We can handle the + # drive letters (cygwin fileutils understands them), so leave them, + # especially as we might pass files found there to a mingw objdump, + # which wouldn't understand a cygwinified path. Ahh. + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` + else + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi + ;; + pw32*) + # pw32 DLLs use 'pw' prefix rather than 'lib' + library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' + ;; + esac + ;; + + *) + library_names_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext} $libname.lib' + ;; + esac + dynamic_linker='Win32 ld.exe' + # FIXME: first we should search . and the directory the executable is in + shlibpath_var=PATH + ;; + +darwin* | rhapsody*) + dynamic_linker="$host_os dyld" + version_type=darwin + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${versuffix}$shared_ext ${libname}${release}${major}$shared_ext ${libname}$shared_ext' + soname_spec='${libname}${release}${major}$shared_ext' + shlibpath_overrides_runpath=yes + shlibpath_var=DYLD_LIBRARY_PATH + shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' + m4_if([$1], [],[ + sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib"]) + sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' + ;; + +dgux*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +freebsd1*) + dynamic_linker=no + ;; + +freebsd* | dragonfly*) + # DragonFly does not have aout. When/if they implement a new + # versioning mechanism, adjust this. + if test -x /usr/bin/objformat; then + objformat=`/usr/bin/objformat` + else + case $host_os in + freebsd[[123]]*) objformat=aout ;; + *) objformat=elf ;; + esac + fi + version_type=freebsd-$objformat + case $version_type in + freebsd-elf*) + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' + need_version=no + need_lib_prefix=no + ;; + freebsd-*) + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' + need_version=yes + ;; + esac + shlibpath_var=LD_LIBRARY_PATH + case $host_os in + freebsd2*) + shlibpath_overrides_runpath=yes + ;; + freebsd3.[[01]]* | freebsdelf3.[[01]]*) + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + freebsd3.[[2-9]]* | freebsdelf3.[[2-9]]* | \ + freebsd4.[[0-5]] | freebsdelf4.[[0-5]] | freebsd4.1.1 | freebsdelf4.1.1) + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + *) # from 4.6 on, and DragonFly + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + esac + ;; + +gnu*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + hardcode_into_libs=yes + ;; + +hpux9* | hpux10* | hpux11*) + # Give a soname corresponding to the major version so that dld.sl refuses to + # link against other versions. + version_type=sunos + need_lib_prefix=no + need_version=no + case $host_cpu in + ia64*) + shrext_cmds='.so' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.so" + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + if test "X$HPUX_IA64_MODE" = X32; then + sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" + else + sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" + fi + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + hppa*64*) + shrext_cmds='.sl' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.sl" + shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + *) + shrext_cmds='.sl' + dynamic_linker="$host_os dld.sl" + shlibpath_var=SHLIB_PATH + shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + ;; + esac + # HP-UX runs *really* slowly unless shared libraries are mode 555. + postinstall_cmds='chmod 555 $lib' + ;; + +interix[[3-9]]*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + +irix5* | irix6* | nonstopux*) + case $host_os in + nonstopux*) version_type=nonstopux ;; + *) + if test "$lt_cv_prog_gnu_ld" = yes; then + version_type=linux + else + version_type=irix + fi ;; + esac + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' + case $host_os in + irix5* | nonstopux*) + libsuff= shlibsuff= + ;; + *) + case $LD in # libtool.m4 will add one of these switches to LD + *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") + libsuff= shlibsuff= libmagic=32-bit;; + *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") + libsuff=32 shlibsuff=N32 libmagic=N32;; + *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") + libsuff=64 shlibsuff=64 libmagic=64-bit;; + *) libsuff= shlibsuff= libmagic=never-match;; + esac + ;; + esac + shlibpath_var=LD_LIBRARY${shlibsuff}_PATH + shlibpath_overrides_runpath=no + sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" + sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" + hardcode_into_libs=yes + ;; + +# No shared lib support for Linux oldld, aout, or coff. +linux*oldld* | linux*aout* | linux*coff*) + dynamic_linker=no + ;; + +# This must be Linux ELF. +linux* | k*bsd*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + # This implies no fast_install, which is unacceptable. + # Some rework will be needed to allow for fast_install + # before this can be enabled. + hardcode_into_libs=yes + sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" + sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" + + # Append ld.so.conf contents to the search path + if test -f /etc/ld.so.conf; then + lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` + sys_lib_dlsearch_path_spec="$sys_lib_dlsearch_path_spec $lt_ld_extra" + fi + + # We used to test for /lib/ld.so.1 and disable shared libraries on + # powerpc, because MkLinux only supported shared libraries with the + # GNU dynamic linker. Since this was broken with cross compilers, + # most powerpc-linux boxes support dynamic linking these days and + # people can always --disable-shared, the test was removed, and we + # assume the GNU/Linux dynamic linker is in use. + dynamic_linker='GNU/Linux ld.so' + ;; + +netbsd*) + version_type=sunos + need_lib_prefix=no + need_version=no + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + dynamic_linker='NetBSD (a.out) ld.so' + else + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + dynamic_linker='NetBSD ld.elf_so' + fi + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + +newsos6) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +nto-qnx*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +openbsd*) + version_type=sunos + sys_lib_dlsearch_path_spec="/usr/lib" + need_lib_prefix=no + # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs. + case $host_os in + openbsd3.3 | openbsd3.3.*) need_version=yes ;; + *) need_version=no ;; + esac + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + shlibpath_var=LD_LIBRARY_PATH + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + case $host_os in + openbsd2.[[89]] | openbsd2.[[89]].*) + shlibpath_overrides_runpath=no + ;; + *) + shlibpath_overrides_runpath=yes + ;; + esac + else + shlibpath_overrides_runpath=yes + fi + ;; + +os2*) + libname_spec='$name' + shrext_cmds=".dll" + need_lib_prefix=no + library_names_spec='$libname${shared_ext} $libname.a' + dynamic_linker='OS/2 ld.exe' + shlibpath_var=LIBPATH + ;; + +osf3* | osf4* | osf5*) + version_type=osf + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" + sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" + ;; + +rdos*) + dynamic_linker=no + ;; + +solaris*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + # ldd complains unless libraries are executable + postinstall_cmds='chmod +x $lib' + ;; + +sunos4*) + version_type=sunos + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + if test "$with_gnu_ld" = yes; then + need_lib_prefix=no + fi + need_version=yes + ;; + +sysv4 | sysv4.3*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + case $host_vendor in + sni) + shlibpath_overrides_runpath=no + need_lib_prefix=no + export_dynamic_flag_spec='${wl}-Blargedynsym' + runpath_var=LD_RUN_PATH + ;; + siemens) + need_lib_prefix=no + ;; + motorola) + need_lib_prefix=no + need_version=no + shlibpath_overrides_runpath=no + sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' + ;; + esac + ;; + +sysv4*MP*) + if test -d /usr/nec ;then + version_type=linux + library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' + soname_spec='$libname${shared_ext}.$major' + shlibpath_var=LD_LIBRARY_PATH + fi + ;; + +sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) + version_type=freebsd-elf + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + hardcode_into_libs=yes + if test "$with_gnu_ld" = yes; then + sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' + shlibpath_overrides_runpath=no + else + sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' + shlibpath_overrides_runpath=yes + case $host_os in + sco3.2v5*) + sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" + ;; + esac + fi + sys_lib_dlsearch_path_spec='/usr/lib' + ;; + +uts4*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +*) + dynamic_linker=no + ;; +esac +AC_MSG_RESULT([$dynamic_linker]) +test "$dynamic_linker" = no && can_build_shared=no + +variables_saved_for_relink="PATH $shlibpath_var $runpath_var" +if test "$GCC" = yes; then + variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" +fi +])# AC_LIBTOOL_SYS_DYNAMIC_LINKER + + +# _LT_AC_TAGCONFIG +# ---------------- +AC_DEFUN([_LT_AC_TAGCONFIG], +[AC_REQUIRE([LT_AC_PROG_SED])dnl +AC_ARG_WITH([tags], + [AC_HELP_STRING([--with-tags@<:@=TAGS@:>@], + [include additional configurations @<:@automatic@:>@])], + [tagnames="$withval"]) + +if test -f "$ltmain" && test -n "$tagnames"; then + if test ! -f "${ofile}"; then + AC_MSG_WARN([output file `$ofile' does not exist]) + fi + + if test -z "$LTCC"; then + eval "`$SHELL ${ofile} --config | grep '^LTCC='`" + if test -z "$LTCC"; then + AC_MSG_WARN([output file `$ofile' does not look like a libtool script]) + else + AC_MSG_WARN([using `LTCC=$LTCC', extracted from `$ofile']) + fi + fi + if test -z "$LTCFLAGS"; then + eval "`$SHELL ${ofile} --config | grep '^LTCFLAGS='`" + fi + + # Extract list of available tagged configurations in $ofile. + # Note that this assumes the entire list is on one line. + available_tags=`grep "^available_tags=" "${ofile}" | $SED -e 's/available_tags=\(.*$\)/\1/' -e 's/\"//g'` + + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for tagname in $tagnames; do + IFS="$lt_save_ifs" + # Check whether tagname contains only valid characters + case `$echo "X$tagname" | $Xsed -e 's:[[-_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890,/]]::g'` in + "") ;; + *) AC_MSG_ERROR([invalid tag name: $tagname]) + ;; + esac + + if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$" < "${ofile}" > /dev/null + then + AC_MSG_ERROR([tag name \"$tagname\" already exists]) + fi + + # Update the list of available tags. + if test -n "$tagname"; then + echo appending configuration tag \"$tagname\" to $ofile + + case $tagname in + CXX) + if test -n "$CXX" && ( test "X$CXX" != "Xno" && + ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) || + (test "X$CXX" != "Xg++"))) ; then + AC_LIBTOOL_LANG_CXX_CONFIG + else + tagname="" + fi + ;; + + F77) + if test -n "$F77" && test "X$F77" != "Xno"; then + AC_LIBTOOL_LANG_F77_CONFIG + else + tagname="" + fi + ;; + + GCJ) + if test -n "$GCJ" && test "X$GCJ" != "Xno"; then + AC_LIBTOOL_LANG_GCJ_CONFIG + else + tagname="" + fi + ;; + + RC) + AC_LIBTOOL_LANG_RC_CONFIG + ;; + + *) + AC_MSG_ERROR([Unsupported tag name: $tagname]) + ;; + esac + + # Append the new tag name to the list of available tags. + if test -n "$tagname" ; then + available_tags="$available_tags $tagname" + fi + fi + done + IFS="$lt_save_ifs" + + # Now substitute the updated list of available tags. + if eval "sed -e 's/^available_tags=.*\$/available_tags=\"$available_tags\"/' \"$ofile\" > \"${ofile}T\""; then + mv "${ofile}T" "$ofile" + chmod +x "$ofile" + else + rm -f "${ofile}T" + AC_MSG_ERROR([unable to update list of available tagged configurations.]) + fi +fi +])# _LT_AC_TAGCONFIG + + +# AC_LIBTOOL_DLOPEN +# ----------------- +# enable checks for dlopen support +AC_DEFUN([AC_LIBTOOL_DLOPEN], + [AC_BEFORE([$0],[AC_LIBTOOL_SETUP]) +])# AC_LIBTOOL_DLOPEN + + +# AC_LIBTOOL_WIN32_DLL +# -------------------- +# declare package support for building win32 DLLs +AC_DEFUN([AC_LIBTOOL_WIN32_DLL], +[AC_BEFORE([$0], [AC_LIBTOOL_SETUP]) +])# AC_LIBTOOL_WIN32_DLL + + +# AC_ENABLE_SHARED([DEFAULT]) +# --------------------------- +# implement the --enable-shared flag +# DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. +AC_DEFUN([AC_ENABLE_SHARED], +[define([AC_ENABLE_SHARED_DEFAULT], ifelse($1, no, no, yes))dnl +AC_ARG_ENABLE([shared], + [AC_HELP_STRING([--enable-shared@<:@=PKGS@:>@], + [build shared libraries @<:@default=]AC_ENABLE_SHARED_DEFAULT[@:>@])], + [p=${PACKAGE-default} + case $enableval in + yes) enable_shared=yes ;; + no) enable_shared=no ;; + *) + enable_shared=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for pkg in $enableval; do + IFS="$lt_save_ifs" + if test "X$pkg" = "X$p"; then + enable_shared=yes + fi + done + IFS="$lt_save_ifs" + ;; + esac], + [enable_shared=]AC_ENABLE_SHARED_DEFAULT) +])# AC_ENABLE_SHARED + + +# AC_DISABLE_SHARED +# ----------------- +# set the default shared flag to --disable-shared +AC_DEFUN([AC_DISABLE_SHARED], +[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl +AC_ENABLE_SHARED(no) +])# AC_DISABLE_SHARED + + +# AC_ENABLE_STATIC([DEFAULT]) +# --------------------------- +# implement the --enable-static flag +# DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. +AC_DEFUN([AC_ENABLE_STATIC], +[define([AC_ENABLE_STATIC_DEFAULT], ifelse($1, no, no, yes))dnl +AC_ARG_ENABLE([static], + [AC_HELP_STRING([--enable-static@<:@=PKGS@:>@], + [build static libraries @<:@default=]AC_ENABLE_STATIC_DEFAULT[@:>@])], + [p=${PACKAGE-default} + case $enableval in + yes) enable_static=yes ;; + no) enable_static=no ;; + *) + enable_static=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for pkg in $enableval; do + IFS="$lt_save_ifs" + if test "X$pkg" = "X$p"; then + enable_static=yes + fi + done + IFS="$lt_save_ifs" + ;; + esac], + [enable_static=]AC_ENABLE_STATIC_DEFAULT) +])# AC_ENABLE_STATIC + + +# AC_DISABLE_STATIC +# ----------------- +# set the default static flag to --disable-static +AC_DEFUN([AC_DISABLE_STATIC], +[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl +AC_ENABLE_STATIC(no) +])# AC_DISABLE_STATIC + + +# AC_ENABLE_FAST_INSTALL([DEFAULT]) +# --------------------------------- +# implement the --enable-fast-install flag +# DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. +AC_DEFUN([AC_ENABLE_FAST_INSTALL], +[define([AC_ENABLE_FAST_INSTALL_DEFAULT], ifelse($1, no, no, yes))dnl +AC_ARG_ENABLE([fast-install], + [AC_HELP_STRING([--enable-fast-install@<:@=PKGS@:>@], + [optimize for fast installation @<:@default=]AC_ENABLE_FAST_INSTALL_DEFAULT[@:>@])], + [p=${PACKAGE-default} + case $enableval in + yes) enable_fast_install=yes ;; + no) enable_fast_install=no ;; + *) + enable_fast_install=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for pkg in $enableval; do + IFS="$lt_save_ifs" + if test "X$pkg" = "X$p"; then + enable_fast_install=yes + fi + done + IFS="$lt_save_ifs" + ;; + esac], + [enable_fast_install=]AC_ENABLE_FAST_INSTALL_DEFAULT) +])# AC_ENABLE_FAST_INSTALL + + +# AC_DISABLE_FAST_INSTALL +# ----------------------- +# set the default to --disable-fast-install +AC_DEFUN([AC_DISABLE_FAST_INSTALL], +[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl +AC_ENABLE_FAST_INSTALL(no) +])# AC_DISABLE_FAST_INSTALL + + +# AC_LIBTOOL_PICMODE([MODE]) +# -------------------------- +# implement the --with-pic flag +# MODE is either `yes' or `no'. If omitted, it defaults to `both'. +AC_DEFUN([AC_LIBTOOL_PICMODE], +[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl +pic_mode=ifelse($#,1,$1,default) +])# AC_LIBTOOL_PICMODE + + +# AC_PROG_EGREP +# ------------- +# This is predefined starting with Autoconf 2.54, so this conditional +# definition can be removed once we require Autoconf 2.54 or later. +m4_ifndef([AC_PROG_EGREP], [AC_DEFUN([AC_PROG_EGREP], +[AC_CACHE_CHECK([for egrep], [ac_cv_prog_egrep], + [if echo a | (grep -E '(a|b)') >/dev/null 2>&1 + then ac_cv_prog_egrep='grep -E' + else ac_cv_prog_egrep='egrep' + fi]) + EGREP=$ac_cv_prog_egrep + AC_SUBST([EGREP]) +])]) + + +# AC_PATH_TOOL_PREFIX +# ------------------- +# find a file program which can recognize shared library +AC_DEFUN([AC_PATH_TOOL_PREFIX], +[AC_REQUIRE([AC_PROG_EGREP])dnl +AC_MSG_CHECKING([for $1]) +AC_CACHE_VAL(lt_cv_path_MAGIC_CMD, +[case $MAGIC_CMD in +[[\\/*] | ?:[\\/]*]) + lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. + ;; +*) + lt_save_MAGIC_CMD="$MAGIC_CMD" + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR +dnl $ac_dummy forces splitting on constant user-supplied paths. +dnl POSIX.2 word splitting is done only on the output of word expansions, +dnl not every word. This closes a longstanding sh security hole. + ac_dummy="ifelse([$2], , $PATH, [$2])" + for ac_dir in $ac_dummy; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + if test -f $ac_dir/$1; then + lt_cv_path_MAGIC_CMD="$ac_dir/$1" + if test -n "$file_magic_test_file"; then + case $deplibs_check_method in + "file_magic "*) + file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` + MAGIC_CMD="$lt_cv_path_MAGIC_CMD" + if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | + $EGREP "$file_magic_regex" > /dev/null; then + : + else + cat <&2 + +*** Warning: the command libtool uses to detect shared libraries, +*** $file_magic_cmd, produces output that libtool cannot recognize. +*** The result is that libtool may fail to recognize shared libraries +*** as such. This will affect the creation of libtool libraries that +*** depend on shared libraries, but programs linked with such libtool +*** libraries will work regardless of this problem. Nevertheless, you +*** may want to report the problem to your system manager and/or to +*** bug-libtool at gnu.org + +EOF + fi ;; + esac + fi + break + fi + done + IFS="$lt_save_ifs" + MAGIC_CMD="$lt_save_MAGIC_CMD" + ;; +esac]) +MAGIC_CMD="$lt_cv_path_MAGIC_CMD" +if test -n "$MAGIC_CMD"; then + AC_MSG_RESULT($MAGIC_CMD) +else + AC_MSG_RESULT(no) +fi +])# AC_PATH_TOOL_PREFIX + + +# AC_PATH_MAGIC +# ------------- +# find a file program which can recognize a shared library +AC_DEFUN([AC_PATH_MAGIC], +[AC_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH) +if test -z "$lt_cv_path_MAGIC_CMD"; then + if test -n "$ac_tool_prefix"; then + AC_PATH_TOOL_PREFIX(file, /usr/bin$PATH_SEPARATOR$PATH) + else + MAGIC_CMD=: + fi +fi +])# AC_PATH_MAGIC + + +# AC_PROG_LD +# ---------- +# find the pathname to the GNU or non-GNU linker +AC_DEFUN([AC_PROG_LD], +[AC_ARG_WITH([gnu-ld], + [AC_HELP_STRING([--with-gnu-ld], + [assume the C compiler uses GNU ld @<:@default=no@:>@])], + [test "$withval" = no || with_gnu_ld=yes], + [with_gnu_ld=no]) +AC_REQUIRE([LT_AC_PROG_SED])dnl +AC_REQUIRE([AC_PROG_CC])dnl +AC_REQUIRE([AC_CANONICAL_HOST])dnl +AC_REQUIRE([AC_CANONICAL_BUILD])dnl +ac_prog=ld +if test "$GCC" = yes; then + # Check if gcc -print-prog-name=ld gives a path. + AC_MSG_CHECKING([for ld used by $CC]) + case $host in + *-*-mingw*) + # gcc leaves a trailing carriage return which upsets mingw + ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; + *) + ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; + esac + case $ac_prog in + # Accept absolute paths. + [[\\/]]* | ?:[[\\/]]*) + re_direlt='/[[^/]][[^/]]*/\.\./' + # Canonicalize the pathname of ld + ac_prog=`echo $ac_prog| $SED 's%\\\\%/%g'` + while echo $ac_prog | grep "$re_direlt" > /dev/null 2>&1; do + ac_prog=`echo $ac_prog| $SED "s%$re_direlt%/%"` + done + test -z "$LD" && LD="$ac_prog" + ;; + "") + # If it fails, then pretend we aren't using GCC. + ac_prog=ld + ;; + *) + # If it is relative, then search for the first ld in PATH. + with_gnu_ld=unknown + ;; + esac +elif test "$with_gnu_ld" = yes; then + AC_MSG_CHECKING([for GNU ld]) +else + AC_MSG_CHECKING([for non-GNU ld]) +fi +AC_CACHE_VAL(lt_cv_path_LD, +[if test -z "$LD"; then + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + for ac_dir in $PATH; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then + lt_cv_path_LD="$ac_dir/$ac_prog" + # Check to see if the program is GNU ld. I'd rather use --version, + # but apparently some variants of GNU ld only accept -v. + # Break only if it was the GNU/non-GNU ld that we prefer. + case `"$lt_cv_path_LD" -v 2>&1 &1 /dev/null 2>&1; then + lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' + lt_cv_file_magic_cmd='func_win32_libid' + else + lt_cv_deplibs_check_method='file_magic file format pei*-i386(.*architecture: i386)?' + lt_cv_file_magic_cmd='$OBJDUMP -f' + fi + ;; + +darwin* | rhapsody*) + lt_cv_deplibs_check_method=pass_all + ;; + +freebsd* | dragonfly*) + if echo __ELF__ | $CC -E - | grep __ELF__ > /dev/null; then + case $host_cpu in + i*86 ) + # Not sure whether the presence of OpenBSD here was a mistake. + # Let's accept both of them until this is cleared up. + lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[[3-9]]86 (compact )?demand paged shared library' + lt_cv_file_magic_cmd=/usr/bin/file + lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` + ;; + esac + else + lt_cv_deplibs_check_method=pass_all + fi + ;; + +gnu*) + lt_cv_deplibs_check_method=pass_all + ;; + +hpux10.20* | hpux11*) + lt_cv_file_magic_cmd=/usr/bin/file + case $host_cpu in + ia64*) + lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[[0-9]][[0-9]]) shared object file - IA64' + lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so + ;; + hppa*64*) + [lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - PA-RISC [0-9].[0-9]'] + lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl + ;; + *) + lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RISC[[0-9]].[[0-9]]) shared library' + lt_cv_file_magic_test_file=/usr/lib/libc.sl + ;; + esac + ;; + +interix[[3-9]]*) + # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here + lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|\.a)$' + ;; + +irix5* | irix6* | nonstopux*) + case $LD in + *-32|*"-32 ") libmagic=32-bit;; + *-n32|*"-n32 ") libmagic=N32;; + *-64|*"-64 ") libmagic=64-bit;; + *) libmagic=never-match;; + esac + lt_cv_deplibs_check_method=pass_all + ;; + +# This must be Linux ELF. +linux* | k*bsd*-gnu) + lt_cv_deplibs_check_method=pass_all + ;; + +netbsd*) + if echo __ELF__ | $CC -E - | grep __ELF__ > /dev/null; then + lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$' + else + lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|_pic\.a)$' + fi + ;; + +newos6*) + lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (executable|dynamic lib)' + lt_cv_file_magic_cmd=/usr/bin/file + lt_cv_file_magic_test_file=/usr/lib/libnls.so + ;; + +nto-qnx*) + lt_cv_deplibs_check_method=unknown + ;; + +openbsd*) + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|\.so|_pic\.a)$' + else + lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$' + fi + ;; + +osf3* | osf4* | osf5*) + lt_cv_deplibs_check_method=pass_all + ;; + +rdos*) + lt_cv_deplibs_check_method=pass_all + ;; + +solaris*) + lt_cv_deplibs_check_method=pass_all + ;; + +sysv4 | sysv4.3*) + case $host_vendor in + motorola) + lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]' + lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` + ;; + ncr) + lt_cv_deplibs_check_method=pass_all + ;; + sequent) + lt_cv_file_magic_cmd='/bin/file' + lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB (shared object|dynamic lib )' + ;; + sni) + lt_cv_file_magic_cmd='/bin/file' + lt_cv_deplibs_check_method="file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB dynamic lib" + lt_cv_file_magic_test_file=/lib/libc.so + ;; + siemens) + lt_cv_deplibs_check_method=pass_all + ;; + pc) + lt_cv_deplibs_check_method=pass_all + ;; + esac + ;; + +sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) + lt_cv_deplibs_check_method=pass_all + ;; +esac +]) +file_magic_cmd=$lt_cv_file_magic_cmd +deplibs_check_method=$lt_cv_deplibs_check_method +test -z "$deplibs_check_method" && deplibs_check_method=unknown +])# AC_DEPLIBS_CHECK_METHOD + + +# AC_PROG_NM +# ---------- +# find the pathname to a BSD-compatible name lister +AC_DEFUN([AC_PROG_NM], +[AC_CACHE_CHECK([for BSD-compatible nm], lt_cv_path_NM, +[if test -n "$NM"; then + # Let the user override the test. + lt_cv_path_NM="$NM" +else + lt_nm_to_check="${ac_tool_prefix}nm" + if test -n "$ac_tool_prefix" && test "$build" = "$host"; then + lt_nm_to_check="$lt_nm_to_check nm" + fi + for lt_tmp_nm in $lt_nm_to_check; do + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + tmp_nm="$ac_dir/$lt_tmp_nm" + if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then + # Check to see if the nm accepts a BSD-compat flag. + # Adding the `sed 1q' prevents false positives on HP-UX, which says: + # nm: unknown option "B" ignored + # Tru64's nm complains that /dev/null is an invalid object file + case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in + */dev/null* | *'Invalid file or object type'*) + lt_cv_path_NM="$tmp_nm -B" + break + ;; + *) + case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in + */dev/null*) + lt_cv_path_NM="$tmp_nm -p" + break + ;; + *) + lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but + continue # so that we can try to find one that supports BSD flags + ;; + esac + ;; + esac + fi + done + IFS="$lt_save_ifs" + done + test -z "$lt_cv_path_NM" && lt_cv_path_NM=nm +fi]) +NM="$lt_cv_path_NM" +])# AC_PROG_NM + + +# AC_CHECK_LIBM +# ------------- +# check for math library +AC_DEFUN([AC_CHECK_LIBM], +[AC_REQUIRE([AC_CANONICAL_HOST])dnl +LIBM= +case $host in +*-*-beos* | *-*-cygwin* | *-*-pw32* | *-*-darwin*) + # These system don't have libm, or don't need it + ;; +*-ncr-sysv4.3*) + AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM="-lmw") + AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm") + ;; +*) + AC_CHECK_LIB(m, cos, LIBM="-lm") + ;; +esac +])# AC_CHECK_LIBM + + +# AC_LIBLTDL_CONVENIENCE([DIRECTORY]) +# ----------------------------------- +# sets LIBLTDL to the link flags for the libltdl convenience library and +# LTDLINCL to the include flags for the libltdl header and adds +# --enable-ltdl-convenience to the configure arguments. Note that +# AC_CONFIG_SUBDIRS is not called here. If DIRECTORY is not provided, +# it is assumed to be `libltdl'. LIBLTDL will be prefixed with +# '${top_builddir}/' and LTDLINCL will be prefixed with '${top_srcdir}/' +# (note the single quotes!). If your package is not flat and you're not +# using automake, define top_builddir and top_srcdir appropriately in +# the Makefiles. +AC_DEFUN([AC_LIBLTDL_CONVENIENCE], +[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl + case $enable_ltdl_convenience in + no) AC_MSG_ERROR([this package needs a convenience libltdl]) ;; + "") enable_ltdl_convenience=yes + ac_configure_args="$ac_configure_args --enable-ltdl-convenience" ;; + esac + LIBLTDL='${top_builddir}/'ifelse($#,1,[$1],['libltdl'])/libltdlc.la + LTDLINCL='-I${top_srcdir}/'ifelse($#,1,[$1],['libltdl']) + # For backwards non-gettext consistent compatibility... + INCLTDL="$LTDLINCL" +])# AC_LIBLTDL_CONVENIENCE + + +# AC_LIBLTDL_INSTALLABLE([DIRECTORY]) +# ----------------------------------- +# sets LIBLTDL to the link flags for the libltdl installable library and +# LTDLINCL to the include flags for the libltdl header and adds +# --enable-ltdl-install to the configure arguments. Note that +# AC_CONFIG_SUBDIRS is not called here. If DIRECTORY is not provided, +# and an installed libltdl is not found, it is assumed to be `libltdl'. +# LIBLTDL will be prefixed with '${top_builddir}/'# and LTDLINCL with +# '${top_srcdir}/' (note the single quotes!). If your package is not +# flat and you're not using automake, define top_builddir and top_srcdir +# appropriately in the Makefiles. +# In the future, this macro may have to be called after AC_PROG_LIBTOOL. +AC_DEFUN([AC_LIBLTDL_INSTALLABLE], +[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl + AC_CHECK_LIB(ltdl, lt_dlinit, + [test x"$enable_ltdl_install" != xyes && enable_ltdl_install=no], + [if test x"$enable_ltdl_install" = xno; then + AC_MSG_WARN([libltdl not installed, but installation disabled]) + else + enable_ltdl_install=yes + fi + ]) + if test x"$enable_ltdl_install" = x"yes"; then + ac_configure_args="$ac_configure_args --enable-ltdl-install" + LIBLTDL='${top_builddir}/'ifelse($#,1,[$1],['libltdl'])/libltdl.la + LTDLINCL='-I${top_srcdir}/'ifelse($#,1,[$1],['libltdl']) + else + ac_configure_args="$ac_configure_args --enable-ltdl-install=no" + LIBLTDL="-lltdl" + LTDLINCL= + fi + # For backwards non-gettext consistent compatibility... + INCLTDL="$LTDLINCL" +])# AC_LIBLTDL_INSTALLABLE + + +# AC_LIBTOOL_CXX +# -------------- +# enable support for C++ libraries +AC_DEFUN([AC_LIBTOOL_CXX], +[AC_REQUIRE([_LT_AC_LANG_CXX]) +])# AC_LIBTOOL_CXX + + +# _LT_AC_LANG_CXX +# --------------- +AC_DEFUN([_LT_AC_LANG_CXX], +[AC_REQUIRE([AC_PROG_CXX]) +AC_REQUIRE([_LT_AC_PROG_CXXCPP]) +_LT_AC_SHELL_INIT([tagnames=${tagnames+${tagnames},}CXX]) +])# _LT_AC_LANG_CXX + +# _LT_AC_PROG_CXXCPP +# ------------------ +AC_DEFUN([_LT_AC_PROG_CXXCPP], +[ +AC_REQUIRE([AC_PROG_CXX]) +if test -n "$CXX" && ( test "X$CXX" != "Xno" && + ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) || + (test "X$CXX" != "Xg++"))) ; then + AC_PROG_CXXCPP +fi +])# _LT_AC_PROG_CXXCPP + +# AC_LIBTOOL_F77 +# -------------- +# enable support for Fortran 77 libraries +AC_DEFUN([AC_LIBTOOL_F77], +[AC_REQUIRE([_LT_AC_LANG_F77]) +])# AC_LIBTOOL_F77 + + +# _LT_AC_LANG_F77 +# --------------- +AC_DEFUN([_LT_AC_LANG_F77], +[AC_REQUIRE([AC_PROG_F77]) +_LT_AC_SHELL_INIT([tagnames=${tagnames+${tagnames},}F77]) +])# _LT_AC_LANG_F77 + + +# AC_LIBTOOL_GCJ +# -------------- +# enable support for GCJ libraries +AC_DEFUN([AC_LIBTOOL_GCJ], +[AC_REQUIRE([_LT_AC_LANG_GCJ]) +])# AC_LIBTOOL_GCJ + + +# _LT_AC_LANG_GCJ +# --------------- +AC_DEFUN([_LT_AC_LANG_GCJ], +[AC_PROVIDE_IFELSE([AC_PROG_GCJ],[], + [AC_PROVIDE_IFELSE([A][M_PROG_GCJ],[], + [AC_PROVIDE_IFELSE([LT_AC_PROG_GCJ],[], + [ifdef([AC_PROG_GCJ],[AC_REQUIRE([AC_PROG_GCJ])], + [ifdef([A][M_PROG_GCJ],[AC_REQUIRE([A][M_PROG_GCJ])], + [AC_REQUIRE([A][C_PROG_GCJ_OR_A][M_PROG_GCJ])])])])])]) +_LT_AC_SHELL_INIT([tagnames=${tagnames+${tagnames},}GCJ]) +])# _LT_AC_LANG_GCJ + + +# AC_LIBTOOL_RC +# ------------- +# enable support for Windows resource files +AC_DEFUN([AC_LIBTOOL_RC], +[AC_REQUIRE([LT_AC_PROG_RC]) +_LT_AC_SHELL_INIT([tagnames=${tagnames+${tagnames},}RC]) +])# AC_LIBTOOL_RC + + +# AC_LIBTOOL_LANG_C_CONFIG +# ------------------------ +# Ensure that the configuration vars for the C compiler are +# suitably defined. Those variables are subsequently used by +# AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'. +AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG], [_LT_AC_LANG_C_CONFIG]) +AC_DEFUN([_LT_AC_LANG_C_CONFIG], +[lt_save_CC="$CC" +AC_LANG_PUSH(C) + +# Source file extension for C test sources. +ac_ext=c + +# Object file extension for compiled C test sources. +objext=o +_LT_AC_TAGVAR(objext, $1)=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code="int some_variable = 0;" + +# Code to be used in simple link tests +lt_simple_link_test_code='int main(){return(0);}' + +_LT_AC_SYS_COMPILER + +# save warnings/boilerplate of simple test code +_LT_COMPILER_BOILERPLATE +_LT_LINKER_BOILERPLATE + +AC_LIBTOOL_PROG_COMPILER_NO_RTTI($1) +AC_LIBTOOL_PROG_COMPILER_PIC($1) +AC_LIBTOOL_PROG_CC_C_O($1) +AC_LIBTOOL_SYS_HARD_LINK_LOCKS($1) +AC_LIBTOOL_PROG_LD_SHLIBS($1) +AC_LIBTOOL_SYS_DYNAMIC_LINKER($1) +AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH($1) +AC_LIBTOOL_SYS_LIB_STRIP +AC_LIBTOOL_DLOPEN_SELF + +# Report which library types will actually be built +AC_MSG_CHECKING([if libtool supports shared libraries]) +AC_MSG_RESULT([$can_build_shared]) + +AC_MSG_CHECKING([whether to build shared libraries]) +test "$can_build_shared" = "no" && enable_shared=no + +# On AIX, shared libraries and static libraries use the same namespace, and +# are all built from PIC. +case $host_os in +aix3*) + test "$enable_shared" = yes && enable_static=no + if test -n "$RANLIB"; then + archive_cmds="$archive_cmds~\$RANLIB \$lib" + postinstall_cmds='$RANLIB $lib' + fi + ;; + +aix4* | aix5*) + if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then + test "$enable_shared" = yes && enable_static=no + fi + ;; +esac +AC_MSG_RESULT([$enable_shared]) + +AC_MSG_CHECKING([whether to build static libraries]) +# Make sure either enable_shared or enable_static is yes. +test "$enable_shared" = yes || enable_static=yes +AC_MSG_RESULT([$enable_static]) + +AC_LIBTOOL_CONFIG($1) + +AC_LANG_POP +CC="$lt_save_CC" +])# AC_LIBTOOL_LANG_C_CONFIG + + +# AC_LIBTOOL_LANG_CXX_CONFIG +# -------------------------- +# Ensure that the configuration vars for the C compiler are +# suitably defined. Those variables are subsequently used by +# AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'. +AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG], [_LT_AC_LANG_CXX_CONFIG(CXX)]) +AC_DEFUN([_LT_AC_LANG_CXX_CONFIG], +[AC_LANG_PUSH(C++) +AC_REQUIRE([AC_PROG_CXX]) +AC_REQUIRE([_LT_AC_PROG_CXXCPP]) + +_LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no +_LT_AC_TAGVAR(allow_undefined_flag, $1)= +_LT_AC_TAGVAR(always_export_symbols, $1)=no +_LT_AC_TAGVAR(archive_expsym_cmds, $1)= +_LT_AC_TAGVAR(export_dynamic_flag_spec, $1)= +_LT_AC_TAGVAR(hardcode_direct, $1)=no +_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)= +_LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)= +_LT_AC_TAGVAR(hardcode_libdir_separator, $1)= +_LT_AC_TAGVAR(hardcode_minus_L, $1)=no +_LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=unsupported +_LT_AC_TAGVAR(hardcode_automatic, $1)=no +_LT_AC_TAGVAR(module_cmds, $1)= +_LT_AC_TAGVAR(module_expsym_cmds, $1)= +_LT_AC_TAGVAR(link_all_deplibs, $1)=unknown +_LT_AC_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds +_LT_AC_TAGVAR(no_undefined_flag, $1)= +_LT_AC_TAGVAR(whole_archive_flag_spec, $1)= +_LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=no + +# Dependencies to place before and after the object being linked: +_LT_AC_TAGVAR(predep_objects, $1)= +_LT_AC_TAGVAR(postdep_objects, $1)= +_LT_AC_TAGVAR(predeps, $1)= +_LT_AC_TAGVAR(postdeps, $1)= +_LT_AC_TAGVAR(compiler_lib_search_path, $1)= + +# Source file extension for C++ test sources. +ac_ext=cpp + +# Object file extension for compiled C++ test sources. +objext=o +_LT_AC_TAGVAR(objext, $1)=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code="int some_variable = 0;" + +# Code to be used in simple link tests +lt_simple_link_test_code='int main(int, char *[[]]) { return(0); }' + +# ltmain only uses $CC for tagged configurations so make sure $CC is set. +_LT_AC_SYS_COMPILER + +# save warnings/boilerplate of simple test code +_LT_COMPILER_BOILERPLATE +_LT_LINKER_BOILERPLATE + +# Allow CC to be a program name with arguments. +lt_save_CC=$CC +lt_save_LD=$LD +lt_save_GCC=$GCC +GCC=$GXX +lt_save_with_gnu_ld=$with_gnu_ld +lt_save_path_LD=$lt_cv_path_LD +if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then + lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx +else + $as_unset lt_cv_prog_gnu_ld +fi +if test -n "${lt_cv_path_LDCXX+set}"; then + lt_cv_path_LD=$lt_cv_path_LDCXX +else + $as_unset lt_cv_path_LD +fi +test -z "${LDCXX+set}" || LD=$LDCXX +CC=${CXX-"c++"} +compiler=$CC +_LT_AC_TAGVAR(compiler, $1)=$CC +_LT_CC_BASENAME([$compiler]) + +# We don't want -fno-exception wen compiling C++ code, so set the +# no_builtin_flag separately +if test "$GXX" = yes; then + _LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' +else + _LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)= +fi + +if test "$GXX" = yes; then + # Set up default GNU C++ configuration + + AC_PROG_LD + + # Check if GNU C++ uses GNU ld as the underlying linker, since the + # archiving commands below assume that GNU ld is being used. + if test "$with_gnu_ld" = yes; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir' + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' + + # If archive_cmds runs LD, not CC, wlarc should be empty + # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to + # investigate it a little bit more. (MM) + wlarc='${wl}' + + # ancient GNU ld didn't support --whole-archive et. al. + if eval "`$CC -print-prog-name=ld` --help 2>&1" | \ + grep 'no-whole-archive' > /dev/null; then + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' + else + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)= + fi + else + with_gnu_ld=no + wlarc= + + # A generic and very simple default shared library creation + # command for GNU C++ for the case where it uses the native + # linker, instead of GNU ld. If possible, this setting should + # overridden to take advantage of the native linker features on + # the platform it is being used on. + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' + fi + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "\-L"' + +else + GXX=no + with_gnu_ld=no + wlarc= +fi + +# PORTME: fill in a description of your system's C++ link characteristics +AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries]) +_LT_AC_TAGVAR(ld_shlibs, $1)=yes +case $host_os in + aix3*) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + aix4* | aix5*) + if test "$host_cpu" = ia64; then + # On IA64, the linker does run time linking by default, so we don't + # have to do anything special. + aix_use_runtimelinking=no + exp_sym_flag='-Bexport' + no_entry_flag="" + else + aix_use_runtimelinking=no + + # Test if we are trying to use run time linking or normal + # AIX style linking. If -brtl is somewhere in LDFLAGS, we + # need to do runtime linking. + case $host_os in aix4.[[23]]|aix4.[[23]].*|aix5*) + for ld_flag in $LDFLAGS; do + case $ld_flag in + *-brtl*) + aix_use_runtimelinking=yes + break + ;; + esac + done + ;; + esac + + exp_sym_flag='-bexport' + no_entry_flag='-bnoentry' + fi + + # When large executables or shared objects are built, AIX ld can + # have problems creating the table of contents. If linking a library + # or program results in "error TOC overflow" add -mminimal-toc to + # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not + # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. + + _LT_AC_TAGVAR(archive_cmds, $1)='' + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=':' + _LT_AC_TAGVAR(link_all_deplibs, $1)=yes + + if test "$GXX" = yes; then + case $host_os in aix4.[[012]]|aix4.[[012]].*) + # We only want to do this on AIX 4.2 and lower, the check + # below for broken collect2 doesn't work under 4.3+ + collect2name=`${CC} -print-prog-name=collect2` + if test -f "$collect2name" && \ + strings "$collect2name" | grep resolve_lib_name >/dev/null + then + # We have reworked collect2 + : + else + # We have old collect2 + _LT_AC_TAGVAR(hardcode_direct, $1)=unsupported + # It fails to find uninstalled libraries when the uninstalled + # path is not listed in the libpath. Setting hardcode_minus_L + # to unsupported forces relinking + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)= + fi + ;; + esac + shared_flag='-shared' + if test "$aix_use_runtimelinking" = yes; then + shared_flag="$shared_flag "'${wl}-G' + fi + else + # not using gcc + if test "$host_cpu" = ia64; then + # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release + # chokes on -Wl,-G. The following line is correct: + shared_flag='-G' + else + if test "$aix_use_runtimelinking" = yes; then + shared_flag='${wl}-G' + else + shared_flag='${wl}-bM:SRE' + fi + fi + fi + + # It seems that -bexpall does not export symbols beginning with + # underscore (_), so it is better to generate a list of symbols to export. + _LT_AC_TAGVAR(always_export_symbols, $1)=yes + if test "$aix_use_runtimelinking" = yes; then + # Warning - without using the other runtime loading flags (-brtl), + # -berok will link without error, but may produce a broken library. + _LT_AC_TAGVAR(allow_undefined_flag, $1)='-berok' + # Determine the default libpath from the value encoded in an empty executable. + _LT_AC_SYS_LIBPATH_AIX + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" + + _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" + else + if test "$host_cpu" = ia64; then + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib' + _LT_AC_TAGVAR(allow_undefined_flag, $1)="-z nodefs" + _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" + else + # Determine the default libpath from the value encoded in an empty executable. + _LT_AC_SYS_LIBPATH_AIX + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" + # Warning - without using the other run time loading flags, + # -berok will link without error, but may produce a broken library. + _LT_AC_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok' + _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok' + # Exported symbols can be pulled into shared objects from archives + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='$convenience' + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=yes + # This is similar to how AIX traditionally builds its shared libraries. + _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' + fi + fi + ;; + + beos*) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported + # Joseph Beckenbach says some releases of gcc + # support --undefined. This deserves some investigation. FIXME + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + else + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + chorus*) + case $cc_basename in + *) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + esac + ;; + + cygwin* | mingw* | pw32*) + # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless, + # as there is no search path for DLLs. + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported + _LT_AC_TAGVAR(always_export_symbols, $1)=no + _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=yes + + if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + # If the export-symbols file already is a .def file (1st line + # is EXPORTS), use it as is; otherwise, prepend... + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then + cp $export_symbols $output_objdir/$soname.def; + else + echo EXPORTS > $output_objdir/$soname.def; + cat $export_symbols >> $output_objdir/$soname.def; + fi~ + $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + else + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + darwin* | rhapsody*) + case $host_os in + rhapsody* | darwin1.[[012]]) + _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-undefined ${wl}suppress' + ;; + *) # Darwin 1.3 on + if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then + _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' + else + case ${MACOSX_DEPLOYMENT_TARGET} in + 10.[[012]]) + _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' + ;; + 10.*) + _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-undefined ${wl}dynamic_lookup' + ;; + esac + fi + ;; + esac + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no + _LT_AC_TAGVAR(hardcode_direct, $1)=no + _LT_AC_TAGVAR(hardcode_automatic, $1)=yes + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=unsupported + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='' + _LT_AC_TAGVAR(link_all_deplibs, $1)=yes + + if test "$GXX" = yes ; then + lt_int_apple_cc_single_mod=no + output_verbose_link_cmd='echo' + if $CC -dumpspecs 2>&1 | $EGREP 'single_module' >/dev/null ; then + lt_int_apple_cc_single_mod=yes + fi + if test "X$lt_int_apple_cc_single_mod" = Xyes ; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring' + else + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -r -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring' + fi + _LT_AC_TAGVAR(module_cmds, $1)='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags' + # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds + if test "X$lt_int_apple_cc_single_mod" = Xyes ; then + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + else + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -r -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + fi + _LT_AC_TAGVAR(module_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + else + case $cc_basename in + xlc*) + output_verbose_link_cmd='echo' + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj ${wl}-single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$soname` $xlcverstring' + _LT_AC_TAGVAR(module_cmds, $1)='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags' + # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -qmkshrobj ${wl}-single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}$rpath/$soname $xlcverstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + _LT_AC_TAGVAR(module_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + ;; + *) + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + esac + fi + ;; + + dgux*) + case $cc_basename in + ec++*) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + ghcx*) + # Green Hills C++ Compiler + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + *) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + esac + ;; + freebsd[[12]]*) + # C++ shared libraries reported to be fairly broken before switch to ELF + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + freebsd-elf*) + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no + ;; + freebsd* | dragonfly*) + # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF + # conventions + _LT_AC_TAGVAR(ld_shlibs, $1)=yes + ;; + gnu*) + ;; + hpux9*) + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH, + # but as the default + # location of the library. + + case $cc_basename in + CC*) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + aCC*) + _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | grep "[[-]]L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + ;; + *) + if test "$GXX" = yes; then + _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/$soname~$CC -shared -nostdlib -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + else + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + esac + ;; + hpux10*|hpux11*) + if test $with_gnu_ld = no; then + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + + case $host_cpu in + hppa*64*|ia64*) ;; + *) + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' + ;; + esac + fi + case $host_cpu in + hppa*64*|ia64*) + _LT_AC_TAGVAR(hardcode_direct, $1)=no + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + *) + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH, + # but as the default + # location of the library. + ;; + esac + + case $cc_basename in + CC*) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + aCC*) + case $host_cpu in + hppa*64*) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + ia64*) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + *) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + esac + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | grep "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + ;; + *) + if test "$GXX" = yes; then + if test $with_gnu_ld = no; then + case $host_cpu in + hppa*64*) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + ia64*) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + *) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + esac + fi + else + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + esac + ;; + interix[[3-9]]*) + _LT_AC_TAGVAR(hardcode_direct, $1)=no + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' + # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. + # Instead, shared libraries are loaded at an image base (0x10000000 by + # default) and relocated if they conflict, which is a slow very memory + # consuming and fragmenting process. To avoid this, we pick a random, + # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link + # time. Moving up from 0x10000000 also allows more sbrk(2) space. + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + ;; + irix5* | irix6*) + case $cc_basename in + CC*) + # SGI C++ + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + + # Archives containing C++ object files must be created using + # "CC -ar", where "CC" is the IRIX C++ compiler. This is + # necessary to make sure instantiated templates are included + # in the archive. + _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -ar -WR,-u -o $oldlib $oldobjs' + ;; + *) + if test "$GXX" = yes; then + if test "$with_gnu_ld" = no; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + else + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` -o $lib' + fi + fi + _LT_AC_TAGVAR(link_all_deplibs, $1)=yes + ;; + esac + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + ;; + linux* | k*bsd*-gnu) + case $cc_basename in + KCC*) + # Kuck and Associates, Inc. (KAI) C++ Compiler + + # KCC will only create a shared library if the output file + # ends with ".so" (or ".sl" for HP-UX), so rename the library + # to its proper name (with version) after linking. + _LT_AC_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib' + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | grep "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath,$libdir' + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' + + # Archives containing C++ object files must be created using + # "CC -Bstatic", where "CC" is the KAI C++ compiler. + _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' + ;; + icpc*) + # Intel C++ + with_gnu_ld=yes + # version 8.0 and above of icpc choke on multiply defined symbols + # if we add $predep_objects and $postdep_objects, however 7.1 and + # earlier do not add the objects themselves. + case `$CC -V 2>&1` in + *"Version 7."*) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + ;; + *) # Version 8.0 or newer + tmp_idyn= + case $host_cpu in + ia64*) tmp_idyn=' -i_dynamic';; + esac + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + ;; + esac + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive' + ;; + pgCC*) + # Portland Group C++ compiler + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib' + + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir' + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive' + ;; + cxx*) + # Compaq C++ + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib ${wl}-retain-symbols-file $wl$export_symbols' + + runpath_var=LD_RUN_PATH + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "ld"`; templist=`echo $templist | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + ;; + *) + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) + # Sun C++ 5.9 + _LT_AC_TAGVAR(no_undefined_flag, $1)=' -zdefs' + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file ${wl}$export_symbols' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive' + + # Not sure whether something based on + # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 + # would be better. + output_verbose_link_cmd='echo' + + # Archives containing C++ object files must be created using + # "CC -xar", where "CC" is the Sun C++ compiler. This is + # necessary to make sure instantiated templates are included + # in the archive. + _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs' + ;; + esac + ;; + esac + ;; + lynxos*) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + m88k*) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + mvs*) + case $cc_basename in + cxx*) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + *) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + esac + ;; + netbsd*) + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags' + wlarc= + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + fi + # Workaround some broken pre-1.5 toolchains + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"' + ;; + openbsd2*) + # C++ shared libraries are fairly broken + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + openbsd*) + if test -f /usr/libexec/ld.so; then + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib' + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' + fi + output_verbose_link_cmd='echo' + else + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + osf3*) + case $cc_basename in + KCC*) + # Kuck and Associates, Inc. (KAI) C++ Compiler + + # KCC will only create a shared library if the output file + # ends with ".so" (or ".sl" for HP-UX), so rename the library + # to its proper name (with version) after linking. + _LT_AC_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' + + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + + # Archives containing C++ object files must be created using + # "CC -Bstatic", where "CC" is the KAI C++ compiler. + _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' + + ;; + RCC*) + # Rational C++ 2.4.1 + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + cxx*) + _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && echo ${wl}-set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "ld" | grep -v "ld:"`; templist=`echo $templist | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + ;; + *) + if test "$GXX" = yes && test "$with_gnu_ld" = no; then + _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "\-L"' + + else + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + esac + ;; + osf4* | osf5*) + case $cc_basename in + KCC*) + # Kuck and Associates, Inc. (KAI) C++ Compiler + + # KCC will only create a shared library if the output file + # ends with ".so" (or ".sl" for HP-UX), so rename the library + # to its proper name (with version) after linking. + _LT_AC_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' + + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + + # Archives containing C++ object files must be created using + # the KAI C++ compiler. + _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -o $oldlib $oldobjs' + ;; + RCC*) + # Rational C++ 2.4.1 + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + cxx*) + _LT_AC_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~ + echo "-hidden">> $lib.exp~ + $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname -Wl,-input -Wl,$lib.exp `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib~ + $rm $lib.exp' + + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "ld" | grep -v "ld:"`; templist=`echo $templist | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + ;; + *) + if test "$GXX" = yes && test "$with_gnu_ld" = no; then + _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "\-L"' + + else + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + esac + ;; + psos*) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + sunos4*) + case $cc_basename in + CC*) + # Sun C++ 4.x + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + lcc*) + # Lucid + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + *) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + esac + ;; + solaris*) + case $cc_basename in + CC*) + # Sun C++ 4.2, 5.x and Centerline C++ + _LT_AC_TAGVAR(archive_cmds_need_lc,$1)=yes + _LT_AC_TAGVAR(no_undefined_flag, $1)=' -zdefs' + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp' + + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + case $host_os in + solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; + *) + # The compiler driver will combine and reorder linker options, + # but understands `-z linker_flag'. + # Supported since Solaris 2.6 (maybe 2.5.1?) + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' + ;; + esac + _LT_AC_TAGVAR(link_all_deplibs, $1)=yes + + output_verbose_link_cmd='echo' + + # Archives containing C++ object files must be created using + # "CC -xar", where "CC" is the Sun C++ compiler. This is + # necessary to make sure instantiated templates are included + # in the archive. + _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs' + ;; + gcx*) + # Green Hills C++ Compiler + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' + + # The C++ compiler must be used to create the archive. + _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC $LDFLAGS -archive -o $oldlib $oldobjs' + ;; + *) + # GNU C++ compiler with Solaris linker + if test "$GXX" = yes && test "$with_gnu_ld" = no; then + _LT_AC_TAGVAR(no_undefined_flag, $1)=' ${wl}-z ${wl}defs' + if $CC --version | grep -v '^2\.7' > /dev/null; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $CC -shared -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp' + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd="$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep \"\-L\"" + else + # g++ 2.7 appears to require `-G' NOT `-shared' on this + # platform. + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp' + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd="$CC -G $CFLAGS -v conftest.$objext 2>&1 | grep \"\-L\"" + fi + + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $wl$libdir' + case $host_os in + solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; + *) + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' + ;; + esac + fi + ;; + esac + ;; + sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*) + _LT_AC_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + runpath_var='LD_RUN_PATH' + + case $cc_basename in + CC*) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + ;; + sysv5* | sco3.2v5* | sco5v6*) + # Note: We can NOT use -z defs as we might desire, because we do not + # link with -lc, and that would cause any symbols used from libc to + # always be unresolved, which means just about no library would + # ever link correctly. If we're not using GNU ld we use -z text + # though, which does catch some bad symbols but isn't as heavy-handed + # as -z defs. + # For security reasons, it is highly recommended that you always + # use absolute paths for naming shared libraries, and exclude the + # DT_RUNPATH tag from executables and libraries. But doing so + # requires that you compile everything twice, which is a pain. + # So that behaviour is only enabled if SCOABSPATH is set to a + # non-empty value in the environment. Most likely only useful for + # creating official distributions of packages. + # This is a hack until libtool officially supports absolute path + # names for shared libraries. + _LT_AC_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' + _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs' + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='`test -z "$SCOABSPATH" && echo ${wl}-R,$libdir`' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=':' + _LT_AC_TAGVAR(link_all_deplibs, $1)=yes + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport' + runpath_var='LD_RUN_PATH' + + case $cc_basename in + CC*) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + ;; + tandem*) + case $cc_basename in + NCC*) + # NonStop-UX NCC 3.20 + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + *) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + esac + ;; + vxworks*) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + *) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; +esac +AC_MSG_RESULT([$_LT_AC_TAGVAR(ld_shlibs, $1)]) +test "$_LT_AC_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no + +_LT_AC_TAGVAR(GCC, $1)="$GXX" +_LT_AC_TAGVAR(LD, $1)="$LD" + +AC_LIBTOOL_POSTDEP_PREDEP($1) +AC_LIBTOOL_PROG_COMPILER_PIC($1) +AC_LIBTOOL_PROG_CC_C_O($1) +AC_LIBTOOL_SYS_HARD_LINK_LOCKS($1) +AC_LIBTOOL_PROG_LD_SHLIBS($1) +AC_LIBTOOL_SYS_DYNAMIC_LINKER($1) +AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH($1) + +AC_LIBTOOL_CONFIG($1) + +AC_LANG_POP +CC=$lt_save_CC +LDCXX=$LD +LD=$lt_save_LD +GCC=$lt_save_GCC +with_gnu_ldcxx=$with_gnu_ld +with_gnu_ld=$lt_save_with_gnu_ld +lt_cv_path_LDCXX=$lt_cv_path_LD +lt_cv_path_LD=$lt_save_path_LD +lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld +lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld +])# AC_LIBTOOL_LANG_CXX_CONFIG + +# AC_LIBTOOL_POSTDEP_PREDEP([TAGNAME]) +# ------------------------------------ +# Figure out "hidden" library dependencies from verbose +# compiler output when linking a shared library. +# Parse the compiler output and extract the necessary +# objects, libraries and library flags. +AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP],[ +dnl we can't use the lt_simple_compile_test_code here, +dnl because it contains code intended for an executable, +dnl not a library. It's possible we should let each +dnl tag define a new lt_????_link_test_code variable, +dnl but it's only used here... +ifelse([$1],[],[cat > conftest.$ac_ext < conftest.$ac_ext < conftest.$ac_ext < conftest.$ac_ext <&1 | sed 5q` in + *Sun\ C*) + # Sun C++ 5.9 + # + # The more standards-conforming stlport4 library is + # incompatible with the Cstd library. Avoid specifying + # it if it's in CXXFLAGS. Ignore libCrun as + # -library=stlport4 depends on it. + case " $CXX $CXXFLAGS " in + *" -library=stlport4 "*) + solaris_use_stlport4=yes + ;; + esac + if test "$solaris_use_stlport4" != yes; then + _LT_AC_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun' + fi + ;; + esac + ;; + +solaris*) + case $cc_basename in + CC*) + # The more standards-conforming stlport4 library is + # incompatible with the Cstd library. Avoid specifying + # it if it's in CXXFLAGS. Ignore libCrun as + # -library=stlport4 depends on it. + case " $CXX $CXXFLAGS " in + *" -library=stlport4 "*) + solaris_use_stlport4=yes + ;; + esac + + # Adding this requires a known-good setup of shared libraries for + # Sun compiler versions before 5.6, else PIC objects from an old + # archive will be linked into the output, leading to subtle bugs. + if test "$solaris_use_stlport4" != yes; then + _LT_AC_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun' + fi + ;; + esac + ;; +esac +]) + +case " $_LT_AC_TAGVAR(postdeps, $1) " in +*" -lc "*) _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no ;; +esac +])# AC_LIBTOOL_POSTDEP_PREDEP + +# AC_LIBTOOL_LANG_F77_CONFIG +# -------------------------- +# Ensure that the configuration vars for the C compiler are +# suitably defined. Those variables are subsequently used by +# AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'. +AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG], [_LT_AC_LANG_F77_CONFIG(F77)]) +AC_DEFUN([_LT_AC_LANG_F77_CONFIG], +[AC_REQUIRE([AC_PROG_F77]) +AC_LANG_PUSH(Fortran 77) + +_LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no +_LT_AC_TAGVAR(allow_undefined_flag, $1)= +_LT_AC_TAGVAR(always_export_symbols, $1)=no +_LT_AC_TAGVAR(archive_expsym_cmds, $1)= +_LT_AC_TAGVAR(export_dynamic_flag_spec, $1)= +_LT_AC_TAGVAR(hardcode_direct, $1)=no +_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)= +_LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)= +_LT_AC_TAGVAR(hardcode_libdir_separator, $1)= +_LT_AC_TAGVAR(hardcode_minus_L, $1)=no +_LT_AC_TAGVAR(hardcode_automatic, $1)=no +_LT_AC_TAGVAR(module_cmds, $1)= +_LT_AC_TAGVAR(module_expsym_cmds, $1)= +_LT_AC_TAGVAR(link_all_deplibs, $1)=unknown +_LT_AC_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds +_LT_AC_TAGVAR(no_undefined_flag, $1)= +_LT_AC_TAGVAR(whole_archive_flag_spec, $1)= +_LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=no + +# Source file extension for f77 test sources. +ac_ext=f + +# Object file extension for compiled f77 test sources. +objext=o +_LT_AC_TAGVAR(objext, $1)=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code="\ + subroutine t + return + end +" + +# Code to be used in simple link tests +lt_simple_link_test_code="\ + program t + end +" + +# ltmain only uses $CC for tagged configurations so make sure $CC is set. +_LT_AC_SYS_COMPILER + +# save warnings/boilerplate of simple test code +_LT_COMPILER_BOILERPLATE +_LT_LINKER_BOILERPLATE + +# Allow CC to be a program name with arguments. +lt_save_CC="$CC" +CC=${F77-"f77"} +compiler=$CC +_LT_AC_TAGVAR(compiler, $1)=$CC +_LT_CC_BASENAME([$compiler]) + +AC_MSG_CHECKING([if libtool supports shared libraries]) +AC_MSG_RESULT([$can_build_shared]) + +AC_MSG_CHECKING([whether to build shared libraries]) +test "$can_build_shared" = "no" && enable_shared=no + +# On AIX, shared libraries and static libraries use the same namespace, and +# are all built from PIC. +case $host_os in +aix3*) + test "$enable_shared" = yes && enable_static=no + if test -n "$RANLIB"; then + archive_cmds="$archive_cmds~\$RANLIB \$lib" + postinstall_cmds='$RANLIB $lib' + fi + ;; +aix4* | aix5*) + if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then + test "$enable_shared" = yes && enable_static=no + fi + ;; +esac +AC_MSG_RESULT([$enable_shared]) + +AC_MSG_CHECKING([whether to build static libraries]) +# Make sure either enable_shared or enable_static is yes. +test "$enable_shared" = yes || enable_static=yes +AC_MSG_RESULT([$enable_static]) + +_LT_AC_TAGVAR(GCC, $1)="$G77" +_LT_AC_TAGVAR(LD, $1)="$LD" + +AC_LIBTOOL_PROG_COMPILER_PIC($1) +AC_LIBTOOL_PROG_CC_C_O($1) +AC_LIBTOOL_SYS_HARD_LINK_LOCKS($1) +AC_LIBTOOL_PROG_LD_SHLIBS($1) +AC_LIBTOOL_SYS_DYNAMIC_LINKER($1) +AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH($1) + +AC_LIBTOOL_CONFIG($1) + +AC_LANG_POP +CC="$lt_save_CC" +])# AC_LIBTOOL_LANG_F77_CONFIG + + +# AC_LIBTOOL_LANG_GCJ_CONFIG +# -------------------------- +# Ensure that the configuration vars for the C compiler are +# suitably defined. Those variables are subsequently used by +# AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'. +AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG], [_LT_AC_LANG_GCJ_CONFIG(GCJ)]) +AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG], +[AC_LANG_SAVE + +# Source file extension for Java test sources. +ac_ext=java + +# Object file extension for compiled Java test sources. +objext=o +_LT_AC_TAGVAR(objext, $1)=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code="class foo {}" + +# Code to be used in simple link tests +lt_simple_link_test_code='public class conftest { public static void main(String[[]] argv) {}; }' + +# ltmain only uses $CC for tagged configurations so make sure $CC is set. +_LT_AC_SYS_COMPILER + +# save warnings/boilerplate of simple test code +_LT_COMPILER_BOILERPLATE +_LT_LINKER_BOILERPLATE + +# Allow CC to be a program name with arguments. +lt_save_CC="$CC" +CC=${GCJ-"gcj"} +compiler=$CC +_LT_AC_TAGVAR(compiler, $1)=$CC +_LT_CC_BASENAME([$compiler]) + +# GCJ did not exist at the time GCC didn't implicitly link libc in. +_LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no + +_LT_AC_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds + +AC_LIBTOOL_PROG_COMPILER_NO_RTTI($1) +AC_LIBTOOL_PROG_COMPILER_PIC($1) +AC_LIBTOOL_PROG_CC_C_O($1) +AC_LIBTOOL_SYS_HARD_LINK_LOCKS($1) +AC_LIBTOOL_PROG_LD_SHLIBS($1) +AC_LIBTOOL_SYS_DYNAMIC_LINKER($1) +AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH($1) + +AC_LIBTOOL_CONFIG($1) + +AC_LANG_RESTORE +CC="$lt_save_CC" +])# AC_LIBTOOL_LANG_GCJ_CONFIG + + +# AC_LIBTOOL_LANG_RC_CONFIG +# ------------------------- +# Ensure that the configuration vars for the Windows resource compiler are +# suitably defined. Those variables are subsequently used by +# AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'. +AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG], [_LT_AC_LANG_RC_CONFIG(RC)]) +AC_DEFUN([_LT_AC_LANG_RC_CONFIG], +[AC_LANG_SAVE + +# Source file extension for RC test sources. +ac_ext=rc + +# Object file extension for compiled RC test sources. +objext=o +_LT_AC_TAGVAR(objext, $1)=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }' + +# Code to be used in simple link tests +lt_simple_link_test_code="$lt_simple_compile_test_code" + +# ltmain only uses $CC for tagged configurations so make sure $CC is set. +_LT_AC_SYS_COMPILER + +# save warnings/boilerplate of simple test code +_LT_COMPILER_BOILERPLATE +_LT_LINKER_BOILERPLATE + +# Allow CC to be a program name with arguments. +lt_save_CC="$CC" +CC=${RC-"windres"} +compiler=$CC +_LT_AC_TAGVAR(compiler, $1)=$CC +_LT_CC_BASENAME([$compiler]) +_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes + +AC_LIBTOOL_CONFIG($1) + +AC_LANG_RESTORE +CC="$lt_save_CC" +])# AC_LIBTOOL_LANG_RC_CONFIG + + +# AC_LIBTOOL_CONFIG([TAGNAME]) +# ---------------------------- +# If TAGNAME is not passed, then create an initial libtool script +# with a default configuration from the untagged config vars. Otherwise +# add code to config.status for appending the configuration named by +# TAGNAME from the matching tagged config vars. +AC_DEFUN([AC_LIBTOOL_CONFIG], +[# The else clause should only fire when bootstrapping the +# libtool distribution, otherwise you forgot to ship ltmain.sh +# with your package, and you will get complaints that there are +# no rules to generate ltmain.sh. +if test -f "$ltmain"; then + # See if we are running on zsh, and set the options which allow our commands through + # without removal of \ escapes. + if test -n "${ZSH_VERSION+set}" ; then + setopt NO_GLOB_SUBST + fi + # Now quote all the things that may contain metacharacters while being + # careful not to overquote the AC_SUBSTed values. We take copies of the + # variables and quote the copies for generation of the libtool script. + for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTCFLAGS NM \ + SED SHELL STRIP \ + libname_spec library_names_spec soname_spec extract_expsyms_cmds \ + old_striplib striplib file_magic_cmd finish_cmds finish_eval \ + deplibs_check_method reload_flag reload_cmds need_locks \ + lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \ + lt_cv_sys_global_symbol_to_c_name_address \ + sys_lib_search_path_spec sys_lib_dlsearch_path_spec \ + old_postinstall_cmds old_postuninstall_cmds \ + _LT_AC_TAGVAR(compiler, $1) \ + _LT_AC_TAGVAR(CC, $1) \ + _LT_AC_TAGVAR(LD, $1) \ + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1) \ + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1) \ + _LT_AC_TAGVAR(lt_prog_compiler_static, $1) \ + _LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) \ + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1) \ + _LT_AC_TAGVAR(thread_safe_flag_spec, $1) \ + _LT_AC_TAGVAR(whole_archive_flag_spec, $1) \ + _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1) \ + _LT_AC_TAGVAR(old_archive_cmds, $1) \ + _LT_AC_TAGVAR(old_archive_from_new_cmds, $1) \ + _LT_AC_TAGVAR(predep_objects, $1) \ + _LT_AC_TAGVAR(postdep_objects, $1) \ + _LT_AC_TAGVAR(predeps, $1) \ + _LT_AC_TAGVAR(postdeps, $1) \ + _LT_AC_TAGVAR(compiler_lib_search_path, $1) \ + _LT_AC_TAGVAR(archive_cmds, $1) \ + _LT_AC_TAGVAR(archive_expsym_cmds, $1) \ + _LT_AC_TAGVAR(postinstall_cmds, $1) \ + _LT_AC_TAGVAR(postuninstall_cmds, $1) \ + _LT_AC_TAGVAR(old_archive_from_expsyms_cmds, $1) \ + _LT_AC_TAGVAR(allow_undefined_flag, $1) \ + _LT_AC_TAGVAR(no_undefined_flag, $1) \ + _LT_AC_TAGVAR(export_symbols_cmds, $1) \ + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1) \ + _LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1) \ + _LT_AC_TAGVAR(hardcode_libdir_separator, $1) \ + _LT_AC_TAGVAR(hardcode_automatic, $1) \ + _LT_AC_TAGVAR(module_cmds, $1) \ + _LT_AC_TAGVAR(module_expsym_cmds, $1) \ + _LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1) \ + _LT_AC_TAGVAR(fix_srcfile_path, $1) \ + _LT_AC_TAGVAR(exclude_expsyms, $1) \ + _LT_AC_TAGVAR(include_expsyms, $1); do + + case $var in + _LT_AC_TAGVAR(old_archive_cmds, $1) | \ + _LT_AC_TAGVAR(old_archive_from_new_cmds, $1) | \ + _LT_AC_TAGVAR(archive_cmds, $1) | \ + _LT_AC_TAGVAR(archive_expsym_cmds, $1) | \ + _LT_AC_TAGVAR(module_cmds, $1) | \ + _LT_AC_TAGVAR(module_expsym_cmds, $1) | \ + _LT_AC_TAGVAR(old_archive_from_expsyms_cmds, $1) | \ + _LT_AC_TAGVAR(export_symbols_cmds, $1) | \ + extract_expsyms_cmds | reload_cmds | finish_cmds | \ + postinstall_cmds | postuninstall_cmds | \ + old_postinstall_cmds | old_postuninstall_cmds | \ + sys_lib_search_path_spec | sys_lib_dlsearch_path_spec) + # Double-quote double-evaled strings. + eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\"" + ;; + *) + eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`\\\"" + ;; + esac + done + + case $lt_echo in + *'\[$]0 --fallback-echo"') + lt_echo=`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\[$]0 --fallback-echo"[$]/[$]0 --fallback-echo"/'` + ;; + esac + +ifelse([$1], [], + [cfgfile="${ofile}T" + trap "$rm \"$cfgfile\"; exit 1" 1 2 15 + $rm -f "$cfgfile" + AC_MSG_NOTICE([creating $ofile])], + [cfgfile="$ofile"]) + + cat <<__EOF__ >> "$cfgfile" +ifelse([$1], [], +[#! $SHELL + +# `$echo "$cfgfile" | sed 's%^.*/%%'` - Provide generalized library-building support services. +# Generated automatically by $PROGRAM (GNU $PACKAGE $VERSION$TIMESTAMP) +# NOTE: Changes made to this file will be lost: look at ltmain.sh. +# +# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 +# Free Software Foundation, Inc. +# +# This file is part of GNU Libtool: +# Originally by Gordon Matzigkeit , 1996 +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# A sed program that does not truncate output. +SED=$lt_SED + +# Sed that helps us avoid accidentally triggering echo(1) options like -n. +Xsed="$SED -e 1s/^X//" + +# The HP-UX ksh and POSIX shell print the target directory to stdout +# if CDPATH is set. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + +# The names of the tagged configurations supported by this script. +available_tags= + +# ### BEGIN LIBTOOL CONFIG], +[# ### BEGIN LIBTOOL TAG CONFIG: $tagname]) + +# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: + +# Shell to use when invoking shell scripts. +SHELL=$lt_SHELL + +# Whether or not to build shared libraries. +build_libtool_libs=$enable_shared + +# Whether or not to build static libraries. +build_old_libs=$enable_static + +# Whether or not to add -lc for building shared libraries. +build_libtool_need_lc=$_LT_AC_TAGVAR(archive_cmds_need_lc, $1) + +# Whether or not to disallow shared libs when runtime libs are static +allow_libtool_libs_with_static_runtimes=$_LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1) + +# Whether or not to optimize for fast installation. +fast_install=$enable_fast_install + +# The host system. +host_alias=$host_alias +host=$host +host_os=$host_os + +# The build system. +build_alias=$build_alias +build=$build +build_os=$build_os + +# An echo program that does not interpret backslashes. +echo=$lt_echo + +# The archiver. +AR=$lt_AR +AR_FLAGS=$lt_AR_FLAGS + +# A C compiler. +LTCC=$lt_LTCC + +# LTCC compiler flags. +LTCFLAGS=$lt_LTCFLAGS + +# A language-specific compiler. +CC=$lt_[]_LT_AC_TAGVAR(compiler, $1) + +# Is the compiler the GNU C compiler? +with_gcc=$_LT_AC_TAGVAR(GCC, $1) + +# An ERE matcher. +EGREP=$lt_EGREP + +# The linker used to build libraries. +LD=$lt_[]_LT_AC_TAGVAR(LD, $1) + +# Whether we need hard or soft links. +LN_S=$lt_LN_S + +# A BSD-compatible nm program. +NM=$lt_NM + +# A symbol stripping program +STRIP=$lt_STRIP + +# Used to examine libraries when file_magic_cmd begins "file" +MAGIC_CMD=$MAGIC_CMD + +# Used on cygwin: DLL creation program. +DLLTOOL="$DLLTOOL" + +# Used on cygwin: object dumper. +OBJDUMP="$OBJDUMP" + +# Used on cygwin: assembler. +AS="$AS" + +# The name of the directory that contains temporary libtool files. +objdir=$objdir + +# How to create reloadable object files. +reload_flag=$lt_reload_flag +reload_cmds=$lt_reload_cmds + +# How to pass a linker flag through the compiler. +wl=$lt_[]_LT_AC_TAGVAR(lt_prog_compiler_wl, $1) + +# Object file suffix (normally "o"). +objext="$ac_objext" + +# Old archive suffix (normally "a"). +libext="$libext" + +# Shared library suffix (normally ".so"). +shrext_cmds='$shrext_cmds' + +# Executable file suffix (normally ""). +exeext="$exeext" + +# Additional compiler flags for building library objects. +pic_flag=$lt_[]_LT_AC_TAGVAR(lt_prog_compiler_pic, $1) +pic_mode=$pic_mode + +# What is the maximum length of a command? +max_cmd_len=$lt_cv_sys_max_cmd_len + +# Does compiler simultaneously support -c and -o options? +compiler_c_o=$lt_[]_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1) + +# Must we lock files when doing compilation? +need_locks=$lt_need_locks + +# Do we need the lib prefix for modules? +need_lib_prefix=$need_lib_prefix + +# Do we need a version for libraries? +need_version=$need_version + +# Whether dlopen is supported. +dlopen_support=$enable_dlopen + +# Whether dlopen of programs is supported. +dlopen_self=$enable_dlopen_self + +# Whether dlopen of statically linked programs is supported. +dlopen_self_static=$enable_dlopen_self_static + +# Compiler flag to prevent dynamic linking. +link_static_flag=$lt_[]_LT_AC_TAGVAR(lt_prog_compiler_static, $1) + +# Compiler flag to turn off builtin functions. +no_builtin_flag=$lt_[]_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) + +# Compiler flag to allow reflexive dlopens. +export_dynamic_flag_spec=$lt_[]_LT_AC_TAGVAR(export_dynamic_flag_spec, $1) + +# Compiler flag to generate shared objects directly from archives. +whole_archive_flag_spec=$lt_[]_LT_AC_TAGVAR(whole_archive_flag_spec, $1) + +# Compiler flag to generate thread-safe objects. +thread_safe_flag_spec=$lt_[]_LT_AC_TAGVAR(thread_safe_flag_spec, $1) + +# Library versioning type. +version_type=$version_type + +# Format of library name prefix. +libname_spec=$lt_libname_spec + +# List of archive names. First name is the real one, the rest are links. +# The last name is the one that the linker finds with -lNAME. +library_names_spec=$lt_library_names_spec + +# The coded name of the library, if different from the real name. +soname_spec=$lt_soname_spec + +# Commands used to build and install an old-style archive. +RANLIB=$lt_RANLIB +old_archive_cmds=$lt_[]_LT_AC_TAGVAR(old_archive_cmds, $1) +old_postinstall_cmds=$lt_old_postinstall_cmds +old_postuninstall_cmds=$lt_old_postuninstall_cmds + +# Create an old-style archive from a shared archive. +old_archive_from_new_cmds=$lt_[]_LT_AC_TAGVAR(old_archive_from_new_cmds, $1) + +# Create a temporary old-style archive to link instead of a shared archive. +old_archive_from_expsyms_cmds=$lt_[]_LT_AC_TAGVAR(old_archive_from_expsyms_cmds, $1) + +# Commands used to build and install a shared archive. +archive_cmds=$lt_[]_LT_AC_TAGVAR(archive_cmds, $1) +archive_expsym_cmds=$lt_[]_LT_AC_TAGVAR(archive_expsym_cmds, $1) +postinstall_cmds=$lt_postinstall_cmds +postuninstall_cmds=$lt_postuninstall_cmds + +# Commands used to build a loadable module (assumed same as above if empty) +module_cmds=$lt_[]_LT_AC_TAGVAR(module_cmds, $1) +module_expsym_cmds=$lt_[]_LT_AC_TAGVAR(module_expsym_cmds, $1) + +# Commands to strip libraries. +old_striplib=$lt_old_striplib +striplib=$lt_striplib + +# Dependencies to place before the objects being linked to create a +# shared library. +predep_objects=$lt_[]_LT_AC_TAGVAR(predep_objects, $1) + +# Dependencies to place after the objects being linked to create a +# shared library. +postdep_objects=$lt_[]_LT_AC_TAGVAR(postdep_objects, $1) + +# Dependencies to place before the objects being linked to create a +# shared library. +predeps=$lt_[]_LT_AC_TAGVAR(predeps, $1) + +# Dependencies to place after the objects being linked to create a +# shared library. +postdeps=$lt_[]_LT_AC_TAGVAR(postdeps, $1) + +# The library search path used internally by the compiler when linking +# a shared library. +compiler_lib_search_path=$lt_[]_LT_AC_TAGVAR(compiler_lib_search_path, $1) + +# Method to check whether dependent libraries are shared objects. +deplibs_check_method=$lt_deplibs_check_method + +# Command to use when deplibs_check_method == file_magic. +file_magic_cmd=$lt_file_magic_cmd + +# Flag that allows shared libraries with undefined symbols to be built. +allow_undefined_flag=$lt_[]_LT_AC_TAGVAR(allow_undefined_flag, $1) + +# Flag that forces no undefined symbols. +no_undefined_flag=$lt_[]_LT_AC_TAGVAR(no_undefined_flag, $1) + +# Commands used to finish a libtool library installation in a directory. +finish_cmds=$lt_finish_cmds + +# Same as above, but a single script fragment to be evaled but not shown. +finish_eval=$lt_finish_eval + +# Take the output of nm and produce a listing of raw symbols and C names. +global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe + +# Transform the output of nm in a proper C declaration +global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl + +# Transform the output of nm in a C name address pair +global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address + +# This is the shared library runtime path variable. +runpath_var=$runpath_var + +# This is the shared library path variable. +shlibpath_var=$shlibpath_var + +# Is shlibpath searched before the hard-coded library search path? +shlibpath_overrides_runpath=$shlibpath_overrides_runpath + +# How to hardcode a shared library path into an executable. +hardcode_action=$_LT_AC_TAGVAR(hardcode_action, $1) + +# Whether we should hardcode library paths into libraries. +hardcode_into_libs=$hardcode_into_libs + +# Flag to hardcode \$libdir into a binary during linking. +# This must work even if \$libdir does not exist. +hardcode_libdir_flag_spec=$lt_[]_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1) + +# If ld is used when linking, flag to hardcode \$libdir into +# a binary during linking. This must work even if \$libdir does +# not exist. +hardcode_libdir_flag_spec_ld=$lt_[]_LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1) + +# Whether we need a single -rpath flag with a separated argument. +hardcode_libdir_separator=$lt_[]_LT_AC_TAGVAR(hardcode_libdir_separator, $1) + +# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the +# resulting binary. +hardcode_direct=$_LT_AC_TAGVAR(hardcode_direct, $1) + +# Set to yes if using the -LDIR flag during linking hardcodes DIR into the +# resulting binary. +hardcode_minus_L=$_LT_AC_TAGVAR(hardcode_minus_L, $1) + +# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into +# the resulting binary. +hardcode_shlibpath_var=$_LT_AC_TAGVAR(hardcode_shlibpath_var, $1) + +# Set to yes if building a shared library automatically hardcodes DIR into the library +# and all subsequent libraries and executables linked against it. +hardcode_automatic=$_LT_AC_TAGVAR(hardcode_automatic, $1) + +# Variables whose values should be saved in libtool wrapper scripts and +# restored at relink time. +variables_saved_for_relink="$variables_saved_for_relink" + +# Whether libtool must link a program against all its dependency libraries. +link_all_deplibs=$_LT_AC_TAGVAR(link_all_deplibs, $1) + +# Compile-time system search path for libraries +sys_lib_search_path_spec=$lt_sys_lib_search_path_spec + +# Run-time system search path for libraries +sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec + +# Fix the shell variable \$srcfile for the compiler. +fix_srcfile_path=$lt_fix_srcfile_path + +# Set to yes if exported symbols are required. +always_export_symbols=$_LT_AC_TAGVAR(always_export_symbols, $1) + +# The commands to list exported symbols. +export_symbols_cmds=$lt_[]_LT_AC_TAGVAR(export_symbols_cmds, $1) + +# The commands to extract the exported symbol list from a shared archive. +extract_expsyms_cmds=$lt_extract_expsyms_cmds + +# Symbols that should not be listed in the preloaded symbols. +exclude_expsyms=$lt_[]_LT_AC_TAGVAR(exclude_expsyms, $1) + +# Symbols that must always be exported. +include_expsyms=$lt_[]_LT_AC_TAGVAR(include_expsyms, $1) + +ifelse([$1],[], +[# ### END LIBTOOL CONFIG], +[# ### END LIBTOOL TAG CONFIG: $tagname]) + +__EOF__ + +ifelse([$1],[], [ + case $host_os in + aix3*) + cat <<\EOF >> "$cfgfile" + +# AIX sometimes has problems with the GCC collect2 program. For some +# reason, if we set the COLLECT_NAMES environment variable, the problems +# vanish in a puff of smoke. +if test "X${COLLECT_NAMES+set}" != Xset; then + COLLECT_NAMES= + export COLLECT_NAMES +fi +EOF + ;; + esac + + # We use sed instead of cat because bash on DJGPP gets confused if + # if finds mixed CR/LF and LF-only lines. Since sed operates in + # text mode, it properly converts lines to CR/LF. This bash problem + # is reportedly fixed, but why not run on old versions too? + sed '$q' "$ltmain" >> "$cfgfile" || (rm -f "$cfgfile"; exit 1) + + mv -f "$cfgfile" "$ofile" || \ + (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") + chmod +x "$ofile" +]) +else + # If there is no Makefile yet, we rely on a make rule to execute + # `config.status --recheck' to rerun these tests and create the + # libtool script then. + ltmain_in=`echo $ltmain | sed -e 's/\.sh$/.in/'` + if test -f "$ltmain_in"; then + test -f Makefile && make "$ltmain" + fi +fi +])# AC_LIBTOOL_CONFIG + + +# AC_LIBTOOL_PROG_COMPILER_NO_RTTI([TAGNAME]) +# ------------------------------------------- +AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI], +[AC_REQUIRE([_LT_AC_SYS_COMPILER])dnl + +_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)= + +if test "$GCC" = yes; then + _LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' + + AC_LIBTOOL_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions], + lt_cv_prog_compiler_rtti_exceptions, + [-fno-rtti -fno-exceptions], [], + [_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)="$_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) -fno-rtti -fno-exceptions"]) +fi +])# AC_LIBTOOL_PROG_COMPILER_NO_RTTI + + +# AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE +# --------------------------------- +AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE], +[AC_REQUIRE([AC_CANONICAL_HOST]) +AC_REQUIRE([LT_AC_PROG_SED]) +AC_REQUIRE([AC_PROG_NM]) +AC_REQUIRE([AC_OBJEXT]) +# Check for command to grab the raw symbol name followed by C symbol from nm. +AC_MSG_CHECKING([command to parse $NM output from $compiler object]) +AC_CACHE_VAL([lt_cv_sys_global_symbol_pipe], [ -AC_CHECK_HEADER([sys/mman.h], - [libffi_header_sys_mman_h=yes], [libffi_header_sys_mman_h=no]) -AC_CHECK_FUNC([mmap], [libffi_func_mmap=yes], [libffi_func_mmap=no]) -if test "$libffi_header_sys_mman_h" != yes \ - || test "$libffi_func_mmap" != yes; then - ac_cv_func_mmap_file=no - ac_cv_func_mmap_dev_zero=no - ac_cv_func_mmap_anon=no -else - AC_CACHE_CHECK([whether read-only mmap of a plain file works], - ac_cv_func_mmap_file, - [# Add a system to this blacklist if - # mmap(0, stat_size, PROT_READ, MAP_PRIVATE, fd, 0) doesn't return a - # memory area containing the same data that you'd get if you applied - # read() to the same fd. The only system known to have a problem here - # is VMS, where text files have record structure. - case "$host_os" in - vms* | ultrix*) - ac_cv_func_mmap_file=no ;; - *) - ac_cv_func_mmap_file=yes;; - esac]) - AC_CACHE_CHECK([whether mmap from /dev/zero works], - ac_cv_func_mmap_dev_zero, - [# Add a system to this blacklist if it has mmap() but /dev/zero - # does not exist, or if mmapping /dev/zero does not give anonymous - # zeroed pages with both the following properties: - # 1. If you map N consecutive pages in with one call, and then - # unmap any subset of those pages, the pages that were not - # explicitly unmapped remain accessible. - # 2. If you map two adjacent blocks of memory and then unmap them - # both at once, they must both go away. - # Systems known to be in this category are Windows (all variants), - # VMS, and Darwin. - case "$host_os" in - vms* | cygwin* | pe | mingw* | darwin* | ultrix* | hpux10* | hpux11.00) - ac_cv_func_mmap_dev_zero=no ;; - *) - ac_cv_func_mmap_dev_zero=yes;; - esac]) - - # Unlike /dev/zero, the MAP_ANON(YMOUS) defines can be probed for. - AC_CACHE_CHECK([for MAP_ANON(YMOUS)], ac_cv_decl_map_anon, - [AC_TRY_COMPILE( -[#include -#include -#include +# These are sane defaults that work on at least a few old systems. +# [They come from Ultrix. What could be older than Ultrix?!! ;)] + +# Character class describing NM global symbol codes. +symcode='[[BCDEGRST]]' + +# Regexp to match symbols that can be accessed directly from C. +sympat='\([[_A-Za-z]][[_A-Za-z0-9]]*\)' + +# Transform an extracted symbol line into a proper C declaration +lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^. .* \(.*\)$/extern int \1;/p'" + +# Transform an extracted symbol line into symbol name and symbol address +lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\) $/ {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode \([[^ ]]*\) \([[^ ]]*\)$/ {\"\2\", (lt_ptr) \&\2},/p'" + +# Define system-specific variables. +case $host_os in +aix*) + symcode='[[BCDT]]' + ;; +cygwin* | mingw* | pw32*) + symcode='[[ABCDGISTW]]' + ;; +hpux*) # Its linker distinguishes data from code symbols + if test "$host_cpu" = ia64; then + symcode='[[ABCDEGRST]]' + fi + lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'" + lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\) $/ {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/ {\"\2\", (lt_ptr) \&\2},/p'" + ;; +linux* | k*bsd*-gnu) + if test "$host_cpu" = ia64; then + symcode='[[ABCDGIRSTW]]' + lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'" + lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\) $/ {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/ {\"\2\", (lt_ptr) \&\2},/p'" + fi + ;; +irix* | nonstopux*) + symcode='[[BCDEGRST]]' + ;; +osf*) + symcode='[[BCDEGQRST]]' + ;; +solaris*) + symcode='[[BDRT]]' + ;; +sco3.2v5*) + symcode='[[DT]]' + ;; +sysv4.2uw2*) + symcode='[[DT]]' + ;; +sysv5* | sco5v6* | unixware* | OpenUNIX*) + symcode='[[ABDT]]' + ;; +sysv4) + symcode='[[DFNSTU]]' + ;; +esac + +# Handle CRLF in mingw tool chain +opt_cr= +case $build_os in +mingw*) + opt_cr=`echo 'x\{0,1\}' | tr x '\015'` # option cr in regexp + ;; +esac + +# If we're using GNU nm, then use its standard symbol codes. +case `$NM -V 2>&1` in +*GNU* | *'with BFD'*) + symcode='[[ABCDGIRSTW]]' ;; +esac + +# Try without a prefix undercore, then with it. +for ac_symprfx in "" "_"; do + + # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol. + symxfrm="\\1 $ac_symprfx\\2 \\2" + + # Write the raw and C identifiers. + lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[[ ]]\($symcode$symcode*\)[[ ]][[ ]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'" + + # Check to see that the pipe works correctly. + pipe_works=no + + rm -f conftest* + cat > conftest.$ac_ext < $nlist) && test -s "$nlist"; then + # Try sorting and uniquifying the output. + if sort "$nlist" | uniq > "$nlist"T; then + mv -f "$nlist"T "$nlist" + else + rm -f "$nlist"T + fi + + # Make sure that we snagged all the symbols we need. + if grep ' nm_test_var$' "$nlist" >/dev/null; then + if grep ' nm_test_func$' "$nlist" >/dev/null; then + cat < conftest.$ac_ext +#ifdef __cplusplus +extern "C" { +#endif + +EOF + # Now generate the symbol file. + eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | grep -v main >> conftest.$ac_ext' + + cat <> conftest.$ac_ext +#if defined (__STDC__) && __STDC__ +# define lt_ptr_t void * +#else +# define lt_ptr_t char * +# define const +#endif + +/* The mapping between symbol names and symbols. */ +const struct { + const char *name; + lt_ptr_t address; +} +lt_preloaded_symbols[[]] = +{ +EOF + $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/ {\"\2\", (lt_ptr_t) \&\2},/" < "$nlist" | grep -v main >> conftest.$ac_ext + cat <<\EOF >> conftest.$ac_ext + {0, (lt_ptr_t) 0} +}; + +#ifdef __cplusplus +} +#endif +EOF + # Now try linking the two files. + mv conftest.$ac_objext conftstm.$ac_objext + lt_save_LIBS="$LIBS" + lt_save_CFLAGS="$CFLAGS" + LIBS="conftstm.$ac_objext" + CFLAGS="$CFLAGS$_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)" + if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext}; then + pipe_works=yes + fi + LIBS="$lt_save_LIBS" + CFLAGS="$lt_save_CFLAGS" + else + echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD + fi + else + echo "cannot find nm_test_var in $nlist" >&AS_MESSAGE_LOG_FD + fi + else + echo "cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD + fi + else + echo "$progname: failed program was:" >&AS_MESSAGE_LOG_FD + cat conftest.$ac_ext >&5 + fi + rm -f conftest* conftst* + + # Do not use the global_symbol_pipe unless it works. + if test "$pipe_works" = yes; then + break + else + lt_cv_sys_global_symbol_pipe= + fi +done +]) +if test -z "$lt_cv_sys_global_symbol_pipe"; then + lt_cv_sys_global_symbol_to_cdecl= +fi +if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then + AC_MSG_RESULT(failed) +else + AC_MSG_RESULT(ok) +fi +]) # AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE -#ifndef MAP_ANONYMOUS -#define MAP_ANONYMOUS MAP_ANON -#endif + +# AC_LIBTOOL_PROG_COMPILER_PIC([TAGNAME]) +# --------------------------------------- +AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC], +[_LT_AC_TAGVAR(lt_prog_compiler_wl, $1)= +_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)= +_LT_AC_TAGVAR(lt_prog_compiler_static, $1)= + +AC_MSG_CHECKING([for $compiler option to produce PIC]) + ifelse([$1],[CXX],[ + # C++ specific cases for pic, static, wl, etc. + if test "$GXX" = yes; then + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-static' + + case $host_os in + aix*) + # All AIX code is PIC. + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + fi + ;; + amigaos*) + # FIXME: we need at least 68020 code to build shared libraries, but + # adding the `-m68020' flag to GCC prevents building anything better, + # like `-m68040'. + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4' + ;; + beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) + # PIC is the default for these OSes. + ;; + mingw* | cygwin* | os2* | pw32*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + # Although the cygwin gcc ignores -fPIC, still need this for old-style + # (--disable-auto-import) libraries + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT' + ;; + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' + ;; + *djgpp*) + # DJGPP does not support shared libraries at all + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)= + ;; + interix[[3-9]]*) + # Interix 3.x gcc -fpic/-fPIC options generate broken code. + # Instead, we relocate shared libraries at runtime. + ;; + sysv4*MP*) + if test -d /usr/nec; then + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic + fi + ;; + hpux*) + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case $host_cpu in + hppa*64*|ia64*) + ;; + *) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + esac + ;; + *) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + esac + else + case $host_os in + aix4* | aix5*) + # All AIX code is PIC. + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + else + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp' + fi + ;; + chorus*) + case $cc_basename in + cxch68*) + # Green Hills C++ Compiler + # _LT_AC_TAGVAR(lt_prog_compiler_static, $1)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a" + ;; + esac + ;; + darwin*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + case $cc_basename in + xlc*) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-qnocommon' + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + ;; + esac + ;; + dgux*) + case $cc_basename in + ec++*) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + ;; + ghcx*) + # Green Hills C++ Compiler + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic' + ;; + *) + ;; + esac + ;; + freebsd* | dragonfly*) + # FreeBSD uses GNU C++ + ;; + hpux9* | hpux10* | hpux11*) + case $cc_basename in + CC*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive' + if test "$host_cpu" != ia64; then + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='+Z' + fi + ;; + aCC*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive' + case $host_cpu in + hppa*64*|ia64*) + # +Z the default + ;; + *) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='+Z' + ;; + esac + ;; + *) + ;; + esac + ;; + interix*) + # This is c89, which is MS Visual C++ (no shared libs) + # Anyone wants to do a port? + ;; + irix5* | irix6* | nonstopux*) + case $cc_basename in + CC*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + # CC pic flag -KPIC is the default. + ;; + *) + ;; + esac + ;; + linux* | k*bsd*-gnu) + case $cc_basename in + KCC*) + # KAI C++ Compiler + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + icpc* | ecpc*) + # Intel C++ + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-static' + ;; + pgCC*) + # Portland Group C++ compiler. + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + cxx*) + # Compaq C++ + # Make sure the PIC flag is empty. It appears that all Alpha + # Linux and Compaq Tru64 Unix objects are PIC. + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)= + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + ;; + *) + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) + # Sun C++ 5.9 + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' + ;; + esac + ;; + esac + ;; + lynxos*) + ;; + m88k*) + ;; + mvs*) + case $cc_basename in + cxx*) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-W c,exportall' + ;; + *) + ;; + esac + ;; + netbsd*) + ;; + osf3* | osf4* | osf5*) + case $cc_basename in + KCC*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,' + ;; + RCC*) + # Rational C++ 2.4.1 + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic' + ;; + cxx*) + # Digital/Compaq C++ + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + # Make sure the PIC flag is empty. It appears that all Alpha + # Linux and Compaq Tru64 Unix objects are PIC. + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)= + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + ;; + *) + ;; + esac + ;; + psos*) + ;; + solaris*) + case $cc_basename in + CC*) + # Sun C++ 4.2, 5.x and Centerline C++ + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' + ;; + gcx*) + # Green Hills C++ Compiler + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' + ;; + *) + ;; + esac + ;; + sunos4*) + case $cc_basename in + CC*) + # Sun C++ 4.x + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + lcc*) + # Lucid + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic' + ;; + *) + ;; + esac + ;; + tandem*) + case $cc_basename in + NCC*) + # NonStop-UX NCC 3.20 + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + ;; + *) + ;; + esac + ;; + sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) + case $cc_basename in + CC*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + esac + ;; + vxworks*) + ;; + *) + _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no + ;; + esac + fi ], -[int n = MAP_ANONYMOUS;], - ac_cv_decl_map_anon=yes, - ac_cv_decl_map_anon=no)]) +[ + if test "$GCC" = yes; then + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-static' - if test $ac_cv_decl_map_anon = no; then - ac_cv_func_mmap_anon=no - else - AC_CACHE_CHECK([whether mmap with MAP_ANON(YMOUS) works], - ac_cv_func_mmap_anon, - [# Add a system to this blacklist if it has mmap() and MAP_ANON or - # MAP_ANONYMOUS, but using mmap(..., MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) - # doesn't give anonymous zeroed pages with the same properties listed - # above for use of /dev/zero. - # Systems known to be in this category are Windows, VMS, and SCO Unix. - case "$host_os" in - vms* | cygwin* | pe | mingw* | sco* | udk* ) - ac_cv_func_mmap_anon=no ;; - *) - ac_cv_func_mmap_anon=yes;; - esac]) + case $host_os in + aix*) + # All AIX code is PIC. + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + fi + ;; + + amigaos*) + # FIXME: we need at least 68020 code to build shared libraries, but + # adding the `-m68020' flag to GCC prevents building anything better, + # like `-m68040'. + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4' + ;; + + beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) + # PIC is the default for these OSes. + ;; + + mingw* | cygwin* | pw32* | os2*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + # Although the cygwin gcc ignores -fPIC, still need this for old-style + # (--disable-auto-import) libraries + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT' + ;; + + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' + ;; + + interix[[3-9]]*) + # Interix 3.x gcc -fpic/-fPIC options generate broken code. + # Instead, we relocate shared libraries at runtime. + ;; + + msdosdjgpp*) + # Just because we use GCC doesn't mean we suddenly get shared libraries + # on systems that don't support them. + _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no + enable_shared=no + ;; + + sysv4*MP*) + if test -d /usr/nec; then + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic + fi + ;; + + hpux*) + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case $host_cpu in + hppa*64*|ia64*) + # +Z the default + ;; + *) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + esac + ;; + + *) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + esac + else + # PORTME Check for flag to pass linker flags through the system compiler. + case $host_os in + aix*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + else + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp' + fi + ;; + darwin*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + case $cc_basename in + xlc*) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-qnocommon' + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + ;; + esac + ;; + + mingw* | cygwin* | pw32* | os2*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT' + ;; + + hpux9* | hpux10* | hpux11*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case $host_cpu in + hppa*64*|ia64*) + # +Z the default + ;; + *) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='+Z' + ;; + esac + # Is there a better lt_prog_compiler_static that works with the bundled CC? + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive' + ;; + + irix5* | irix6* | nonstopux*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + # PIC (with -KPIC) is the default. + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + ;; + + newsos6) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + + linux* | k*bsd*-gnu) + case $cc_basename in + icc* | ecc*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-static' + ;; + pgcc* | pgf77* | pgf90* | pgf95*) + # Portland Group compilers (*not* the Pentium gcc compiler, + # which looks to be a dead project) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + ccc*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + # All Alpha code is PIC. + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + ;; + *) + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) + # Sun C 5.9 + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + ;; + *Sun\ F*) + # Sun Fortran 8.3 passes all unrecognized flags to the linker + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='' + ;; + esac + ;; + esac + ;; + + osf3* | osf4* | osf5*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + # All OSF/1 code is PIC. + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + ;; + + rdos*) + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + ;; + + solaris*) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + case $cc_basename in + f77* | f90* | f95*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ';; + *) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,';; + esac + ;; + + sunos4*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + + sysv4 | sysv4.2uw2* | sysv4.3*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + + sysv4*MP*) + if test -d /usr/nec ;then + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-Kconform_pic' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + fi + ;; + + sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + + unicos*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no + ;; + + uts4*) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + + *) + _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no + ;; + esac + fi +]) +AC_MSG_RESULT([$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)]) + +# +# Check to make sure the PIC flag actually works. +# +if test -n "$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)"; then + AC_LIBTOOL_COMPILER_OPTION([if $compiler PIC flag $_LT_AC_TAGVAR(lt_prog_compiler_pic, $1) works], + _LT_AC_TAGVAR(lt_prog_compiler_pic_works, $1), + [$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)ifelse([$1],[],[ -DPIC],[ifelse([$1],[CXX],[ -DPIC],[])])], [], + [case $_LT_AC_TAGVAR(lt_prog_compiler_pic, $1) in + "" | " "*) ;; + *) _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=" $_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)" ;; + esac], + [_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)= + _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no]) +fi +case $host_os in + # For platforms which do not support PIC, -DPIC is meaningless: + *djgpp*) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)= + ;; + *) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)="$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)ifelse([$1],[],[ -DPIC],[ifelse([$1],[CXX],[ -DPIC],[])])" + ;; +esac + +# +# Check to make sure the static flag actually works. +# +wl=$_LT_AC_TAGVAR(lt_prog_compiler_wl, $1) eval lt_tmp_static_flag=\"$_LT_AC_TAGVAR(lt_prog_compiler_static, $1)\" +AC_LIBTOOL_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag works], + _LT_AC_TAGVAR(lt_prog_compiler_static_works, $1), + $lt_tmp_static_flag, + [], + [_LT_AC_TAGVAR(lt_prog_compiler_static, $1)=]) +]) + + +# AC_LIBTOOL_PROG_LD_SHLIBS([TAGNAME]) +# ------------------------------------ +# See if the linker supports building shared libraries. +AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS], +[AC_REQUIRE([LT_AC_PROG_SED])dnl +AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries]) +ifelse([$1],[CXX],[ + _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + case $host_os in + aix4* | aix5*) + # If we're using GNU nm, then we don't want the "-C" option. + # -C means demangle to AIX nm, but means don't demangle with GNU nm + if $NM -V 2>&1 | grep 'GNU' > /dev/null; then + _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\[$]2 == "T") || (\[$]2 == "D") || (\[$]2 == "B")) && ([substr](\[$]3,1,1) != ".")) { print \[$]3 } }'\'' | sort -u > $export_symbols' + else + _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\[$]2 == "T") || (\[$]2 == "D") || (\[$]2 == "B")) && ([substr](\[$]3,1,1) != ".")) { print \[$]3 } }'\'' | sort -u > $export_symbols' + fi + ;; + pw32*) + _LT_AC_TAGVAR(export_symbols_cmds, $1)="$ltdll_cmds" + ;; + cygwin* | mingw*) + _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;/^.*[[ ]]__nm__/s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.*[[ ]]//'\'' | sort | uniq > $export_symbols' + ;; + *) + _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + ;; + esac +],[ + runpath_var= + _LT_AC_TAGVAR(allow_undefined_flag, $1)= + _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=no + _LT_AC_TAGVAR(archive_cmds, $1)= + _LT_AC_TAGVAR(archive_expsym_cmds, $1)= + _LT_AC_TAGVAR(old_archive_From_new_cmds, $1)= + _LT_AC_TAGVAR(old_archive_from_expsyms_cmds, $1)= + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)= + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)= + _LT_AC_TAGVAR(thread_safe_flag_spec, $1)= + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)= + _LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)= + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)= + _LT_AC_TAGVAR(hardcode_direct, $1)=no + _LT_AC_TAGVAR(hardcode_minus_L, $1)=no + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=unsupported + _LT_AC_TAGVAR(link_all_deplibs, $1)=unknown + _LT_AC_TAGVAR(hardcode_automatic, $1)=no + _LT_AC_TAGVAR(module_cmds, $1)= + _LT_AC_TAGVAR(module_expsym_cmds, $1)= + _LT_AC_TAGVAR(always_export_symbols, $1)=no + _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + # include_expsyms should be a list of space-separated symbols to be *always* + # included in the symbol list + _LT_AC_TAGVAR(include_expsyms, $1)= + # exclude_expsyms can be an extended regexp of symbols to exclude + # it will be wrapped by ` (' and `)$', so one must not match beginning or + # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc', + # as well as any symbol that contains `d'. + _LT_AC_TAGVAR(exclude_expsyms, $1)="_GLOBAL_OFFSET_TABLE_" + # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out + # platforms (ab)use it in PIC code, but their linkers get confused if + # the symbol is explicitly referenced. Since portable code cannot + # rely on this symbol name, it's probably fine to never include it in + # preloaded symbol tables. + extract_expsyms_cmds= + # Just being paranoid about ensuring that cc_basename is set. + _LT_CC_BASENAME([$compiler]) + case $host_os in + cygwin* | mingw* | pw32*) + # FIXME: the MSVC++ port hasn't been tested in a loooong time + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + if test "$GCC" != yes; then + with_gnu_ld=no + fi + ;; + interix*) + # we just hope/assume this is gcc and not c89 (= MSVC++) + with_gnu_ld=yes + ;; + openbsd*) + with_gnu_ld=no + ;; + esac + + _LT_AC_TAGVAR(ld_shlibs, $1)=yes + if test "$with_gnu_ld" = yes; then + # If archive_cmds runs LD, not CC, wlarc should be empty + wlarc='${wl}' + + # Set some defaults for GNU ld with shared library support. These + # are reset later if shared libraries are not supported. Putting them + # here allows them to be overridden if necessary. + runpath_var=LD_RUN_PATH + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir' + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' + # ancient GNU ld didn't support --whole-archive et. al. + if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' + else + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)= + fi + supports_anon_versioning=no + case `$LD -v 2>/dev/null` in + *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11 + *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... + *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... + *\ 2.11.*) ;; # other 2.11 versions + *) supports_anon_versioning=yes ;; + esac + + # See if GNU ld supports shared libraries. + case $host_os in + aix3* | aix4* | aix5*) + # On AIX/PPC, the GNU linker is very broken + if test "$host_cpu" != ia64; then + _LT_AC_TAGVAR(ld_shlibs, $1)=no + cat <&2 + +*** Warning: the GNU linker, at least up to release 2.9.1, is reported +*** to be unable to reliably create shared libraries on AIX. +*** Therefore, libtool is disabling shared libraries support. If you +*** really care for shared libraries, you may want to modify your PATH +*** so that a non-GNU linker is found, and then restart. + +EOF + fi + ;; + + amigaos*) + _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes + + # Samuel A. Falvo II reports + # that the semantics of dynamic libraries on AmigaOS, at least up + # to version 4, is to share data among multiple programs linked + # with the same dynamic library. Since this doesn't match the + # behavior of shared libraries on other platforms, we can't use + # them. + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + + beos*) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported + # Joseph Beckenbach says some releases of gcc + # support --undefined. This deserves some investigation. FIXME + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + else + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + cygwin* | mingw* | pw32*) + # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless, + # as there is no search path for DLLs. + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported + _LT_AC_TAGVAR(always_export_symbols, $1)=no + _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=yes + _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/'\'' -e '\''/^[[AITW]][[ ]]/s/.*[[ ]]//'\'' | sort | uniq > $export_symbols' + + if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + # If the export-symbols file already is a .def file (1st line + # is EXPORTS), use it as is; otherwise, prepend... + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then + cp $export_symbols $output_objdir/$soname.def; + else + echo EXPORTS > $output_objdir/$soname.def; + cat $export_symbols >> $output_objdir/$soname.def; + fi~ + $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + else + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + interix[[3-9]]*) + _LT_AC_TAGVAR(hardcode_direct, $1)=no + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' + # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. + # Instead, shared libraries are loaded at an image base (0x10000000 by + # default) and relocated if they conflict, which is a slow very memory + # consuming and fragmenting process. To avoid this, we pick a random, + # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link + # time. Moving up from 0x10000000 also allows more sbrk(2) space. + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + ;; + + gnu* | linux* | k*bsd*-gnu) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + tmp_addflag= + case $cc_basename,$host_cpu in + pgcc*) # Portland Group C compiler + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive' + tmp_addflag=' $pic_flag' + ;; + pgf77* | pgf90* | pgf95*) # Portland Group f77 and f90 compilers + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive' + tmp_addflag=' $pic_flag -Mnomain' ;; + ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 + tmp_addflag=' -i_dynamic' ;; + efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 + tmp_addflag=' -i_dynamic -nofor_main' ;; + ifc* | ifort*) # Intel Fortran compiler + tmp_addflag=' -nofor_main' ;; + esac + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) # Sun C 5.9 + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive' + tmp_sharedflag='-G' ;; + *Sun\ F*) # Sun Fortran 8.3 + tmp_sharedflag='-G' ;; + *) + tmp_sharedflag='-shared' ;; + esac + _LT_AC_TAGVAR(archive_cmds, $1)='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + + if test $supports_anon_versioning = yes; then + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $output_objdir/$libname.ver~ + cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ + $echo "local: *; };" >> $output_objdir/$libname.ver~ + $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' + fi + else + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + netbsd*) + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' + wlarc= + else + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + fi + ;; + + solaris*) + if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then + _LT_AC_TAGVAR(ld_shlibs, $1)=no + cat <&2 + +*** Warning: The releases 2.8.* of the GNU linker cannot reliably +*** create shared libraries on Solaris systems. Therefore, libtool +*** is disabling shared libraries support. We urge you to upgrade GNU +*** binutils to release 2.9.1 or newer. Another option is to modify +*** your PATH or compiler configuration so that the native linker is +*** used, and then restart. + +EOF + elif $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) + case `$LD -v 2>&1` in + *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.1[[0-5]].*) + _LT_AC_TAGVAR(ld_shlibs, $1)=no + cat <<_LT_EOF 1>&2 + +*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not +*** reliably create shared libraries on SCO systems. Therefore, libtool +*** is disabling shared libraries support. We urge you to upgrade GNU +*** binutils to release 2.16.91.0.3 or newer. Another option is to modify +*** your PATH or compiler configuration so that the native linker is +*** used, and then restart. + +_LT_EOF + ;; + *) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='`test -z "$SCOABSPATH" && echo ${wl}-rpath,$libdir`' + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname,-retain-symbols-file,$export_symbols -o $lib' + else + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + esac + ;; + + sunos4*) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' + wlarc= + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + *) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + esac + + if test "$_LT_AC_TAGVAR(ld_shlibs, $1)" = no; then + runpath_var= + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)= + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)= + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)= + fi + else + # PORTME fill in a description of your system's linker (not GNU ld) + case $host_os in + aix3*) + _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported + _LT_AC_TAGVAR(always_export_symbols, $1)=yes + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' + # Note: this linker hardcodes the directories in LIBPATH if there + # are no directories specified by -L. + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes + if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then + # Neither direct hardcoding nor static linking is supported with a + # broken collect2. + _LT_AC_TAGVAR(hardcode_direct, $1)=unsupported + fi + ;; + + aix4* | aix5*) + if test "$host_cpu" = ia64; then + # On IA64, the linker does run time linking by default, so we don't + # have to do anything special. + aix_use_runtimelinking=no + exp_sym_flag='-Bexport' + no_entry_flag="" + else + # If we're using GNU nm, then we don't want the "-C" option. + # -C means demangle to AIX nm, but means don't demangle with GNU nm + if $NM -V 2>&1 | grep 'GNU' > /dev/null; then + _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\[$]2 == "T") || (\[$]2 == "D") || (\[$]2 == "B")) && ([substr](\[$]3,1,1) != ".")) { print \[$]3 } }'\'' | sort -u > $export_symbols' + else + _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\[$]2 == "T") || (\[$]2 == "D") || (\[$]2 == "B")) && ([substr](\[$]3,1,1) != ".")) { print \[$]3 } }'\'' | sort -u > $export_symbols' + fi + aix_use_runtimelinking=no + + # Test if we are trying to use run time linking or normal + # AIX style linking. If -brtl is somewhere in LDFLAGS, we + # need to do runtime linking. + case $host_os in aix4.[[23]]|aix4.[[23]].*|aix5*) + for ld_flag in $LDFLAGS; do + if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then + aix_use_runtimelinking=yes + break + fi + done + ;; + esac + + exp_sym_flag='-bexport' + no_entry_flag='-bnoentry' + fi + + # When large executables or shared objects are built, AIX ld can + # have problems creating the table of contents. If linking a library + # or program results in "error TOC overflow" add -mminimal-toc to + # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not + # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. + + _LT_AC_TAGVAR(archive_cmds, $1)='' + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=':' + _LT_AC_TAGVAR(link_all_deplibs, $1)=yes + + if test "$GCC" = yes; then + case $host_os in aix4.[[012]]|aix4.[[012]].*) + # We only want to do this on AIX 4.2 and lower, the check + # below for broken collect2 doesn't work under 4.3+ + collect2name=`${CC} -print-prog-name=collect2` + if test -f "$collect2name" && \ + strings "$collect2name" | grep resolve_lib_name >/dev/null + then + # We have reworked collect2 + : + else + # We have old collect2 + _LT_AC_TAGVAR(hardcode_direct, $1)=unsupported + # It fails to find uninstalled libraries when the uninstalled + # path is not listed in the libpath. Setting hardcode_minus_L + # to unsupported forces relinking + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)= + fi + ;; + esac + shared_flag='-shared' + if test "$aix_use_runtimelinking" = yes; then + shared_flag="$shared_flag "'${wl}-G' + fi + else + # not using gcc + if test "$host_cpu" = ia64; then + # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release + # chokes on -Wl,-G. The following line is correct: + shared_flag='-G' + else + if test "$aix_use_runtimelinking" = yes; then + shared_flag='${wl}-G' + else + shared_flag='${wl}-bM:SRE' + fi + fi + fi + + # It seems that -bexpall does not export symbols beginning with + # underscore (_), so it is better to generate a list of symbols to export. + _LT_AC_TAGVAR(always_export_symbols, $1)=yes + if test "$aix_use_runtimelinking" = yes; then + # Warning - without using the other runtime loading flags (-brtl), + # -berok will link without error, but may produce a broken library. + _LT_AC_TAGVAR(allow_undefined_flag, $1)='-berok' + # Determine the default libpath from the value encoded in an empty executable. + _LT_AC_SYS_LIBPATH_AIX + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" + _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" + else + if test "$host_cpu" = ia64; then + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib' + _LT_AC_TAGVAR(allow_undefined_flag, $1)="-z nodefs" + _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" + else + # Determine the default libpath from the value encoded in an empty executable. + _LT_AC_SYS_LIBPATH_AIX + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" + # Warning - without using the other run time loading flags, + # -berok will link without error, but may produce a broken library. + _LT_AC_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok' + _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok' + # Exported symbols can be pulled into shared objects from archives + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='$convenience' + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=yes + # This is similar to how AIX traditionally builds its shared libraries. + _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' + fi + fi + ;; + + amigaos*) + _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes + # see comment about different semantics on the GNU ld section + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + + bsdi[[45]]*) + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic + ;; + + cygwin* | mingw* | pw32*) + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + # hardcode_libdir_flag_spec is actually meaningless, as there is + # no search path for DLLs. + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' + _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported + # Tell ltmain to make .lib files, not .a files. + libext=lib + # Tell ltmain to make .dll files, not .so files. + shrext_cmds=".dll" + # FIXME: Setting linknames here is a bad hack. + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `echo "$deplibs" | $SED -e '\''s/ -lc$//'\''` -link -dll~linknames=' + # The linker will automatically build a .lib file if we build a DLL. + _LT_AC_TAGVAR(old_archive_From_new_cmds, $1)='true' + # FIXME: Should let the user specify the lib program. + _LT_AC_TAGVAR(old_archive_cmds, $1)='lib -OUT:$oldlib$oldobjs$old_deplibs' + _LT_AC_TAGVAR(fix_srcfile_path, $1)='`cygpath -w "$srcfile"`' + _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=yes + ;; + + darwin* | rhapsody*) + case $host_os in + rhapsody* | darwin1.[[012]]) + _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-undefined ${wl}suppress' + ;; + *) # Darwin 1.3 on + if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then + _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' + else + case ${MACOSX_DEPLOYMENT_TARGET} in + 10.[[012]]) + _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' + ;; + 10.*) + _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-undefined ${wl}dynamic_lookup' + ;; + esac + fi + ;; + esac + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no + _LT_AC_TAGVAR(hardcode_direct, $1)=no + _LT_AC_TAGVAR(hardcode_automatic, $1)=yes + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=unsupported + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='' + _LT_AC_TAGVAR(link_all_deplibs, $1)=yes + if test "$GCC" = yes ; then + output_verbose_link_cmd='echo' + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring' + _LT_AC_TAGVAR(module_cmds, $1)='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags' + # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + _LT_AC_TAGVAR(module_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + else + case $cc_basename in + xlc*) + output_verbose_link_cmd='echo' + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$soname` $xlcverstring' + _LT_AC_TAGVAR(module_cmds, $1)='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags' + # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}$rpath/$soname $xlcverstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + _LT_AC_TAGVAR(module_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + ;; + *) + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + esac + fi + ;; + + dgux*) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + freebsd1*) + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + + # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor + # support. Future versions do this automatically, but an explicit c++rt0.o + # does not break anything, and helps significantly (at the cost of a little + # extra space). + freebsd2.2*) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + # Unfortunately, older versions of FreeBSD 2 do not have this feature. + freebsd2*) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + # FreeBSD 3 and greater uses gcc -shared to do shared libraries. + freebsd* | dragonfly*) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -o $lib $libobjs $deplibs $compiler_flags' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + hpux9*) + if test "$GCC" = yes; then + _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + else + _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + fi + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' + ;; + + hpux10*) + if test "$GCC" = yes -a "$with_gnu_ld" = no; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + else + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' + fi + if test "$with_gnu_ld" = no; then + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes + fi + ;; + + hpux11*) + if test "$GCC" = yes -a "$with_gnu_ld" = no; then + case $host_cpu in + hppa*64*) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + ia64*) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + else + case $host_cpu in + hppa*64*) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + ia64*) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + fi + if test "$with_gnu_ld" = no; then + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + + case $host_cpu in + hppa*64*|ia64*) + _LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='+b $libdir' + _LT_AC_TAGVAR(hardcode_direct, $1)=no + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + *) + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes + ;; + esac + fi + ;; + + irix5* | irix6* | nonstopux*) + if test "$GCC" = yes; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + else + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='-rpath $libdir' + fi + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + _LT_AC_TAGVAR(link_all_deplibs, $1)=yes + ;; + + netbsd*) + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out + else + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF + fi + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + newsos6) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + openbsd*) + if test -f /usr/libexec/ld.so; then + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' + else + case $host_os in + openbsd[[01]].* | openbsd2.[[0-7]] | openbsd2.[[0-7]].*) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + ;; + *) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' + ;; + esac + fi + else + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + os2*) + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes + _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported + _LT_AC_TAGVAR(archive_cmds, $1)='$echo "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$echo "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~$echo DATA >> $output_objdir/$libname.def~$echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~$echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def' + _LT_AC_TAGVAR(old_archive_From_new_cmds, $1)='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def' + ;; + + osf3*) + if test "$GCC" = yes; then + _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + else + _LT_AC_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + fi + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + ;; + + osf4* | osf5*) # as osf3* with the addition of -msym flag + if test "$GCC" = yes; then + _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + else + _LT_AC_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; echo "-hidden">> $lib.exp~ + $LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib~$rm $lib.exp' + + # Both c and cxx compiler support -rpath directly + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' + fi + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + ;; + + solaris*) + _LT_AC_TAGVAR(no_undefined_flag, $1)=' -z text' + if test "$GCC" = yes; then + wlarc='${wl}' + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $CC -shared ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$rm $lib.exp' + else + wlarc='' + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp' + fi + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + case $host_os in + solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; + *) + # The compiler driver will combine and reorder linker options, + # but understands `-z linker_flag'. GCC discards it without `$wl', + # but is careful enough not to reorder. + # Supported since Solaris 2.6 (maybe 2.5.1?) + if test "$GCC" = yes; then + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' + else + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' + fi + ;; + esac + _LT_AC_TAGVAR(link_all_deplibs, $1)=yes + ;; + + sunos4*) + if test "x$host_vendor" = xsequent; then + # Use $CC to link under sequent, because it throws in some extra .o + # files that make .init and .fini sections work. + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags' + else + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' + fi + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + sysv4) + case $host_vendor in + sni) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(hardcode_direct, $1)=yes # is this really true??? + ;; + siemens) + ## LD is ld it makes a PLAMLIB + ## CC just makes a GrossModule. + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(reload_cmds, $1)='$CC -r -o $output$reload_objs' + _LT_AC_TAGVAR(hardcode_direct, $1)=no + ;; + motorola) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(hardcode_direct, $1)=no #Motorola manual says yes, but my tests say they lie + ;; + esac + runpath_var='LD_RUN_PATH' + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + sysv4.3*) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='-Bexport' + ;; + + sysv4*MP*) + if test -d /usr/nec; then + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + runpath_var=LD_RUN_PATH + hardcode_runpath_var=yes + _LT_AC_TAGVAR(ld_shlibs, $1)=yes + fi + ;; + + sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*) + _LT_AC_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + runpath_var='LD_RUN_PATH' + + if test "$GCC" = yes; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + else + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + fi + ;; + + sysv5* | sco3.2v5* | sco5v6*) + # Note: We can NOT use -z defs as we might desire, because we do not + # link with -lc, and that would cause any symbols used from libc to + # always be unresolved, which means just about no library would + # ever link correctly. If we're not using GNU ld we use -z text + # though, which does catch some bad symbols but isn't as heavy-handed + # as -z defs. + _LT_AC_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' + _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs' + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='`test -z "$SCOABSPATH" && echo ${wl}-R,$libdir`' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=':' + _LT_AC_TAGVAR(link_all_deplibs, $1)=yes + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport' + runpath_var='LD_RUN_PATH' + + if test "$GCC" = yes; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + else + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + fi + ;; + + uts4*) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + *) + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + esac + fi +]) +AC_MSG_RESULT([$_LT_AC_TAGVAR(ld_shlibs, $1)]) +test "$_LT_AC_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no + +# +# Do we need to explicitly link libc? +# +case "x$_LT_AC_TAGVAR(archive_cmds_need_lc, $1)" in +x|xyes) + # Assume -lc should be added + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=yes + + if test "$enable_shared" = yes && test "$GCC" = yes; then + case $_LT_AC_TAGVAR(archive_cmds, $1) in + *'~'*) + # FIXME: we may have to deal with multi-command sequences. + ;; + '$CC '*) + # Test whether the compiler implicitly links with -lc since on some + # systems, -lgcc has to come before -lc. If gcc already passes -lc + # to ld, don't add -lc before -lgcc. + AC_MSG_CHECKING([whether -lc should be explicitly linked in]) + $rm conftest* + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + if AC_TRY_EVAL(ac_compile) 2>conftest.err; then + soname=conftest + lib=conftest + libobjs=conftest.$ac_objext + deplibs= + wl=$_LT_AC_TAGVAR(lt_prog_compiler_wl, $1) + pic_flag=$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1) + compiler_flags=-v + linker_flags=-v + verstring= + output_objdir=. + libname=conftest + lt_save_allow_undefined_flag=$_LT_AC_TAGVAR(allow_undefined_flag, $1) + _LT_AC_TAGVAR(allow_undefined_flag, $1)= + if AC_TRY_EVAL(_LT_AC_TAGVAR(archive_cmds, $1) 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1) + then + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no + else + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=yes + fi + _LT_AC_TAGVAR(allow_undefined_flag, $1)=$lt_save_allow_undefined_flag + else + cat conftest.err 1>&5 + fi + $rm conftest* + AC_MSG_RESULT([$_LT_AC_TAGVAR(archive_cmds_need_lc, $1)]) + ;; + esac + fi + ;; +esac +])# AC_LIBTOOL_PROG_LD_SHLIBS + + +# _LT_AC_FILE_LTDLL_C +# ------------------- +# Be careful that the start marker always follows a newline. +AC_DEFUN([_LT_AC_FILE_LTDLL_C], [ +# /* ltdll.c starts here */ +# #define WIN32_LEAN_AND_MEAN +# #include +# #undef WIN32_LEAN_AND_MEAN +# #include +# +# #ifndef __CYGWIN__ +# # ifdef __CYGWIN32__ +# # define __CYGWIN__ __CYGWIN32__ +# # endif +# #endif +# +# #ifdef __cplusplus +# extern "C" { +# #endif +# BOOL APIENTRY DllMain (HINSTANCE hInst, DWORD reason, LPVOID reserved); +# #ifdef __cplusplus +# } +# #endif +# +# #ifdef __CYGWIN__ +# #include +# DECLARE_CYGWIN_DLL( DllMain ); +# #endif +# HINSTANCE __hDllInstance_base; +# +# BOOL APIENTRY +# DllMain (HINSTANCE hInst, DWORD reason, LPVOID reserved) +# { +# __hDllInstance_base = hInst; +# return TRUE; +# } +# /* ltdll.c ends here */ +])# _LT_AC_FILE_LTDLL_C + + +# _LT_AC_TAGVAR(VARNAME, [TAGNAME]) +# --------------------------------- +AC_DEFUN([_LT_AC_TAGVAR], [ifelse([$2], [], [$1], [$1_$2])]) + + +# old names +AC_DEFUN([AM_PROG_LIBTOOL], [AC_PROG_LIBTOOL]) +AC_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)]) +AC_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)]) +AC_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)]) +AC_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)]) +AC_DEFUN([AM_PROG_LD], [AC_PROG_LD]) +AC_DEFUN([AM_PROG_NM], [AC_PROG_NM]) + +# This is just to silence aclocal about the macro not being used +ifelse([AC_DISABLE_FAST_INSTALL]) + +AC_DEFUN([LT_AC_PROG_GCJ], +[AC_CHECK_TOOL(GCJ, gcj, no) + test "x${GCJFLAGS+set}" = xset || GCJFLAGS="-g -O2" + AC_SUBST(GCJFLAGS) +]) + +AC_DEFUN([LT_AC_PROG_RC], +[AC_CHECK_TOOL(RC, windres, no) +]) + + +# Cheap backport of AS_EXECUTABLE_P and required macros +# from Autoconf 2.59; we should not use $as_executable_p directly. + +# _AS_TEST_PREPARE +# ---------------- +m4_ifndef([_AS_TEST_PREPARE], +[m4_defun([_AS_TEST_PREPARE], +[if test -x / >/dev/null 2>&1; then + as_executable_p='test -x' +else + as_executable_p='test -f' +fi +])])# _AS_TEST_PREPARE + +# AS_EXECUTABLE_P +# --------------- +# Check whether a file is executable. +m4_ifndef([AS_EXECUTABLE_P], +[m4_defun([AS_EXECUTABLE_P], +[AS_REQUIRE([_AS_TEST_PREPARE])dnl +$as_executable_p $1[]dnl +])])# AS_EXECUTABLE_P + +# NOTE: This macro has been submitted for inclusion into # +# GNU Autoconf as AC_PROG_SED. When it is available in # +# a released version of Autoconf we should remove this # +# macro and use it instead. # +# LT_AC_PROG_SED +# -------------- +# Check for a fully-functional sed program, that truncates +# as few characters as possible. Prefer GNU sed if found. +AC_DEFUN([LT_AC_PROG_SED], +[AC_MSG_CHECKING([for a sed that does not truncate output]) +AC_CACHE_VAL(lt_cv_path_SED, +[# Loop through the user's path and test for sed and gsed. +# Then use that list of sed's as ones to test for truncation. +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for lt_ac_prog in sed gsed; do + for ac_exec_ext in '' $ac_executable_extensions; do + if AS_EXECUTABLE_P(["$as_dir/$lt_ac_prog$ac_exec_ext"]); then + lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext" + fi + done + done +done +IFS=$as_save_IFS +lt_ac_max=0 +lt_ac_count=0 +# Add /usr/xpg4/bin/sed as it is typically found on Solaris +# along with /bin/sed that truncates output. +for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do + test ! -f $lt_ac_sed && continue + cat /dev/null > conftest.in + lt_ac_count=0 + echo $ECHO_N "0123456789$ECHO_C" >conftest.in + # Check for GNU sed and select it if it is found. + if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then + lt_cv_path_SED=$lt_ac_sed + break + fi + while true; do + cat conftest.in conftest.in >conftest.tmp + mv conftest.tmp conftest.in + cp conftest.in conftest.nl + echo >>conftest.nl + $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break + cmp -s conftest.out conftest.nl || break + # 10000 chars as input seems more than enough + test $lt_ac_count -gt 10 && break + lt_ac_count=`expr $lt_ac_count + 1` + if test $lt_ac_count -gt $lt_ac_max; then + lt_ac_max=$lt_ac_count + lt_cv_path_SED=$lt_ac_sed + fi + done +done +]) +SED=$lt_cv_path_SED +AC_SUBST([SED]) +AC_MSG_RESULT([$SED]) +]) + +# Copyright (C) 2002, 2003, 2005, 2006 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# AM_AUTOMAKE_VERSION(VERSION) +# ---------------------------- +# Automake X.Y traces this macro to ensure aclocal.m4 has been +# generated from the m4 files accompanying Automake X.Y. +# (This private macro should not be called outside this file.) +AC_DEFUN([AM_AUTOMAKE_VERSION], +[am__api_version='1.10' +dnl Some users find AM_AUTOMAKE_VERSION and mistake it for a way to +dnl require some minimum version. Point them to the right macro. +m4_if([$1], [1.10], [], + [AC_FATAL([Do not call $0, use AM_INIT_AUTOMAKE([$1]).])])dnl +]) + +# _AM_AUTOCONF_VERSION(VERSION) +# ----------------------------- +# aclocal traces this macro to find the Autoconf version. +# This is a private macro too. Using m4_define simplifies +# the logic in aclocal, which can simply ignore this definition. +m4_define([_AM_AUTOCONF_VERSION], []) + +# AM_SET_CURRENT_AUTOMAKE_VERSION +# ------------------------------- +# Call AM_AUTOMAKE_VERSION and AM_AUTOMAKE_VERSION so they can be traced. +# This function is AC_REQUIREd by AC_INIT_AUTOMAKE. +AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION], +[AM_AUTOMAKE_VERSION([1.10])dnl +_AM_AUTOCONF_VERSION(m4_PACKAGE_VERSION)]) + +# Figure out how to run the assembler. -*- Autoconf -*- + +# Copyright (C) 2001, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# serial 5 + +# AM_PROG_AS +# ---------- +AC_DEFUN([AM_PROG_AS], +[# By default we simply use the C compiler to build assembly code. +AC_REQUIRE([AC_PROG_CC]) +test "${CCAS+set}" = set || CCAS=$CC +test "${CCASFLAGS+set}" = set || CCASFLAGS=$CFLAGS +AC_ARG_VAR([CCAS], [assembler compiler command (defaults to CC)]) +AC_ARG_VAR([CCASFLAGS], [assembler compiler flags (defaults to CFLAGS)]) +_AM_IF_OPTION([no-dependencies],, [_AM_DEPENDENCIES([CCAS])])dnl +]) + +# AM_AUX_DIR_EXPAND -*- Autoconf -*- + +# Copyright (C) 2001, 2003, 2005 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# For projects using AC_CONFIG_AUX_DIR([foo]), Autoconf sets +# $ac_aux_dir to `$srcdir/foo'. In other projects, it is set to +# `$srcdir', `$srcdir/..', or `$srcdir/../..'. +# +# Of course, Automake must honor this variable whenever it calls a +# tool from the auxiliary directory. The problem is that $srcdir (and +# therefore $ac_aux_dir as well) can be either absolute or relative, +# depending on how configure is run. This is pretty annoying, since +# it makes $ac_aux_dir quite unusable in subdirectories: in the top +# source directory, any form will work fine, but in subdirectories a +# relative path needs to be adjusted first. +# +# $ac_aux_dir/missing +# fails when called from a subdirectory if $ac_aux_dir is relative +# $top_srcdir/$ac_aux_dir/missing +# fails if $ac_aux_dir is absolute, +# fails when called from a subdirectory in a VPATH build with +# a relative $ac_aux_dir +# +# The reason of the latter failure is that $top_srcdir and $ac_aux_dir +# are both prefixed by $srcdir. In an in-source build this is usually +# harmless because $srcdir is `.', but things will broke when you +# start a VPATH build or use an absolute $srcdir. +# +# So we could use something similar to $top_srcdir/$ac_aux_dir/missing, +# iff we strip the leading $srcdir from $ac_aux_dir. That would be: +# am_aux_dir='\$(top_srcdir)/'`expr "$ac_aux_dir" : "$srcdir//*\(.*\)"` +# and then we would define $MISSING as +# MISSING="\${SHELL} $am_aux_dir/missing" +# This will work as long as MISSING is not called from configure, because +# unfortunately $(top_srcdir) has no meaning in configure. +# However there are other variables, like CC, which are often used in +# configure, and could therefore not use this "fixed" $ac_aux_dir. +# +# Another solution, used here, is to always expand $ac_aux_dir to an +# absolute PATH. The drawback is that using absolute paths prevent a +# configured tree to be moved without reconfiguration. + +AC_DEFUN([AM_AUX_DIR_EXPAND], +[dnl Rely on autoconf to set up CDPATH properly. +AC_PREREQ([2.50])dnl +# expand $ac_aux_dir to an absolute path +am_aux_dir=`cd $ac_aux_dir && pwd` +]) + +# AM_CONDITIONAL -*- Autoconf -*- + +# Copyright (C) 1997, 2000, 2001, 2003, 2004, 2005, 2006 +# Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# serial 8 + +# AM_CONDITIONAL(NAME, SHELL-CONDITION) +# ------------------------------------- +# Define a conditional. +AC_DEFUN([AM_CONDITIONAL], +[AC_PREREQ(2.52)dnl + ifelse([$1], [TRUE], [AC_FATAL([$0: invalid condition: $1])], + [$1], [FALSE], [AC_FATAL([$0: invalid condition: $1])])dnl +AC_SUBST([$1_TRUE])dnl +AC_SUBST([$1_FALSE])dnl +_AM_SUBST_NOTMAKE([$1_TRUE])dnl +_AM_SUBST_NOTMAKE([$1_FALSE])dnl +if $2; then + $1_TRUE= + $1_FALSE='#' +else + $1_TRUE='#' + $1_FALSE= +fi +AC_CONFIG_COMMANDS_PRE( +[if test -z "${$1_TRUE}" && test -z "${$1_FALSE}"; then + AC_MSG_ERROR([[conditional "$1" was never defined. +Usually this means the macro was only invoked conditionally.]]) +fi])]) + +# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 +# Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# serial 9 + +# There are a few dirty hacks below to avoid letting `AC_PROG_CC' be +# written in clear, in which case automake, when reading aclocal.m4, +# will think it sees a *use*, and therefore will trigger all it's +# C support machinery. Also note that it means that autoscan, seeing +# CC etc. in the Makefile, will ask for an AC_PROG_CC use... + + +# _AM_DEPENDENCIES(NAME) +# ---------------------- +# See how the compiler implements dependency checking. +# NAME is "CC", "CXX", "GCJ", or "OBJC". +# We try a few techniques and use that to set a single cache variable. +# +# We don't AC_REQUIRE the corresponding AC_PROG_CC since the latter was +# modified to invoke _AM_DEPENDENCIES(CC); we would have a circular +# dependency, and given that the user is not expected to run this macro, +# just rely on AC_PROG_CC. +AC_DEFUN([_AM_DEPENDENCIES], +[AC_REQUIRE([AM_SET_DEPDIR])dnl +AC_REQUIRE([AM_OUTPUT_DEPENDENCY_COMMANDS])dnl +AC_REQUIRE([AM_MAKE_INCLUDE])dnl +AC_REQUIRE([AM_DEP_TRACK])dnl + +ifelse([$1], CC, [depcc="$CC" am_compiler_list=], + [$1], CXX, [depcc="$CXX" am_compiler_list=], + [$1], OBJC, [depcc="$OBJC" am_compiler_list='gcc3 gcc'], + [$1], UPC, [depcc="$UPC" am_compiler_list=], + [$1], GCJ, [depcc="$GCJ" am_compiler_list='gcc3 gcc'], + [depcc="$$1" am_compiler_list=]) + +AC_CACHE_CHECK([dependency style of $depcc], + [am_cv_$1_dependencies_compiler_type], +[if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then + # We make a subdir and do the tests there. Otherwise we can end up + # making bogus files that we don't know about and never remove. For + # instance it was reported that on HP-UX the gcc test will end up + # making a dummy file named `D' -- because `-MD' means `put the output + # in D'. + mkdir conftest.dir + # Copy depcomp to subdir because otherwise we won't find it if we're + # using a relative directory. + cp "$am_depcomp" conftest.dir + cd conftest.dir + # We will build objects and dependencies in a subdirectory because + # it helps to detect inapplicable dependency modes. For instance + # both Tru64's cc and ICC support -MD to output dependencies as a + # side effect of compilation, but ICC will put the dependencies in + # the current directory while Tru64 will put them in the object + # directory. + mkdir sub + + am_cv_$1_dependencies_compiler_type=none + if test "$am_compiler_list" = ""; then + am_compiler_list=`sed -n ['s/^#*\([a-zA-Z0-9]*\))$/\1/p'] < ./depcomp` + fi + for depmode in $am_compiler_list; do + # Setup a source with many dependencies, because some compilers + # like to wrap large dependency lists on column 80 (with \), and + # we should not choose a depcomp mode which is confused by this. + # + # We need to recreate these files for each test, as the compiler may + # overwrite some of them when testing with obscure command lines. + # This happens at least with the AIX C compiler. + : > sub/conftest.c + for i in 1 2 3 4 5 6; do + echo '#include "conftst'$i'.h"' >> sub/conftest.c + # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with + # Solaris 8's {/usr,}/bin/sh. + touch sub/conftst$i.h + done + echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf + + case $depmode in + nosideeffect) + # after this tag, mechanisms are not by side-effect, so they'll + # only be used when explicitly requested + if test "x$enable_dependency_tracking" = xyes; then + continue + else + break + fi + ;; + none) break ;; + esac + # We check with `-c' and `-o' for the sake of the "dashmstdout" + # mode. It turns out that the SunPro C++ compiler does not properly + # handle `-M -o', and we need to detect this. + if depmode=$depmode \ + source=sub/conftest.c object=sub/conftest.${OBJEXT-o} \ + depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ + $SHELL ./depcomp $depcc -c -o sub/conftest.${OBJEXT-o} sub/conftest.c \ + >/dev/null 2>conftest.err && + grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && + grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && + grep sub/conftest.${OBJEXT-o} sub/conftest.Po > /dev/null 2>&1 && + ${MAKE-make} -s -f confmf > /dev/null 2>&1; then + # icc doesn't choke on unknown options, it will just issue warnings + # or remarks (even with -Werror). So we grep stderr for any message + # that says an option was ignored or not supported. + # When given -MP, icc 7.0 and 7.1 complain thusly: + # icc: Command line warning: ignoring option '-M'; no argument required + # The diagnosis changed in icc 8.0: + # icc: Command line remark: option '-MP' not supported + if (grep 'ignoring option' conftest.err || + grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else + am_cv_$1_dependencies_compiler_type=$depmode + break + fi + fi + done + + cd .. + rm -rf conftest.dir +else + am_cv_$1_dependencies_compiler_type=none +fi +]) +AC_SUBST([$1DEPMODE], [depmode=$am_cv_$1_dependencies_compiler_type]) +AM_CONDITIONAL([am__fastdep$1], [ + test "x$enable_dependency_tracking" != xno \ + && test "$am_cv_$1_dependencies_compiler_type" = gcc3]) +]) + + +# AM_SET_DEPDIR +# ------------- +# Choose a directory name for dependency files. +# This macro is AC_REQUIREd in _AM_DEPENDENCIES +AC_DEFUN([AM_SET_DEPDIR], +[AC_REQUIRE([AM_SET_LEADING_DOT])dnl +AC_SUBST([DEPDIR], ["${am__leading_dot}deps"])dnl +]) + + +# AM_DEP_TRACK +# ------------ +AC_DEFUN([AM_DEP_TRACK], +[AC_ARG_ENABLE(dependency-tracking, +[ --disable-dependency-tracking speeds up one-time build + --enable-dependency-tracking do not reject slow dependency extractors]) +if test "x$enable_dependency_tracking" != xno; then + am_depcomp="$ac_aux_dir/depcomp" + AMDEPBACKSLASH='\' +fi +AM_CONDITIONAL([AMDEP], [test "x$enable_dependency_tracking" != xno]) +AC_SUBST([AMDEPBACKSLASH])dnl +_AM_SUBST_NOTMAKE([AMDEPBACKSLASH])dnl +]) + +# Generate code to set up dependency tracking. -*- Autoconf -*- + +# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005 +# Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +#serial 3 + +# _AM_OUTPUT_DEPENDENCY_COMMANDS +# ------------------------------ +AC_DEFUN([_AM_OUTPUT_DEPENDENCY_COMMANDS], +[for mf in $CONFIG_FILES; do + # Strip MF so we end up with the name of the file. + mf=`echo "$mf" | sed -e 's/:.*$//'` + # Check whether this is an Automake generated Makefile or not. + # We used to match only the files named `Makefile.in', but + # some people rename them; so instead we look at the file content. + # Grep'ing the first line is not enough: some people post-process + # each Makefile.in and add a new line on top of each file to say so. + # Grep'ing the whole file is not good either: AIX grep has a line + # limit of 2048, but all sed's we know have understand at least 4000. + if sed 10q "$mf" | grep '^#.*generated by automake' > /dev/null 2>&1; then + dirpart=`AS_DIRNAME("$mf")` + else + continue + fi + # Extract the definition of DEPDIR, am__include, and am__quote + # from the Makefile without running `make'. + DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` + test -z "$DEPDIR" && continue + am__include=`sed -n 's/^am__include = //p' < "$mf"` + test -z "am__include" && continue + am__quote=`sed -n 's/^am__quote = //p' < "$mf"` + # When using ansi2knr, U may be empty or an underscore; expand it + U=`sed -n 's/^U = //p' < "$mf"` + # Find all dependency output files, they are included files with + # $(DEPDIR) in their names. We invoke sed twice because it is the + # simplest approach to changing $(DEPDIR) to its actual value in the + # expansion. + for file in `sed -n " + s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \ + sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do + # Make sure the directory exists. + test -f "$dirpart/$file" && continue + fdir=`AS_DIRNAME(["$file"])` + AS_MKDIR_P([$dirpart/$fdir]) + # echo "creating $dirpart/$file" + echo '# dummy' > "$dirpart/$file" + done +done +])# _AM_OUTPUT_DEPENDENCY_COMMANDS + + +# AM_OUTPUT_DEPENDENCY_COMMANDS +# ----------------------------- +# This macro should only be invoked once -- use via AC_REQUIRE. +# +# This code is only required when automatic dependency tracking +# is enabled. FIXME. This creates each `.P' file that we will +# need in order to bootstrap the dependency handling code. +AC_DEFUN([AM_OUTPUT_DEPENDENCY_COMMANDS], +[AC_CONFIG_COMMANDS([depfiles], + [test x"$AMDEP_TRUE" != x"" || _AM_OUTPUT_DEPENDENCY_COMMANDS], + [AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir"]) +]) + +# Do all the work for Automake. -*- Autoconf -*- + +# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, +# 2005, 2006 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# serial 12 + +# This macro actually does too much. Some checks are only needed if +# your package does certain things. But this isn't really a big deal. + +# AM_INIT_AUTOMAKE(PACKAGE, VERSION, [NO-DEFINE]) +# AM_INIT_AUTOMAKE([OPTIONS]) +# ----------------------------------------------- +# The call with PACKAGE and VERSION arguments is the old style +# call (pre autoconf-2.50), which is being phased out. PACKAGE +# and VERSION should now be passed to AC_INIT and removed from +# the call to AM_INIT_AUTOMAKE. +# We support both call styles for the transition. After +# the next Automake release, Autoconf can make the AC_INIT +# arguments mandatory, and then we can depend on a new Autoconf +# release and drop the old call support. +AC_DEFUN([AM_INIT_AUTOMAKE], +[AC_PREREQ([2.60])dnl +dnl Autoconf wants to disallow AM_ names. We explicitly allow +dnl the ones we care about. +m4_pattern_allow([^AM_[A-Z]+FLAGS$])dnl +AC_REQUIRE([AM_SET_CURRENT_AUTOMAKE_VERSION])dnl +AC_REQUIRE([AC_PROG_INSTALL])dnl +if test "`cd $srcdir && pwd`" != "`pwd`"; then + # Use -I$(srcdir) only when $(srcdir) != ., so that make's output + # is not polluted with repeated "-I." + AC_SUBST([am__isrc], [' -I$(srcdir)'])_AM_SUBST_NOTMAKE([am__isrc])dnl + # test to see if srcdir already configured + if test -f $srcdir/config.status; then + AC_MSG_ERROR([source directory already configured; run "make distclean" there first]) + fi +fi + +# test whether we have cygpath +if test -z "$CYGPATH_W"; then + if (cygpath --version) >/dev/null 2>/dev/null; then + CYGPATH_W='cygpath -w' + else + CYGPATH_W=echo + fi +fi +AC_SUBST([CYGPATH_W]) + +# Define the identity of the package. +dnl Distinguish between old-style and new-style calls. +m4_ifval([$2], +[m4_ifval([$3], [_AM_SET_OPTION([no-define])])dnl + AC_SUBST([PACKAGE], [$1])dnl + AC_SUBST([VERSION], [$2])], +[_AM_SET_OPTIONS([$1])dnl +dnl Diagnose old-style AC_INIT with new-style AM_AUTOMAKE_INIT. +m4_if(m4_ifdef([AC_PACKAGE_NAME], 1)m4_ifdef([AC_PACKAGE_VERSION], 1), 11,, + [m4_fatal([AC_INIT should be called with package and version arguments])])dnl + AC_SUBST([PACKAGE], ['AC_PACKAGE_TARNAME'])dnl + AC_SUBST([VERSION], ['AC_PACKAGE_VERSION'])])dnl + +_AM_IF_OPTION([no-define],, +[AC_DEFINE_UNQUOTED(PACKAGE, "$PACKAGE", [Name of package]) + AC_DEFINE_UNQUOTED(VERSION, "$VERSION", [Version number of package])])dnl + +# Some tools Automake needs. +AC_REQUIRE([AM_SANITY_CHECK])dnl +AC_REQUIRE([AC_ARG_PROGRAM])dnl +AM_MISSING_PROG(ACLOCAL, aclocal-${am__api_version}) +AM_MISSING_PROG(AUTOCONF, autoconf) +AM_MISSING_PROG(AUTOMAKE, automake-${am__api_version}) +AM_MISSING_PROG(AUTOHEADER, autoheader) +AM_MISSING_PROG(MAKEINFO, makeinfo) +AM_PROG_INSTALL_SH +AM_PROG_INSTALL_STRIP +AC_REQUIRE([AM_PROG_MKDIR_P])dnl +# We need awk for the "check" target. The system "awk" is bad on +# some platforms. +AC_REQUIRE([AC_PROG_AWK])dnl +AC_REQUIRE([AC_PROG_MAKE_SET])dnl +AC_REQUIRE([AM_SET_LEADING_DOT])dnl +_AM_IF_OPTION([tar-ustar], [_AM_PROG_TAR([ustar])], + [_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])], + [_AM_PROG_TAR([v7])])]) +_AM_IF_OPTION([no-dependencies],, +[AC_PROVIDE_IFELSE([AC_PROG_CC], + [_AM_DEPENDENCIES(CC)], + [define([AC_PROG_CC], + defn([AC_PROG_CC])[_AM_DEPENDENCIES(CC)])])dnl +AC_PROVIDE_IFELSE([AC_PROG_CXX], + [_AM_DEPENDENCIES(CXX)], + [define([AC_PROG_CXX], + defn([AC_PROG_CXX])[_AM_DEPENDENCIES(CXX)])])dnl +AC_PROVIDE_IFELSE([AC_PROG_OBJC], + [_AM_DEPENDENCIES(OBJC)], + [define([AC_PROG_OBJC], + defn([AC_PROG_OBJC])[_AM_DEPENDENCIES(OBJC)])])dnl +]) +]) + + +# When config.status generates a header, we must update the stamp-h file. +# This file resides in the same directory as the config header +# that is generated. The stamp files are numbered to have different names. + +# Autoconf calls _AC_AM_CONFIG_HEADER_HOOK (when defined) in the +# loop where config.status creates the headers, so we can generate +# our stamp files there. +AC_DEFUN([_AC_AM_CONFIG_HEADER_HOOK], +[# Compute $1's index in $config_headers. +_am_stamp_count=1 +for _am_header in $config_headers :; do + case $_am_header in + $1 | $1:* ) + break ;; + * ) + _am_stamp_count=`expr $_am_stamp_count + 1` ;; + esac +done +echo "timestamp for $1" >`AS_DIRNAME([$1])`/stamp-h[]$_am_stamp_count]) + +# Copyright (C) 2001, 2003, 2005 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# AM_PROG_INSTALL_SH +# ------------------ +# Define $install_sh. +AC_DEFUN([AM_PROG_INSTALL_SH], +[AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl +install_sh=${install_sh-"\$(SHELL) $am_aux_dir/install-sh"} +AC_SUBST(install_sh)]) + +# Copyright (C) 2003, 2005 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# serial 2 + +# Check whether the underlying file-system supports filenames +# with a leading dot. For instance MS-DOS doesn't. +AC_DEFUN([AM_SET_LEADING_DOT], +[rm -rf .tst 2>/dev/null +mkdir .tst 2>/dev/null +if test -d .tst; then + am__leading_dot=. +else + am__leading_dot=_ +fi +rmdir .tst 2>/dev/null +AC_SUBST([am__leading_dot])]) + +# Add --enable-maintainer-mode option to configure. -*- Autoconf -*- +# From Jim Meyering + +# Copyright (C) 1996, 1998, 2000, 2001, 2002, 2003, 2004, 2005 +# Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# serial 4 + +AC_DEFUN([AM_MAINTAINER_MODE], +[AC_MSG_CHECKING([whether to enable maintainer-specific portions of Makefiles]) + dnl maintainer-mode is disabled by default + AC_ARG_ENABLE(maintainer-mode, +[ --enable-maintainer-mode enable make rules and dependencies not useful + (and sometimes confusing) to the casual installer], + USE_MAINTAINER_MODE=$enableval, + USE_MAINTAINER_MODE=no) + AC_MSG_RESULT([$USE_MAINTAINER_MODE]) + AM_CONDITIONAL(MAINTAINER_MODE, [test $USE_MAINTAINER_MODE = yes]) + MAINT=$MAINTAINER_MODE_TRUE + AC_SUBST(MAINT)dnl +] +) + +AU_DEFUN([jm_MAINTAINER_MODE], [AM_MAINTAINER_MODE]) + +# Check to see how 'make' treats includes. -*- Autoconf -*- + +# Copyright (C) 2001, 2002, 2003, 2005 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# serial 3 + +# AM_MAKE_INCLUDE() +# ----------------- +# Check to see how make treats includes. +AC_DEFUN([AM_MAKE_INCLUDE], +[am_make=${MAKE-make} +cat > confinc << 'END' +am__doit: + @echo done +.PHONY: am__doit +END +# If we don't find an include directive, just comment out the code. +AC_MSG_CHECKING([for style of include used by $am_make]) +am__include="#" +am__quote= +_am_result=none +# First try GNU make style include. +echo "include confinc" > confmf +# We grep out `Entering directory' and `Leaving directory' +# messages which can occur if `w' ends up in MAKEFLAGS. +# In particular we don't look at `^make:' because GNU make might +# be invoked under some other name (usually "gmake"), in which +# case it prints its new name instead of `make'. +if test "`$am_make -s -f confmf 2> /dev/null | grep -v 'ing directory'`" = "done"; then + am__include=include + am__quote= + _am_result=GNU +fi +# Now try BSD make style include. +if test "$am__include" = "#"; then + echo '.include "confinc"' > confmf + if test "`$am_make -s -f confmf 2> /dev/null`" = "done"; then + am__include=.include + am__quote="\"" + _am_result=BSD fi fi +AC_SUBST([am__include]) +AC_SUBST([am__quote]) +AC_MSG_RESULT([$_am_result]) +rm -f confinc confmf +]) + +# Copyright (C) 1999, 2000, 2001, 2003, 2004, 2005 +# Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# serial 5 + +# AM_PROG_CC_C_O +# -------------- +# Like AC_PROG_CC_C_O, but changed for automake. +AC_DEFUN([AM_PROG_CC_C_O], +[AC_REQUIRE([AC_PROG_CC_C_O])dnl +AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl +AC_REQUIRE_AUX_FILE([compile])dnl +# FIXME: we rely on the cache variable name because +# there is no other way. +set dummy $CC +ac_cc=`echo $[2] | sed ['s/[^a-zA-Z0-9_]/_/g;s/^[0-9]/_/']` +if eval "test \"`echo '$ac_cv_prog_cc_'${ac_cc}_c_o`\" != yes"; then + # Losing compiler, so override with the script. + # FIXME: It is wrong to rewrite CC. + # But if we don't then we get into trouble of one sort or another. + # A longer-term fix would be to have automake use am__CC in this case, + # and then we could set am__CC="\$(top_srcdir)/compile \$(CC)" + CC="$am_aux_dir/compile $CC" +fi +dnl Make sure AC_PROG_CC is never called again, or it will override our +dnl setting of CC. +m4_define([AC_PROG_CC], + [m4_fatal([AC_PROG_CC cannot be called after AM_PROG_CC_C_O])]) +]) + +# Fake the existence of programs that GNU maintainers use. -*- Autoconf -*- + +# Copyright (C) 1997, 1999, 2000, 2001, 2003, 2004, 2005 +# Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# serial 5 -if test $ac_cv_func_mmap_file = yes; then - AC_DEFINE(HAVE_MMAP_FILE, 1, - [Define if read-only mmap of a plain file works.]) -fi -if test $ac_cv_func_mmap_dev_zero = yes; then - AC_DEFINE(HAVE_MMAP_DEV_ZERO, 1, - [Define if mmap of /dev/zero works.]) -fi -if test $ac_cv_func_mmap_anon = yes; then - AC_DEFINE(HAVE_MMAP_ANON, 1, - [Define if mmap with MAP_ANON(YMOUS) works.]) +# AM_MISSING_PROG(NAME, PROGRAM) +# ------------------------------ +AC_DEFUN([AM_MISSING_PROG], +[AC_REQUIRE([AM_MISSING_HAS_RUN]) +$1=${$1-"${am_missing_run}$2"} +AC_SUBST($1)]) + + +# AM_MISSING_HAS_RUN +# ------------------ +# Define MISSING if not defined so far and test if it supports --run. +# If it does, set am_missing_run to use it, otherwise, to nothing. +AC_DEFUN([AM_MISSING_HAS_RUN], +[AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl +AC_REQUIRE_AUX_FILE([missing])dnl +test x"${MISSING+set}" = xset || MISSING="\${SHELL} $am_aux_dir/missing" +# Use eval to expand $SHELL +if eval "$MISSING --run true"; then + am_missing_run="$MISSING --run " +else + am_missing_run= + AC_MSG_WARN([`missing' script is too old or missing]) fi ]) + +# Copyright (C) 2003, 2004, 2005, 2006 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# AM_PROG_MKDIR_P +# --------------- +# Check for `mkdir -p'. +AC_DEFUN([AM_PROG_MKDIR_P], +[AC_PREREQ([2.60])dnl +AC_REQUIRE([AC_PROG_MKDIR_P])dnl +dnl Automake 1.8 to 1.9.6 used to define mkdir_p. We now use MKDIR_P, +dnl while keeping a definition of mkdir_p for backward compatibility. +dnl @MKDIR_P@ is magic: AC_OUTPUT adjusts its value for each Makefile. +dnl However we cannot define mkdir_p as $(MKDIR_P) for the sake of +dnl Makefile.ins that do not define MKDIR_P, so we do our own +dnl adjustment using top_builddir (which is defined more often than +dnl MKDIR_P). +AC_SUBST([mkdir_p], ["$MKDIR_P"])dnl +case $mkdir_p in + [[\\/$]]* | ?:[[\\/]]*) ;; + */*) mkdir_p="\$(top_builddir)/$mkdir_p" ;; +esac +]) + +# Helper functions for option handling. -*- Autoconf -*- + +# Copyright (C) 2001, 2002, 2003, 2005 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# serial 3 + +# _AM_MANGLE_OPTION(NAME) +# ----------------------- +AC_DEFUN([_AM_MANGLE_OPTION], +[[_AM_OPTION_]m4_bpatsubst($1, [[^a-zA-Z0-9_]], [_])]) + +# _AM_SET_OPTION(NAME) +# ------------------------------ +# Set option NAME. Presently that only means defining a flag for this option. +AC_DEFUN([_AM_SET_OPTION], +[m4_define(_AM_MANGLE_OPTION([$1]), 1)]) + +# _AM_SET_OPTIONS(OPTIONS) +# ---------------------------------- +# OPTIONS is a space-separated list of Automake options. +AC_DEFUN([_AM_SET_OPTIONS], +[AC_FOREACH([_AM_Option], [$1], [_AM_SET_OPTION(_AM_Option)])]) + +# _AM_IF_OPTION(OPTION, IF-SET, [IF-NOT-SET]) +# ------------------------------------------- +# Execute IF-SET if OPTION is set, IF-NOT-SET otherwise. +AC_DEFUN([_AM_IF_OPTION], +[m4_ifset(_AM_MANGLE_OPTION([$1]), [$2], [$3])]) + +# Check to make sure that the build environment is sane. -*- Autoconf -*- + +# Copyright (C) 1996, 1997, 2000, 2001, 2003, 2005 +# Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# serial 4 + +# AM_SANITY_CHECK +# --------------- +AC_DEFUN([AM_SANITY_CHECK], +[AC_MSG_CHECKING([whether build environment is sane]) +# Just in case +sleep 1 +echo timestamp > conftest.file +# Do `set' in a subshell so we don't clobber the current shell's +# arguments. Must try -L first in case configure is actually a +# symlink; some systems play weird games with the mod time of symlinks +# (eg FreeBSD returns the mod time of the symlink's containing +# directory). +if ( + set X `ls -Lt $srcdir/configure conftest.file 2> /dev/null` + if test "$[*]" = "X"; then + # -L didn't work. + set X `ls -t $srcdir/configure conftest.file` + fi + rm -f conftest.file + if test "$[*]" != "X $srcdir/configure conftest.file" \ + && test "$[*]" != "X conftest.file $srcdir/configure"; then + + # If neither matched, then we have a broken ls. This can happen + # if, for instance, CONFIG_SHELL is bash and it inherits a + # broken ls alias from the environment. This has actually + # happened. Such a system could not be considered "sane". + AC_MSG_ERROR([ls -t appears to fail. Make sure there is not a broken +alias in your environment]) + fi + + test "$[2]" = conftest.file + ) +then + # Ok. + : +else + AC_MSG_ERROR([newly created file is older than distributed files! +Check your system clock]) +fi +AC_MSG_RESULT(yes)]) + +# Copyright (C) 2001, 2003, 2005 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# AM_PROG_INSTALL_STRIP +# --------------------- +# One issue with vendor `install' (even GNU) is that you can't +# specify the program used to strip binaries. This is especially +# annoying in cross-compiling environments, where the build's strip +# is unlikely to handle the host's binaries. +# Fortunately install-sh will honor a STRIPPROG variable, so we +# always use install-sh in `make install-strip', and initialize +# STRIPPROG with the value of the STRIP variable (set by the user). +AC_DEFUN([AM_PROG_INSTALL_STRIP], +[AC_REQUIRE([AM_PROG_INSTALL_SH])dnl +# Installed binaries are usually stripped using `strip' when the user +# run `make install-strip'. However `strip' might not be the right +# tool to use in cross-compilation environments, therefore Automake +# will honor the `STRIP' environment variable to overrule this program. +dnl Don't test for $cross_compiling = yes, because it might be `maybe'. +if test "$cross_compiling" != no; then + AC_CHECK_TOOL([STRIP], [strip], :) +fi +INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" +AC_SUBST([INSTALL_STRIP_PROGRAM])]) + +# Copyright (C) 2006 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# _AM_SUBST_NOTMAKE(VARIABLE) +# --------------------------- +# Prevent Automake from outputing VARIABLE = @VARIABLE@ in Makefile.in. +# This macro is traced by Automake. +AC_DEFUN([_AM_SUBST_NOTMAKE]) + +# Check how to create a tarball. -*- Autoconf -*- + +# Copyright (C) 2004, 2005 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# serial 2 + +# _AM_PROG_TAR(FORMAT) +# -------------------- +# Check how to create a tarball in format FORMAT. +# FORMAT should be one of `v7', `ustar', or `pax'. +# +# Substitute a variable $(am__tar) that is a command +# writing to stdout a FORMAT-tarball containing the directory +# $tardir. +# tardir=directory && $(am__tar) > result.tar +# +# Substitute a variable $(am__untar) that extract such +# a tarball read from stdin. +# $(am__untar) < result.tar +AC_DEFUN([_AM_PROG_TAR], +[# Always define AMTAR for backward compatibility. +AM_MISSING_PROG([AMTAR], [tar]) +m4_if([$1], [v7], + [am__tar='${AMTAR} chof - "$$tardir"'; am__untar='${AMTAR} xf -'], + [m4_case([$1], [ustar],, [pax],, + [m4_fatal([Unknown tar format])]) +AC_MSG_CHECKING([how to create a $1 tar archive]) +# Loop over all known methods to create a tar archive until one works. +_am_tools='gnutar m4_if([$1], [ustar], [plaintar]) pax cpio none' +_am_tools=${am_cv_prog_tar_$1-$_am_tools} +# Do not fold the above two line into one, because Tru64 sh and +# Solaris sh will not grok spaces in the rhs of `-'. +for _am_tool in $_am_tools +do + case $_am_tool in + gnutar) + for _am_tar in tar gnutar gtar; + do + AM_RUN_LOG([$_am_tar --version]) && break + done + am__tar="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$$tardir"' + am__tar_="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$tardir"' + am__untar="$_am_tar -xf -" + ;; + plaintar) + # Must skip GNU tar: if it does not support --format= it doesn't create + # ustar tarball either. + (tar --version) >/dev/null 2>&1 && continue + am__tar='tar chf - "$$tardir"' + am__tar_='tar chf - "$tardir"' + am__untar='tar xf -' + ;; + pax) + am__tar='pax -L -x $1 -w "$$tardir"' + am__tar_='pax -L -x $1 -w "$tardir"' + am__untar='pax -r' + ;; + cpio) + am__tar='find "$$tardir" -print | cpio -o -H $1 -L' + am__tar_='find "$tardir" -print | cpio -o -H $1 -L' + am__untar='cpio -i -H $1 -d' + ;; + none) + am__tar=false + am__tar_=false + am__untar=false + ;; + esac + + # If the value was cached, stop now. We just wanted to have am__tar + # and am__untar set. + test -n "${am_cv_prog_tar_$1}" && break + + # tar/untar a dummy directory, and stop if the command works + rm -rf conftest.dir + mkdir conftest.dir + echo GrepMe > conftest.dir/file + AM_RUN_LOG([tardir=conftest.dir && eval $am__tar_ >conftest.tar]) + rm -rf conftest.dir + if test -s conftest.tar; then + AM_RUN_LOG([$am__untar /dev/null 2>&1 && break + fi +done +rm -rf conftest.dir + +AC_CACHE_VAL([am_cv_prog_tar_$1], [am_cv_prog_tar_$1=$_am_tool]) +AC_MSG_RESULT([$am_cv_prog_tar_$1])]) +AC_SUBST([am__tar]) +AC_SUBST([am__untar]) +]) # _AM_PROG_TAR + +m4_include([acinclude.m4]) Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/config.guess ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/config.guess (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/config.guess Wed Apr 30 15:57:13 2008 @@ -1,9 +1,10 @@ #! /bin/sh # Attempt to guess a canonical system name. # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, -# 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc. +# 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, +# Inc. -timestamp='2004-11-12' +timestamp='2007-05-17' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by @@ -17,13 +18,15 @@ # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA +# 02110-1301, USA. # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. + # Originally written by Per Bothner . # Please send patches to . Submit a context # diff and a properly formatted ChangeLog entry. @@ -53,7 +56,7 @@ GNU config.guess ($timestamp) Originally written by Per Bothner. -Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004 +Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO @@ -66,11 +69,11 @@ while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) - echo "$timestamp" ; exit 0 ;; + echo "$timestamp" ; exit ;; --version | -v ) - echo "$version" ; exit 0 ;; + echo "$version" ; exit ;; --help | --h* | -h ) - echo "$usage"; exit 0 ;; + echo "$usage"; exit ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. @@ -104,7 +107,7 @@ trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ; trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ; : ${TMPDIR=/tmp} ; - { tmp=`(umask 077 && mktemp -d -q "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || + { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } || { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } || { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ; @@ -123,7 +126,7 @@ ;; ,,*) CC_FOR_BUILD=$CC ;; ,*,*) CC_FOR_BUILD=$HOST_CC ;; -esac ;' +esac ; set_cc_for_build= ;' # This is needed to find uname on a Pyramid OSx when run in the BSD universe. # (ghazi at noc.rutgers.edu 1994-08-24) @@ -158,6 +161,7 @@ arm*) machine=arm-unknown ;; sh3el) machine=shl-unknown ;; sh3eb) machine=sh-unknown ;; + sh5el) machine=sh5le-unknown ;; *) machine=${UNAME_MACHINE_ARCH}-unknown ;; esac # The Operating System including object format, if it has switched @@ -196,55 +200,23 @@ # contains redundant information, the shorter form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. echo "${machine}-${os}${release}" - exit 0 ;; - amd64:OpenBSD:*:*) - echo x86_64-unknown-openbsd${UNAME_RELEASE} - exit 0 ;; - amiga:OpenBSD:*:*) - echo m68k-unknown-openbsd${UNAME_RELEASE} - exit 0 ;; - cats:OpenBSD:*:*) - echo arm-unknown-openbsd${UNAME_RELEASE} - exit 0 ;; - hp300:OpenBSD:*:*) - echo m68k-unknown-openbsd${UNAME_RELEASE} - exit 0 ;; - luna88k:OpenBSD:*:*) - echo m88k-unknown-openbsd${UNAME_RELEASE} - exit 0 ;; - mac68k:OpenBSD:*:*) - echo m68k-unknown-openbsd${UNAME_RELEASE} - exit 0 ;; - macppc:OpenBSD:*:*) - echo powerpc-unknown-openbsd${UNAME_RELEASE} - exit 0 ;; - mvme68k:OpenBSD:*:*) - echo m68k-unknown-openbsd${UNAME_RELEASE} - exit 0 ;; - mvme88k:OpenBSD:*:*) - echo m88k-unknown-openbsd${UNAME_RELEASE} - exit 0 ;; - mvmeppc:OpenBSD:*:*) - echo powerpc-unknown-openbsd${UNAME_RELEASE} - exit 0 ;; - sgi:OpenBSD:*:*) - echo mips64-unknown-openbsd${UNAME_RELEASE} - exit 0 ;; - sun3:OpenBSD:*:*) - echo m68k-unknown-openbsd${UNAME_RELEASE} - exit 0 ;; + exit ;; *:OpenBSD:*:*) - echo ${UNAME_MACHINE}-unknown-openbsd${UNAME_RELEASE} - exit 0 ;; + UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` + echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE} + exit ;; *:ekkoBSD:*:*) echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE} - exit 0 ;; + exit ;; + *:SolidBSD:*:*) + echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE} + exit ;; macppc:MirBSD:*:*) - echo powerppc-unknown-mirbsd${UNAME_RELEASE} - exit 0 ;; + echo powerpc-unknown-mirbsd${UNAME_RELEASE} + exit ;; *:MirBSD:*:*) echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE} - exit 0 ;; + exit ;; alpha:OSF1:*:*) case $UNAME_RELEASE in *4.0) @@ -297,40 +269,43 @@ # A Xn.n version is an unreleased experimental baselevel. # 1.2 uses "1.2" for uname -r. echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - exit 0 ;; + exit ;; Alpha\ *:Windows_NT*:*) # How do we know it's Interix rather than the generic POSIX subsystem? # Should we change UNAME_MACHINE based on the output of uname instead # of the specific Alpha model? echo alpha-pc-interix - exit 0 ;; + exit ;; 21064:Windows_NT:50:3) echo alpha-dec-winnt3.5 - exit 0 ;; + exit ;; Amiga*:UNIX_System_V:4.0:*) echo m68k-unknown-sysv4 - exit 0;; + exit ;; *:[Aa]miga[Oo][Ss]:*:*) echo ${UNAME_MACHINE}-unknown-amigaos - exit 0 ;; + exit ;; *:[Mm]orph[Oo][Ss]:*:*) echo ${UNAME_MACHINE}-unknown-morphos - exit 0 ;; + exit ;; *:OS/390:*:*) echo i370-ibm-openedition - exit 0 ;; + exit ;; *:z/VM:*:*) echo s390-ibm-zvmoe - exit 0 ;; + exit ;; *:OS400:*:*) echo powerpc-ibm-os400 - exit 0 ;; + exit ;; arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) echo arm-acorn-riscix${UNAME_RELEASE} - exit 0;; + exit ;; + arm:riscos:*:*|arm:RISCOS:*:*) + echo arm-unknown-riscos + exit ;; SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) echo hppa1.1-hitachi-hiuxmpp - exit 0;; + exit ;; Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) # akee at wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. if test "`(/bin/universe) 2>/dev/null`" = att ; then @@ -338,32 +313,32 @@ else echo pyramid-pyramid-bsd fi - exit 0 ;; + exit ;; NILE*:*:*:dcosx) echo pyramid-pyramid-svr4 - exit 0 ;; + exit ;; DRS?6000:unix:4.0:6*) echo sparc-icl-nx6 - exit 0 ;; + exit ;; DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) case `/usr/bin/uname -p` in - sparc) echo sparc-icl-nx7 && exit 0 ;; + sparc) echo sparc-icl-nx7; exit ;; esac ;; sun4H:SunOS:5.*:*) echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` - exit 0 ;; + exit ;; sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` - exit 0 ;; - i86pc:SunOS:5.*:*) + exit ;; + i86pc:SunOS:5.*:* | ix86xen:SunOS:5.*:*) echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` - exit 0 ;; + exit ;; sun4*:SunOS:6*:*) # According to config.sub, this is the proper way to canonicalize # SunOS6. Hard to guess exactly what SunOS6 will be like, but # it's likely to be more like Solaris than SunOS4. echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` - exit 0 ;; + exit ;; sun4*:SunOS:*:*) case "`/usr/bin/arch -k`" in Series*|S4*) @@ -372,10 +347,10 @@ esac # Japanese Language versions have a version number like `4.1.3-JL'. echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` - exit 0 ;; + exit ;; sun3*:SunOS:*:*) echo m68k-sun-sunos${UNAME_RELEASE} - exit 0 ;; + exit ;; sun*:*:4.2BSD:*) UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3 @@ -387,10 +362,10 @@ echo sparc-sun-sunos${UNAME_RELEASE} ;; esac - exit 0 ;; + exit ;; aushp:SunOS:*:*) echo sparc-auspex-sunos${UNAME_RELEASE} - exit 0 ;; + exit ;; # The situation for MiNT is a little confusing. The machine name # can be virtually everything (everything which is not # "atarist" or "atariste" at least should have a processor @@ -401,40 +376,40 @@ # be no problem. atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} - exit 0 ;; + exit ;; atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} - exit 0 ;; + exit ;; *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} - exit 0 ;; + exit ;; milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) echo m68k-milan-mint${UNAME_RELEASE} - exit 0 ;; + exit ;; hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) echo m68k-hades-mint${UNAME_RELEASE} - exit 0 ;; + exit ;; *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) echo m68k-unknown-mint${UNAME_RELEASE} - exit 0 ;; + exit ;; m68k:machten:*:*) echo m68k-apple-machten${UNAME_RELEASE} - exit 0 ;; + exit ;; powerpc:machten:*:*) echo powerpc-apple-machten${UNAME_RELEASE} - exit 0 ;; + exit ;; RISC*:Mach:*:*) echo mips-dec-mach_bsd4.3 - exit 0 ;; + exit ;; RISC*:ULTRIX:*:*) echo mips-dec-ultrix${UNAME_RELEASE} - exit 0 ;; + exit ;; VAX*:ULTRIX*:*:*) echo vax-dec-ultrix${UNAME_RELEASE} - exit 0 ;; + exit ;; 2020:CLIX:*:* | 2430:CLIX:*:*) echo clipper-intergraph-clix${UNAME_RELEASE} - exit 0 ;; + exit ;; mips:*:*:UMIPS | mips:*:*:RISCos) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c @@ -458,32 +433,33 @@ exit (-1); } EOF - $CC_FOR_BUILD -o $dummy $dummy.c \ - && $dummy `echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` \ - && exit 0 + $CC_FOR_BUILD -o $dummy $dummy.c && + dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` && + SYSTEM_NAME=`$dummy $dummyarg` && + { echo "$SYSTEM_NAME"; exit; } echo mips-mips-riscos${UNAME_RELEASE} - exit 0 ;; + exit ;; Motorola:PowerMAX_OS:*:*) echo powerpc-motorola-powermax - exit 0 ;; + exit ;; Motorola:*:4.3:PL8-*) echo powerpc-harris-powermax - exit 0 ;; + exit ;; Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) echo powerpc-harris-powermax - exit 0 ;; + exit ;; Night_Hawk:Power_UNIX:*:*) echo powerpc-harris-powerunix - exit 0 ;; + exit ;; m88k:CX/UX:7*:*) echo m88k-harris-cxux7 - exit 0 ;; + exit ;; m88k:*:4*:R4*) echo m88k-motorola-sysv4 - exit 0 ;; + exit ;; m88k:*:3*:R3*) echo m88k-motorola-sysv3 - exit 0 ;; + exit ;; AViiON:dgux:*:*) # DG/UX returns AViiON for all architectures UNAME_PROCESSOR=`/usr/bin/uname -p` @@ -499,29 +475,29 @@ else echo i586-dg-dgux${UNAME_RELEASE} fi - exit 0 ;; + exit ;; M88*:DolphinOS:*:*) # DolphinOS (SVR3) echo m88k-dolphin-sysv3 - exit 0 ;; + exit ;; M88*:*:R3*:*) # Delta 88k system running SVR3 echo m88k-motorola-sysv3 - exit 0 ;; + exit ;; XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) echo m88k-tektronix-sysv3 - exit 0 ;; + exit ;; Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) echo m68k-tektronix-bsd - exit 0 ;; + exit ;; *:IRIX*:*:*) echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` - exit 0 ;; + exit ;; ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. - echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id - exit 0 ;; # Note that: echo "'`uname -s`'" gives 'AIX ' + echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id + exit ;; # Note that: echo "'`uname -s`'" gives 'AIX ' i*86:AIX:*:*) echo i386-ibm-aix - exit 0 ;; + exit ;; ia64:AIX:*:*) if [ -x /usr/bin/oslevel ] ; then IBM_REV=`/usr/bin/oslevel` @@ -529,7 +505,7 @@ IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} fi echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} - exit 0 ;; + exit ;; *:AIX:2:3) if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then eval $set_cc_for_build @@ -544,14 +520,18 @@ exit(0); } EOF - $CC_FOR_BUILD -o $dummy $dummy.c && $dummy && exit 0 - echo rs6000-ibm-aix3.2.5 + if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` + then + echo "$SYSTEM_NAME" + else + echo rs6000-ibm-aix3.2.5 + fi elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then echo rs6000-ibm-aix3.2.4 else echo rs6000-ibm-aix3.2 fi - exit 0 ;; + exit ;; *:AIX:*:[45]) IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then @@ -565,28 +545,28 @@ IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} fi echo ${IBM_ARCH}-ibm-aix${IBM_REV} - exit 0 ;; + exit ;; *:AIX:*:*) echo rs6000-ibm-aix - exit 0 ;; + exit ;; ibmrt:4.4BSD:*|romp-ibm:BSD:*) echo romp-ibm-bsd4.4 - exit 0 ;; + exit ;; ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to - exit 0 ;; # report: romp-ibm BSD 4.3 + exit ;; # report: romp-ibm BSD 4.3 *:BOSX:*:*) echo rs6000-bull-bosx - exit 0 ;; + exit ;; DPX/2?00:B.O.S.:*:*) echo m68k-bull-sysv3 - exit 0 ;; + exit ;; 9000/[34]??:4.3bsd:1.*:*) echo m68k-hp-bsd - exit 0 ;; + exit ;; hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) echo m68k-hp-bsd4.4 - exit 0 ;; + exit ;; 9000/[34678]??:HP-UX:*:*) HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` case "${UNAME_MACHINE}" in @@ -648,9 +628,19 @@ esac if [ ${HP_ARCH} = "hppa2.0w" ] then - # avoid double evaluation of $set_cc_for_build - test -n "$CC_FOR_BUILD" || eval $set_cc_for_build - if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E -) | grep __LP64__ >/dev/null + eval $set_cc_for_build + + # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating + # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler + # generating 64-bit code. GNU and HP use different nomenclature: + # + # $ CC_FOR_BUILD=cc ./config.guess + # => hppa2.0w-hp-hpux11.23 + # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess + # => hppa64-hp-hpux11.23 + + if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | + grep __LP64__ >/dev/null then HP_ARCH="hppa2.0w" else @@ -658,11 +648,11 @@ fi fi echo ${HP_ARCH}-hp-hpux${HPUX_REV} - exit 0 ;; + exit ;; ia64:HP-UX:*:*) HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` echo ia64-hp-hpux${HPUX_REV} - exit 0 ;; + exit ;; 3050*:HI-UX:*:*) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c @@ -690,158 +680,182 @@ exit (0); } EOF - $CC_FOR_BUILD -o $dummy $dummy.c && $dummy && exit 0 + $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` && + { echo "$SYSTEM_NAME"; exit; } echo unknown-hitachi-hiuxwe2 - exit 0 ;; + exit ;; 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* ) echo hppa1.1-hp-bsd - exit 0 ;; + exit ;; 9000/8??:4.3bsd:*:*) echo hppa1.0-hp-bsd - exit 0 ;; + exit ;; *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) echo hppa1.0-hp-mpeix - exit 0 ;; + exit ;; hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* ) echo hppa1.1-hp-osf - exit 0 ;; + exit ;; hp8??:OSF1:*:*) echo hppa1.0-hp-osf - exit 0 ;; + exit ;; i*86:OSF1:*:*) if [ -x /usr/sbin/sysversion ] ; then echo ${UNAME_MACHINE}-unknown-osf1mk else echo ${UNAME_MACHINE}-unknown-osf1 fi - exit 0 ;; + exit ;; parisc*:Lites*:*:*) echo hppa1.1-hp-lites - exit 0 ;; + exit ;; C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) echo c1-convex-bsd - exit 0 ;; + exit ;; C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) if getsysinfo -f scalar_acc then echo c32-convex-bsd else echo c2-convex-bsd fi - exit 0 ;; + exit ;; C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) echo c34-convex-bsd - exit 0 ;; + exit ;; C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) echo c38-convex-bsd - exit 0 ;; + exit ;; C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) echo c4-convex-bsd - exit 0 ;; + exit ;; CRAY*Y-MP:*:*:*) echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' - exit 0 ;; + exit ;; CRAY*[A-Z]90:*:*:*) echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ -e 's/\.[^.]*$/.X/' - exit 0 ;; + exit ;; CRAY*TS:*:*:*) echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' - exit 0 ;; + exit ;; CRAY*T3E:*:*:*) echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' - exit 0 ;; + exit ;; CRAY*SV1:*:*:*) echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' - exit 0 ;; + exit ;; *:UNICOS/mp:*:*) echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' - exit 0 ;; + exit ;; F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" - exit 0 ;; + exit ;; 5000:UNIX_System_V:4.*:*) FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'` echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" - exit 0 ;; + exit ;; i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} - exit 0 ;; + exit ;; sparc*:BSD/OS:*:*) echo sparc-unknown-bsdi${UNAME_RELEASE} - exit 0 ;; + exit ;; *:BSD/OS:*:*) echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} - exit 0 ;; + exit ;; *:FreeBSD:*:*) - echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` - exit 0 ;; + case ${UNAME_MACHINE} in + pc98) + echo i386-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; + amd64) + echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; + *) + echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; + esac + exit ;; i*:CYGWIN*:*) echo ${UNAME_MACHINE}-pc-cygwin - exit 0 ;; - i*:MINGW*:*) + exit ;; + *:MINGW*:*) echo ${UNAME_MACHINE}-pc-mingw32 - exit 0 ;; + exit ;; + i*:windows32*:*) + # uname -m includes "-pc" on this system. + echo ${UNAME_MACHINE}-mingw32 + exit ;; i*:PW*:*) echo ${UNAME_MACHINE}-pc-pw32 - exit 0 ;; - x86:Interix*:[34]*) - echo i586-pc-interix${UNAME_RELEASE}|sed -e 's/\..*//' - exit 0 ;; + exit ;; + *:Interix*:[3456]*) + case ${UNAME_MACHINE} in + x86) + echo i586-pc-interix${UNAME_RELEASE} + exit ;; + EM64T | authenticamd) + echo x86_64-unknown-interix${UNAME_RELEASE} + exit ;; + esac ;; [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*) echo i${UNAME_MACHINE}-pc-mks - exit 0 ;; + exit ;; i*:Windows_NT*:* | Pentium*:Windows_NT*:*) # How do we know it's Interix rather than the generic POSIX subsystem? # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we # UNAME_MACHINE based on the output of uname instead of i386? echo i586-pc-interix - exit 0 ;; + exit ;; i*:UWIN*:*) echo ${UNAME_MACHINE}-pc-uwin - exit 0 ;; + exit ;; + amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) + echo x86_64-unknown-cygwin + exit ;; p*:CYGWIN*:*) echo powerpcle-unknown-cygwin - exit 0 ;; + exit ;; prep*:SunOS:5.*:*) echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` - exit 0 ;; + exit ;; *:GNU:*:*) # the GNU system echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` - exit 0 ;; + exit ;; *:GNU/*:*:*) # other systems with GNU libc and userland echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu - exit 0 ;; + exit ;; i*86:Minix:*:*) echo ${UNAME_MACHINE}-pc-minix - exit 0 ;; + exit ;; arm*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu - exit 0 ;; + exit ;; + avr32*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; cris:Linux:*:*) echo cris-axis-linux-gnu - exit 0 ;; + exit ;; crisv32:Linux:*:*) echo crisv32-axis-linux-gnu - exit 0 ;; + exit ;; frv:Linux:*:*) echo frv-unknown-linux-gnu - exit 0 ;; + exit ;; ia64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu - exit 0 ;; + exit ;; m32r*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu - exit 0 ;; + exit ;; m68*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu - exit 0 ;; + exit ;; mips:Linux:*:*) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c @@ -858,8 +872,12 @@ #endif #endif EOF - eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^CPU=` - test x"${CPU}" != x && echo "${CPU}-unknown-linux-gnu" && exit 0 + eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n ' + /^CPU/{ + s: ::g + p + }'`" + test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; } ;; mips64:Linux:*:*) eval $set_cc_for_build @@ -877,15 +895,22 @@ #endif #endif EOF - eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^CPU=` - test x"${CPU}" != x && echo "${CPU}-unknown-linux-gnu" && exit 0 + eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n ' + /^CPU/{ + s: ::g + p + }'`" + test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; } ;; + or32:Linux:*:*) + echo or32-unknown-linux-gnu + exit ;; ppc:Linux:*:*) echo powerpc-unknown-linux-gnu - exit 0 ;; + exit ;; ppc64:Linux:*:*) echo powerpc64-unknown-linux-gnu - exit 0 ;; + exit ;; alpha:Linux:*:*) case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in EV5) UNAME_MACHINE=alphaev5 ;; @@ -899,7 +924,7 @@ objdump --private-headers /bin/sh | grep ld.so.1 >/dev/null if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC} - exit 0 ;; + exit ;; parisc:Linux:*:* | hppa:Linux:*:*) # Look for CPU level case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in @@ -907,25 +932,31 @@ PA8*) echo hppa2.0-unknown-linux-gnu ;; *) echo hppa-unknown-linux-gnu ;; esac - exit 0 ;; + exit ;; parisc64:Linux:*:* | hppa64:Linux:*:*) echo hppa64-unknown-linux-gnu - exit 0 ;; + exit ;; s390:Linux:*:* | s390x:Linux:*:*) echo ${UNAME_MACHINE}-ibm-linux - exit 0 ;; + exit ;; sh64*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu - exit 0 ;; + exit ;; sh*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu - exit 0 ;; + exit ;; sparc:Linux:*:* | sparc64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu - exit 0 ;; + exit ;; + vax:Linux:*:*) + echo ${UNAME_MACHINE}-dec-linux-gnu + exit ;; x86_64:Linux:*:*) echo x86_64-unknown-linux-gnu - exit 0 ;; + exit ;; + xtensa:Linux:*:*) + echo xtensa-unknown-linux-gnu + exit ;; i*86:Linux:*:*) # The BFD linker knows what the default object file format is, so # first see if it will tell us. cd to the root directory to prevent @@ -943,15 +974,15 @@ ;; a.out-i386-linux) echo "${UNAME_MACHINE}-pc-linux-gnuaout" - exit 0 ;; + exit ;; coff-i386) echo "${UNAME_MACHINE}-pc-linux-gnucoff" - exit 0 ;; + exit ;; "") # Either a pre-BFD a.out linker (linux-gnuoldld) or # one that does not give us useful --help. echo "${UNAME_MACHINE}-pc-linux-gnuoldld" - exit 0 ;; + exit ;; esac # Determine whether the default compiler is a.out or elf eval $set_cc_for_build @@ -968,7 +999,7 @@ LIBC=gnulibc1 # endif #else - #ifdef __INTEL_COMPILER + #if defined(__INTEL_COMPILER) || defined(__PGI) || defined(__SUNPRO_C) || defined(__SUNPRO_CC) LIBC=gnu #else LIBC=gnuaout @@ -978,16 +1009,23 @@ LIBC=dietlibc #endif EOF - eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^LIBC=` - test x"${LIBC}" != x && echo "${UNAME_MACHINE}-pc-linux-${LIBC}" && exit 0 - test x"${TENTATIVE}" != x && echo "${TENTATIVE}" && exit 0 + eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n ' + /^LIBC/{ + s: ::g + p + }'`" + test x"${LIBC}" != x && { + echo "${UNAME_MACHINE}-pc-linux-${LIBC}" + exit + } + test x"${TENTATIVE}" != x && { echo "${TENTATIVE}"; exit; } ;; i*86:DYNIX/ptx:4*:*) # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. # earlier versions are messed up and put the nodename in both # sysname and nodename. echo i386-sequent-sysv4 - exit 0 ;; + exit ;; i*86:UNIX_SV:4.2MP:2.*) # Unixware is an offshoot of SVR4, but it has its own version # number series starting with 2... @@ -995,27 +1033,27 @@ # I just have to hope. -- rms. # Use sysv4.2uw... so that sysv4* matches it. echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} - exit 0 ;; + exit ;; i*86:OS/2:*:*) # If we were able to find `uname', then EMX Unix compatibility # is probably installed. echo ${UNAME_MACHINE}-pc-os2-emx - exit 0 ;; + exit ;; i*86:XTS-300:*:STOP) echo ${UNAME_MACHINE}-unknown-stop - exit 0 ;; + exit ;; i*86:atheos:*:*) echo ${UNAME_MACHINE}-unknown-atheos - exit 0 ;; - i*86:syllable:*:*) + exit ;; + i*86:syllable:*:*) echo ${UNAME_MACHINE}-pc-syllable - exit 0 ;; + exit ;; i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*) echo i386-unknown-lynxos${UNAME_RELEASE} - exit 0 ;; + exit ;; i*86:*DOS:*:*) echo ${UNAME_MACHINE}-pc-msdosdjgpp - exit 0 ;; + exit ;; i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*) UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then @@ -1023,15 +1061,16 @@ else echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} fi - exit 0 ;; - i*86:*:5:[78]*) + exit ;; + i*86:*:5:[678]*) + # UnixWare 7.x, OpenUNIX and OpenServer 6. case `/bin/uname -X | grep "^Machine"` in *486*) UNAME_MACHINE=i486 ;; *Pentium) UNAME_MACHINE=i586 ;; *Pent*|*Celeron) UNAME_MACHINE=i686 ;; esac echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} - exit 0 ;; + exit ;; i*86:*:3.2:*) if test -f /usr/options/cb.name; then UNAME_REL=`sed -n 's/.*Version //p' /dev/null 2>&1 ; then echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 else # Add other i860-SVR4 vendors below as they are discovered. echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 fi - exit 0 ;; + exit ;; mini*:CTIX:SYS*5:*) # "miniframe" echo m68010-convergent-sysv - exit 0 ;; + exit ;; mc68k:UNIX:SYSTEM5:3.51m) echo m68k-convergent-sysv - exit 0 ;; + exit ;; M680?0:D-NIX:5.3:*) echo m68k-diab-dnix - exit 0 ;; + exit ;; M68*:*:R3V[5678]*:*) - test -r /sysV68 && echo 'm68k-motorola-sysv' && exit 0 ;; + test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) OS_REL='' test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ - && echo i486-ncr-sysv4.3${OS_REL} && exit 0 + && { echo i486-ncr-sysv4.3${OS_REL}; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ - && echo i586-ncr-sysv4.3${OS_REL} && exit 0 ;; + && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ - && echo i486-ncr-sysv4 && exit 0 ;; + && { echo i486-ncr-sysv4; exit; } ;; m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) echo m68k-unknown-lynxos${UNAME_RELEASE} - exit 0 ;; + exit ;; mc68030:UNIX_System_V:4.*:*) echo m68k-atari-sysv4 - exit 0 ;; + exit ;; TSUNAMI:LynxOS:2.*:*) echo sparc-unknown-lynxos${UNAME_RELEASE} - exit 0 ;; + exit ;; rs6000:LynxOS:2.*:*) echo rs6000-unknown-lynxos${UNAME_RELEASE} - exit 0 ;; + exit ;; PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*) echo powerpc-unknown-lynxos${UNAME_RELEASE} - exit 0 ;; + exit ;; SM[BE]S:UNIX_SV:*:*) echo mips-dde-sysv${UNAME_RELEASE} - exit 0 ;; + exit ;; RM*:ReliantUNIX-*:*:*) echo mips-sni-sysv4 - exit 0 ;; + exit ;; RM*:SINIX-*:*:*) echo mips-sni-sysv4 - exit 0 ;; + exit ;; *:SINIX-*:*:*) if uname -p 2>/dev/null >/dev/null ; then UNAME_MACHINE=`(uname -p) 2>/dev/null` @@ -1123,69 +1162,81 @@ else echo ns32k-sni-sysv fi - exit 0 ;; + exit ;; PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort # says echo i586-unisys-sysv4 - exit 0 ;; + exit ;; *:UNIX_System_V:4*:FTX*) # From Gerald Hewes . # How about differentiating between stratus architectures? -djm echo hppa1.1-stratus-sysv4 - exit 0 ;; + exit ;; *:*:*:FTX*) # From seanf at swdc.stratus.com. echo i860-stratus-sysv4 - exit 0 ;; + exit ;; + i*86:VOS:*:*) + # From Paul.Green at stratus.com. + echo ${UNAME_MACHINE}-stratus-vos + exit ;; *:VOS:*:*) # From Paul.Green at stratus.com. echo hppa1.1-stratus-vos - exit 0 ;; + exit ;; mc68*:A/UX:*:*) echo m68k-apple-aux${UNAME_RELEASE} - exit 0 ;; + exit ;; news*:NEWS-OS:6*:*) echo mips-sony-newsos6 - exit 0 ;; + exit ;; R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) if [ -d /usr/nec ]; then echo mips-nec-sysv${UNAME_RELEASE} else echo mips-unknown-sysv${UNAME_RELEASE} fi - exit 0 ;; + exit ;; BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. echo powerpc-be-beos - exit 0 ;; + exit ;; BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. echo powerpc-apple-beos - exit 0 ;; + exit ;; BePC:BeOS:*:*) # BeOS running on Intel PC compatible. echo i586-pc-beos - exit 0 ;; + exit ;; SX-4:SUPER-UX:*:*) echo sx4-nec-superux${UNAME_RELEASE} - exit 0 ;; + exit ;; SX-5:SUPER-UX:*:*) echo sx5-nec-superux${UNAME_RELEASE} - exit 0 ;; + exit ;; SX-6:SUPER-UX:*:*) echo sx6-nec-superux${UNAME_RELEASE} - exit 0 ;; + exit ;; + SX-7:SUPER-UX:*:*) + echo sx7-nec-superux${UNAME_RELEASE} + exit ;; + SX-8:SUPER-UX:*:*) + echo sx8-nec-superux${UNAME_RELEASE} + exit ;; + SX-8R:SUPER-UX:*:*) + echo sx8r-nec-superux${UNAME_RELEASE} + exit ;; Power*:Rhapsody:*:*) echo powerpc-apple-rhapsody${UNAME_RELEASE} - exit 0 ;; + exit ;; *:Rhapsody:*:*) echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} - exit 0 ;; + exit ;; *:Darwin:*:*) UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown case $UNAME_PROCESSOR in - *86) UNAME_PROCESSOR=i686 ;; unknown) UNAME_PROCESSOR=powerpc ;; esac echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE} - exit 0 ;; + exit ;; *:procnto*:*:* | *:QNX:[0123456789]*:*) UNAME_PROCESSOR=`uname -p` if test "$UNAME_PROCESSOR" = "x86"; then @@ -1193,22 +1244,25 @@ UNAME_MACHINE=pc fi echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE} - exit 0 ;; + exit ;; *:QNX:*:4*) echo i386-pc-qnx - exit 0 ;; + exit ;; + NSE-?:NONSTOP_KERNEL:*:*) + echo nse-tandem-nsk${UNAME_RELEASE} + exit ;; NSR-?:NONSTOP_KERNEL:*:*) echo nsr-tandem-nsk${UNAME_RELEASE} - exit 0 ;; + exit ;; *:NonStop-UX:*:*) echo mips-compaq-nonstopux - exit 0 ;; + exit ;; BS2000:POSIX*:*:*) echo bs2000-siemens-sysv - exit 0 ;; + exit ;; DS/*:UNIX_System_V:*:*) echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} - exit 0 ;; + exit ;; *:Plan9:*:*) # "uname -m" is not consistent, so use $cputype instead. 386 # is converted to i386 for consistency with other x86 @@ -1219,41 +1273,47 @@ UNAME_MACHINE="$cputype" fi echo ${UNAME_MACHINE}-unknown-plan9 - exit 0 ;; + exit ;; *:TOPS-10:*:*) echo pdp10-unknown-tops10 - exit 0 ;; + exit ;; *:TENEX:*:*) echo pdp10-unknown-tenex - exit 0 ;; + exit ;; KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) echo pdp10-dec-tops20 - exit 0 ;; + exit ;; XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) echo pdp10-xkl-tops20 - exit 0 ;; + exit ;; *:TOPS-20:*:*) echo pdp10-unknown-tops20 - exit 0 ;; + exit ;; *:ITS:*:*) echo pdp10-unknown-its - exit 0 ;; + exit ;; SEI:*:*:SEIUX) echo mips-sei-seiux${UNAME_RELEASE} - exit 0 ;; + exit ;; *:DragonFly:*:*) echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` - exit 0 ;; + exit ;; *:*VMS:*:*) UNAME_MACHINE=`(uname -p) 2>/dev/null` case "${UNAME_MACHINE}" in - A*) echo alpha-dec-vms && exit 0 ;; - I*) echo ia64-dec-vms && exit 0 ;; - V*) echo vax-dec-vms && exit 0 ;; + A*) echo alpha-dec-vms ; exit ;; + I*) echo ia64-dec-vms ; exit ;; + V*) echo vax-dec-vms ; exit ;; esac ;; *:XENIX:*:SysV) echo i386-pc-xenix - exit 0 ;; + exit ;; + i*86:skyos:*:*) + echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//' + exit ;; + i*86:rdos:*:*) + echo ${UNAME_MACHINE}-pc-rdos + exit ;; esac #echo '(No uname command or uname output not recognized.)' 1>&2 @@ -1285,7 +1345,7 @@ #endif #if defined (__arm) && defined (__acorn) && defined (__unix) - printf ("arm-acorn-riscix"); exit (0); + printf ("arm-acorn-riscix\n"); exit (0); #endif #if defined (hp300) && !defined (hpux) @@ -1374,11 +1434,12 @@ } EOF -$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && $dummy && exit 0 +$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` && + { echo "$SYSTEM_NAME"; exit; } # Apollos put the system type in the environment. -test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit 0; } +test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; } # Convex versions that predate uname can use getsysinfo(1) @@ -1387,22 +1448,22 @@ case `getsysinfo -f cpu_type` in c1*) echo c1-convex-bsd - exit 0 ;; + exit ;; c2*) if getsysinfo -f scalar_acc then echo c32-convex-bsd else echo c2-convex-bsd fi - exit 0 ;; + exit ;; c34*) echo c34-convex-bsd - exit 0 ;; + exit ;; c38*) echo c38-convex-bsd - exit 0 ;; + exit ;; c4*) echo c4-convex-bsd - exit 0 ;; + exit ;; esac fi @@ -1413,7 +1474,9 @@ the operating system you are using. It is advised that you download the most up to date version of the config scripts from - ftp://ftp.gnu.org/pub/gnu/config/ + http://savannah.gnu.org/cgi-bin/viewcvs/*checkout*/config/config/config.guess +and + http://savannah.gnu.org/cgi-bin/viewcvs/*checkout*/config/config/config.sub If the version you run ($0) is already up to date, please send the following data and any information you think might be Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/config.sub ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/config.sub (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/config.sub Wed Apr 30 15:57:13 2008 @@ -1,9 +1,10 @@ #! /bin/sh # Configuration validation subroutine script. # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, -# 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc. +# 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, +# Inc. -timestamp='2005-04-22' +timestamp='2007-04-29' # This file is (in principle) common to ALL GNU software. # The presence of a machine in this file suggests that SOME GNU software @@ -21,14 +22,15 @@ # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, -# Boston, MA 02111-1307, USA. - +# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA +# 02110-1301, USA. +# # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. + # Please send patches to . Submit a context # diff and a properly formatted ChangeLog entry. # @@ -83,11 +85,11 @@ while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) - echo "$timestamp" ; exit 0 ;; + echo "$timestamp" ; exit ;; --version | -v ) - echo "$version" ; exit 0 ;; + echo "$version" ; exit ;; --help | --h* | -h ) - echo "$usage"; exit 0 ;; + echo "$usage"; exit ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. @@ -99,7 +101,7 @@ *local*) # First pass through any local machine types. echo $1 - exit 0;; + exit ;; * ) break ;; @@ -118,8 +120,9 @@ # Here we must recognize all the valid KERNEL-OS combinations. maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` case $maybe_os in - nto-qnx* | linux-gnu* | linux-dietlibc | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | \ - kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* | storm-chaos* | os2-emx* | rtmk-nova*) + nto-qnx* | linux-gnu* | linux-dietlibc | linux-newlib* | linux-uclibc* | \ + uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* | \ + storm-chaos* | os2-emx* | rtmk-nova*) os=-$maybe_os basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` ;; @@ -170,6 +173,10 @@ -hiux*) os=-hiuxwe2 ;; + -sco6) + os=-sco5v6 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; -sco5) os=-sco3.2v5 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` @@ -186,6 +193,10 @@ # Don't forget version if it is 3.2v4 or newer. basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; + -sco5v6*) + # Don't forget version if it is 3.2v4 or newer. + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; -sco*) os=-sco3.2v2 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` @@ -230,15 +241,16 @@ | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \ | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \ | am33_2.0 \ - | arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr \ + | arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr | avr32 \ | bfin \ | c4x | clipper \ | d10v | d30v | dlx | dsp16xx \ - | fr30 | frv \ + | fido | fr30 | frv \ | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \ | i370 | i860 | i960 | ia64 \ | ip2k | iq2000 \ - | m32r | m32rle | m68000 | m68k | m88k | maxq | mcore \ + | m32c | m32r | m32rle | m68000 | m68k | m88k \ + | maxq | mb | microblaze | mcore | mep \ | mips | mipsbe | mipseb | mipsel | mipsle \ | mips16 \ | mips64 | mips64el \ @@ -247,6 +259,7 @@ | mips64vr4100 | mips64vr4100el \ | mips64vr4300 | mips64vr4300el \ | mips64vr5000 | mips64vr5000el \ + | mips64vr5900 | mips64vr5900el \ | mipsisa32 | mipsisa32el \ | mipsisa32r2 | mipsisa32r2el \ | mipsisa64 | mipsisa64el \ @@ -255,21 +268,24 @@ | mipsisa64sr71k | mipsisa64sr71kel \ | mipstx39 | mipstx39el \ | mn10200 | mn10300 \ + | mt \ | msp430 \ + | nios | nios2 \ | ns16k | ns32k \ - | openrisc | or32 \ + | or32 \ | pdp10 | pdp11 | pj | pjl \ | powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \ | pyramid \ - | sh | sh[1234] | sh[23]e | sh[34]eb | shbe | shle | sh[1234]le | sh3ele \ + | score \ + | sh | sh[1234] | sh[24]a | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \ | sh64 | sh64le \ - | sparc | sparc64 | sparc64b | sparc86x | sparclet | sparclite \ - | sparcv8 | sparcv9 | sparcv9b \ - | strongarm \ + | sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \ + | sparcv8 | sparcv9 | sparcv9b | sparcv9v \ + | spu | strongarm \ | tahoe | thumb | tic4x | tic80 | tron \ | v850 | v850e \ | we32k \ - | x86 | xscale | xscalee[bl] | xstormy16 | xtensa \ + | x86 | xc16x | xscale | xscalee[bl] | xstormy16 | xtensa \ | z8k) basic_machine=$basic_machine-unknown ;; @@ -280,6 +296,9 @@ ;; m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k) ;; + ms1) + basic_machine=mt-unknown + ;; # We use `pc' rather than `unknown' # because (1) that's what they normally are, and @@ -299,18 +318,18 @@ | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \ | alphapca5[67]-* | alpha64pca5[67]-* | arc-* \ | arm-* | armbe-* | armle-* | armeb-* | armv*-* \ - | avr-* \ + | avr-* | avr32-* \ | bfin-* | bs2000-* \ | c[123]* | c30-* | [cjt]90-* | c4x-* | c54x-* | c55x-* | c6x-* \ | clipper-* | craynv-* | cydra-* \ | d10v-* | d30v-* | dlx-* \ | elxsi-* \ - | f30[01]-* | f700-* | fr30-* | frv-* | fx80-* \ + | f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \ | h8300-* | h8500-* \ | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \ | i*86-* | i860-* | i960-* | ia64-* \ | ip2k-* | iq2000-* \ - | m32r-* | m32rle-* \ + | m32c-* | m32r-* | m32rle-* \ | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \ | m88110-* | m88k-* | maxq-* | mcore-* \ | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \ @@ -321,6 +340,7 @@ | mips64vr4100-* | mips64vr4100el-* \ | mips64vr4300-* | mips64vr4300el-* \ | mips64vr5000-* | mips64vr5000el-* \ + | mips64vr5900-* | mips64vr5900el-* \ | mipsisa32-* | mipsisa32el-* \ | mipsisa32r2-* | mipsisa32r2el-* \ | mipsisa64-* | mipsisa64el-* \ @@ -329,24 +349,26 @@ | mipsisa64sr71k-* | mipsisa64sr71kel-* \ | mipstx39-* | mipstx39el-* \ | mmix-* \ + | mt-* \ | msp430-* \ + | nios-* | nios2-* \ | none-* | np1-* | ns16k-* | ns32k-* \ | orion-* \ | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \ | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \ | pyramid-* \ | romp-* | rs6000-* \ - | sh-* | sh[1234]-* | sh[23]e-* | sh[34]eb-* | shbe-* \ + | sh-* | sh[1234]-* | sh[24]a-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \ | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \ - | sparc-* | sparc64-* | sparc64b-* | sparc86x-* | sparclet-* \ + | sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \ | sparclite-* \ - | sparcv8-* | sparcv9-* | sparcv9b-* | strongarm-* | sv1-* | sx?-* \ + | sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | strongarm-* | sv1-* | sx?-* \ | tahoe-* | thumb-* \ | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \ | tron-* \ | v850-* | v850e-* | vax-* \ | we32k-* \ - | x86-* | x86_64-* | xps100-* | xscale-* | xscalee[bl]-* \ + | x86-* | x86_64-* | xc16x-* | xps100-* | xscale-* | xscalee[bl]-* \ | xstormy16-* | xtensa-* \ | ymp-* \ | z8k-*) @@ -661,6 +683,10 @@ basic_machine=i386-pc os=-mingw32 ;; + mingw32ce) + basic_machine=arm-unknown + os=-mingw32ce + ;; miniframe) basic_machine=m68000-convergent ;; @@ -686,6 +712,9 @@ basic_machine=i386-pc os=-msdos ;; + ms1-*) + basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'` + ;; mvs) basic_machine=i370-ibm os=-mvs @@ -761,9 +790,8 @@ basic_machine=hppa1.1-oki os=-proelf ;; - or32 | or32-*) + openrisc | openrisc-*) basic_machine=or32-unknown - os=-coff ;; os400) basic_machine=powerpc-ibm @@ -794,6 +822,12 @@ pc532 | pc532-*) basic_machine=ns32k-pc532 ;; + pc98) + basic_machine=i386-pc + ;; + pc98-*) + basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; pentium | p5 | k5 | k6 | nexgen | viac3) basic_machine=i586-pc ;; @@ -850,6 +884,10 @@ basic_machine=i586-unknown os=-pw32 ;; + rdos) + basic_machine=i386-pc + os=-rdos + ;; rom68k) basic_machine=m68k-rom68k os=-coff @@ -876,6 +914,10 @@ sb1el) basic_machine=mipsisa64sb1el-unknown ;; + sde) + basic_machine=mipsisa32-sde + os=-elf + ;; sei) basic_machine=mips-sei os=-seiux @@ -887,6 +929,9 @@ basic_machine=sh-hitachi os=-hms ;; + sh5el) + basic_machine=sh5le-unknown + ;; sh64) basic_machine=sh64-unknown ;; @@ -1089,13 +1134,10 @@ we32k) basic_machine=we32k-att ;; - sh3 | sh4 | sh[34]eb | sh[1234]le | sh[23]ele) + sh[1234] | sh[24]a | sh[34]eb | sh[1234]le | sh[23]ele) basic_machine=sh-unknown ;; - sh64) - basic_machine=sh64-unknown - ;; - sparc | sparcv8 | sparcv9 | sparcv9b) + sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v) basic_machine=sparc-sun ;; cydra) @@ -1168,20 +1210,23 @@ | -aos* \ | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \ - | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* | -openbsd* \ + | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \ + | -openbsd* | -solidbsd* \ | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \ | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \ | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ | -chorusos* | -chorusrdb* \ | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ - | -mingw32* | -linux-gnu* | -linux-uclibc* | -uxpv* | -beos* | -mpeix* | -udk* \ + | -mingw32* | -linux-gnu* | -linux-newlib* | -linux-uclibc* \ + | -uxpv* | -beos* | -mpeix* | -udk* \ | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \ | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \ | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \ | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \ | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \ - | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly*) + | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \ + | -skyos* | -haiku* | -rdos* | -toppers* | -drops*) # Remember, each alternative MUST END IN *, to match a version number. ;; -qnx*) @@ -1199,7 +1244,7 @@ os=`echo $os | sed -e 's|nto|nto-qnx|'` ;; -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \ - | -windows* | -osx | -abug | -netware* | -os9* | -beos* \ + | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \ | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*) ;; -mac*) @@ -1333,6 +1378,12 @@ # system, and we'll never get to this point. case $basic_machine in + score-*) + os=-elf + ;; + spu-*) + os=-elf + ;; *-acorn) os=-riscix1.2 ;; @@ -1342,9 +1393,9 @@ arm*-semi) os=-aout ;; - c4x-* | tic4x-*) - os=-coff - ;; + c4x-* | tic4x-*) + os=-coff + ;; # This must come before the *-dec entry. pdp10-*) os=-tops20 @@ -1370,6 +1421,9 @@ m68*-cisco) os=-aout ;; + mep-*) + os=-elf + ;; mips*-cisco) os=-elf ;; @@ -1388,6 +1442,9 @@ *-be) os=-beos ;; + *-haiku) + os=-haiku + ;; *-ibm) os=-aix ;; @@ -1559,7 +1616,7 @@ esac echo $basic_machine$os -exit 0 +exit # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/configure ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/configure (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/configure Wed Apr 30 15:57:13 2008 @@ -1,27 +1,56 @@ #! /bin/sh # Guess values for system-dependent variables and create Makefiles. -# Generated by GNU Autoconf 2.59 for libffi 2.1. +# Generated by GNU Autoconf 2.61 for libffi 3.0.5. # # Report bugs to . # -# Copyright (C) 2003 Free Software Foundation, Inc. +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, +# 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. # This configure script is free software; the Free Software Foundation # gives unlimited permission to copy, distribute and modify it. ## --------------------- ## ## M4sh Initialization. ## ## --------------------- ## -# Be Bourne compatible +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' -elif test -n "${BASH_VERSION+set}" && (set -o posix) >/dev/null 2>&1; then - set -o posix + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in + *posix*) set -o posix ;; +esac + +fi + + + + +# PATH needs CR +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + echo "#! /bin/sh" >conf$$.sh + echo "exit 0" >>conf$$.sh + chmod +x conf$$.sh + if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then + PATH_SEPARATOR=';' + else + PATH_SEPARATOR=: + fi + rm -f conf$$.sh fi -DUALCASE=1; export DUALCASE # for MKS sh # Support unset when possible. if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then @@ -31,8 +60,43 @@ fi +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +as_nl=' +' +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +case $0 in + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break +done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + { (exit 1); exit 1; } +fi + # Work around bugs in pre-3.0 UWIN ksh. -$as_unset ENV MAIL MAILPATH +for as_var in ENV MAIL MAILPATH +do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var +done PS1='$ ' PS2='> ' PS4='+ ' @@ -46,18 +110,19 @@ if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then eval $as_var=C; export $as_var else - $as_unset $as_var + ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var fi done # Required to use basename. -if expr a : '\(a\)' >/dev/null 2>&1; then +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi -if (basename /) >/dev/null 2>&1 && test "X`basename / 2>&1`" = "X/"; then +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false @@ -65,157 +130,388 @@ # Name of the executable. -as_me=`$as_basename "$0" || +as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ - X"$0" : 'X\(/\)$' \| \ - . : '\(.\)' 2>/dev/null || + X"$0" : 'X\(/\)' \| . 2>/dev/null || echo X/"$0" | - sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/; q; } - /^X\/\(\/\/\)$/{ s//\1/; q; } - /^X\/\(\/\).*/{ s//\1/; q; } - s/.*/./; q'` + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` +# CDPATH. +$as_unset CDPATH -# PATH needs CR, and LINENO needs CR and PATH. -# Avoid depending upon Character Ranges. -as_cr_letters='abcdefghijklmnopqrstuvwxyz' -as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' -as_cr_Letters=$as_cr_letters$as_cr_LETTERS -as_cr_digits='0123456789' -as_cr_alnum=$as_cr_Letters$as_cr_digits -# The user is always right. -if test "${PATH_SEPARATOR+set}" != set; then - echo "#! /bin/sh" >conf$$.sh - echo "exit 0" >>conf$$.sh - chmod +x conf$$.sh - if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then - PATH_SEPARATOR=';' - else - PATH_SEPARATOR=: - fi - rm -f conf$$.sh +if test "x$CONFIG_SHELL" = x; then + if (eval ":") 2>/dev/null; then + as_have_required=yes +else + as_have_required=no fi + if test $as_have_required = yes && (eval ": +(as_func_return () { + (exit \$1) +} +as_func_success () { + as_func_return 0 +} +as_func_failure () { + as_func_return 1 +} +as_func_ret_success () { + return 0 +} +as_func_ret_failure () { + return 1 +} - as_lineno_1=$LINENO - as_lineno_2=$LINENO - as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null` - test "x$as_lineno_1" != "x$as_lineno_2" && - test "x$as_lineno_3" = "x$as_lineno_2" || { - # Find who we are. Look in the path if we contain no path at all - # relative or not. - case $0 in - *[\\/]* ) as_myself=$0 ;; - *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break -done +exitcode=0 +if as_func_success; then + : +else + exitcode=1 + echo as_func_success failed. +fi - ;; - esac - # We did not find ourselves, most probably we were run as `sh COMMAND' - # in which case we are not to be found in the path. - if test "x$as_myself" = x; then - as_myself=$0 - fi - if test ! -f "$as_myself"; then - { echo "$as_me: error: cannot find myself; rerun with an absolute path" >&2 - { (exit 1); exit 1; }; } - fi - case $CONFIG_SHELL in - '') +if as_func_failure; then + exitcode=1 + echo as_func_failure succeeded. +fi + +if as_func_ret_success; then + : +else + exitcode=1 + echo as_func_ret_success failed. +fi + +if as_func_ret_failure; then + exitcode=1 + echo as_func_ret_failure succeeded. +fi + +if ( set x; as_func_ret_success y && test x = \"\$1\" ); then + : +else + exitcode=1 + echo positional parameters were not saved. +fi + +test \$exitcode = 0) || { (exit 1); exit 1; } + +( + as_lineno_1=\$LINENO + as_lineno_2=\$LINENO + test \"x\$as_lineno_1\" != \"x\$as_lineno_2\" && + test \"x\`expr \$as_lineno_1 + 1\`\" = \"x\$as_lineno_2\") || { (exit 1); exit 1; } +") 2> /dev/null; then + : +else + as_candidate_shells= as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for as_base in sh bash ksh sh5; do - case $as_dir in + case $as_dir in /*) - if ("$as_dir/$as_base" -c ' + for as_base in sh bash ksh sh5; do + as_candidate_shells="$as_candidate_shells $as_dir/$as_base" + done;; + esac +done +IFS=$as_save_IFS + + + for as_shell in $as_candidate_shells $SHELL; do + # Try only shells that exist, to save several forks. + if { test -f "$as_shell" || test -f "$as_shell.exe"; } && + { ("$as_shell") 2> /dev/null <<\_ASEOF +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in + *posix*) set -o posix ;; +esac + +fi + + +: +_ASEOF +}; then + CONFIG_SHELL=$as_shell + as_have_required=yes + if { "$as_shell" 2> /dev/null <<\_ASEOF +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in + *posix*) set -o posix ;; +esac + +fi + + +: +(as_func_return () { + (exit $1) +} +as_func_success () { + as_func_return 0 +} +as_func_failure () { + as_func_return 1 +} +as_func_ret_success () { + return 0 +} +as_func_ret_failure () { + return 1 +} + +exitcode=0 +if as_func_success; then + : +else + exitcode=1 + echo as_func_success failed. +fi + +if as_func_failure; then + exitcode=1 + echo as_func_failure succeeded. +fi + +if as_func_ret_success; then + : +else + exitcode=1 + echo as_func_ret_success failed. +fi + +if as_func_ret_failure; then + exitcode=1 + echo as_func_ret_failure succeeded. +fi + +if ( set x; as_func_ret_success y && test x = "$1" ); then + : +else + exitcode=1 + echo positional parameters were not saved. +fi + +test $exitcode = 0) || { (exit 1); exit 1; } + +( as_lineno_1=$LINENO as_lineno_2=$LINENO - as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null` test "x$as_lineno_1" != "x$as_lineno_2" && - test "x$as_lineno_3" = "x$as_lineno_2" ') 2>/dev/null; then - $as_unset BASH_ENV || test "${BASH_ENV+set}" != set || { BASH_ENV=; export BASH_ENV; } - $as_unset ENV || test "${ENV+set}" != set || { ENV=; export ENV; } - CONFIG_SHELL=$as_dir/$as_base - export CONFIG_SHELL - exec "$CONFIG_SHELL" "$0" ${1+"$@"} - fi;; - esac - done -done -;; - esac + test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2") || { (exit 1); exit 1; } + +_ASEOF +}; then + break +fi + +fi + + done + + if test "x$CONFIG_SHELL" != x; then + for as_var in BASH_ENV ENV + do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var + done + export CONFIG_SHELL + exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"} +fi + + + if test $as_have_required = no; then + echo This script requires a shell more modern than all the + echo shells that I found on your system. Please install a + echo modern shell, or manually run the script under such a + echo shell if you do have one. + { (exit 1); exit 1; } +fi + + +fi + +fi + + + +(eval "as_func_return () { + (exit \$1) +} +as_func_success () { + as_func_return 0 +} +as_func_failure () { + as_func_return 1 +} +as_func_ret_success () { + return 0 +} +as_func_ret_failure () { + return 1 +} + +exitcode=0 +if as_func_success; then + : +else + exitcode=1 + echo as_func_success failed. +fi + +if as_func_failure; then + exitcode=1 + echo as_func_failure succeeded. +fi + +if as_func_ret_success; then + : +else + exitcode=1 + echo as_func_ret_success failed. +fi + +if as_func_ret_failure; then + exitcode=1 + echo as_func_ret_failure succeeded. +fi + +if ( set x; as_func_ret_success y && test x = \"\$1\" ); then + : +else + exitcode=1 + echo positional parameters were not saved. +fi + +test \$exitcode = 0") || { + echo No shell found that supports shell functions. + echo Please tell autoconf at gnu.org about your system, + echo including any error possibly output before this + echo message +} + + + + as_lineno_1=$LINENO + as_lineno_2=$LINENO + test "x$as_lineno_1" != "x$as_lineno_2" && + test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || { # Create $as_me.lineno as a copy of $as_myself, but with $LINENO # uniformly replaced by the line number. The first 'sed' inserts a - # line-number line before each line; the second 'sed' does the real - # work. The second script uses 'N' to pair each line-number line - # with the numbered line, and appends trailing '-' during - # substitution so that $LINENO is not a special case at line end. + # line-number line after each line using $LINENO; the second 'sed' + # does the real work. The second script uses 'N' to pair each + # line-number line with the line containing $LINENO, and appends + # trailing '-' during substitution so that $LINENO is not a special + # case at line end. # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the - # second 'sed' script. Blame Lee E. McMahon for sed's syntax. :-) - sed '=' <$as_myself | + # scripts with optimization help from Paolo Bonzini. Blame Lee + # E. McMahon (1931-1989) for sed's syntax. :-) + sed -n ' + p + /[$]LINENO/= + ' <$as_myself | sed ' + s/[$]LINENO.*/&-/ + t lineno + b + :lineno N - s,$,-, - : loop - s,^\(['$as_cr_digits']*\)\(.*\)[$]LINENO\([^'$as_cr_alnum'_]\),\1\2\1\3, + :loop + s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ t loop - s,-$,, - s,^['$as_cr_digits']*\n,, + s/-\n.*// ' >$as_me.lineno && - chmod +x $as_me.lineno || + chmod +x "$as_me.lineno" || { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 { (exit 1); exit 1; }; } # Don't try to exec as it changes $[0], causing all sort of problems # (the dirname of $[0] is not the place where we might find the - # original and so on. Autoconf is especially sensible to this). - . ./$as_me.lineno + # original and so on. Autoconf is especially sensitive to this). + . "./$as_me.lineno" # Exit status is that of the last command. exit } -case `echo "testing\c"; echo 1,2,3`,`echo -n testing; echo 1,2,3` in - *c*,-n*) ECHO_N= ECHO_C=' -' ECHO_T=' ' ;; - *c*,* ) ECHO_N=-n ECHO_C= ECHO_T= ;; - *) ECHO_N= ECHO_C='\c' ECHO_T= ;; +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in +-n*) + case `echo 'x\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + *) ECHO_C='\c';; + esac;; +*) + ECHO_N='-n';; esac -if expr a : '\(a\)' >/dev/null 2>&1; then +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir +fi echo >conf$$.file if ln -s conf$$.file conf$$ 2>/dev/null; then - # We could just check for DJGPP; but this test a) works b) is more generic - # and c) will remain valid once DJGPP supports symlinks (DJGPP 2.04). - if test -f conf$$.exe; then - # Don't use ln at all; we don't have any links + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -p'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -p' - else - as_ln_s='ln -s' - fi elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -p' fi -rm -f conf$$ conf$$.exe conf$$.file +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null if mkdir -p . 2>/dev/null; then as_mkdir_p=: @@ -224,7 +520,28 @@ as_mkdir_p=false fi -as_executable_p="test -f" +if test -x / >/dev/null 2>&1; then + as_test_x='test -x' +else + if ls -dL / >/dev/null 2>&1; then + as_ls_L_option=L + else + as_ls_L_option= + fi + as_test_x=' + eval sh -c '\'' + if test -d "$1"; then + test -d "$1/."; + else + case $1 in + -*)set "./$1";; + esac; + case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in + ???[sx]*):;;*)false;;esac;fi + '\'' sh + ' +fi +as_executable_p=$as_test_x # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" @@ -233,85 +550,414 @@ as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" -# IFS -# We need space, tab and new line, in precisely that order. -as_nl=' -' -IFS=" $as_nl" - -# CDPATH. -$as_unset CDPATH -# Name of the host. -# hostname on some systems (SVR3.2, Linux) returns a bogus exit status, -# so uname gets run too. -ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` +# Check that we are running under the correct shell. +SHELL=${CONFIG_SHELL-/bin/sh} -exec 6>&1 +case X$ECHO in +X*--fallback-echo) + # Remove one level of quotation (which was required for Make). + ECHO=`echo "$ECHO" | sed 's,\\\\\$\\$0,'$0','` + ;; +esac -# -# Initializations. -# -ac_default_prefix=/usr/local -ac_config_libobj_dir=. -cross_compiling=no -subdirs= -MFLAGS= -MAKEFLAGS= -SHELL=${CONFIG_SHELL-/bin/sh} +echo=${ECHO-echo} +if test "X$1" = X--no-reexec; then + # Discard the --no-reexec flag, and continue. + shift +elif test "X$1" = X--fallback-echo; then + # Avoid inline document here, it may be left over + : +elif test "X`($echo '\t') 2>/dev/null`" = 'X\t' ; then + # Yippee, $echo works! + : +else + # Restart under the correct shell. + exec $SHELL "$0" --no-reexec ${1+"$@"} +fi -# Maximum number of lines to put in a shell here document. -# This variable seems obsolete. It should probably be removed, and -# only ac_max_sed_lines should be used. -: ${ac_max_here_lines=38} +if test "X$1" = X--fallback-echo; then + # used as fallback echo + shift + cat </dev/null 2>&1 && unset CDPATH + +if test -z "$ECHO"; then +if test "X${echo_test_string+set}" != Xset; then +# find a string as large as possible, as long as the shell can cope with it + for cmd in 'sed 50q "$0"' 'sed 20q "$0"' 'sed 10q "$0"' 'sed 2q "$0"' 'echo test'; do + # expected sizes: less than 2Kb, 1Kb, 512 bytes, 16 bytes, ... + if (echo_test_string=`eval $cmd`) 2>/dev/null && + echo_test_string=`eval $cmd` && + (test "X$echo_test_string" = "X$echo_test_string") 2>/dev/null + then + break + fi + done +fi + +if test "X`($echo '\t') 2>/dev/null`" = 'X\t' && + echo_testing_string=`($echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + : +else + # The Solaris, AIX, and Digital Unix default echo programs unquote + # backslashes. This makes it impossible to quote backslashes using + # echo "$something" | sed 's/\\/\\\\/g' + # + # So, first we look for a working echo in the user's PATH. + + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + for dir in $PATH /usr/ucb; do + IFS="$lt_save_ifs" + if (test -f $dir/echo || test -f $dir/echo$ac_exeext) && + test "X`($dir/echo '\t') 2>/dev/null`" = 'X\t' && + echo_testing_string=`($dir/echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + echo="$dir/echo" + break + fi + done + IFS="$lt_save_ifs" + + if test "X$echo" = Xecho; then + # We didn't find a better echo, so look for alternatives. + if test "X`(print -r '\t') 2>/dev/null`" = 'X\t' && + echo_testing_string=`(print -r "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + # This shell has a builtin print -r that does the trick. + echo='print -r' + elif (test -f /bin/ksh || test -f /bin/ksh$ac_exeext) && + test "X$CONFIG_SHELL" != X/bin/ksh; then + # If we have ksh, try running configure again with it. + ORIGINAL_CONFIG_SHELL=${CONFIG_SHELL-/bin/sh} + export ORIGINAL_CONFIG_SHELL + CONFIG_SHELL=/bin/ksh + export CONFIG_SHELL + exec $CONFIG_SHELL "$0" --no-reexec ${1+"$@"} + else + # Try using printf. + echo='printf %s\n' + if test "X`($echo '\t') 2>/dev/null`" = 'X\t' && + echo_testing_string=`($echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + # Cool, printf works + : + elif echo_testing_string=`($ORIGINAL_CONFIG_SHELL "$0" --fallback-echo '\t') 2>/dev/null` && + test "X$echo_testing_string" = 'X\t' && + echo_testing_string=`($ORIGINAL_CONFIG_SHELL "$0" --fallback-echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + CONFIG_SHELL=$ORIGINAL_CONFIG_SHELL + export CONFIG_SHELL + SHELL="$CONFIG_SHELL" + export SHELL + echo="$CONFIG_SHELL $0 --fallback-echo" + elif echo_testing_string=`($CONFIG_SHELL "$0" --fallback-echo '\t') 2>/dev/null` && + test "X$echo_testing_string" = 'X\t' && + echo_testing_string=`($CONFIG_SHELL "$0" --fallback-echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + echo="$CONFIG_SHELL $0 --fallback-echo" + else + # maybe with a smaller string... + prev=: + + for cmd in 'echo test' 'sed 2q "$0"' 'sed 10q "$0"' 'sed 20q "$0"' 'sed 50q "$0"'; do + if (test "X$echo_test_string" = "X`eval $cmd`") 2>/dev/null + then + break + fi + prev="$cmd" + done + + if test "$prev" != 'sed 50q "$0"'; then + echo_test_string=`eval $prev` + export echo_test_string + exec ${ORIGINAL_CONFIG_SHELL-${CONFIG_SHELL-/bin/sh}} "$0" ${1+"$@"} + else + # Oops. We lost completely, so just stick with echo. + echo=echo + fi + fi + fi + fi +fi +fi + +# Copy echo and quote the copy suitably for passing to libtool from +# the Makefile, instead of quoting the original, which is used later. +ECHO=$echo +if test "X$ECHO" = "X$CONFIG_SHELL $0 --fallback-echo"; then + ECHO="$CONFIG_SHELL \\\$\$0 --fallback-echo" +fi + + + + +tagnames=${tagnames+${tagnames},}CXX + +tagnames=${tagnames+${tagnames},}F77 + +exec 7<&0 &1 + +# Name of the host. +# hostname on some systems (SVR3.2, Linux) returns a bogus exit status, +# so uname gets run too. +ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` + +# +# Initializations. +# +ac_default_prefix=/usr/local +ac_clean_files= +ac_config_libobj_dir=. +LIBOBJS= +cross_compiling=no +subdirs= +MFLAGS= +MAKEFLAGS= +SHELL=${CONFIG_SHELL-/bin/sh} + +# Identity of this package. +PACKAGE_NAME='libffi' +PACKAGE_TARNAME='libffi' +PACKAGE_VERSION='3.0.5' +PACKAGE_STRING='libffi 3.0.5' +PACKAGE_BUGREPORT='http://gcc.gnu.org/bugs.html' # Factoring default headers for most tests. ac_includes_default="\ #include -#if HAVE_SYS_TYPES_H +#ifdef HAVE_SYS_TYPES_H # include #endif -#if HAVE_SYS_STAT_H +#ifdef HAVE_SYS_STAT_H # include #endif -#if STDC_HEADERS +#ifdef STDC_HEADERS # include # include #else -# if HAVE_STDLIB_H +# ifdef HAVE_STDLIB_H # include # endif #endif -#if HAVE_STRING_H -# if !STDC_HEADERS && HAVE_MEMORY_H +#ifdef HAVE_STRING_H +# if !defined STDC_HEADERS && defined HAVE_MEMORY_H # include # endif # include #endif -#if HAVE_STRINGS_H +#ifdef HAVE_STRINGS_H # include #endif -#if HAVE_INTTYPES_H +#ifdef HAVE_INTTYPES_H # include -#else -# if HAVE_STDINT_H -# include -# endif #endif -#if HAVE_UNISTD_H +#ifdef HAVE_STDINT_H +# include +#endif +#ifdef HAVE_UNISTD_H # include #endif" -ac_subst_vars='SHELL PATH_SEPARATOR PACKAGE_NAME PACKAGE_TARNAME PACKAGE_VERSION PACKAGE_STRING PACKAGE_BUGREPORT exec_prefix prefix program_transform_name bindir sbindir libexecdir datadir sysconfdir sharedstatedir localstatedir libdir includedir oldincludedir infodir mandir build_alias host_alias target_alias DEFS ECHO_C ECHO_N ECHO_T LIBS build build_cpu build_vendor build_os host host_cpu host_vendor host_os target target_cpu target_vendor target_os CC ac_ct_CC EXEEXT OBJEXT CFLAGS CPP CPPFLAGS EGREP ALLOCA HAVE_LONG_DOUBLE TARGET TARGETDIR MKTARGET LIBOBJS LTLIBOBJS' +ac_subst_vars='SHELL +PATH_SEPARATOR +PACKAGE_NAME +PACKAGE_TARNAME +PACKAGE_VERSION +PACKAGE_STRING +PACKAGE_BUGREPORT +exec_prefix +prefix +program_transform_name +bindir +sbindir +libexecdir +datarootdir +datadir +sysconfdir +sharedstatedir +localstatedir +includedir +oldincludedir +docdir +infodir +htmldir +dvidir +pdfdir +psdir +libdir +localedir +mandir +DEFS +ECHO_C +ECHO_N +ECHO_T +LIBS +build_alias +host_alias +target_alias +build +build_cpu +build_vendor +build_os +host +host_cpu +host_vendor +host_os +target +target_cpu +target_vendor +target_os +INSTALL_PROGRAM +INSTALL_SCRIPT +INSTALL_DATA +am__isrc +CYGPATH_W +PACKAGE +VERSION +ACLOCAL +AUTOCONF +AUTOMAKE +AUTOHEADER +MAKEINFO +install_sh +STRIP +INSTALL_STRIP_PROGRAM +mkdir_p +AWK +SET_MAKE +am__leading_dot +AMTAR +am__tar +am__untar +CC +CFLAGS +LDFLAGS +CPPFLAGS +ac_ct_CC +EXEEXT +OBJEXT +DEPDIR +am__include +am__quote +AMDEP_TRUE +AMDEP_FALSE +AMDEPBACKSLASH +CCDEPMODE +am__fastdepCC_TRUE +am__fastdepCC_FALSE +CCAS +CCASFLAGS +CCASDEPMODE +am__fastdepCCAS_TRUE +am__fastdepCCAS_FALSE +SED +GREP +EGREP +LN_S +ECHO +AR +RANLIB +CPP +CXX +CXXFLAGS +ac_ct_CXX +CXXDEPMODE +am__fastdepCXX_TRUE +am__fastdepCXX_FALSE +CXXCPP +F77 +FFLAGS +ac_ct_F77 +LIBTOOL +MAINTAINER_MODE_TRUE +MAINTAINER_MODE_FALSE +MAINT +TESTSUBDIR_TRUE +TESTSUBDIR_FALSE +AM_RUNTESTFLAGS +MIPS_TRUE +MIPS_FALSE +SPARC_TRUE +SPARC_FALSE +X86_TRUE +X86_FALSE +X86_FREEBSD_TRUE +X86_FREEBSD_FALSE +X86_WIN32_TRUE +X86_WIN32_FALSE +X86_DARWIN_TRUE +X86_DARWIN_FALSE +ALPHA_TRUE +ALPHA_FALSE +IA64_TRUE +IA64_FALSE +M32R_TRUE +M32R_FALSE +M68K_TRUE +M68K_FALSE +POWERPC_TRUE +POWERPC_FALSE +POWERPC_AIX_TRUE +POWERPC_AIX_FALSE +POWERPC_DARWIN_TRUE +POWERPC_DARWIN_FALSE +POWERPC_FREEBSD_TRUE +POWERPC_FREEBSD_FALSE +ARM_TRUE +ARM_FALSE +LIBFFI_CRIS_TRUE +LIBFFI_CRIS_FALSE +FRV_TRUE +FRV_FALSE +S390_TRUE +S390_FALSE +X86_64_TRUE +X86_64_FALSE +SH_TRUE +SH_FALSE +SH64_TRUE +SH64_FALSE +PA_LINUX_TRUE +PA_LINUX_FALSE +PA_HPUX_TRUE +PA_HPUX_FALSE +PA64_HPUX_TRUE +PA64_HPUX_FALSE +ALLOCA +HAVE_LONG_DOUBLE +TARGET +TARGETDIR +toolexecdir +toolexeclibdir +LIBOBJS +LTLIBOBJS' ac_subst_files='' + ac_precious_vars='build_alias +host_alias +target_alias +CCAS +CCASFLAGS +CPP +CPPFLAGS +CXX +CXXFLAGS +LDFLAGS +LIBS +CCC +CXXCPP +F77 +FFLAGS' + # Initialize some variables set by options. ac_init_help= @@ -338,34 +984,48 @@ # and all the variables that are supposed to be based on exec_prefix # by default will actually change. # Use braces instead of parens because sh, perl, etc. also accept them. +# (The list follows the same order as the GNU Coding Standards.) bindir='${exec_prefix}/bin' sbindir='${exec_prefix}/sbin' libexecdir='${exec_prefix}/libexec' -datadir='${prefix}/share' +datarootdir='${prefix}/share' +datadir='${datarootdir}' sysconfdir='${prefix}/etc' sharedstatedir='${prefix}/com' localstatedir='${prefix}/var' -libdir='${exec_prefix}/lib' includedir='${prefix}/include' oldincludedir='/usr/include' -infodir='${prefix}/info' -mandir='${prefix}/man' +docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' +infodir='${datarootdir}/info' +htmldir='${docdir}' +dvidir='${docdir}' +pdfdir='${docdir}' +psdir='${docdir}' +libdir='${exec_prefix}/lib' +localedir='${datarootdir}/locale' +mandir='${datarootdir}/man' ac_prev= +ac_dashdash= for ac_option do # If the previous option needs an argument, assign it. if test -n "$ac_prev"; then - eval "$ac_prev=\$ac_option" + eval $ac_prev=\$ac_option ac_prev= continue fi - ac_optarg=`expr "x$ac_option" : 'x[^=]*=\(.*\)'` + case $ac_option in + *=*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; + *) ac_optarg=yes ;; + esac # Accept the important Cygnus configure options, so we can diagnose typos. - case $ac_option in + case $ac_dashdash$ac_option in + --) + ac_dashdash=yes ;; -bindir | --bindir | --bindi | --bind | --bin | --bi) ac_prev=bindir ;; @@ -387,33 +1047,45 @@ --config-cache | -C) cache_file=config.cache ;; - -datadir | --datadir | --datadi | --datad | --data | --dat | --da) + -datadir | --datadir | --datadi | --datad) ac_prev=datadir ;; - -datadir=* | --datadir=* | --datadi=* | --datad=* | --data=* | --dat=* \ - | --da=*) + -datadir=* | --datadir=* | --datadi=* | --datad=*) datadir=$ac_optarg ;; + -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ + | --dataroo | --dataro | --datar) + ac_prev=datarootdir ;; + -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ + | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) + datarootdir=$ac_optarg ;; + -disable-* | --disable-*) ac_feature=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_feature" : ".*[^-_$as_cr_alnum]" >/dev/null && + expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null && { echo "$as_me: error: invalid feature name: $ac_feature" >&2 { (exit 1); exit 1; }; } - ac_feature=`echo $ac_feature | sed 's/-/_/g'` - eval "enable_$ac_feature=no" ;; + ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'` + eval enable_$ac_feature=no ;; + + -docdir | --docdir | --docdi | --doc | --do) + ac_prev=docdir ;; + -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) + docdir=$ac_optarg ;; + + -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) + ac_prev=dvidir ;; + -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) + dvidir=$ac_optarg ;; -enable-* | --enable-*) ac_feature=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_feature" : ".*[^-_$as_cr_alnum]" >/dev/null && + expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null && { echo "$as_me: error: invalid feature name: $ac_feature" >&2 { (exit 1); exit 1; }; } - ac_feature=`echo $ac_feature | sed 's/-/_/g'` - case $ac_option in - *=*) ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"`;; - *) ac_optarg=yes ;; - esac - eval "enable_$ac_feature='$ac_optarg'" ;; + ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'` + eval enable_$ac_feature=\$ac_optarg ;; -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ @@ -440,6 +1112,12 @@ -host=* | --host=* | --hos=* | --ho=*) host_alias=$ac_optarg ;; + -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) + ac_prev=htmldir ;; + -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ + | --ht=*) + htmldir=$ac_optarg ;; + -includedir | --includedir | --includedi | --included | --include \ | --includ | --inclu | --incl | --inc) ac_prev=includedir ;; @@ -464,13 +1142,16 @@ | --libexe=* | --libex=* | --libe=*) libexecdir=$ac_optarg ;; + -localedir | --localedir | --localedi | --localed | --locale) + ac_prev=localedir ;; + -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) + localedir=$ac_optarg ;; + -localstatedir | --localstatedir | --localstatedi | --localstated \ - | --localstate | --localstat | --localsta | --localst \ - | --locals | --local | --loca | --loc | --lo) + | --localstate | --localstat | --localsta | --localst | --locals) ac_prev=localstatedir ;; -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ - | --localstate=* | --localstat=* | --localsta=* | --localst=* \ - | --locals=* | --local=* | --loca=* | --loc=* | --lo=*) + | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) localstatedir=$ac_optarg ;; -mandir | --mandir | --mandi | --mand | --man | --ma | --m) @@ -535,6 +1216,16 @@ | --progr-tra=* | --program-tr=* | --program-t=*) program_transform_name=$ac_optarg ;; + -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) + ac_prev=pdfdir ;; + -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) + pdfdir=$ac_optarg ;; + + -psdir | --psdir | --psdi | --psd | --ps) + ac_prev=psdir ;; + -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) + psdir=$ac_optarg ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) silent=yes ;; @@ -587,24 +1278,20 @@ -with-* | --with-*) ac_package=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_package" : ".*[^-_$as_cr_alnum]" >/dev/null && + expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null && { echo "$as_me: error: invalid package name: $ac_package" >&2 { (exit 1); exit 1; }; } - ac_package=`echo $ac_package| sed 's/-/_/g'` - case $ac_option in - *=*) ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"`;; - *) ac_optarg=yes ;; - esac - eval "with_$ac_package='$ac_optarg'" ;; + ac_package=`echo $ac_package | sed 's/[-.]/_/g'` + eval with_$ac_package=\$ac_optarg ;; -without-* | --without-*) ac_package=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_package" : ".*[^-_$as_cr_alnum]" >/dev/null && + expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null && { echo "$as_me: error: invalid package name: $ac_package" >&2 { (exit 1); exit 1; }; } - ac_package=`echo $ac_package | sed 's/-/_/g'` - eval "with_$ac_package=no" ;; + ac_package=`echo $ac_package | sed 's/[-.]/_/g'` + eval with_$ac_package=no ;; --x) # Obsolete; use --with-x. @@ -635,8 +1322,7 @@ expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null && { echo "$as_me: error: invalid variable name: $ac_envvar" >&2 { (exit 1); exit 1; }; } - ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` - eval "$ac_envvar='$ac_optarg'" + eval $ac_envvar=\$ac_optarg export $ac_envvar ;; *) @@ -656,27 +1342,19 @@ { (exit 1); exit 1; }; } fi -# Be sure to have absolute paths. -for ac_var in exec_prefix prefix -do - eval ac_val=$`echo $ac_var` - case $ac_val in - [\\/$]* | ?:[\\/]* | NONE | '' ) ;; - *) { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2 - { (exit 1); exit 1; }; };; - esac -done - -# Be sure to have absolute paths. -for ac_var in bindir sbindir libexecdir datadir sysconfdir sharedstatedir \ - localstatedir libdir includedir oldincludedir infodir mandir +# Be sure to have absolute directory names. +for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ + datadir sysconfdir sharedstatedir localstatedir includedir \ + oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ + libdir localedir mandir do - eval ac_val=$`echo $ac_var` + eval ac_val=\$$ac_var case $ac_val in - [\\/$]* | ?:[\\/]* ) ;; - *) { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2 - { (exit 1); exit 1; }; };; + [\\/$]* | ?:[\\/]* ) continue;; + NONE | '' ) case $ac_var in *prefix ) continue;; esac;; esac + { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2 + { (exit 1); exit 1; }; } done # There might be people who depend on the old broken behavior: `$host' @@ -703,62 +1381,76 @@ test "$silent" = yes && exec 6>/dev/null +ac_pwd=`pwd` && test -n "$ac_pwd" && +ac_ls_di=`ls -di .` && +ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || + { echo "$as_me: error: Working directory cannot be determined" >&2 + { (exit 1); exit 1; }; } +test "X$ac_ls_di" = "X$ac_pwd_ls_di" || + { echo "$as_me: error: pwd does not report name of working directory" >&2 + { (exit 1); exit 1; }; } + + # Find the source files, if location was not specified. if test -z "$srcdir"; then ac_srcdir_defaulted=yes - # Try the directory containing this script, then its parent. - ac_confdir=`(dirname "$0") 2>/dev/null || + # Try the directory containing this script, then the parent directory. + ac_confdir=`$as_dirname -- "$0" || $as_expr X"$0" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$0" : 'X\(//\)[^/]' \| \ X"$0" : 'X\(//\)$' \| \ - X"$0" : 'X\(/\)' \| \ - . : '\(.\)' 2>/dev/null || + X"$0" : 'X\(/\)' \| . 2>/dev/null || echo X"$0" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; } - /^X\(\/\/\)[^/].*/{ s//\1/; q; } - /^X\(\/\/\)$/{ s//\1/; q; } - /^X\(\/\).*/{ s//\1/; q; } - s/.*/./; q'` + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` srcdir=$ac_confdir - if test ! -r $srcdir/$ac_unique_file; then + if test ! -r "$srcdir/$ac_unique_file"; then srcdir=.. fi else ac_srcdir_defaulted=no fi -if test ! -r $srcdir/$ac_unique_file; then - if test "$ac_srcdir_defaulted" = yes; then - { echo "$as_me: error: cannot find sources ($ac_unique_file) in $ac_confdir or .." >&2 - { (exit 1); exit 1; }; } - else - { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2 +if test ! -r "$srcdir/$ac_unique_file"; then + test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." + { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2 { (exit 1); exit 1; }; } - fi fi -(cd $srcdir && test -r ./$ac_unique_file) 2>/dev/null || - { echo "$as_me: error: sources are in $srcdir, but \`cd $srcdir' does not work" >&2 - { (exit 1); exit 1; }; } -srcdir=`echo "$srcdir" | sed 's%\([^\\/]\)[\\/]*$%\1%'` -ac_env_build_alias_set=${build_alias+set} -ac_env_build_alias_value=$build_alias -ac_cv_env_build_alias_set=${build_alias+set} -ac_cv_env_build_alias_value=$build_alias -ac_env_host_alias_set=${host_alias+set} -ac_env_host_alias_value=$host_alias -ac_cv_env_host_alias_set=${host_alias+set} -ac_cv_env_host_alias_value=$host_alias -ac_env_target_alias_set=${target_alias+set} -ac_env_target_alias_value=$target_alias -ac_cv_env_target_alias_set=${target_alias+set} -ac_cv_env_target_alias_value=$target_alias -ac_env_CPP_set=${CPP+set} -ac_env_CPP_value=$CPP -ac_cv_env_CPP_set=${CPP+set} -ac_cv_env_CPP_value=$CPP -ac_env_CPPFLAGS_set=${CPPFLAGS+set} -ac_env_CPPFLAGS_value=$CPPFLAGS -ac_cv_env_CPPFLAGS_set=${CPPFLAGS+set} -ac_cv_env_CPPFLAGS_value=$CPPFLAGS +ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" +ac_abs_confdir=`( + cd "$srcdir" && test -r "./$ac_unique_file" || { echo "$as_me: error: $ac_msg" >&2 + { (exit 1); exit 1; }; } + pwd)` +# When building in place, set srcdir=. +if test "$ac_abs_confdir" = "$ac_pwd"; then + srcdir=. +fi +# Remove unnecessary trailing slashes from srcdir. +# Double slashes in file names in object file debugging info +# mess up M-x gdb in Emacs. +case $srcdir in +*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; +esac +for ac_var in $ac_precious_vars; do + eval ac_env_${ac_var}_set=\${${ac_var}+set} + eval ac_env_${ac_var}_value=\$${ac_var} + eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} + eval ac_cv_env_${ac_var}_value=\$${ac_var} +done # # Report the --help message. @@ -767,7 +1459,7 @@ # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF -\`configure' configures libffi 2.1 to adapt to many kinds of systems. +\`configure' configures libffi 3.0.5 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... @@ -787,9 +1479,6 @@ -n, --no-create do not create output files --srcdir=DIR find the sources in DIR [configure dir or \`..'] -_ACEOF - - cat <<_ACEOF Installation directories: --prefix=PREFIX install architecture-independent files in PREFIX [$ac_default_prefix] @@ -807,19 +1496,31 @@ --bindir=DIR user executables [EPREFIX/bin] --sbindir=DIR system admin executables [EPREFIX/sbin] --libexecdir=DIR program executables [EPREFIX/libexec] - --datadir=DIR read-only architecture-independent data [PREFIX/share] --sysconfdir=DIR read-only single-machine data [PREFIX/etc] --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] --localstatedir=DIR modifiable single-machine data [PREFIX/var] --libdir=DIR object code libraries [EPREFIX/lib] --includedir=DIR C header files [PREFIX/include] --oldincludedir=DIR C header files for non-gcc [/usr/include] - --infodir=DIR info documentation [PREFIX/info] - --mandir=DIR man documentation [PREFIX/man] + --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] + --datadir=DIR read-only architecture-independent data [DATAROOTDIR] + --infodir=DIR info documentation [DATAROOTDIR/info] + --localedir=DIR locale-dependent data [DATAROOTDIR/locale] + --mandir=DIR man documentation [DATAROOTDIR/man] + --docdir=DIR documentation root [DATAROOTDIR/doc/libffi] + --htmldir=DIR html documentation [DOCDIR] + --dvidir=DIR dvi documentation [DOCDIR] + --pdfdir=DIR pdf documentation [DOCDIR] + --psdir=DIR ps documentation [DOCDIR] _ACEOF cat <<\_ACEOF +Program names: + --program-prefix=PREFIX prepend PREFIX to installed program names + --program-suffix=SUFFIX append SUFFIX to installed program names + --program-transform-name=PROGRAM run sed PROGRAM on installed program names + System types: --build=BUILD configure for building on BUILD [guessed] --host=HOST cross-compile to build programs to run on HOST [BUILD] @@ -829,138 +1530,137 @@ if test -n "$ac_init_help"; then case $ac_init_help in - short | recursive ) echo "Configuration of libffi 2.1:";; + short | recursive ) echo "Configuration of libffi 3.0.5:";; esac cat <<\_ACEOF +Optional Features: + --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) + --enable-FEATURE[=ARG] include FEATURE [ARG=yes] + --disable-dependency-tracking speeds up one-time build + --enable-dependency-tracking do not reject slow dependency extractors + --enable-shared[=PKGS] build shared libraries [default=yes] + --enable-static[=PKGS] build static libraries [default=yes] + --enable-fast-install[=PKGS] + optimize for fast installation [default=yes] + --disable-libtool-lock avoid locking (might break parallel builds) + --enable-maintainer-mode enable make rules and dependencies not useful + (and sometimes confusing) to the casual installer + --enable-debug debugging mode + --disable-structs omit code for struct support + --disable-raw-api make the raw api unavailable + --enable-purify-safety purify-safe mode + +Optional Packages: + --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] + --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) + --with-gnu-ld assume the C compiler uses GNU ld [default=no] + --with-pic try to use only PIC/non-PIC objects [default=use + both] + --with-tags[=TAGS] include additional configurations [automatic] + Some influential environment variables: CC C compiler command CFLAGS C compiler flags LDFLAGS linker flags, e.g. -L if you have libraries in a nonstandard directory - CPPFLAGS C/C++ preprocessor flags, e.g. -I if you have - headers in a nonstandard directory + LIBS libraries to pass to the linker, e.g. -l + CPPFLAGS C/C++/Objective C preprocessor flags, e.g. -I if + you have headers in a nonstandard directory + CCAS assembler compiler command (defaults to CC) + CCASFLAGS assembler compiler flags (defaults to CFLAGS) CPP C preprocessor + CXX C++ compiler command + CXXFLAGS C++ compiler flags + CXXCPP C++ preprocessor + F77 Fortran 77 compiler command + FFLAGS Fortran 77 compiler flags Use these variables to override the choices made by `configure' or to help it to find libraries and programs with nonstandard names/locations. Report bugs to . _ACEOF +ac_status=$? fi if test "$ac_init_help" = "recursive"; then # If there are subdirs, report their specific --help. - ac_popdir=`pwd` for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue - test -d $ac_dir || continue + test -d "$ac_dir" || continue ac_builddir=. -if test "$ac_dir" != .; then +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'` - # A "../" for each directory in $ac_dir_suffix. - ac_top_builddir=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,../,g'` -else - ac_dir_suffix= ac_top_builddir= -fi + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix case $srcdir in - .) # No --srcdir option. We are building in place. + .) # We are building in place. ac_srcdir=. - if test -z "$ac_top_builddir"; then - ac_top_srcdir=. - else - ac_top_srcdir=`echo $ac_top_builddir | sed 's,/$,,'` - fi ;; - [\\/]* | ?:[\\/]* ) # Absolute path. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; - ac_top_srcdir=$srcdir ;; - *) # Relative path. - ac_srcdir=$ac_top_builddir$srcdir$ac_dir_suffix - ac_top_srcdir=$ac_top_builddir$srcdir ;; -esac - -# Do not use `cd foo && pwd` to compute absolute paths, because -# the directories may not exist. -case `pwd` in -.) ac_abs_builddir="$ac_dir";; -*) - case "$ac_dir" in - .) ac_abs_builddir=`pwd`;; - [\\/]* | ?:[\\/]* ) ac_abs_builddir="$ac_dir";; - *) ac_abs_builddir=`pwd`/"$ac_dir";; - esac;; -esac -case $ac_abs_builddir in -.) ac_abs_top_builddir=${ac_top_builddir}.;; -*) - case ${ac_top_builddir}. in - .) ac_abs_top_builddir=$ac_abs_builddir;; - [\\/]* | ?:[\\/]* ) ac_abs_top_builddir=${ac_top_builddir}.;; - *) ac_abs_top_builddir=$ac_abs_builddir/${ac_top_builddir}.;; - esac;; -esac -case $ac_abs_builddir in -.) ac_abs_srcdir=$ac_srcdir;; -*) - case $ac_srcdir in - .) ac_abs_srcdir=$ac_abs_builddir;; - [\\/]* | ?:[\\/]* ) ac_abs_srcdir=$ac_srcdir;; - *) ac_abs_srcdir=$ac_abs_builddir/$ac_srcdir;; - esac;; -esac -case $ac_abs_builddir in -.) ac_abs_top_srcdir=$ac_top_srcdir;; -*) - case $ac_top_srcdir in - .) ac_abs_top_srcdir=$ac_abs_builddir;; - [\\/]* | ?:[\\/]* ) ac_abs_top_srcdir=$ac_top_srcdir;; - *) ac_abs_top_srcdir=$ac_abs_builddir/$ac_top_srcdir;; - esac;; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix - cd $ac_dir - # Check for guested configure; otherwise get Cygnus style configure. - if test -f $ac_srcdir/configure.gnu; then - echo - $SHELL $ac_srcdir/configure.gnu --help=recursive - elif test -f $ac_srcdir/configure; then - echo - $SHELL $ac_srcdir/configure --help=recursive - elif test -f $ac_srcdir/configure.ac || - test -f $ac_srcdir/configure.in; then - echo - $ac_configure --help + cd "$ac_dir" || { ac_status=$?; continue; } + # Check for guested configure. + if test -f "$ac_srcdir/configure.gnu"; then + echo && + $SHELL "$ac_srcdir/configure.gnu" --help=recursive + elif test -f "$ac_srcdir/configure"; then + echo && + $SHELL "$ac_srcdir/configure" --help=recursive else echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 - fi - cd "$ac_popdir" + fi || ac_status=$? + cd "$ac_pwd" || { ac_status=$?; break; } done fi -test -n "$ac_init_help" && exit 0 +test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF -libffi configure 2.1 -generated by GNU Autoconf 2.59 +libffi configure 3.0.5 +generated by GNU Autoconf 2.61 -Copyright (C) 2003 Free Software Foundation, Inc. +Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, +2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF - exit 0 + exit fi -exec 5>config.log -cat >&5 <<_ACEOF +cat >config.log <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. -It was created by libffi $as_me 2.1, which was -generated by GNU Autoconf 2.59. Invocation command line was +It was created by libffi $as_me 3.0.5, which was +generated by GNU Autoconf 2.61. Invocation command line was $ $0 $@ _ACEOF +exec 5>>config.log { cat <<_ASUNAME ## --------- ## @@ -979,7 +1679,7 @@ /bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` -hostinfo = `(hostinfo) 2>/dev/null || echo unknown` +/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` /bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` /bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` @@ -993,6 +1693,7 @@ test -z "$as_dir" && as_dir=. echo "PATH: $as_dir" done +IFS=$as_save_IFS } >&5 @@ -1014,7 +1715,6 @@ ac_configure_args= ac_configure_args0= ac_configure_args1= -ac_sep= ac_must_keep_next=false for ac_pass in 1 2 do @@ -1025,7 +1725,7 @@ -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) continue ;; - *" "*|*" "*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?\"\']*) + *\'*) ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; esac case $ac_pass in @@ -1047,9 +1747,7 @@ -* ) ac_must_keep_next=true ;; esac fi - ac_configure_args="$ac_configure_args$ac_sep'$ac_arg'" - # Get rid of the leading space. - ac_sep=" " + ac_configure_args="$ac_configure_args '$ac_arg'" ;; esac done @@ -1060,8 +1758,8 @@ # When interrupted or exit'd, cleanup temporary files, and complete # config.log. We remove comments because anyway the quotes in there # would cause problems or look ugly. -# WARNING: Be sure not to use single quotes in there, as some shells, -# such as our DU 5.0 friend, will then `close' the trap. +# WARNING: Use '\'' to represent an apostrophe within the trap. +# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. trap 'exit_status=$? # Save into config.log some information that might help in debugging. { @@ -1074,20 +1772,34 @@ _ASBOX echo # The following way of writing the cache mishandles newlines in values, -{ +( + for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5 +echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + *) $as_unset $ac_var ;; + esac ;; + esac + done (set) 2>&1 | - case `(ac_space='"'"' '"'"'; set | grep ac_space) 2>&1` in - *ac_space=\ *) + case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( + *${as_nl}ac_space=\ *) sed -n \ - "s/'"'"'/'"'"'\\\\'"'"''"'"'/g; - s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='"'"'\\2'"'"'/p" - ;; + "s/'\''/'\''\\\\'\'''\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" + ;; #( *) - sed -n \ - "s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1=\\2/p" + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; - esac; -} + esac | + sort +) echo cat <<\_ASBOX @@ -1098,22 +1810,28 @@ echo for ac_var in $ac_subst_vars do - eval ac_val=$`echo $ac_var` - echo "$ac_var='"'"'$ac_val'"'"'" + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + echo "$ac_var='\''$ac_val'\''" done | sort echo if test -n "$ac_subst_files"; then cat <<\_ASBOX -## ------------- ## -## Output files. ## -## ------------- ## +## ------------------- ## +## File substitutions. ## +## ------------------- ## _ASBOX echo for ac_var in $ac_subst_files do - eval ac_val=$`echo $ac_var` - echo "$ac_var='"'"'$ac_val'"'"'" + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + echo "$ac_var='\''$ac_val'\''" done | sort echo fi @@ -1125,26 +1843,24 @@ ## ----------- ## _ASBOX echo - sed "/^$/d" confdefs.h | sort + cat confdefs.h echo fi test "$ac_signal" != 0 && echo "$as_me: caught signal $ac_signal" echo "$as_me: exit $exit_status" } >&5 - rm -f core *.core && - rm -rf conftest* confdefs* conf$$* $ac_clean_files && + rm -f core *.core core.conftest.* && + rm -f -r conftest* confdefs* conf$$* $ac_clean_files && exit $exit_status - ' 0 +' 0 for ac_signal in 1 2 13 15; do trap 'ac_signal='$ac_signal'; { (exit 1); exit 1; }' $ac_signal done ac_signal=0 # confdefs.h avoids OS command line length limits that DEFS can exceed. -rm -rf conftest* confdefs.h -# AIX cpp loses on an empty file, so make sure it contains at least a newline. -echo >confdefs.h +rm -f -r conftest* confdefs.h # Predefined preprocessor variables. @@ -1175,14 +1891,17 @@ # Let the site file select an alternate cache file if it wants to. # Prefer explicitly selected file to automatically selected ones. -if test -z "$CONFIG_SITE"; then - if test "x$prefix" != xNONE; then - CONFIG_SITE="$prefix/share/config.site $prefix/etc/config.site" - else - CONFIG_SITE="$ac_default_prefix/share/config.site $ac_default_prefix/etc/config.site" - fi +if test -n "$CONFIG_SITE"; then + set x "$CONFIG_SITE" +elif test "x$prefix" != xNONE; then + set x "$prefix/share/config.site" "$prefix/etc/config.site" +else + set x "$ac_default_prefix/share/config.site" \ + "$ac_default_prefix/etc/config.site" fi -for ac_site_file in $CONFIG_SITE; do +shift +for ac_site_file +do if test -r "$ac_site_file"; then { echo "$as_me:$LINENO: loading site script $ac_site_file" >&5 echo "$as_me: loading site script $ac_site_file" >&6;} @@ -1198,8 +1917,8 @@ { echo "$as_me:$LINENO: loading cache $cache_file" >&5 echo "$as_me: loading cache $cache_file" >&6;} case $cache_file in - [\\/]* | ?:[\\/]* ) . $cache_file;; - *) . ./$cache_file;; + [\\/]* | ?:[\\/]* ) . "$cache_file";; + *) . "./$cache_file";; esac fi else @@ -1211,12 +1930,11 @@ # Check that the precious variables saved in the cache have kept the same # value. ac_cache_corrupted=false -for ac_var in `(set) 2>&1 | - sed -n 's/^ac_env_\([a-zA-Z_0-9]*\)_set=.*/\1/p'`; do +for ac_var in $ac_precious_vars; do eval ac_old_set=\$ac_cv_env_${ac_var}_set eval ac_new_set=\$ac_env_${ac_var}_set - eval ac_old_val="\$ac_cv_env_${ac_var}_value" - eval ac_new_val="\$ac_env_${ac_var}_value" + eval ac_old_val=\$ac_cv_env_${ac_var}_value + eval ac_new_val=\$ac_env_${ac_var}_value case $ac_old_set,$ac_new_set in set,) { echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 @@ -1241,8 +1959,7 @@ # Pass precious variables to config.status. if test "$ac_new_set" = set; then case $ac_new_val in - *" "*|*" "*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?\"\']*) - ac_arg=$ac_var=`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; + *\'*) ac_arg=$ac_var=`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; *) ac_arg=$ac_var=$ac_new_val ;; esac case " $ac_configure_args " in @@ -1259,12 +1976,6 @@ { (exit 1); exit 1; }; } fi -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - @@ -1289,110 +2000,165 @@ +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu - ac_config_headers="$ac_config_headers fficonfig.h" +ac_config_headers="$ac_config_headers fficonfig.h" ac_aux_dir= -for ac_dir in $srcdir $srcdir/.. $srcdir/../..; do - if test -f $ac_dir/install-sh; then +for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do + if test -f "$ac_dir/install-sh"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install-sh -c" break - elif test -f $ac_dir/install.sh; then + elif test -f "$ac_dir/install.sh"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install.sh -c" break - elif test -f $ac_dir/shtool; then + elif test -f "$ac_dir/shtool"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/shtool install -c" break fi done if test -z "$ac_aux_dir"; then - { { echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in $srcdir $srcdir/.. $srcdir/../.." >&5 -echo "$as_me: error: cannot find install-sh or install.sh in $srcdir $srcdir/.. $srcdir/../.." >&2;} + { { echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&5 +echo "$as_me: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&2;} { (exit 1); exit 1; }; } fi -ac_config_guess="$SHELL $ac_aux_dir/config.guess" -ac_config_sub="$SHELL $ac_aux_dir/config.sub" -ac_configure="$SHELL $ac_aux_dir/configure" # This should be Cygnus configure. + +# These three variables are undocumented and unsupported, +# and are intended to be withdrawn in a future Autoconf release. +# They can cause serious problems if a builder's source tree is in a directory +# whose full name contains unusual characters. +ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var. +ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var. +ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. + # Make sure we can run config.sub. -$ac_config_sub sun4 >/dev/null 2>&1 || - { { echo "$as_me:$LINENO: error: cannot run $ac_config_sub" >&5 -echo "$as_me: error: cannot run $ac_config_sub" >&2;} +$SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 || + { { echo "$as_me:$LINENO: error: cannot run $SHELL $ac_aux_dir/config.sub" >&5 +echo "$as_me: error: cannot run $SHELL $ac_aux_dir/config.sub" >&2;} { (exit 1); exit 1; }; } -echo "$as_me:$LINENO: checking build system type" >&5 -echo $ECHO_N "checking build system type... $ECHO_C" >&6 +{ echo "$as_me:$LINENO: checking build system type" >&5 +echo $ECHO_N "checking build system type... $ECHO_C" >&6; } if test "${ac_cv_build+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else - ac_cv_build_alias=$build_alias -test -z "$ac_cv_build_alias" && - ac_cv_build_alias=`$ac_config_guess` -test -z "$ac_cv_build_alias" && + ac_build_alias=$build_alias +test "x$ac_build_alias" = x && + ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"` +test "x$ac_build_alias" = x && { { echo "$as_me:$LINENO: error: cannot guess build type; you must specify one" >&5 echo "$as_me: error: cannot guess build type; you must specify one" >&2;} { (exit 1); exit 1; }; } -ac_cv_build=`$ac_config_sub $ac_cv_build_alias` || - { { echo "$as_me:$LINENO: error: $ac_config_sub $ac_cv_build_alias failed" >&5 -echo "$as_me: error: $ac_config_sub $ac_cv_build_alias failed" >&2;} +ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` || + { { echo "$as_me:$LINENO: error: $SHELL $ac_aux_dir/config.sub $ac_build_alias failed" >&5 +echo "$as_me: error: $SHELL $ac_aux_dir/config.sub $ac_build_alias failed" >&2;} { (exit 1); exit 1; }; } fi -echo "$as_me:$LINENO: result: $ac_cv_build" >&5 -echo "${ECHO_T}$ac_cv_build" >&6 +{ echo "$as_me:$LINENO: result: $ac_cv_build" >&5 +echo "${ECHO_T}$ac_cv_build" >&6; } +case $ac_cv_build in +*-*-*) ;; +*) { { echo "$as_me:$LINENO: error: invalid value of canonical build" >&5 +echo "$as_me: error: invalid value of canonical build" >&2;} + { (exit 1); exit 1; }; };; +esac build=$ac_cv_build -build_cpu=`echo $ac_cv_build | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\1/'` -build_vendor=`echo $ac_cv_build | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\2/'` -build_os=`echo $ac_cv_build | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\3/'` +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_build +shift +build_cpu=$1 +build_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +build_os=$* +IFS=$ac_save_IFS +case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac -echo "$as_me:$LINENO: checking host system type" >&5 -echo $ECHO_N "checking host system type... $ECHO_C" >&6 +{ echo "$as_me:$LINENO: checking host system type" >&5 +echo $ECHO_N "checking host system type... $ECHO_C" >&6; } if test "${ac_cv_host+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else - ac_cv_host_alias=$host_alias -test -z "$ac_cv_host_alias" && - ac_cv_host_alias=$ac_cv_build_alias -ac_cv_host=`$ac_config_sub $ac_cv_host_alias` || - { { echo "$as_me:$LINENO: error: $ac_config_sub $ac_cv_host_alias failed" >&5 -echo "$as_me: error: $ac_config_sub $ac_cv_host_alias failed" >&2;} + if test "x$host_alias" = x; then + ac_cv_host=$ac_cv_build +else + ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` || + { { echo "$as_me:$LINENO: error: $SHELL $ac_aux_dir/config.sub $host_alias failed" >&5 +echo "$as_me: error: $SHELL $ac_aux_dir/config.sub $host_alias failed" >&2;} { (exit 1); exit 1; }; } +fi fi -echo "$as_me:$LINENO: result: $ac_cv_host" >&5 -echo "${ECHO_T}$ac_cv_host" >&6 +{ echo "$as_me:$LINENO: result: $ac_cv_host" >&5 +echo "${ECHO_T}$ac_cv_host" >&6; } +case $ac_cv_host in +*-*-*) ;; +*) { { echo "$as_me:$LINENO: error: invalid value of canonical host" >&5 +echo "$as_me: error: invalid value of canonical host" >&2;} + { (exit 1); exit 1; }; };; +esac host=$ac_cv_host -host_cpu=`echo $ac_cv_host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\1/'` -host_vendor=`echo $ac_cv_host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\2/'` -host_os=`echo $ac_cv_host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\3/'` +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_host +shift +host_cpu=$1 +host_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +host_os=$* +IFS=$ac_save_IFS +case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac -echo "$as_me:$LINENO: checking target system type" >&5 -echo $ECHO_N "checking target system type... $ECHO_C" >&6 +{ echo "$as_me:$LINENO: checking target system type" >&5 +echo $ECHO_N "checking target system type... $ECHO_C" >&6; } if test "${ac_cv_target+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else - ac_cv_target_alias=$target_alias -test "x$ac_cv_target_alias" = "x" && - ac_cv_target_alias=$ac_cv_host_alias -ac_cv_target=`$ac_config_sub $ac_cv_target_alias` || - { { echo "$as_me:$LINENO: error: $ac_config_sub $ac_cv_target_alias failed" >&5 -echo "$as_me: error: $ac_config_sub $ac_cv_target_alias failed" >&2;} + if test "x$target_alias" = x; then + ac_cv_target=$ac_cv_host +else + ac_cv_target=`$SHELL "$ac_aux_dir/config.sub" $target_alias` || + { { echo "$as_me:$LINENO: error: $SHELL $ac_aux_dir/config.sub $target_alias failed" >&5 +echo "$as_me: error: $SHELL $ac_aux_dir/config.sub $target_alias failed" >&2;} { (exit 1); exit 1; }; } +fi fi -echo "$as_me:$LINENO: result: $ac_cv_target" >&5 -echo "${ECHO_T}$ac_cv_target" >&6 +{ echo "$as_me:$LINENO: result: $ac_cv_target" >&5 +echo "${ECHO_T}$ac_cv_target" >&6; } +case $ac_cv_target in +*-*-*) ;; +*) { { echo "$as_me:$LINENO: error: invalid value of canonical target" >&5 +echo "$as_me: error: invalid value of canonical target" >&2;} + { (exit 1); exit 1; }; };; +esac target=$ac_cv_target -target_cpu=`echo $ac_cv_target | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\1/'` -target_vendor=`echo $ac_cv_target | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\2/'` -target_os=`echo $ac_cv_target | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\3/'` +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_target +shift +target_cpu=$1 +target_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +target_os=$* +IFS=$ac_save_IFS +case $target_os in *\ *) target_os=`echo "$target_os" | sed 's/ /-/g'`;; esac # The aliases save the names the user supplied, while $host etc. @@ -1403,61 +2169,220 @@ program_prefix=${target_alias}- target_alias=${target_alias-$host_alias} +. ${srcdir}/configure.host +am__api_version='1.10' -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu -if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. -set dummy ${ac_tool_prefix}gcc; ac_word=$2 -echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 -if test "${ac_cv_prog_CC+set}" = set; then +# Find a good install program. We prefer a C program (faster), +# so one script is as good as another. But avoid the broken or +# incompatible versions: +# SysV /etc/install, /usr/sbin/install +# SunOS /usr/etc/install +# IRIX /sbin/install +# AIX /bin/install +# AmigaOS /C/install, which installs bootblocks on floppy discs +# AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag +# AFS /usr/afsws/bin/install, which mishandles nonexistent args +# SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" +# OS/2's system install, which has a completely different semantic +# ./install, which can be erroneously created by make from ./install.sh. +{ echo "$as_me:$LINENO: checking for a BSD-compatible install" >&5 +echo $ECHO_N "checking for a BSD-compatible install... $ECHO_C" >&6; } +if test -z "$INSTALL"; then +if test "${ac_cv_path_install+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then - ac_cv_prog_CC="${ac_tool_prefix}gcc" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done + # Account for people who put trailing slashes in PATH elements. +case $as_dir/ in + ./ | .// | /cC/* | \ + /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ + ?:\\/os2\\/install\\/* | ?:\\/OS2\\/INSTALL\\/* | \ + /usr/ucb/* ) ;; + *) + # OSF1 and SCO ODT 3.0 have their own names for install. + # Don't use installbsd from OSF since it installs stuff as root + # by default. + for ac_prog in ginstall scoinst install; do + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_prog$ac_exec_ext" && $as_test_x "$as_dir/$ac_prog$ac_exec_ext"; }; then + if test $ac_prog = install && + grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then + # AIX install. It has an incompatible calling convention. + : + elif test $ac_prog = install && + grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then + # program-specific install script used by HP pwplus--don't use. + : + else + ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" + break 3 + fi + fi + done + done + ;; +esac done +IFS=$as_save_IFS + fi + if test "${ac_cv_path_install+set}" = set; then + INSTALL=$ac_cv_path_install + else + # As a last resort, use the slow shell script. Don't cache a + # value for INSTALL within a source directory, because that will + # break other packages using the cache if that directory is + # removed, or if the value is a relative name. + INSTALL=$ac_install_sh + fi fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6 +{ echo "$as_me:$LINENO: result: $INSTALL" >&5 +echo "${ECHO_T}$INSTALL" >&6; } + +# Use test -z because SunOS4 sh mishandles braces in ${var-val}. +# It thinks the first close brace ends the variable substitution. +test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' + +test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' + +test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' + +{ echo "$as_me:$LINENO: checking whether build environment is sane" >&5 +echo $ECHO_N "checking whether build environment is sane... $ECHO_C" >&6; } +# Just in case +sleep 1 +echo timestamp > conftest.file +# Do `set' in a subshell so we don't clobber the current shell's +# arguments. Must try -L first in case configure is actually a +# symlink; some systems play weird games with the mod time of symlinks +# (eg FreeBSD returns the mod time of the symlink's containing +# directory). +if ( + set X `ls -Lt $srcdir/configure conftest.file 2> /dev/null` + if test "$*" = "X"; then + # -L didn't work. + set X `ls -t $srcdir/configure conftest.file` + fi + rm -f conftest.file + if test "$*" != "X $srcdir/configure conftest.file" \ + && test "$*" != "X conftest.file $srcdir/configure"; then + + # If neither matched, then we have a broken ls. This can happen + # if, for instance, CONFIG_SHELL is bash and it inherits a + # broken ls alias from the environment. This has actually + # happened. Such a system could not be considered "sane". + { { echo "$as_me:$LINENO: error: ls -t appears to fail. Make sure there is not a broken +alias in your environment" >&5 +echo "$as_me: error: ls -t appears to fail. Make sure there is not a broken +alias in your environment" >&2;} + { (exit 1); exit 1; }; } + fi + + test "$2" = conftest.file + ) +then + # Ok. + : +else + { { echo "$as_me:$LINENO: error: newly created file is older than distributed files! +Check your system clock" >&5 +echo "$as_me: error: newly created file is older than distributed files! +Check your system clock" >&2;} + { (exit 1); exit 1; }; } +fi +{ echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6; } +test "$program_prefix" != NONE && + program_transform_name="s&^&$program_prefix&;$program_transform_name" +# Use a double $ so make ignores it. +test "$program_suffix" != NONE && + program_transform_name="s&\$&$program_suffix&;$program_transform_name" +# Double any \ or $. echo might interpret backslashes. +# By default was `s,x,x', remove it if useless. +cat <<\_ACEOF >conftest.sed +s/[\\$]/&&/g;s/;s,x,x,$// +_ACEOF +program_transform_name=`echo $program_transform_name | sed -f conftest.sed` +rm -f conftest.sed + +# expand $ac_aux_dir to an absolute path +am_aux_dir=`cd $ac_aux_dir && pwd` + +test x"${MISSING+set}" = xset || MISSING="\${SHELL} $am_aux_dir/missing" +# Use eval to expand $SHELL +if eval "$MISSING --run true"; then + am_missing_run="$MISSING --run " +else + am_missing_run= + { echo "$as_me:$LINENO: WARNING: \`missing' script is too old or missing" >&5 +echo "$as_me: WARNING: \`missing' script is too old or missing" >&2;} +fi + +{ echo "$as_me:$LINENO: checking for a thread-safe mkdir -p" >&5 +echo $ECHO_N "checking for a thread-safe mkdir -p... $ECHO_C" >&6; } +if test -z "$MKDIR_P"; then + if test "${ac_cv_path_mkdir+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 else - echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6 + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/opt/sfw/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in mkdir gmkdir; do + for ac_exec_ext in '' $ac_executable_extensions; do + { test -f "$as_dir/$ac_prog$ac_exec_ext" && $as_test_x "$as_dir/$ac_prog$ac_exec_ext"; } || continue + case `"$as_dir/$ac_prog$ac_exec_ext" --version 2>&1` in #( + 'mkdir (GNU coreutils) '* | \ + 'mkdir (coreutils) '* | \ + 'mkdir (fileutils) '4.1*) + ac_cv_path_mkdir=$as_dir/$ac_prog$ac_exec_ext + break 3;; + esac + done + done +done +IFS=$as_save_IFS + fi + if test "${ac_cv_path_mkdir+set}" = set; then + MKDIR_P="$ac_cv_path_mkdir -p" + else + # As a last resort, use the slow shell script. Don't cache a + # value for MKDIR_P within a source directory, because that will + # break other packages using the cache if that directory is + # removed, or if the value is a relative name. + test -d ./--version && rmdir ./--version + MKDIR_P="$ac_install_sh -d" + fi fi -if test -z "$ac_cv_prog_CC"; then - ac_ct_CC=$CC - # Extract the first word of "gcc", so it can be a program name with args. -set dummy gcc; ac_word=$2 -echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 -if test "${ac_cv_prog_ac_ct_CC+set}" = set; then +{ echo "$as_me:$LINENO: result: $MKDIR_P" >&5 +echo "${ECHO_T}$MKDIR_P" >&6; } + +mkdir_p="$MKDIR_P" +case $mkdir_p in + [\\/$]* | ?:[\\/]*) ;; + */*) mkdir_p="\$(top_builddir)/$mkdir_p" ;; +esac + +for ac_prog in gawk mawk nawk awk +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_AWK+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else - if test -n "$ac_ct_CC"; then - ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. + if test -n "$AWK"; then + ac_cv_prog_AWK="$AWK" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH @@ -1465,41 +2390,138 @@ IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do - if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then - ac_cv_prog_ac_ct_CC="gcc" + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_AWK="$ac_prog" echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done +IFS=$as_save_IFS fi fi -ac_ct_CC=$ac_cv_prog_ac_ct_CC -if test -n "$ac_ct_CC"; then - echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 -echo "${ECHO_T}$ac_ct_CC" >&6 +AWK=$ac_cv_prog_AWK +if test -n "$AWK"; then + { echo "$as_me:$LINENO: result: $AWK" >&5 +echo "${ECHO_T}$AWK" >&6; } else - echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6 + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } fi - CC=$ac_ct_CC + + test -n "$AWK" && break +done + +{ echo "$as_me:$LINENO: checking whether ${MAKE-make} sets \$(MAKE)" >&5 +echo $ECHO_N "checking whether ${MAKE-make} sets \$(MAKE)... $ECHO_C" >&6; } +set x ${MAKE-make}; ac_make=`echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` +if { as_var=ac_cv_prog_make_${ac_make}_set; eval "test \"\${$as_var+set}\" = set"; }; then + echo $ECHO_N "(cached) $ECHO_C" >&6 else - CC="$ac_cv_prog_CC" + cat >conftest.make <<\_ACEOF +SHELL = /bin/sh +all: + @echo '@@@%%%=$(MAKE)=@@@%%%' +_ACEOF +# GNU make sometimes prints "make[1]: Entering...", which would confuse us. +case `${MAKE-make} -f conftest.make 2>/dev/null` in + *@@@%%%=?*=@@@%%%*) + eval ac_cv_prog_make_${ac_make}_set=yes;; + *) + eval ac_cv_prog_make_${ac_make}_set=no;; +esac +rm -f conftest.make +fi +if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then + { echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6; } + SET_MAKE= +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } + SET_MAKE="MAKE=${MAKE-make}" +fi + +rm -rf .tst 2>/dev/null +mkdir .tst 2>/dev/null +if test -d .tst; then + am__leading_dot=. +else + am__leading_dot=_ +fi +rmdir .tst 2>/dev/null + +if test "`cd $srcdir && pwd`" != "`pwd`"; then + # Use -I$(srcdir) only when $(srcdir) != ., so that make's output + # is not polluted with repeated "-I." + am__isrc=' -I$(srcdir)' + # test to see if srcdir already configured + if test -f $srcdir/config.status; then + { { echo "$as_me:$LINENO: error: source directory already configured; run \"make distclean\" there first" >&5 +echo "$as_me: error: source directory already configured; run \"make distclean\" there first" >&2;} + { (exit 1); exit 1; }; } + fi fi -if test -z "$CC"; then +# test whether we have cygpath +if test -z "$CYGPATH_W"; then + if (cygpath --version) >/dev/null 2>/dev/null; then + CYGPATH_W='cygpath -w' + else + CYGPATH_W=echo + fi +fi + + +# Define the identity of the package. + PACKAGE='libffi' + VERSION='3.0.5' + + +cat >>confdefs.h <<_ACEOF +#define PACKAGE "$PACKAGE" +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define VERSION "$VERSION" +_ACEOF + +# Some tools Automake needs. + +ACLOCAL=${ACLOCAL-"${am_missing_run}aclocal-${am__api_version}"} + + +AUTOCONF=${AUTOCONF-"${am_missing_run}autoconf"} + + +AUTOMAKE=${AUTOMAKE-"${am_missing_run}automake-${am__api_version}"} + + +AUTOHEADER=${AUTOHEADER-"${am_missing_run}autoheader"} + + +MAKEINFO=${MAKEINFO-"${am_missing_run}makeinfo"} + +install_sh=${install_sh-"\$(SHELL) $am_aux_dir/install-sh"} + +# Installed binaries are usually stripped using `strip' when the user +# run `make install-strip'. However `strip' might not be the right +# tool to use in cross-compilation environments, therefore Automake +# will honor the `STRIP' environment variable to overrule this program. +if test "$cross_compiling" != no; then if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. -set dummy ${ac_tool_prefix}cc; ac_word=$2 -echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 -if test "${ac_cv_prog_CC+set}" = set; then + # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. +set dummy ${ac_tool_prefix}strip; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_STRIP+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. + if test -n "$STRIP"; then + ac_cv_prog_STRIP="$STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH @@ -1507,37 +2529,39 @@ IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do - if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then - ac_cv_prog_CC="${ac_tool_prefix}cc" + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_STRIP="${ac_tool_prefix}strip" echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done +IFS=$as_save_IFS fi fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6 +STRIP=$ac_cv_prog_STRIP +if test -n "$STRIP"; then + { echo "$as_me:$LINENO: result: $STRIP" >&5 +echo "${ECHO_T}$STRIP" >&6; } else - echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6 + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } fi + fi -if test -z "$ac_cv_prog_CC"; then - ac_ct_CC=$CC - # Extract the first word of "cc", so it can be a program name with args. -set dummy cc; ac_word=$2 -echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 -if test "${ac_cv_prog_ac_ct_CC+set}" = set; then +if test -z "$ac_cv_prog_STRIP"; then + ac_ct_STRIP=$STRIP + # Extract the first word of "strip", so it can be a program name with args. +set dummy strip; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_ac_ct_STRIP+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else - if test -n "$ac_ct_CC"; then - ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. + if test -n "$ac_ct_STRIP"; then + ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH @@ -1545,36 +2569,215 @@ IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do - if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then - ac_cv_prog_ac_ct_CC="cc" + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_STRIP="strip" echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done +IFS=$as_save_IFS + +fi +fi +ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP +if test -n "$ac_ct_STRIP"; then + { echo "$as_me:$LINENO: result: $ac_ct_STRIP" >&5 +echo "${ECHO_T}$ac_ct_STRIP" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + if test "x$ac_ct_STRIP" = x; then + STRIP=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf at gnu.org." >&5 +echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf at gnu.org." >&2;} +ac_tool_warned=yes ;; +esac + STRIP=$ac_ct_STRIP + fi +else + STRIP="$ac_cv_prog_STRIP" +fi + +fi +INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" + +# We need awk for the "check" target. The system "awk" is bad on +# some platforms. +# Always define AMTAR for backward compatibility. + +AMTAR=${AMTAR-"${am_missing_run}tar"} + +am__tar='${AMTAR} chof - "$$tardir"'; am__untar='${AMTAR} xf -' + + + + + + +# The same as in boehm-gc and libstdc++. Have to borrow it from there. +# We must force CC to /not/ be precious variables; otherwise +# the wrong, non-multilib-adjusted value will be used in multilibs. +# As a side effect, we have to subst CFLAGS ourselves. + + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. +set dummy ${ac_tool_prefix}gcc; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_CC+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_CC="${ac_tool_prefix}gcc" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { echo "$as_me:$LINENO: result: $CC" >&5 +echo "${ECHO_T}$CC" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_CC"; then + ac_ct_CC=$CC + # Extract the first word of "gcc", so it can be a program name with args. +set dummy gcc; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_ac_ct_CC+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_CC="gcc" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then - echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 -echo "${ECHO_T}$ac_ct_CC" >&6 + { echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 +echo "${ECHO_T}$ac_ct_CC" >&6; } else - echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6 + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } fi - CC=$ac_ct_CC + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf at gnu.org." >&5 +echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf at gnu.org." >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi else CC="$ac_cv_prog_CC" fi +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. +set dummy ${ac_tool_prefix}cc; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_CC+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_CC="${ac_tool_prefix}cc" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { echo "$as_me:$LINENO: result: $CC" >&5 +echo "${ECHO_T}$CC" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + + fi fi if test -z "$CC"; then # Extract the first word of "cc", so it can be a program name with args. set dummy cc; ac_word=$2 -echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } if test "${ac_cv_prog_CC+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else @@ -1588,7 +2791,7 @@ IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do - if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then ac_prog_rejected=yes continue @@ -1599,6 +2802,7 @@ fi done done +IFS=$as_save_IFS if test $ac_prog_rejected = yes; then # We found a bogon in the path, so make sure we never use it. @@ -1616,22 +2820,23 @@ fi CC=$ac_cv_prog_CC if test -n "$CC"; then - echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6 + { echo "$as_me:$LINENO: result: $CC" >&5 +echo "${ECHO_T}$CC" >&6; } else - echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6 + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } fi + fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then - for ac_prog in cl + for ac_prog in cl.exe do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 -echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } if test "${ac_cv_prog_CC+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else @@ -1644,36 +2849,38 @@ IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do - if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_CC="$ac_tool_prefix$ac_prog" echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done +IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then - echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6 + { echo "$as_me:$LINENO: result: $CC" >&5 +echo "${ECHO_T}$CC" >&6; } else - echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6 + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } fi + test -n "$CC" && break done fi if test -z "$CC"; then ac_ct_CC=$CC - for ac_prog in cl + for ac_prog in cl.exe do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 -echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } if test "${ac_cv_prog_ac_ct_CC+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else @@ -1686,29 +2893,45 @@ IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do - if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_ac_ct_CC="$ac_prog" echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done +IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then - echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 -echo "${ECHO_T}$ac_ct_CC" >&6 + { echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 +echo "${ECHO_T}$ac_ct_CC" >&6; } else - echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6 + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } fi + test -n "$ac_ct_CC" && break done - CC=$ac_ct_CC + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf at gnu.org." >&5 +echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf at gnu.org." >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi fi fi @@ -1721,21 +2944,35 @@ { (exit 1); exit 1; }; } # Provide some information about the compiler. -echo "$as_me:$LINENO:" \ - "checking for C compiler version" >&5 +echo "$as_me:$LINENO: checking for C compiler version" >&5 ac_compiler=`set X $ac_compile; echo $2` -{ (eval echo "$as_me:$LINENO: \"$ac_compiler --version &5\"") >&5 - (eval $ac_compiler --version &5) 2>&5 +{ (ac_try="$ac_compiler --version >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compiler --version >&5") 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } -{ (eval echo "$as_me:$LINENO: \"$ac_compiler -v &5\"") >&5 - (eval $ac_compiler -v &5) 2>&5 +{ (ac_try="$ac_compiler -v >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compiler -v >&5") 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } -{ (eval echo "$as_me:$LINENO: \"$ac_compiler -V &5\"") >&5 - (eval $ac_compiler -V &5) 2>&5 +{ (ac_try="$ac_compiler -V >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compiler -V >&5") 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } @@ -1760,47 +2997,77 @@ # Try to create an executable without -o first, disregard a.out. # It will help us diagnose broken compilers, and finding out an intuition # of exeext. -echo "$as_me:$LINENO: checking for C compiler default output file name" >&5 -echo $ECHO_N "checking for C compiler default output file name... $ECHO_C" >&6 +{ echo "$as_me:$LINENO: checking for C compiler default output file name" >&5 +echo $ECHO_N "checking for C compiler default output file name... $ECHO_C" >&6; } ac_link_default=`echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` -if { (eval echo "$as_me:$LINENO: \"$ac_link_default\"") >&5 - (eval $ac_link_default) 2>&5 +# +# List of possible output files, starting from the most likely. +# The algorithm is not robust to junk in `.', hence go to wildcards (a.*) +# only as a last resort. b.out is created by i960 compilers. +ac_files='a_out.exe a.exe conftest.exe a.out conftest a.* conftest.* b.out' +# +# The IRIX 6 linker writes into existing files which may not be +# executable, retaining their permissions. Remove them first so a +# subsequent execution test works. +ac_rmfiles= +for ac_file in $ac_files +do + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) ;; + * ) ac_rmfiles="$ac_rmfiles $ac_file";; + esac +done +rm -f $ac_rmfiles + +if { (ac_try="$ac_link_default" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link_default") 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; then - # Find the output, starting from the most likely. This scheme is -# not robust to junk in `.', hence go to wildcards (a.*) only as a last -# resort. - -# Be careful to initialize this variable, since it used to be cached. -# Otherwise an old cache value of `no' led to `EXEEXT = no' in a Makefile. -ac_cv_exeext= -# b.out is created by i960 compilers. -for ac_file in a_out.exe a.exe conftest.exe a.out conftest a.* conftest.* b.out + # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. +# So ignore a value of `no', otherwise this would lead to `EXEEXT = no' +# in a Makefile. We should not override ac_cv_exeext if it was cached, +# so that the user can short-circuit this test for compilers unknown to +# Autoconf. +for ac_file in $ac_files '' do test -f "$ac_file" || continue case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.o | *.obj ) - ;; - conftest.$ac_ext ) - # This is the source file. + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) ;; [ab].out ) # We found the default executable, but exeext='' is most # certainly right. break;; *.* ) - ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` - # FIXME: I believe we export ac_cv_exeext for Libtool, - # but it would be cool to find out if it's true. Does anybody - # maintain Libtool? --akim. - export ac_cv_exeext + if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; + then :; else + ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + fi + # We set ac_cv_exeext here because the later test for it is not + # safe: cross compilers may not add the suffix if given an `-o' + # argument, so we may need to know it at that point already. + # Even if this section looks crufty: it has the advantage of + # actually working. break;; * ) break;; esac done +test "$ac_cv_exeext" = no && ac_cv_exeext= + else + ac_file='' +fi + +{ echo "$as_me:$LINENO: result: $ac_file" >&5 +echo "${ECHO_T}$ac_file" >&6; } +if test -z "$ac_file"; then echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 @@ -1812,19 +3079,21 @@ fi ac_exeext=$ac_cv_exeext -echo "$as_me:$LINENO: result: $ac_file" >&5 -echo "${ECHO_T}$ac_file" >&6 -# Check the compiler produces executables we can run. If not, either +# Check that the compiler produces executables we can run. If not, either # the compiler is broken, or we cross compile. -echo "$as_me:$LINENO: checking whether the C compiler works" >&5 -echo $ECHO_N "checking whether the C compiler works... $ECHO_C" >&6 +{ echo "$as_me:$LINENO: checking whether the C compiler works" >&5 +echo $ECHO_N "checking whether the C compiler works... $ECHO_C" >&6; } # FIXME: These cross compiler hacks should be removed for Autoconf 3.0 # If not cross compiling, check that we can run a simple program. if test "$cross_compiling" != yes; then if { ac_try='./$ac_file' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then @@ -1843,22 +3112,27 @@ fi fi fi -echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6 +{ echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6; } rm -f a.out a.exe conftest$ac_cv_exeext b.out ac_clean_files=$ac_clean_files_save -# Check the compiler produces executables we can run. If not, either +# Check that the compiler produces executables we can run. If not, either # the compiler is broken, or we cross compile. -echo "$as_me:$LINENO: checking whether we are cross compiling" >&5 -echo $ECHO_N "checking whether we are cross compiling... $ECHO_C" >&6 -echo "$as_me:$LINENO: result: $cross_compiling" >&5 -echo "${ECHO_T}$cross_compiling" >&6 - -echo "$as_me:$LINENO: checking for suffix of executables" >&5 -echo $ECHO_N "checking for suffix of executables... $ECHO_C" >&6 -if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 - (eval $ac_link) 2>&5 +{ echo "$as_me:$LINENO: checking whether we are cross compiling" >&5 +echo $ECHO_N "checking whether we are cross compiling... $ECHO_C" >&6; } +{ echo "$as_me:$LINENO: result: $cross_compiling" >&5 +echo "${ECHO_T}$cross_compiling" >&6; } + +{ echo "$as_me:$LINENO: checking for suffix of executables" >&5 +echo $ECHO_N "checking for suffix of executables... $ECHO_C" >&6; } +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; then @@ -1869,9 +3143,8 @@ for ac_file in conftest.exe conftest conftest.*; do test -f "$ac_file" || continue case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.o | *.obj ) ;; + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) ;; *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` - export ac_cv_exeext break;; * ) break;; esac @@ -1885,14 +3158,14 @@ fi rm -f conftest$ac_cv_exeext -echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5 -echo "${ECHO_T}$ac_cv_exeext" >&6 +{ echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5 +echo "${ECHO_T}$ac_cv_exeext" >&6; } rm -f conftest.$ac_ext EXEEXT=$ac_cv_exeext ac_exeext=$EXEEXT -echo "$as_me:$LINENO: checking for suffix of object files" >&5 -echo $ECHO_N "checking for suffix of object files... $ECHO_C" >&6 +{ echo "$as_me:$LINENO: checking for suffix of object files" >&5 +echo $ECHO_N "checking for suffix of object files... $ECHO_C" >&6; } if test "${ac_cv_objext+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else @@ -1912,14 +3185,20 @@ } _ACEOF rm -f conftest.o conftest.obj -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>&5 +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; then - for ac_file in `(ls conftest.o conftest.obj; ls conftest.*) 2>/dev/null`; do + for ac_file in conftest.o conftest.obj conftest.*; do + test -f "$ac_file" || continue; case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg ) ;; + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf ) ;; *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` break;; esac @@ -1937,12 +3216,12 @@ rm -f conftest.$ac_cv_objext conftest.$ac_ext fi -echo "$as_me:$LINENO: result: $ac_cv_objext" >&5 -echo "${ECHO_T}$ac_cv_objext" >&6 +{ echo "$as_me:$LINENO: result: $ac_cv_objext" >&5 +echo "${ECHO_T}$ac_cv_objext" >&6; } OBJEXT=$ac_cv_objext ac_objext=$OBJEXT -echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5 -echo $ECHO_N "checking whether we are using the GNU C compiler... $ECHO_C" >&6 +{ echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5 +echo $ECHO_N "checking whether we are using the GNU C compiler... $ECHO_C" >&6; } if test "${ac_cv_c_compiler_gnu+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else @@ -1965,49 +3244,49 @@ } _ACEOF rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then ac_compiler_gnu=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -ac_compiler_gnu=no + ac_compiler_gnu=no fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_c_compiler_gnu=$ac_compiler_gnu fi -echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5 -echo "${ECHO_T}$ac_cv_c_compiler_gnu" >&6 +{ echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5 +echo "${ECHO_T}$ac_cv_c_compiler_gnu" >&6; } GCC=`test $ac_compiler_gnu = yes && echo yes` ac_test_CFLAGS=${CFLAGS+set} ac_save_CFLAGS=$CFLAGS -CFLAGS="-g" -echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5 -echo $ECHO_N "checking whether $CC accepts -g... $ECHO_C" >&6 +{ echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5 +echo $ECHO_N "checking whether $CC accepts -g... $ECHO_C" >&6; } if test "${ac_cv_prog_cc_g+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else - cat >conftest.$ac_ext <<_ACEOF + ac_save_c_werror_flag=$ac_c_werror_flag + ac_c_werror_flag=yes + ac_cv_prog_cc_g=no + CFLAGS="-g" + cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext @@ -2023,37 +3302,118 @@ } _ACEOF rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_prog_cc_g=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + CFLAGS="" + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + : +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_c_werror_flag=$ac_save_c_werror_flag + CFLAGS="-g" + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then ac_cv_prog_cc_g=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -ac_cv_prog_cc_g=no + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + ac_c_werror_flag=$ac_save_c_werror_flag fi -echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5 -echo "${ECHO_T}$ac_cv_prog_cc_g" >&6 +{ echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5 +echo "${ECHO_T}$ac_cv_prog_cc_g" >&6; } if test "$ac_test_CFLAGS" = set; then CFLAGS=$ac_save_CFLAGS elif test $ac_cv_prog_cc_g = yes; then @@ -2069,12 +3429,12 @@ CFLAGS= fi fi -echo "$as_me:$LINENO: checking for $CC option to accept ANSI C" >&5 -echo $ECHO_N "checking for $CC option to accept ANSI C... $ECHO_C" >&6 -if test "${ac_cv_prog_cc_stdc+set}" = set; then +{ echo "$as_me:$LINENO: checking for $CC option to accept ISO C89" >&5 +echo $ECHO_N "checking for $CC option to accept ISO C89... $ECHO_C" >&6; } +if test "${ac_cv_prog_cc_c89+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else - ac_cv_prog_cc_stdc=no + ac_cv_prog_cc_c89=no ac_save_CC=$CC cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -2108,12 +3468,17 @@ /* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has function prototypes and stuff, but not '\xHH' hex character constants. These don't provoke an error unfortunately, instead are silently treated - as 'x'. The following induces an error, until -std1 is added to get + as 'x'. The following induces an error, until -std is added to get proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an array size at least. It's necessary to write '\x00'==0 to get something - that's true only with -std1. */ + that's true only with -std. */ int osf4_cc_array ['\x00' == 0 ? 1 : -1]; +/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters + inside strings and character constants. */ +#define FOO(x) 'x' +int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; + int test (int i, double x); struct s1 {int (*f) (int a);}; struct s2 {int (*f) (double a);}; @@ -2128,1096 +3493,1718 @@ return 0; } _ACEOF -# Don't try gcc -ansi; that turns off useful extensions and -# breaks some systems' header files. -# AIX -qlanglvl=ansi -# Ultrix and OSF/1 -std1 -# HP-UX 10.20 and later -Ae -# HP-UX older versions -Aa -D_HPUX_SOURCE -# SVR4 -Xc -D__EXTENSIONS__ -for ac_arg in "" -qlanglvl=ansi -std1 -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" +for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ + -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" do CC="$ac_save_CC $ac_arg" rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_prog_cc_stdc=$ac_arg -break + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_prog_cc_c89=$ac_arg else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 + fi -rm -f conftest.err conftest.$ac_objext + +rm -f core conftest.err conftest.$ac_objext + test "x$ac_cv_prog_cc_c89" != "xno" && break done -rm -f conftest.$ac_ext conftest.$ac_objext +rm -f conftest.$ac_ext CC=$ac_save_CC fi - -case "x$ac_cv_prog_cc_stdc" in - x|xno) - echo "$as_me:$LINENO: result: none needed" >&5 -echo "${ECHO_T}none needed" >&6 ;; +# AC_CACHE_VAL +case "x$ac_cv_prog_cc_c89" in + x) + { echo "$as_me:$LINENO: result: none needed" >&5 +echo "${ECHO_T}none needed" >&6; } ;; + xno) + { echo "$as_me:$LINENO: result: unsupported" >&5 +echo "${ECHO_T}unsupported" >&6; } ;; *) - echo "$as_me:$LINENO: result: $ac_cv_prog_cc_stdc" >&5 -echo "${ECHO_T}$ac_cv_prog_cc_stdc" >&6 - CC="$CC $ac_cv_prog_cc_stdc" ;; + CC="$CC $ac_cv_prog_cc_c89" + { echo "$as_me:$LINENO: result: $ac_cv_prog_cc_c89" >&5 +echo "${ECHO_T}$ac_cv_prog_cc_c89" >&6; } ;; esac -# Some people use a C++ compiler to compile C. Since we use `exit', -# in C++ we need to declare it. In case someone uses the same compiler -# for both compiling C and C++ we need to have the C++ compiler decide -# the declaration of exit, since it's the most demanding environment. -cat >conftest.$ac_ext <<_ACEOF -#ifndef __cplusplus - choke me -#endif -_ACEOF -rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - for ac_declaration in \ - '' \ - 'extern "C" void std::exit (int) throw (); using std::exit;' \ - 'extern "C" void std::exit (int); using std::exit;' \ - 'extern "C" void exit (int) throw ();' \ - 'extern "C" void exit (int);' \ - 'void exit (int);' -do + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +DEPDIR="${am__leading_dot}deps" + +ac_config_commands="$ac_config_commands depfiles" + + +am_make=${MAKE-make} +cat > confinc << 'END' +am__doit: + @echo done +.PHONY: am__doit +END +# If we don't find an include directive, just comment out the code. +{ echo "$as_me:$LINENO: checking for style of include used by $am_make" >&5 +echo $ECHO_N "checking for style of include used by $am_make... $ECHO_C" >&6; } +am__include="#" +am__quote= +_am_result=none +# First try GNU make style include. +echo "include confinc" > confmf +# We grep out `Entering directory' and `Leaving directory' +# messages which can occur if `w' ends up in MAKEFLAGS. +# In particular we don't look at `^make:' because GNU make might +# be invoked under some other name (usually "gmake"), in which +# case it prints its new name instead of `make'. +if test "`$am_make -s -f confmf 2> /dev/null | grep -v 'ing directory'`" = "done"; then + am__include=include + am__quote= + _am_result=GNU +fi +# Now try BSD make style include. +if test "$am__include" = "#"; then + echo '.include "confinc"' > confmf + if test "`$am_make -s -f confmf 2> /dev/null`" = "done"; then + am__include=.include + am__quote="\"" + _am_result=BSD + fi +fi + + +{ echo "$as_me:$LINENO: result: $_am_result" >&5 +echo "${ECHO_T}$_am_result" >&6; } +rm -f confinc confmf + +# Check whether --enable-dependency-tracking was given. +if test "${enable_dependency_tracking+set}" = set; then + enableval=$enable_dependency_tracking; +fi + +if test "x$enable_dependency_tracking" != xno; then + am_depcomp="$ac_aux_dir/depcomp" + AMDEPBACKSLASH='\' +fi + if test "x$enable_dependency_tracking" != xno; then + AMDEP_TRUE= + AMDEP_FALSE='#' +else + AMDEP_TRUE='#' + AMDEP_FALSE= +fi + + + +depcc="$CC" am_compiler_list= + +{ echo "$as_me:$LINENO: checking dependency style of $depcc" >&5 +echo $ECHO_N "checking dependency style of $depcc... $ECHO_C" >&6; } +if test "${am_cv_CC_dependencies_compiler_type+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then + # We make a subdir and do the tests there. Otherwise we can end up + # making bogus files that we don't know about and never remove. For + # instance it was reported that on HP-UX the gcc test will end up + # making a dummy file named `D' -- because `-MD' means `put the output + # in D'. + mkdir conftest.dir + # Copy depcomp to subdir because otherwise we won't find it if we're + # using a relative directory. + cp "$am_depcomp" conftest.dir + cd conftest.dir + # We will build objects and dependencies in a subdirectory because + # it helps to detect inapplicable dependency modes. For instance + # both Tru64's cc and ICC support -MD to output dependencies as a + # side effect of compilation, but ICC will put the dependencies in + # the current directory while Tru64 will put them in the object + # directory. + mkdir sub + + am_cv_CC_dependencies_compiler_type=none + if test "$am_compiler_list" = ""; then + am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` + fi + for depmode in $am_compiler_list; do + # Setup a source with many dependencies, because some compilers + # like to wrap large dependency lists on column 80 (with \), and + # we should not choose a depcomp mode which is confused by this. + # + # We need to recreate these files for each test, as the compiler may + # overwrite some of them when testing with obscure command lines. + # This happens at least with the AIX C compiler. + : > sub/conftest.c + for i in 1 2 3 4 5 6; do + echo '#include "conftst'$i'.h"' >> sub/conftest.c + # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with + # Solaris 8's {/usr,}/bin/sh. + touch sub/conftst$i.h + done + echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf + + case $depmode in + nosideeffect) + # after this tag, mechanisms are not by side-effect, so they'll + # only be used when explicitly requested + if test "x$enable_dependency_tracking" = xyes; then + continue + else + break + fi + ;; + none) break ;; + esac + # We check with `-c' and `-o' for the sake of the "dashmstdout" + # mode. It turns out that the SunPro C++ compiler does not properly + # handle `-M -o', and we need to detect this. + if depmode=$depmode \ + source=sub/conftest.c object=sub/conftest.${OBJEXT-o} \ + depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ + $SHELL ./depcomp $depcc -c -o sub/conftest.${OBJEXT-o} sub/conftest.c \ + >/dev/null 2>conftest.err && + grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && + grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && + grep sub/conftest.${OBJEXT-o} sub/conftest.Po > /dev/null 2>&1 && + ${MAKE-make} -s -f confmf > /dev/null 2>&1; then + # icc doesn't choke on unknown options, it will just issue warnings + # or remarks (even with -Werror). So we grep stderr for any message + # that says an option was ignored or not supported. + # When given -MP, icc 7.0 and 7.1 complain thusly: + # icc: Command line warning: ignoring option '-M'; no argument required + # The diagnosis changed in icc 8.0: + # icc: Command line remark: option '-MP' not supported + if (grep 'ignoring option' conftest.err || + grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else + am_cv_CC_dependencies_compiler_type=$depmode + break + fi + fi + done + + cd .. + rm -rf conftest.dir +else + am_cv_CC_dependencies_compiler_type=none +fi + +fi +{ echo "$as_me:$LINENO: result: $am_cv_CC_dependencies_compiler_type" >&5 +echo "${ECHO_T}$am_cv_CC_dependencies_compiler_type" >&6; } +CCDEPMODE=depmode=$am_cv_CC_dependencies_compiler_type + + if + test "x$enable_dependency_tracking" != xno \ + && test "$am_cv_CC_dependencies_compiler_type" = gcc3; then + am__fastdepCC_TRUE= + am__fastdepCC_FALSE='#' +else + am__fastdepCC_TRUE='#' + am__fastdepCC_FALSE= +fi + + + + + + +# By default we simply use the C compiler to build assembly code. + +test "${CCAS+set}" = set || CCAS=$CC +test "${CCASFLAGS+set}" = set || CCASFLAGS=$CFLAGS + + + +depcc="$CCAS" am_compiler_list= + +{ echo "$as_me:$LINENO: checking dependency style of $depcc" >&5 +echo $ECHO_N "checking dependency style of $depcc... $ECHO_C" >&6; } +if test "${am_cv_CCAS_dependencies_compiler_type+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then + # We make a subdir and do the tests there. Otherwise we can end up + # making bogus files that we don't know about and never remove. For + # instance it was reported that on HP-UX the gcc test will end up + # making a dummy file named `D' -- because `-MD' means `put the output + # in D'. + mkdir conftest.dir + # Copy depcomp to subdir because otherwise we won't find it if we're + # using a relative directory. + cp "$am_depcomp" conftest.dir + cd conftest.dir + # We will build objects and dependencies in a subdirectory because + # it helps to detect inapplicable dependency modes. For instance + # both Tru64's cc and ICC support -MD to output dependencies as a + # side effect of compilation, but ICC will put the dependencies in + # the current directory while Tru64 will put them in the object + # directory. + mkdir sub + + am_cv_CCAS_dependencies_compiler_type=none + if test "$am_compiler_list" = ""; then + am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` + fi + for depmode in $am_compiler_list; do + # Setup a source with many dependencies, because some compilers + # like to wrap large dependency lists on column 80 (with \), and + # we should not choose a depcomp mode which is confused by this. + # + # We need to recreate these files for each test, as the compiler may + # overwrite some of them when testing with obscure command lines. + # This happens at least with the AIX C compiler. + : > sub/conftest.c + for i in 1 2 3 4 5 6; do + echo '#include "conftst'$i'.h"' >> sub/conftest.c + # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with + # Solaris 8's {/usr,}/bin/sh. + touch sub/conftst$i.h + done + echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf + + case $depmode in + nosideeffect) + # after this tag, mechanisms are not by side-effect, so they'll + # only be used when explicitly requested + if test "x$enable_dependency_tracking" = xyes; then + continue + else + break + fi + ;; + none) break ;; + esac + # We check with `-c' and `-o' for the sake of the "dashmstdout" + # mode. It turns out that the SunPro C++ compiler does not properly + # handle `-M -o', and we need to detect this. + if depmode=$depmode \ + source=sub/conftest.c object=sub/conftest.${OBJEXT-o} \ + depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ + $SHELL ./depcomp $depcc -c -o sub/conftest.${OBJEXT-o} sub/conftest.c \ + >/dev/null 2>conftest.err && + grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && + grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && + grep sub/conftest.${OBJEXT-o} sub/conftest.Po > /dev/null 2>&1 && + ${MAKE-make} -s -f confmf > /dev/null 2>&1; then + # icc doesn't choke on unknown options, it will just issue warnings + # or remarks (even with -Werror). So we grep stderr for any message + # that says an option was ignored or not supported. + # When given -MP, icc 7.0 and 7.1 complain thusly: + # icc: Command line warning: ignoring option '-M'; no argument required + # The diagnosis changed in icc 8.0: + # icc: Command line remark: option '-MP' not supported + if (grep 'ignoring option' conftest.err || + grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else + am_cv_CCAS_dependencies_compiler_type=$depmode + break + fi + fi + done + + cd .. + rm -rf conftest.dir +else + am_cv_CCAS_dependencies_compiler_type=none +fi + +fi +{ echo "$as_me:$LINENO: result: $am_cv_CCAS_dependencies_compiler_type" >&5 +echo "${ECHO_T}$am_cv_CCAS_dependencies_compiler_type" >&6; } +CCASDEPMODE=depmode=$am_cv_CCAS_dependencies_compiler_type + + if + test "x$enable_dependency_tracking" != xno \ + && test "$am_cv_CCAS_dependencies_compiler_type" = gcc3; then + am__fastdepCCAS_TRUE= + am__fastdepCCAS_FALSE='#' +else + am__fastdepCCAS_TRUE='#' + am__fastdepCCAS_FALSE= +fi + + +if test "x$CC" != xcc; then + { echo "$as_me:$LINENO: checking whether $CC and cc understand -c and -o together" >&5 +echo $ECHO_N "checking whether $CC and cc understand -c and -o together... $ECHO_C" >&6; } +else + { echo "$as_me:$LINENO: checking whether cc understands -c and -o together" >&5 +echo $ECHO_N "checking whether cc understands -c and -o together... $ECHO_C" >&6; } +fi +set dummy $CC; ac_cc=`echo $2 | + sed 's/[^a-zA-Z0-9_]/_/g;s/^[0-9]/_/'` +if { as_var=ac_cv_prog_cc_${ac_cc}_c_o; eval "test \"\${$as_var+set}\" = set"; }; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -$ac_declaration -#include + int main () { -exit (42); + ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +# Make sure it works both with $CC and with simple cc. +# We do the test twice because some compilers refuse to overwrite an +# existing .o file with -o, though they will create one. +ac_try='$CC -c conftest.$ac_ext -o conftest2.$ac_objext >&5' +rm -f conftest2.* +if { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 + test -f conftest2.$ac_objext && { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 + (exit $ac_status); }; +then + eval ac_cv_prog_cc_${ac_cc}_c_o=yes + if test "x$CC" != xcc; then + # Test first that cc exists at all. + if { ac_try='cc -c conftest.$ac_ext >&5' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then - : -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -continue -fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_declaration -int -main () -{ -exit (42); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 + ac_try='cc -c conftest.$ac_ext -o conftest2.$ac_objext >&5' + rm -f conftest2.* + if { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 + test -f conftest2.$ac_objext && { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - break + (exit $ac_status); }; + then + # cc works too. + : + else + # cc exists but doesn't like -o. + eval ac_cv_prog_cc_${ac_cc}_c_o=no + fi + fi + fi else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext -done -rm -f conftest* -if test -n "$ac_declaration"; then - echo '#ifdef __cplusplus' >>confdefs.h - echo $ac_declaration >>confdefs.h - echo '#endif' >>confdefs.h + eval ac_cv_prog_cc_${ac_cc}_c_o=no fi +rm -f core conftest* +fi +if eval test \$ac_cv_prog_cc_${ac_cc}_c_o = yes; then + { echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } + +cat >>confdefs.h <<\_ACEOF +#define NO_MINUS_C_MINUS_O 1 +_ACEOF fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu + +# FIXME: we rely on the cache variable name because +# there is no other way. +set dummy $CC +ac_cc=`echo $2 | sed 's/[^a-zA-Z0-9_]/_/g;s/^[0-9]/_/'` +if eval "test \"`echo '$ac_cv_prog_cc_'${ac_cc}_c_o`\" != yes"; then + # Losing compiler, so override with the script. + # FIXME: It is wrong to rewrite CC. + # But if we don't then we get into trouble of one sort or another. + # A longer-term fix would be to have automake use am__CC in this case, + # and then we could set am__CC="\$(top_srcdir)/compile \$(CC)" + CC="$am_aux_dir/compile $CC" +fi +# Check whether --enable-shared was given. +if test "${enable_shared+set}" = set; then + enableval=$enable_shared; p=${PACKAGE-default} + case $enableval in + yes) enable_shared=yes ;; + no) enable_shared=no ;; + *) + enable_shared=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for pkg in $enableval; do + IFS="$lt_save_ifs" + if test "X$pkg" = "X$p"; then + enable_shared=yes + fi + done + IFS="$lt_save_ifs" + ;; + esac +else + enable_shared=yes +fi +# Check whether --enable-static was given. +if test "${enable_static+set}" = set; then + enableval=$enable_static; p=${PACKAGE-default} + case $enableval in + yes) enable_static=yes ;; + no) enable_static=no ;; + *) + enable_static=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for pkg in $enableval; do + IFS="$lt_save_ifs" + if test "X$pkg" = "X$p"; then + enable_static=yes + fi + done + IFS="$lt_save_ifs" + ;; + esac +else + enable_static=yes +fi -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu -echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5 -echo $ECHO_N "checking how to run the C preprocessor... $ECHO_C" >&6 -# On Suns, sometimes $CPP names a directory. -if test -n "$CPP" && test -d "$CPP"; then - CPP= +# Check whether --enable-fast-install was given. +if test "${enable_fast_install+set}" = set; then + enableval=$enable_fast_install; p=${PACKAGE-default} + case $enableval in + yes) enable_fast_install=yes ;; + no) enable_fast_install=no ;; + *) + enable_fast_install=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for pkg in $enableval; do + IFS="$lt_save_ifs" + if test "X$pkg" = "X$p"; then + enable_fast_install=yes + fi + done + IFS="$lt_save_ifs" + ;; + esac +else + enable_fast_install=yes fi -if test -z "$CPP"; then - if test "${ac_cv_prog_CPP+set}" = set; then + + +{ echo "$as_me:$LINENO: checking for a sed that does not truncate output" >&5 +echo $ECHO_N "checking for a sed that does not truncate output... $ECHO_C" >&6; } +if test "${lt_cv_path_SED+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else - # Double quotes because CPP needs to be expanded - for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" - do - ac_preproc_ok=false -for ac_c_preproc_warn_flag in '' yes + # Loop through the user's path and test for sed and gsed. +# Then use that list of sed's as ones to test for truncation. +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH do - # Use a header file that comes with gcc, so configuring glibc - # with a fresh cross-compiler works. - # Prefer to if __STDC__ is defined, since - # exists even on freestanding compilers. - # On the NeXT, cc -E runs the code through the compiler's parser, - # not just through cpp. "Syntax error" is here to catch this case. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#ifdef __STDC__ -# include -#else -# include -#endif - Syntax error -_ACEOF -if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 - (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null; then - if test -s conftest.err; then - ac_cpp_err=$ac_c_preproc_warn_flag - ac_cpp_err=$ac_cpp_err$ac_c_werror_flag - else - ac_cpp_err= + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for lt_ac_prog in sed gsed; do + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$lt_ac_prog$ac_exec_ext" && $as_test_x "$as_dir/$lt_ac_prog$ac_exec_ext"; }; then + lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext" + fi + done + done +done +IFS=$as_save_IFS +lt_ac_max=0 +lt_ac_count=0 +# Add /usr/xpg4/bin/sed as it is typically found on Solaris +# along with /bin/sed that truncates output. +for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do + test ! -f $lt_ac_sed && continue + cat /dev/null > conftest.in + lt_ac_count=0 + echo $ECHO_N "0123456789$ECHO_C" >conftest.in + # Check for GNU sed and select it if it is found. + if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then + lt_cv_path_SED=$lt_ac_sed + break fi -else - ac_cpp_err=yes + while true; do + cat conftest.in conftest.in >conftest.tmp + mv conftest.tmp conftest.in + cp conftest.in conftest.nl + echo >>conftest.nl + $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break + cmp -s conftest.out conftest.nl || break + # 10000 chars as input seems more than enough + test $lt_ac_count -gt 10 && break + lt_ac_count=`expr $lt_ac_count + 1` + if test $lt_ac_count -gt $lt_ac_max; then + lt_ac_max=$lt_ac_count + lt_cv_path_SED=$lt_ac_sed + fi + done +done + fi -if test -z "$ac_cpp_err"; then - : + +SED=$lt_cv_path_SED + +{ echo "$as_me:$LINENO: result: $SED" >&5 +echo "${ECHO_T}$SED" >&6; } + +{ echo "$as_me:$LINENO: checking for grep that handles long lines and -e" >&5 +echo $ECHO_N "checking for grep that handles long lines and -e... $ECHO_C" >&6; } +if test "${ac_cv_path_GREP+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + # Extract the first word of "grep ggrep" to use in msg output +if test -z "$GREP"; then +set dummy grep ggrep; ac_prog_name=$2 +if test "${ac_cv_path_GREP+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_path_GREP_found=false +# Loop through the user's path and test for each of PROGNAME-LIST +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in grep ggrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue + # Check for GNU ac_path_GREP and select it if it is found. + # Check for GNU $ac_path_GREP +case `"$ac_path_GREP" --version 2>&1` in +*GNU*) + ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; +*) + ac_count=0 + echo $ECHO_N "0123456789$ECHO_C" >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + echo 'GREP' >> "conftest.nl" + "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + ac_count=`expr $ac_count + 1` + if test $ac_count -gt ${ac_path_GREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_GREP="$ac_path_GREP" + ac_path_GREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + + $ac_path_GREP_found && break 3 + done +done + +done +IFS=$as_save_IFS - # Broken: fails on valid input. -continue -fi -rm -f conftest.err conftest.$ac_ext - # OK, works on sane cases. Now check whether non-existent headers - # can be detected and how. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 - (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null; then - if test -s conftest.err; then - ac_cpp_err=$ac_c_preproc_warn_flag - ac_cpp_err=$ac_cpp_err$ac_c_werror_flag - else - ac_cpp_err= - fi -else - ac_cpp_err=yes fi -if test -z "$ac_cpp_err"; then - # Broken: success on invalid input. -continue -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - # Passes both tests. -ac_preproc_ok=: -break +GREP="$ac_cv_path_GREP" +if test -z "$GREP"; then + { { echo "$as_me:$LINENO: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 +echo "$as_me: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} + { (exit 1); exit 1; }; } fi -rm -f conftest.err conftest.$ac_ext -done -# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. -rm -f conftest.err conftest.$ac_ext -if $ac_preproc_ok; then - break +else + ac_cv_path_GREP=$GREP fi - done - ac_cv_prog_CPP=$CPP fi - CPP=$ac_cv_prog_CPP +{ echo "$as_me:$LINENO: result: $ac_cv_path_GREP" >&5 +echo "${ECHO_T}$ac_cv_path_GREP" >&6; } + GREP="$ac_cv_path_GREP" + + +{ echo "$as_me:$LINENO: checking for egrep" >&5 +echo $ECHO_N "checking for egrep... $ECHO_C" >&6; } +if test "${ac_cv_path_EGREP+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 else - ac_cv_prog_CPP=$CPP -fi -echo "$as_me:$LINENO: result: $CPP" >&5 -echo "${ECHO_T}$CPP" >&6 -ac_preproc_ok=false -for ac_c_preproc_warn_flag in '' yes -do - # Use a header file that comes with gcc, so configuring glibc - # with a fresh cross-compiler works. - # Prefer to if __STDC__ is defined, since - # exists even on freestanding compilers. - # On the NeXT, cc -E runs the code through the compiler's parser, - # not just through cpp. "Syntax error" is here to catch this case. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#ifdef __STDC__ -# include -#else -# include -#endif - Syntax error -_ACEOF -if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 - (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null; then - if test -s conftest.err; then - ac_cpp_err=$ac_c_preproc_warn_flag - ac_cpp_err=$ac_cpp_err$ac_c_werror_flag - else - ac_cpp_err= - fi + if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 + then ac_cv_path_EGREP="$GREP -E" + else + # Extract the first word of "egrep" to use in msg output +if test -z "$EGREP"; then +set dummy egrep; ac_prog_name=$2 +if test "${ac_cv_path_EGREP+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 else - ac_cpp_err=yes + ac_path_EGREP_found=false +# Loop through the user's path and test for each of PROGNAME-LIST +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in egrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue + # Check for GNU ac_path_EGREP and select it if it is found. + # Check for GNU $ac_path_EGREP +case `"$ac_path_EGREP" --version 2>&1` in +*GNU*) + ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; +*) + ac_count=0 + echo $ECHO_N "0123456789$ECHO_C" >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + echo 'EGREP' >> "conftest.nl" + "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + ac_count=`expr $ac_count + 1` + if test $ac_count -gt ${ac_path_EGREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_EGREP="$ac_path_EGREP" + ac_path_EGREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + + $ac_path_EGREP_found && break 3 + done +done + +done +IFS=$as_save_IFS + + fi -if test -z "$ac_cpp_err"; then - : -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - # Broken: fails on valid input. -continue +EGREP="$ac_cv_path_EGREP" +if test -z "$EGREP"; then + { { echo "$as_me:$LINENO: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 +echo "$as_me: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} + { (exit 1); exit 1; }; } fi -rm -f conftest.err conftest.$ac_ext - # OK, works on sane cases. Now check whether non-existent headers - # can be detected and how. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 - (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null; then - if test -s conftest.err; then - ac_cpp_err=$ac_c_preproc_warn_flag - ac_cpp_err=$ac_cpp_err$ac_c_werror_flag - else - ac_cpp_err= - fi else - ac_cpp_err=yes + ac_cv_path_EGREP=$EGREP fi -if test -z "$ac_cpp_err"; then - # Broken: success on invalid input. -continue -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - # Passes both tests. -ac_preproc_ok=: -break -fi -rm -f conftest.err conftest.$ac_ext -done -# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. -rm -f conftest.err conftest.$ac_ext -if $ac_preproc_ok; then - : -else - { { echo "$as_me:$LINENO: error: C preprocessor \"$CPP\" fails sanity check -See \`config.log' for more details." >&5 -echo "$as_me: error: C preprocessor \"$CPP\" fails sanity check -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } + fi fi +{ echo "$as_me:$LINENO: result: $ac_cv_path_EGREP" >&5 +echo "${ECHO_T}$ac_cv_path_EGREP" >&6; } + EGREP="$ac_cv_path_EGREP" + -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu +# Check whether --with-gnu-ld was given. +if test "${with_gnu_ld+set}" = set; then + withval=$with_gnu_ld; test "$withval" = no || with_gnu_ld=yes +else + with_gnu_ld=no +fi -echo "$as_me:$LINENO: checking for egrep" >&5 -echo $ECHO_N "checking for egrep... $ECHO_C" >&6 -if test "${ac_cv_prog_egrep+set}" = set; then +ac_prog=ld +if test "$GCC" = yes; then + # Check if gcc -print-prog-name=ld gives a path. + { echo "$as_me:$LINENO: checking for ld used by $CC" >&5 +echo $ECHO_N "checking for ld used by $CC... $ECHO_C" >&6; } + case $host in + *-*-mingw*) + # gcc leaves a trailing carriage return which upsets mingw + ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; + *) + ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; + esac + case $ac_prog in + # Accept absolute paths. + [\\/]* | ?:[\\/]*) + re_direlt='/[^/][^/]*/\.\./' + # Canonicalize the pathname of ld + ac_prog=`echo $ac_prog| $SED 's%\\\\%/%g'` + while echo $ac_prog | grep "$re_direlt" > /dev/null 2>&1; do + ac_prog=`echo $ac_prog| $SED "s%$re_direlt%/%"` + done + test -z "$LD" && LD="$ac_prog" + ;; + "") + # If it fails, then pretend we aren't using GCC. + ac_prog=ld + ;; + *) + # If it is relative, then search for the first ld in PATH. + with_gnu_ld=unknown + ;; + esac +elif test "$with_gnu_ld" = yes; then + { echo "$as_me:$LINENO: checking for GNU ld" >&5 +echo $ECHO_N "checking for GNU ld... $ECHO_C" >&6; } +else + { echo "$as_me:$LINENO: checking for non-GNU ld" >&5 +echo $ECHO_N "checking for non-GNU ld... $ECHO_C" >&6; } +fi +if test "${lt_cv_path_LD+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else - if echo a | (grep -E '(a|b)') >/dev/null 2>&1 - then ac_cv_prog_egrep='grep -E' - else ac_cv_prog_egrep='egrep' + if test -z "$LD"; then + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + for ac_dir in $PATH; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then + lt_cv_path_LD="$ac_dir/$ac_prog" + # Check to see if the program is GNU ld. I'd rather use --version, + # but apparently some variants of GNU ld only accept -v. + # Break only if it was the GNU/non-GNU ld that we prefer. + case `"$lt_cv_path_LD" -v 2>&1 &5 -echo "${ECHO_T}$ac_cv_prog_egrep" >&6 - EGREP=$ac_cv_prog_egrep - -echo "$as_me:$LINENO: checking for ANSI C header files" >&5 -echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6 -if test "${ac_cv_header_stdc+set}" = set; then +LD="$lt_cv_path_LD" +if test -n "$LD"; then + { echo "$as_me:$LINENO: result: $LD" >&5 +echo "${ECHO_T}$LD" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi +test -z "$LD" && { { echo "$as_me:$LINENO: error: no acceptable ld found in \$PATH" >&5 +echo "$as_me: error: no acceptable ld found in \$PATH" >&2;} + { (exit 1); exit 1; }; } +{ echo "$as_me:$LINENO: checking if the linker ($LD) is GNU ld" >&5 +echo $ECHO_N "checking if the linker ($LD) is GNU ld... $ECHO_C" >&6; } +if test "${lt_cv_prog_gnu_ld+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include -#include -#include + # I'd rather use --version here, but apparently some GNU lds only accept -v. +case `$LD -v 2>&1 &5 +echo "${ECHO_T}$lt_cv_prog_gnu_ld" >&6; } +with_gnu_ld=$lt_cv_prog_gnu_ld -int -main () -{ - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_header_stdc=yes +{ echo "$as_me:$LINENO: checking for $LD option to reload object files" >&5 +echo $ECHO_N "checking for $LD option to reload object files... $ECHO_C" >&6; } +if test "${lt_cv_ld_reload_flag+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -ac_cv_header_stdc=no + lt_cv_ld_reload_flag='-r' fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext - -if test $ac_cv_header_stdc = yes; then - # SunOS 4.x string.h does not declare mem*, contrary to ANSI. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include +{ echo "$as_me:$LINENO: result: $lt_cv_ld_reload_flag" >&5 +echo "${ECHO_T}$lt_cv_ld_reload_flag" >&6; } +reload_flag=$lt_cv_ld_reload_flag +case $reload_flag in +"" | " "*) ;; +*) reload_flag=" $reload_flag" ;; +esac +reload_cmds='$LD$reload_flag -o $output$reload_objs' +case $host_os in + darwin*) + if test "$GCC" = yes; then + reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs' + else + reload_cmds='$LD$reload_flag -o $output$reload_objs' + fi + ;; +esac -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "memchr" >/dev/null 2>&1; then - : +{ echo "$as_me:$LINENO: checking for BSD-compatible nm" >&5 +echo $ECHO_N "checking for BSD-compatible nm... $ECHO_C" >&6; } +if test "${lt_cv_path_NM+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 else - ac_cv_header_stdc=no + if test -n "$NM"; then + # Let the user override the test. + lt_cv_path_NM="$NM" +else + lt_nm_to_check="${ac_tool_prefix}nm" + if test -n "$ac_tool_prefix" && test "$build" = "$host"; then + lt_nm_to_check="$lt_nm_to_check nm" + fi + for lt_tmp_nm in $lt_nm_to_check; do + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + tmp_nm="$ac_dir/$lt_tmp_nm" + if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then + # Check to see if the nm accepts a BSD-compat flag. + # Adding the `sed 1q' prevents false positives on HP-UX, which says: + # nm: unknown option "B" ignored + # Tru64's nm complains that /dev/null is an invalid object file + case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in + */dev/null* | *'Invalid file or object type'*) + lt_cv_path_NM="$tmp_nm -B" + break + ;; + *) + case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in + */dev/null*) + lt_cv_path_NM="$tmp_nm -p" + break + ;; + *) + lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but + continue # so that we can try to find one that supports BSD flags + ;; + esac + ;; + esac + fi + done + IFS="$lt_save_ifs" + done + test -z "$lt_cv_path_NM" && lt_cv_path_NM=nm fi -rm -f conftest* - fi +{ echo "$as_me:$LINENO: result: $lt_cv_path_NM" >&5 +echo "${ECHO_T}$lt_cv_path_NM" >&6; } +NM="$lt_cv_path_NM" -if test $ac_cv_header_stdc = yes; then - # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "free" >/dev/null 2>&1; then - : +{ echo "$as_me:$LINENO: checking whether ln -s works" >&5 +echo $ECHO_N "checking whether ln -s works... $ECHO_C" >&6; } +LN_S=$as_ln_s +if test "$LN_S" = "ln -s"; then + { echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6; } else - ac_cv_header_stdc=no -fi -rm -f conftest* - + { echo "$as_me:$LINENO: result: no, using $LN_S" >&5 +echo "${ECHO_T}no, using $LN_S" >&6; } fi -if test $ac_cv_header_stdc = yes; then - # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. - if test "$cross_compiling" = yes; then - : +{ echo "$as_me:$LINENO: checking how to recognize dependent libraries" >&5 +echo $ECHO_N "checking how to recognize dependent libraries... $ECHO_C" >&6; } +if test "${lt_cv_deplibs_check_method+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#if ((' ' & 0x0FF) == 0x020) -# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') -# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) -#else -# define ISLOWER(c) \ - (('a' <= (c) && (c) <= 'i') \ - || ('j' <= (c) && (c) <= 'r') \ - || ('s' <= (c) && (c) <= 'z')) -# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) -#endif + lt_cv_file_magic_cmd='$MAGIC_CMD' +lt_cv_file_magic_test_file= +lt_cv_deplibs_check_method='unknown' +# Need to set the preceding variable on all platforms that support +# interlibrary dependencies. +# 'none' -- dependencies not supported. +# `unknown' -- same as none, but documents that we really don't know. +# 'pass_all' -- all dependencies passed with no checks. +# 'test_compile' -- check by making test program. +# 'file_magic [[regex]]' -- check by looking for files in library path +# which responds to the $file_magic_cmd with a given extended regex. +# If you have `file' or equivalent on your system and you're not sure +# whether `pass_all' will *always* work, you probably want this one. + +case $host_os in +aix4* | aix5*) + lt_cv_deplibs_check_method=pass_all + ;; + +beos*) + lt_cv_deplibs_check_method=pass_all + ;; + +bsdi[45]*) + lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib)' + lt_cv_file_magic_cmd='/usr/bin/file -L' + lt_cv_file_magic_test_file=/shlib/libc.so + ;; + +cygwin*) + # func_win32_libid is a shell function defined in ltmain.sh + lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' + lt_cv_file_magic_cmd='func_win32_libid' + ;; + +mingw* | pw32*) + # Base MSYS/MinGW do not provide the 'file' command needed by + # func_win32_libid shell function, so use a weaker test based on 'objdump', + # unless we find 'file', for example because we are cross-compiling. + if ( file / ) >/dev/null 2>&1; then + lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' + lt_cv_file_magic_cmd='func_win32_libid' + else + lt_cv_deplibs_check_method='file_magic file format pei*-i386(.*architecture: i386)?' + lt_cv_file_magic_cmd='$OBJDUMP -f' + fi + ;; -#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) -int -main () -{ - int i; - for (i = 0; i < 256; i++) - if (XOR (islower (i), ISLOWER (i)) - || toupper (i) != TOUPPER (i)) - exit(2); - exit (0); -} -_ACEOF -rm -f conftest$ac_exeext -if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 - (eval $ac_link) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - : -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +darwin* | rhapsody*) + lt_cv_deplibs_check_method=pass_all + ;; + +freebsd* | dragonfly*) + if echo __ELF__ | $CC -E - | grep __ELF__ > /dev/null; then + case $host_cpu in + i*86 ) + # Not sure whether the presence of OpenBSD here was a mistake. + # Let's accept both of them until this is cleared up. + lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[3-9]86 (compact )?demand paged shared library' + lt_cv_file_magic_cmd=/usr/bin/file + lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` + ;; + esac + else + lt_cv_deplibs_check_method=pass_all + fi + ;; -( exit $ac_status ) -ac_cv_header_stdc=no -fi -rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -fi -fi -echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5 -echo "${ECHO_T}$ac_cv_header_stdc" >&6 -if test $ac_cv_header_stdc = yes; then +gnu*) + lt_cv_deplibs_check_method=pass_all + ;; + +hpux10.20* | hpux11*) + lt_cv_file_magic_cmd=/usr/bin/file + case $host_cpu in + ia64*) + lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - IA64' + lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so + ;; + hppa*64*) + lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - PA-RISC [0-9].[0-9]' + lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl + ;; + *) + lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|PA-RISC[0-9].[0-9]) shared library' + lt_cv_file_magic_test_file=/usr/lib/libc.sl + ;; + esac + ;; -cat >>confdefs.h <<\_ACEOF -#define STDC_HEADERS 1 -_ACEOF +interix[3-9]*) + # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here + lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|\.a)$' + ;; + +irix5* | irix6* | nonstopux*) + case $LD in + *-32|*"-32 ") libmagic=32-bit;; + *-n32|*"-n32 ") libmagic=N32;; + *-64|*"-64 ") libmagic=64-bit;; + *) libmagic=never-match;; + esac + lt_cv_deplibs_check_method=pass_all + ;; + +# This must be Linux ELF. +linux* | k*bsd*-gnu) + lt_cv_deplibs_check_method=pass_all + ;; + +netbsd*) + if echo __ELF__ | $CC -E - | grep __ELF__ > /dev/null; then + lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' + else + lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|_pic\.a)$' + fi + ;; + +newos6*) + lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (executable|dynamic lib)' + lt_cv_file_magic_cmd=/usr/bin/file + lt_cv_file_magic_test_file=/usr/lib/libnls.so + ;; + +nto-qnx*) + lt_cv_deplibs_check_method=unknown + ;; + +openbsd*) + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|\.so|_pic\.a)$' + else + lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' + fi + ;; + +osf3* | osf4* | osf5*) + lt_cv_deplibs_check_method=pass_all + ;; + +rdos*) + lt_cv_deplibs_check_method=pass_all + ;; + +solaris*) + lt_cv_deplibs_check_method=pass_all + ;; + +sysv4 | sysv4.3*) + case $host_vendor in + motorola) + lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib) M[0-9][0-9]* Version [0-9]' + lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` + ;; + ncr) + lt_cv_deplibs_check_method=pass_all + ;; + sequent) + lt_cv_file_magic_cmd='/bin/file' + lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [LM]SB (shared object|dynamic lib )' + ;; + sni) + lt_cv_file_magic_cmd='/bin/file' + lt_cv_deplibs_check_method="file_magic ELF [0-9][0-9]*-bit [LM]SB dynamic lib" + lt_cv_file_magic_test_file=/lib/libc.so + ;; + siemens) + lt_cv_deplibs_check_method=pass_all + ;; + pc) + lt_cv_deplibs_check_method=pass_all + ;; + esac + ;; + +sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) + lt_cv_deplibs_check_method=pass_all + ;; +esac fi +{ echo "$as_me:$LINENO: result: $lt_cv_deplibs_check_method" >&5 +echo "${ECHO_T}$lt_cv_deplibs_check_method" >&6; } +file_magic_cmd=$lt_cv_file_magic_cmd +deplibs_check_method=$lt_cv_deplibs_check_method +test -z "$deplibs_check_method" && deplibs_check_method=unknown -# On IRIX 5.3, sys/types and inttypes.h are conflicting. +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} +# If no C compiler flags were specified, use CFLAGS. +LTCFLAGS=${LTCFLAGS-"$CFLAGS"} +# Allow CC to be a program name with arguments. +compiler=$CC +# Check whether --enable-libtool-lock was given. +if test "${enable_libtool_lock+set}" = set; then + enableval=$enable_libtool_lock; +fi +test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes -for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ - inttypes.h stdint.h unistd.h -do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` -echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6 -if eval "test \"\${$as_ac_Header+set}\" = set"; then +# Some flags need to be propagated to the compiler or linker for good +# libtool support. +case $host in +ia64-*-hpux*) + # Find out which ABI we are using. + echo 'int i;' > conftest.$ac_ext + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + case `/usr/bin/file conftest.$ac_objext` in + *ELF-32*) + HPUX_IA64_MODE="32" + ;; + *ELF-64*) + HPUX_IA64_MODE="64" + ;; + esac + fi + rm -rf conftest* + ;; +*-*-irix6*) + # Find out which ABI we are using. + echo '#line 4693 "configure"' > conftest.$ac_ext + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + if test "$lt_cv_prog_gnu_ld" = yes; then + case `/usr/bin/file conftest.$ac_objext` in + *32-bit*) + LD="${LD-ld} -melf32bsmip" + ;; + *N32*) + LD="${LD-ld} -melf32bmipn32" + ;; + *64-bit*) + LD="${LD-ld} -melf64bmip" + ;; + esac + else + case `/usr/bin/file conftest.$ac_objext` in + *32-bit*) + LD="${LD-ld} -32" + ;; + *N32*) + LD="${LD-ld} -n32" + ;; + *64-bit*) + LD="${LD-ld} -64" + ;; + esac + fi + fi + rm -rf conftest* + ;; + +x86_64-*kfreebsd*-gnu|x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*| \ +s390*-*linux*|sparc*-*linux*) + # Find out which ABI we are using. + echo 'int i;' > conftest.$ac_ext + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + case `/usr/bin/file conftest.o` in + *32-bit*) + case $host in + x86_64-*kfreebsd*-gnu) + LD="${LD-ld} -m elf_i386_fbsd" + ;; + x86_64-*linux*) + LD="${LD-ld} -m elf_i386" + ;; + ppc64-*linux*|powerpc64-*linux*) + LD="${LD-ld} -m elf32ppclinux" + ;; + s390x-*linux*) + LD="${LD-ld} -m elf_s390" + ;; + sparc64-*linux*) + LD="${LD-ld} -m elf32_sparc" + ;; + esac + ;; + *64-bit*) + libsuff=64 + case $host in + x86_64-*kfreebsd*-gnu) + LD="${LD-ld} -m elf_x86_64_fbsd" + ;; + x86_64-*linux*) + LD="${LD-ld} -m elf_x86_64" + ;; + ppc*-*linux*|powerpc*-*linux*) + LD="${LD-ld} -m elf64ppc" + ;; + s390*-*linux*) + LD="${LD-ld} -m elf64_s390" + ;; + sparc*-*linux*) + LD="${LD-ld} -m elf64_sparc" + ;; + esac + ;; + esac + fi + rm -rf conftest* + ;; + +*-*-sco3.2v5*) + # On SCO OpenServer 5, we need -belf to get full-featured binaries. + SAVE_CFLAGS="$CFLAGS" + CFLAGS="$CFLAGS -belf" + { echo "$as_me:$LINENO: checking whether the C compiler needs -belf" >&5 +echo $ECHO_N "checking whether the C compiler needs -belf... $ECHO_C" >&6; } +if test "${lt_cv_cc_needs_belf+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else - cat >conftest.$ac_ext <<_ACEOF + ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -$ac_includes_default -#include <$ac_header> +int +main () +{ + + ; + return 0; +} _ACEOF -rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - eval "$as_ac_Header=yes" + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + lt_cv_cc_needs_belf=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -eval "$as_ac_Header=no" + lt_cv_cc_needs_belf=no fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext -fi -echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5 -echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6 -if test `eval echo '${'$as_ac_Header'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext + ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu fi +{ echo "$as_me:$LINENO: result: $lt_cv_cc_needs_belf" >&5 +echo "${ECHO_T}$lt_cv_cc_needs_belf" >&6; } + if test x"$lt_cv_cc_needs_belf" != x"yes"; then + # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf + CFLAGS="$SAVE_CFLAGS" + fi + ;; +sparc*-*solaris*) + # Find out which ABI we are using. + echo 'int i;' > conftest.$ac_ext + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + case `/usr/bin/file conftest.o` in + *64-bit*) + case $lt_cv_prog_gnu_ld in + yes*) LD="${LD-ld} -m elf64_sparc" ;; + *) LD="${LD-ld} -64" ;; + esac + ;; + esac + fi + rm -rf conftest* + ;; -done +esac +need_locks="$enable_libtool_lock" -for ac_header in sys/mman.h -do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` -if eval "test \"\${$as_ac_Header+set}\" = set"; then - echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6 -if eval "test \"\${$as_ac_Header+set}\" = set"; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +{ echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5 +echo $ECHO_N "checking how to run the C preprocessor... $ECHO_C" >&6; } +# On Suns, sometimes $CPP names a directory. +if test -n "$CPP" && test -d "$CPP"; then + CPP= fi -echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5 -echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6 +if test -z "$CPP"; then + if test "${ac_cv_prog_CPP+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 else - # Is the header compilable? -echo "$as_me:$LINENO: checking $ac_header usability" >&5 -echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6 -cat >conftest.$ac_ext <<_ACEOF + # Double quotes because CPP needs to be expanded + for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" + do + ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -$ac_includes_default -#include <$ac_header> +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error _ACEOF -rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_header_compiler=yes + (exit $ac_status); } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then + : else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -ac_header_compiler=no + # Broken: fails on valid input. +continue fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext -echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6 -# Is the header present? -echo "$as_me:$LINENO: checking $ac_header presence" >&5 -echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6 -cat >conftest.$ac_ext <<_ACEOF +rm -f conftest.err conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -#include <$ac_header> +#include _ACEOF -if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 - (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null; then - if test -s conftest.err; then - ac_cpp_err=$ac_c_preproc_warn_flag - ac_cpp_err=$ac_cpp_err$ac_c_werror_flag - else - ac_cpp_err= - fi -else - ac_cpp_err=yes -fi -if test -z "$ac_cpp_err"; then - ac_header_preproc=yes + (exit $ac_status); } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then + # Broken: success on invalid input. +continue else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_header_preproc=no -fi -rm -f conftest.err conftest.$ac_ext -echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6 - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 -echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} - ( - cat <<\_ASBOX -## ------------------------------------------- ## -## Report this to http://gcc.gnu.org/bugs.html ## -## ------------------------------------------- ## -_ASBOX - ) | - sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6 -if eval "test \"\${$as_ac_Header+set}\" = set"; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - eval "$as_ac_Header=\$ac_header_preproc" -fi -echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5 -echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6 - + # Passes both tests. +ac_preproc_ok=: +break fi -if test `eval echo '${'$as_ac_Header'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF -fi +rm -f conftest.err conftest.$ac_ext done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.err conftest.$ac_ext +if $ac_preproc_ok; then + break +fi + done + ac_cv_prog_CPP=$CPP -for ac_func in mmap -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6 -if eval "test \"\${$as_ac_var+set}\" = set"; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +fi + CPP=$ac_cv_prog_CPP else + ac_cv_prog_CPP=$CPP +fi +{ echo "$as_me:$LINENO: result: $CPP" >&5 +echo "${ECHO_T}$CPP" >&6; } +ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - #ifdef __STDC__ # include #else # include #endif + Syntax error +_ACEOF +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then + : +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 -#undef $ac_func + # Broken: fails on valid input. +continue +fi -/* Override any gcc2 internal prototype to avoid an error. */ -#ifdef __cplusplus -extern "C" -{ -#endif -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined (__stub_$ac_func) || defined (__stub___$ac_func) -choke me -#else -char (*f) () = $ac_func; -#endif -#ifdef __cplusplus -} -#endif +rm -f conftest.err conftest.$ac_ext -int -main () -{ -return f != $ac_func; - ; - return 0; -} + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 - (eval $ac_link) 2>conftest.er1 +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +_ACEOF +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest$ac_exeext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - eval "$as_ac_var=yes" + (exit $ac_status); } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then + # Broken: success on invalid input. +continue else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -eval "$as_ac_var=no" -fi -rm -f conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext + # Passes both tests. +ac_preproc_ok=: +break fi -echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_var'}'`" >&5 -echo "${ECHO_T}`eval echo '${'$as_ac_var'}'`" >&6 -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF -fi +rm -f conftest.err conftest.$ac_ext + done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.err conftest.$ac_ext +if $ac_preproc_ok; then + : +else + { { echo "$as_me:$LINENO: error: C preprocessor \"$CPP\" fails sanity check +See \`config.log' for more details." >&5 +echo "$as_me: error: C preprocessor \"$CPP\" fails sanity check +See \`config.log' for more details." >&2;} + { (exit 1); exit 1; }; } +fi +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu -if test "${ac_cv_header_sys_mman_h+set}" = set; then - echo "$as_me:$LINENO: checking for sys/mman.h" >&5 -echo $ECHO_N "checking for sys/mman.h... $ECHO_C" >&6 -if test "${ac_cv_header_sys_mman_h+set}" = set; then + +{ echo "$as_me:$LINENO: checking for ANSI C header files" >&5 +echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6; } +if test "${ac_cv_header_stdc+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 -fi -echo "$as_me:$LINENO: result: $ac_cv_header_sys_mman_h" >&5 -echo "${ECHO_T}$ac_cv_header_sys_mman_h" >&6 else - # Is the header compilable? -echo "$as_me:$LINENO: checking sys/mman.h usability" >&5 -echo $ECHO_N "checking sys/mman.h usability... $ECHO_C" >&6 -cat >conftest.$ac_ext <<_ACEOF + cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -$ac_includes_default -#include +#include +#include +#include +#include + +int +main () +{ + + ; + return 0; +} _ACEOF rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_header_compiler=yes + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_header_stdc=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -ac_header_compiler=no + ac_cv_header_stdc=no fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext -echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6 -# Is the header present? -echo "$as_me:$LINENO: checking sys/mman.h presence" >&5 -echo $ECHO_N "checking sys/mman.h presence... $ECHO_C" >&6 -cat >conftest.$ac_ext <<_ACEOF +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +if test $ac_cv_header_stdc = yes; then + # SunOS 4.x string.h does not declare mem*, contrary to ANSI. + cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -#include +#include + _ACEOF -if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 - (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null; then - if test -s conftest.err; then - ac_cpp_err=$ac_c_preproc_warn_flag - ac_cpp_err=$ac_cpp_err$ac_c_werror_flag - else - ac_cpp_err= - fi +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "memchr" >/dev/null 2>&1; then + : else - ac_cpp_err=yes + ac_cv_header_stdc=no fi -if test -z "$ac_cpp_err"; then - ac_header_preproc=yes +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "free" >/dev/null 2>&1; then + : else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_header_stdc=no +fi +rm -f conftest* - ac_header_preproc=no fi -rm -f conftest.err conftest.$ac_ext -echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6 -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: sys/mman.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: sys/mman.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mman.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: sys/mman.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: sys/mman.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: sys/mman.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mman.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: sys/mman.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mman.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: sys/mman.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mman.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: sys/mman.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mman.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: sys/mman.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mman.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: sys/mman.h: in the future, the compiler will take precedence" >&2;} - ( - cat <<\_ASBOX -## ------------------------------------------- ## -## Report this to http://gcc.gnu.org/bugs.html ## -## ------------------------------------------- ## -_ASBOX - ) | - sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -echo "$as_me:$LINENO: checking for sys/mman.h" >&5 -echo $ECHO_N "checking for sys/mman.h... $ECHO_C" >&6 -if test "${ac_cv_header_sys_mman_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_cv_header_sys_mman_h=$ac_header_preproc -fi -echo "$as_me:$LINENO: result: $ac_cv_header_sys_mman_h" >&5 -echo "${ECHO_T}$ac_cv_header_sys_mman_h" >&6 - -fi -if test $ac_cv_header_sys_mman_h = yes; then - libffi_header_sys_mman_h=yes -else - libffi_header_sys_mman_h=no -fi - - -echo "$as_me:$LINENO: checking for mmap" >&5 -echo $ECHO_N "checking for mmap... $ECHO_C" >&6 -if test "${ac_cv_func_mmap+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +if test $ac_cv_header_stdc = yes; then + # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. + if test "$cross_compiling" = yes; then + : else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -3225,144 +5212,93 @@ cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -/* Define mmap to an innocuous variant, in case declares mmap. - For example, HP-UX 11i declares gettimeofday. */ -#define mmap innocuous_mmap - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char mmap (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef mmap - -/* Override any gcc2 internal prototype to avoid an error. */ -#ifdef __cplusplus -extern "C" -{ -#endif -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char mmap (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined (__stub_mmap) || defined (__stub___mmap) -choke me +#include +#include +#if ((' ' & 0x0FF) == 0x020) +# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') +# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) #else -char (*f) () = mmap; -#endif -#ifdef __cplusplus -} +# define ISLOWER(c) \ + (('a' <= (c) && (c) <= 'i') \ + || ('j' <= (c) && (c) <= 'r') \ + || ('s' <= (c) && (c) <= 'z')) +# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) #endif +#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) int main () { -return f != mmap; - ; + int i; + for (i = 0; i < 256; i++) + if (XOR (islower (i), ISLOWER (i)) + || toupper (i) != TOUPPER (i)) + return 2; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 - (eval $ac_link) 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 +rm -f conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest$ac_exeext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then - ac_cv_func_mmap=yes + : else - echo "$as_me: failed program was:" >&5 + echo "$as_me: program exited with status $ac_status" >&5 +echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -ac_cv_func_mmap=no -fi -rm -f conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext +( exit $ac_status ) +ac_cv_header_stdc=no fi -echo "$as_me:$LINENO: result: $ac_cv_func_mmap" >&5 -echo "${ECHO_T}$ac_cv_func_mmap" >&6 -if test $ac_cv_func_mmap = yes; then - libffi_func_mmap=yes -else - libffi_func_mmap=no +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi -if test "$libffi_header_sys_mman_h" != yes \ - || test "$libffi_func_mmap" != yes; then - ac_cv_func_mmap_file=no - ac_cv_func_mmap_dev_zero=no - ac_cv_func_mmap_anon=no -else - echo "$as_me:$LINENO: checking whether read-only mmap of a plain file works" >&5 -echo $ECHO_N "checking whether read-only mmap of a plain file works... $ECHO_C" >&6 -if test "${ac_cv_func_mmap_file+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - # Add a system to this blacklist if - # mmap(0, stat_size, PROT_READ, MAP_PRIVATE, fd, 0) doesn't return a - # memory area containing the same data that you'd get if you applied - # read() to the same fd. The only system known to have a problem here - # is VMS, where text files have record structure. - case "$host_os" in - vms* | ultrix*) - ac_cv_func_mmap_file=no ;; - *) - ac_cv_func_mmap_file=yes;; - esac + fi -echo "$as_me:$LINENO: result: $ac_cv_func_mmap_file" >&5 -echo "${ECHO_T}$ac_cv_func_mmap_file" >&6 - echo "$as_me:$LINENO: checking whether mmap from /dev/zero works" >&5 -echo $ECHO_N "checking whether mmap from /dev/zero works... $ECHO_C" >&6 -if test "${ac_cv_func_mmap_dev_zero+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - # Add a system to this blacklist if it has mmap() but /dev/zero - # does not exist, or if mmapping /dev/zero does not give anonymous - # zeroed pages with both the following properties: - # 1. If you map N consecutive pages in with one call, and then - # unmap any subset of those pages, the pages that were not - # explicitly unmapped remain accessible. - # 2. If you map two adjacent blocks of memory and then unmap them - # both at once, they must both go away. - # Systems known to be in this category are Windows (all variants), - # VMS, and Darwin. - case "$host_os" in - vms* | cygwin* | pe | mingw* | darwin* | ultrix* | hpux10* | hpux11.00) - ac_cv_func_mmap_dev_zero=no ;; - *) - ac_cv_func_mmap_dev_zero=yes;; - esac fi -echo "$as_me:$LINENO: result: $ac_cv_func_mmap_dev_zero" >&5 -echo "${ECHO_T}$ac_cv_func_mmap_dev_zero" >&6 +{ echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5 +echo "${ECHO_T}$ac_cv_header_stdc" >&6; } +if test $ac_cv_header_stdc = yes; then - # Unlike /dev/zero, the MAP_ANON(YMOUS) defines can be probed for. - echo "$as_me:$LINENO: checking for MAP_ANON(YMOUS)" >&5 -echo $ECHO_N "checking for MAP_ANON(YMOUS)... $ECHO_C" >&6 -if test "${ac_cv_decl_map_anon+set}" = set; then +cat >>confdefs.h <<\_ACEOF +#define STDC_HEADERS 1 +_ACEOF + +fi + +# On IRIX 5.3, sys/types and inttypes.h are conflicting. + + + + + + + + + +for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ + inttypes.h stdint.h unistd.h +do +as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` +{ echo "$as_me:$LINENO: checking for $ac_header" >&5 +echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF @@ -3371,271 +5307,348 @@ cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -#include -#include -#include - -#ifndef MAP_ANONYMOUS -#define MAP_ANONYMOUS MAP_ANON -#endif +$ac_includes_default -int -main () -{ -int n = MAP_ANONYMOUS; - ; - return 0; -} +#include <$ac_header> _ACEOF rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_decl_map_anon=yes + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + eval "$as_ac_Header=yes" else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -ac_cv_decl_map_anon=no -fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + eval "$as_ac_Header=no" fi -echo "$as_me:$LINENO: result: $ac_cv_decl_map_anon" >&5 -echo "${ECHO_T}$ac_cv_decl_map_anon" >&6 - if test $ac_cv_decl_map_anon = no; then - ac_cv_func_mmap_anon=no - else - echo "$as_me:$LINENO: checking whether mmap with MAP_ANON(YMOUS) works" >&5 -echo $ECHO_N "checking whether mmap with MAP_ANON(YMOUS) works... $ECHO_C" >&6 -if test "${ac_cv_func_mmap_anon+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - # Add a system to this blacklist if it has mmap() and MAP_ANON or - # MAP_ANONYMOUS, but using mmap(..., MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) - # doesn't give anonymous zeroed pages with the same properties listed - # above for use of /dev/zero. - # Systems known to be in this category are Windows, VMS, and SCO Unix. - case "$host_os" in - vms* | cygwin* | pe | mingw* | sco* | udk* ) - ac_cv_func_mmap_anon=no ;; - *) - ac_cv_func_mmap_anon=yes;; - esac -fi -echo "$as_me:$LINENO: result: $ac_cv_func_mmap_anon" >&5 -echo "${ECHO_T}$ac_cv_func_mmap_anon" >&6 - fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi - -if test $ac_cv_func_mmap_file = yes; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_MMAP_FILE 1 +ac_res=`eval echo '${'$as_ac_Header'}'` + { echo "$as_me:$LINENO: result: $ac_res" >&5 +echo "${ECHO_T}$ac_res" >&6; } +if test `eval echo '${'$as_ac_Header'}'` = yes; then + cat >>confdefs.h <<_ACEOF +#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi -if test $ac_cv_func_mmap_dev_zero = yes; then -cat >>confdefs.h <<\_ACEOF -#define HAVE_MMAP_DEV_ZERO 1 -_ACEOF +done -fi -if test $ac_cv_func_mmap_anon = yes; then -cat >>confdefs.h <<\_ACEOF -#define HAVE_MMAP_ANON 1 -_ACEOF +for ac_header in dlfcn.h +do +as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then + { echo "$as_me:$LINENO: checking for $ac_header" >&5 +echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then + echo $ECHO_N "(cached) $ECHO_C" >&6 fi - - -TARGETDIR="unknown" -case "$host" in -x86_64-*-openbsd*) TARGET=X86_64; TARGETDIR=x86;; -mips*-*-openbsd*) TARGET=MIPS; TARGETDIR=mips;; -sparc-*-openbsd*) TARGET=SPARC; TARGETDIR=sparc;; -sparc64-*-openbsd*) TARGET=SPARC; TARGETDIR=sparc;; -alpha*-*-openbsd*) TARGET=ALPHA; TARGETDIR=alpha;; -m68k-*-openbsd*) TARGET=M68K; TARGETDIR=m68k;; -powerpc-*-openbsd*) TARGET=POWERPC; TARGETDIR=powerpc;; -i*86-*-darwin*) TARGET=X86_DARWIN; TARGETDIR=x86;; -i*86-*-linux*) TARGET=X86; TARGETDIR=x86;; -i*86-*-gnu*) TARGET=X86; TARGETDIR=x86;; -i*86-*-solaris2.1[0-9]*) TARGET=X86_64; TARGETDIR=x86;; -i*86-*-solaris*) TARGET=X86; TARGETDIR=x86;; -i*86-*-beos*) TARGET=X86; TARGETDIR=x86;; -i*86-*-freebsd* | i*86-*-kfreebsd*-gnu) TARGET=X86; TARGETDIR=x86;; -i*86-*-netbsdelf* | i*86-*-knetbsd*-gnu) TARGET=X86; TARGETDIR=x86;; -i*86-*-openbsd*) TARGET=X86; TARGETDIR=x86;; -i*86-*-rtems*) TARGET=X86; TARGETDIR=x86;; -i*86-*-win32*) TARGET=X86_WIN32; TARGETDIR=x86;; -i*86-*-cygwin*) TARGET=X86_WIN32; TARGETDIR=x86;; -i*86-*-mingw*) TARGET=X86_WIN32; TARGETDIR=x86;; -frv-*-*) TARGET=FRV; TARGETDIR=frv;; -sparc-sun-4*) TARGET=SPARC; TARGETDIR=sparc;; -sparc*-sun-*) TARGET=SPARC; TARGETDIR=sparc;; -sparc-*-linux* | sparc-*-netbsdelf* | sparc-*-knetbsd*-gnu) TARGET=SPARC; TARGETDIR=sparc;; -sparc*-*-rtems*) TARGET=SPARC; TARGETDIR=sparc;; -sparc64-*-linux* | sparc64-*-freebsd* | sparc64-*-netbsd* | sparc64-*-knetbsd*-gnu) TARGET=SPARC; TARGETDIR=sparc;; -alpha*-*-linux* | alpha*-*-osf* | alpha*-*-freebsd* | alpha*-*-kfreebsd*-gnu | alpha*-*-netbsd* | alpha*-*-knetbsd*-gnu) TARGET=ALPHA; TARGETDIR=alpha;; -ia64*-*-*) TARGET=IA64; TARGETDIR=ia64;; -m32r*-*-linux* ) TARGET=M32R; TARGETDIR=m32r;; -m68k-*-linux*) TARGET=M68K; TARGETDIR=m68k;; -mips64*-*);; -mips-sgi-irix5.* | mips-sgi-irix6.*) TARGET=MIPS_IRIX; TARGETDIR=mips;; -mips*-*-linux*) TARGET=MIPS_LINUX; TARGETDIR=mips;; -powerpc*-*-linux* | powerpc-*-sysv*) TARGET=POWERPC; TARGETDIR=powerpc;; -powerpc-*-beos*) TARGET=POWERPC; TARGETDIR=powerpc;; -powerpc-*-darwin*) TARGET=POWERPC_DARWIN; TARGETDIR=powerpc;; -powerpc-*-aix*) TARGET=POWERPC_AIX; TARGETDIR=powerpc;; -powerpc-*-freebsd*) TARGET=POWERPC_FREEBSD; TARGETDIR=powerpc;; -powerpc*-*-rtems*) TARGET=POWERPC; TARGETDIR=powerpc;; -rs6000-*-aix*) TARGET=POWERPC_AIX; TARGETDIR=powerpc;; -arm*-*-linux-*) TARGET=ARM; TARGETDIR=arm;; -arm*-*-netbsdelf* | arm*-*-knetbsd*-gnu) TARGET=ARM; TARGETDIR=arm;; -arm*-*-rtems*) TARGET=ARM; TARGETDIR=arm;; -cris-*-*) TARGET=LIBFFI_CRIS; TARGETDIR=cris;; -s390-*-linux-*) TARGET=S390; TARGETDIR=s390;; -s390x-*-linux-*) TARGET=S390; TARGETDIR=s390;; -amd64-*-freebsd* | x86_64-*-linux* | x86_64-*-freebsd* | x86_64-*-kfreebsd*-gnu) TARGET=X86_64; TARGETDIR=x86;; -sh-*-linux* | sh[34]*-*-linux*) TARGET=SH; TARGETDIR=sh;; -sh-*-rtems*) TARGET=SH; TARGETDIR=sh;; -sh64-*-linux* | sh5*-*-linux*) TARGET=SH64; TARGETDIR=sh64;; -hppa*-*-linux* | parisc*-*-linux*) TARGET=PA; TARGETDIR=pa;; -esac - -if test $TARGETDIR = unknown; then - { { echo "$as_me:$LINENO: error: \"libffi has not been ported to $host.\"" >&5 -echo "$as_me: error: \"libffi has not been ported to $host.\"" >&2;} - { (exit 1); exit 1; }; } -fi - -MKTARGET=$TARGET - -case x$TARGET in - xMIPS*) TARGET=MIPS ;; - *) ;; -esac - -echo "$as_me:$LINENO: checking for ANSI C header files" >&5 -echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6 -if test "${ac_cv_header_stdc+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +ac_res=`eval echo '${'$as_ac_Header'}'` + { echo "$as_me:$LINENO: result: $ac_res" >&5 +echo "${ECHO_T}$ac_res" >&6; } else - cat >conftest.$ac_ext <<_ACEOF + # Is the header compilable? +{ echo "$as_me:$LINENO: checking $ac_header usability" >&5 +echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; } +cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -#include -#include -#include -#include - -int -main () -{ - - ; - return 0; -} +$ac_includes_default +#include <$ac_header> _ACEOF rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_header_stdc=yes + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_header_compiler=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -ac_cv_header_stdc=no + ac_header_compiler=no fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext -if test $ac_cv_header_stdc = yes; then - # SunOS 4.x string.h does not declare mem*, contrary to ANSI. - cat >conftest.$ac_ext <<_ACEOF +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +echo "${ECHO_T}$ac_header_compiler" >&6; } + +# Is the header present? +{ echo "$as_me:$LINENO: checking $ac_header presence" >&5 +echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; } +cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -#include - +#include <$ac_header> _ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "memchr" >/dev/null 2>&1; then - : +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then + ac_header_preproc=yes else - ac_cv_header_stdc=no + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_header_preproc=no fi -rm -f conftest* +rm -f conftest.err conftest.$ac_ext +{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +echo "${ECHO_T}$ac_header_preproc" >&6; } + +# So? What about this header? +case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in + yes:no: ) + { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 +echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 +echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} + ac_header_preproc=yes + ;; + no:yes:* ) + { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 +echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 +echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 +echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 +echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 +echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 +echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} + ( cat <<\_ASBOX +## ------------------------------------------- ## +## Report this to http://gcc.gnu.org/bugs.html ## +## ------------------------------------------- ## +_ASBOX + ) | sed "s/^/$as_me: WARNING: /" >&2 + ;; +esac +{ echo "$as_me:$LINENO: checking for $ac_header" >&5 +echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + eval "$as_ac_Header=\$ac_header_preproc" fi +ac_res=`eval echo '${'$as_ac_Header'}'` + { echo "$as_me:$LINENO: result: $ac_res" >&5 +echo "${ECHO_T}$ac_res" >&6; } -if test $ac_cv_header_stdc = yes; then - # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +fi +if test `eval echo '${'$as_ac_Header'}'` = yes; then + cat >>confdefs.h <<_ACEOF +#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "free" >/dev/null 2>&1; then - : +fi + +done + +ac_ext=cpp +ac_cpp='$CXXCPP $CPPFLAGS' +ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_cxx_compiler_gnu +if test -z "$CXX"; then + if test -n "$CCC"; then + CXX=$CCC + else + if test -n "$ac_tool_prefix"; then + for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_CXX+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 else - ac_cv_header_stdc=no + if test -n "$CXX"; then + ac_cv_prog_CXX="$CXX" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_CXX="$ac_tool_prefix$ac_prog" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + fi -rm -f conftest* +fi +CXX=$ac_cv_prog_CXX +if test -n "$CXX"; then + { echo "$as_me:$LINENO: result: $CXX" >&5 +echo "${ECHO_T}$CXX" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + + test -n "$CXX" && break + done +fi +if test -z "$CXX"; then + ac_ct_CXX=$CXX + for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_ac_ct_CXX+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$ac_ct_CXX"; then + ac_cv_prog_ac_ct_CXX="$ac_ct_CXX" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_CXX="$ac_prog" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS fi +fi +ac_ct_CXX=$ac_cv_prog_ac_ct_CXX +if test -n "$ac_ct_CXX"; then + { echo "$as_me:$LINENO: result: $ac_ct_CXX" >&5 +echo "${ECHO_T}$ac_ct_CXX" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi -if test $ac_cv_header_stdc = yes; then - # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. - if test "$cross_compiling" = yes; then - : + + test -n "$ac_ct_CXX" && break +done + + if test "x$ac_ct_CXX" = x; then + CXX="g++" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf at gnu.org." >&5 +echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf at gnu.org." >&2;} +ac_tool_warned=yes ;; +esac + CXX=$ac_ct_CXX + fi +fi + + fi +fi +# Provide some information about the compiler. +echo "$as_me:$LINENO: checking for C++ compiler version" >&5 +ac_compiler=`set X $ac_compile; echo $2` +{ (ac_try="$ac_compiler --version >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compiler --version >&5") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } +{ (ac_try="$ac_compiler -v >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compiler -v >&5") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } +{ (ac_try="$ac_compiler -V >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compiler -V >&5") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } + +{ echo "$as_me:$LINENO: checking whether we are using the GNU C++ compiler" >&5 +echo $ECHO_N "checking whether we are using the GNU C++ compiler... $ECHO_C" >&6; } +if test "${ac_cv_cxx_compiler_gnu+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -3643,231 +5656,15027 @@ cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -#include -#if ((' ' & 0x0FF) == 0x020) -# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') -# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) -#else -# define ISLOWER(c) \ - (('a' <= (c) && (c) <= 'i') \ - || ('j' <= (c) && (c) <= 'r') \ - || ('s' <= (c) && (c) <= 'z')) -# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) -#endif -#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) int main () { - int i; - for (i = 0; i < 256; i++) - if (XOR (islower (i), ISLOWER (i)) - || toupper (i) != TOUPPER (i)) - exit(2); - exit (0); +#ifndef __GNUC__ + choke me +#endif + + ; + return 0; } _ACEOF -rm -f conftest$ac_exeext -if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 - (eval $ac_link) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - : + (exit $ac_status); } && { + test -z "$ac_cxx_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_compiler_gnu=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -( exit $ac_status ) -ac_cv_header_stdc=no + ac_compiler_gnu=no fi -rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -fi -fi -echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5 -echo "${ECHO_T}$ac_cv_header_stdc" >&6 -if test $ac_cv_header_stdc = yes; then -cat >>confdefs.h <<\_ACEOF -#define STDC_HEADERS 1 -_ACEOF +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +ac_cv_cxx_compiler_gnu=$ac_compiler_gnu fi - - -for ac_func in memcpy -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6 -if eval "test \"\${$as_ac_var+set}\" = set"; then +{ echo "$as_me:$LINENO: result: $ac_cv_cxx_compiler_gnu" >&5 +echo "${ECHO_T}$ac_cv_cxx_compiler_gnu" >&6; } +GXX=`test $ac_compiler_gnu = yes && echo yes` +ac_test_CXXFLAGS=${CXXFLAGS+set} +ac_save_CXXFLAGS=$CXXFLAGS +{ echo "$as_me:$LINENO: checking whether $CXX accepts -g" >&5 +echo $ECHO_N "checking whether $CXX accepts -g... $ECHO_C" >&6; } +if test "${ac_cv_prog_cxx_g+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else - cat >conftest.$ac_ext <<_ACEOF + ac_save_cxx_werror_flag=$ac_cxx_werror_flag + ac_cxx_werror_flag=yes + ac_cv_prog_cxx_g=no + CXXFLAGS="-g" + cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ +int +main () +{ -#ifdef __STDC__ -# include -#else -# include -#endif + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_cxx_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_prog_cxx_g=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 -#undef $ac_func + CXXFLAGS="" + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ -/* Override any gcc2 internal prototype to avoid an error. */ -#ifdef __cplusplus -extern "C" +int +main () { -#endif -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined (__stub_$ac_func) || defined (__stub___$ac_func) -choke me -#else -char (*f) () = $ac_func; -#endif -#ifdef __cplusplus + + ; + return 0; } -#endif +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_cxx_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + : +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cxx_werror_flag=$ac_save_cxx_werror_flag + CXXFLAGS="-g" + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ int main () { -return f != $ac_func; + ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 - (eval $ac_link) 2>conftest.er1 +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest$ac_exeext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - eval "$as_ac_var=yes" + (exit $ac_status); } && { + test -z "$ac_cxx_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_prog_cxx_g=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -eval "$as_ac_var=no" + fi -rm -f conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_var'}'`" >&5 -echo "${ECHO_T}`eval echo '${'$as_ac_var'}'`" >&6 -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -done -# The Ultrix 4.2 mips builtin alloca declared by alloca.h only works -# for constant arguments. Useless! -echo "$as_me:$LINENO: checking for working alloca.h" >&5 -echo $ECHO_N "checking for working alloca.h... $ECHO_C" >&6 -if test "${ac_cv_working_alloca_h+set}" = set; then +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + ac_cxx_werror_flag=$ac_save_cxx_werror_flag +fi +{ echo "$as_me:$LINENO: result: $ac_cv_prog_cxx_g" >&5 +echo "${ECHO_T}$ac_cv_prog_cxx_g" >&6; } +if test "$ac_test_CXXFLAGS" = set; then + CXXFLAGS=$ac_save_CXXFLAGS +elif test $ac_cv_prog_cxx_g = yes; then + if test "$GXX" = yes; then + CXXFLAGS="-g -O2" + else + CXXFLAGS="-g" + fi +else + if test "$GXX" = yes; then + CXXFLAGS="-O2" + else + CXXFLAGS= + fi +fi +ac_ext=cpp +ac_cpp='$CXXCPP $CPPFLAGS' +ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_cxx_compiler_gnu + +depcc="$CXX" am_compiler_list= + +{ echo "$as_me:$LINENO: checking dependency style of $depcc" >&5 +echo $ECHO_N "checking dependency style of $depcc... $ECHO_C" >&6; } +if test "${am_cv_CXX_dependencies_compiler_type+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then + # We make a subdir and do the tests there. Otherwise we can end up + # making bogus files that we don't know about and never remove. For + # instance it was reported that on HP-UX the gcc test will end up + # making a dummy file named `D' -- because `-MD' means `put the output + # in D'. + mkdir conftest.dir + # Copy depcomp to subdir because otherwise we won't find it if we're + # using a relative directory. + cp "$am_depcomp" conftest.dir + cd conftest.dir + # We will build objects and dependencies in a subdirectory because + # it helps to detect inapplicable dependency modes. For instance + # both Tru64's cc and ICC support -MD to output dependencies as a + # side effect of compilation, but ICC will put the dependencies in + # the current directory while Tru64 will put them in the object + # directory. + mkdir sub + + am_cv_CXX_dependencies_compiler_type=none + if test "$am_compiler_list" = ""; then + am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` + fi + for depmode in $am_compiler_list; do + # Setup a source with many dependencies, because some compilers + # like to wrap large dependency lists on column 80 (with \), and + # we should not choose a depcomp mode which is confused by this. + # + # We need to recreate these files for each test, as the compiler may + # overwrite some of them when testing with obscure command lines. + # This happens at least with the AIX C compiler. + : > sub/conftest.c + for i in 1 2 3 4 5 6; do + echo '#include "conftst'$i'.h"' >> sub/conftest.c + # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with + # Solaris 8's {/usr,}/bin/sh. + touch sub/conftst$i.h + done + echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf + + case $depmode in + nosideeffect) + # after this tag, mechanisms are not by side-effect, so they'll + # only be used when explicitly requested + if test "x$enable_dependency_tracking" = xyes; then + continue + else + break + fi + ;; + none) break ;; + esac + # We check with `-c' and `-o' for the sake of the "dashmstdout" + # mode. It turns out that the SunPro C++ compiler does not properly + # handle `-M -o', and we need to detect this. + if depmode=$depmode \ + source=sub/conftest.c object=sub/conftest.${OBJEXT-o} \ + depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ + $SHELL ./depcomp $depcc -c -o sub/conftest.${OBJEXT-o} sub/conftest.c \ + >/dev/null 2>conftest.err && + grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && + grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && + grep sub/conftest.${OBJEXT-o} sub/conftest.Po > /dev/null 2>&1 && + ${MAKE-make} -s -f confmf > /dev/null 2>&1; then + # icc doesn't choke on unknown options, it will just issue warnings + # or remarks (even with -Werror). So we grep stderr for any message + # that says an option was ignored or not supported. + # When given -MP, icc 7.0 and 7.1 complain thusly: + # icc: Command line warning: ignoring option '-M'; no argument required + # The diagnosis changed in icc 8.0: + # icc: Command line remark: option '-MP' not supported + if (grep 'ignoring option' conftest.err || + grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else + am_cv_CXX_dependencies_compiler_type=$depmode + break + fi + fi + done + + cd .. + rm -rf conftest.dir +else + am_cv_CXX_dependencies_compiler_type=none +fi + +fi +{ echo "$as_me:$LINENO: result: $am_cv_CXX_dependencies_compiler_type" >&5 +echo "${ECHO_T}$am_cv_CXX_dependencies_compiler_type" >&6; } +CXXDEPMODE=depmode=$am_cv_CXX_dependencies_compiler_type + + if + test "x$enable_dependency_tracking" != xno \ + && test "$am_cv_CXX_dependencies_compiler_type" = gcc3; then + am__fastdepCXX_TRUE= + am__fastdepCXX_FALSE='#' +else + am__fastdepCXX_TRUE='#' + am__fastdepCXX_FALSE= +fi + + + + +if test -n "$CXX" && ( test "X$CXX" != "Xno" && + ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) || + (test "X$CXX" != "Xg++"))) ; then + ac_ext=cpp +ac_cpp='$CXXCPP $CPPFLAGS' +ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_cxx_compiler_gnu +{ echo "$as_me:$LINENO: checking how to run the C++ preprocessor" >&5 +echo $ECHO_N "checking how to run the C++ preprocessor... $ECHO_C" >&6; } +if test -z "$CXXCPP"; then + if test "${ac_cv_prog_CXXCPP+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else + # Double quotes because CXXCPP needs to be expanded + for CXXCPP in "$CXX -E" "/lib/cpp" + do + ac_preproc_ok=false +for ac_cxx_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -#include -int -main () -{ -char *p = (char *) alloca (2 * sizeof (int)); - ; - return 0; -} +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 - (eval $ac_link) 2>conftest.er1 +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 + (exit $ac_status); } >/dev/null && { + test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" || + test ! -s conftest.err + }; then + : +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + # Broken: fails on valid input. +continue +fi + +rm -f conftest.err conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +_ACEOF +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest$ac_exeext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 + (exit $ac_status); } >/dev/null && { + test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" || + test ! -s conftest.err + }; then + # Broken: success on invalid input. +continue +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + # Passes both tests. +ac_preproc_ok=: +break +fi + +rm -f conftest.err conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.err conftest.$ac_ext +if $ac_preproc_ok; then + break +fi + + done + ac_cv_prog_CXXCPP=$CXXCPP + +fi + CXXCPP=$ac_cv_prog_CXXCPP +else + ac_cv_prog_CXXCPP=$CXXCPP +fi +{ echo "$as_me:$LINENO: result: $CXXCPP" >&5 +echo "${ECHO_T}$CXXCPP" >&6; } +ac_preproc_ok=false +for ac_cxx_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_working_alloca_h=yes + (exit $ac_status); } >/dev/null && { + test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" || + test ! -s conftest.err + }; then + : else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -ac_cv_working_alloca_h=no + # Broken: fails on valid input. +continue +fi + +rm -f conftest.err conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +_ACEOF +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null && { + test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" || + test ! -s conftest.err + }; then + # Broken: success on invalid input. +continue +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + # Passes both tests. +ac_preproc_ok=: +break +fi + +rm -f conftest.err conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.err conftest.$ac_ext +if $ac_preproc_ok; then + : +else + { { echo "$as_me:$LINENO: error: C++ preprocessor \"$CXXCPP\" fails sanity check +See \`config.log' for more details." >&5 +echo "$as_me: error: C++ preprocessor \"$CXXCPP\" fails sanity check +See \`config.log' for more details." >&2;} + { (exit 1); exit 1; }; } +fi + +ac_ext=cpp +ac_cpp='$CXXCPP $CPPFLAGS' +ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_cxx_compiler_gnu + +fi + + +ac_ext=f +ac_compile='$F77 -c $FFLAGS conftest.$ac_ext >&5' +ac_link='$F77 -o conftest$ac_exeext $FFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_f77_compiler_gnu +if test -n "$ac_tool_prefix"; then + for ac_prog in g77 xlf f77 frt pgf77 cf77 fort77 fl32 af77 xlf90 f90 pgf90 pghpf epcf90 gfortran g95 xlf95 f95 fort ifort ifc efc pgf95 lf95 ftn + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_F77+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$F77"; then + ac_cv_prog_F77="$F77" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_F77="$ac_tool_prefix$ac_prog" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +F77=$ac_cv_prog_F77 +if test -n "$F77"; then + { echo "$as_me:$LINENO: result: $F77" >&5 +echo "${ECHO_T}$F77" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + + test -n "$F77" && break + done +fi +if test -z "$F77"; then + ac_ct_F77=$F77 + for ac_prog in g77 xlf f77 frt pgf77 cf77 fort77 fl32 af77 xlf90 f90 pgf90 pghpf epcf90 gfortran g95 xlf95 f95 fort ifort ifc efc pgf95 lf95 ftn +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_ac_ct_F77+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$ac_ct_F77"; then + ac_cv_prog_ac_ct_F77="$ac_ct_F77" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_F77="$ac_prog" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +ac_ct_F77=$ac_cv_prog_ac_ct_F77 +if test -n "$ac_ct_F77"; then + { echo "$as_me:$LINENO: result: $ac_ct_F77" >&5 +echo "${ECHO_T}$ac_ct_F77" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + + test -n "$ac_ct_F77" && break +done + + if test "x$ac_ct_F77" = x; then + F77="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf at gnu.org." >&5 +echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf at gnu.org." >&2;} +ac_tool_warned=yes ;; +esac + F77=$ac_ct_F77 + fi +fi + + +# Provide some information about the compiler. +echo "$as_me:$LINENO: checking for Fortran 77 compiler version" >&5 +ac_compiler=`set X $ac_compile; echo $2` +{ (ac_try="$ac_compiler --version >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compiler --version >&5") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } +{ (ac_try="$ac_compiler -v >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compiler -v >&5") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } +{ (ac_try="$ac_compiler -V >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compiler -V >&5") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } +rm -f a.out + +# If we don't use `.F' as extension, the preprocessor is not run on the +# input file. (Note that this only needs to work for GNU compilers.) +ac_save_ext=$ac_ext +ac_ext=F +{ echo "$as_me:$LINENO: checking whether we are using the GNU Fortran 77 compiler" >&5 +echo $ECHO_N "checking whether we are using the GNU Fortran 77 compiler... $ECHO_C" >&6; } +if test "${ac_cv_f77_compiler_gnu+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF + program main +#ifndef __GNUC__ + choke me +#endif + + end +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_f77_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_compiler_gnu=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_compiler_gnu=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +ac_cv_f77_compiler_gnu=$ac_compiler_gnu + +fi +{ echo "$as_me:$LINENO: result: $ac_cv_f77_compiler_gnu" >&5 +echo "${ECHO_T}$ac_cv_f77_compiler_gnu" >&6; } +ac_ext=$ac_save_ext +ac_test_FFLAGS=${FFLAGS+set} +ac_save_FFLAGS=$FFLAGS +FFLAGS= +{ echo "$as_me:$LINENO: checking whether $F77 accepts -g" >&5 +echo $ECHO_N "checking whether $F77 accepts -g... $ECHO_C" >&6; } +if test "${ac_cv_prog_f77_g+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + FFLAGS=-g +cat >conftest.$ac_ext <<_ACEOF + program main + + end +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_f77_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_prog_f77_g=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_prog_f77_g=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +fi +{ echo "$as_me:$LINENO: result: $ac_cv_prog_f77_g" >&5 +echo "${ECHO_T}$ac_cv_prog_f77_g" >&6; } +if test "$ac_test_FFLAGS" = set; then + FFLAGS=$ac_save_FFLAGS +elif test $ac_cv_prog_f77_g = yes; then + if test "x$ac_cv_f77_compiler_gnu" = xyes; then + FFLAGS="-g -O2" + else + FFLAGS="-g" + fi +else + if test "x$ac_cv_f77_compiler_gnu" = xyes; then + FFLAGS="-O2" + else + FFLAGS= + fi +fi + +G77=`test $ac_compiler_gnu = yes && echo yes` +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + + +# Autoconf 2.13's AC_OBJEXT and AC_EXEEXT macros only works for C compilers! + +# find the maximum length of command line arguments +{ echo "$as_me:$LINENO: checking the maximum length of command line arguments" >&5 +echo $ECHO_N "checking the maximum length of command line arguments... $ECHO_C" >&6; } +if test "${lt_cv_sys_max_cmd_len+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + i=0 + teststring="ABCD" + + case $build_os in + msdosdjgpp*) + # On DJGPP, this test can blow up pretty badly due to problems in libc + # (any single argument exceeding 2000 bytes causes a buffer overrun + # during glob expansion). Even if it were fixed, the result of this + # check would be larger than it should be. + lt_cv_sys_max_cmd_len=12288; # 12K is about right + ;; + + gnu*) + # Under GNU Hurd, this test is not required because there is + # no limit to the length of command line arguments. + # Libtool will interpret -1 as no limit whatsoever + lt_cv_sys_max_cmd_len=-1; + ;; + + cygwin* | mingw*) + # On Win9x/ME, this test blows up -- it succeeds, but takes + # about 5 minutes as the teststring grows exponentially. + # Worse, since 9x/ME are not pre-emptively multitasking, + # you end up with a "frozen" computer, even though with patience + # the test eventually succeeds (with a max line length of 256k). + # Instead, let's just punt: use the minimum linelength reported by + # all of the supported platforms: 8192 (on NT/2K/XP). + lt_cv_sys_max_cmd_len=8192; + ;; + + amigaos*) + # On AmigaOS with pdksh, this test takes hours, literally. + # So we just punt and use a minimum line length of 8192. + lt_cv_sys_max_cmd_len=8192; + ;; + + netbsd* | freebsd* | openbsd* | darwin* | dragonfly*) + # This has been around since 386BSD, at least. Likely further. + if test -x /sbin/sysctl; then + lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` + elif test -x /usr/sbin/sysctl; then + lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax` + else + lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs + fi + # And add a safety zone + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` + ;; + + interix*) + # We know the value 262144 and hardcode it with a safety zone (like BSD) + lt_cv_sys_max_cmd_len=196608 + ;; + + osf*) + # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure + # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not + # nice to cause kernel panics so lets avoid the loop below. + # First set a reasonable default. + lt_cv_sys_max_cmd_len=16384 + # + if test -x /sbin/sysconfig; then + case `/sbin/sysconfig -q proc exec_disable_arg_limit` in + *1*) lt_cv_sys_max_cmd_len=-1 ;; + esac + fi + ;; + sco3.2v5*) + lt_cv_sys_max_cmd_len=102400 + ;; + sysv5* | sco5v6* | sysv4.2uw2*) + kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null` + if test -n "$kargmax"; then + lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[ ]//'` + else + lt_cv_sys_max_cmd_len=32768 + fi + ;; + *) + lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null` + if test -n "$lt_cv_sys_max_cmd_len"; then + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` + else + SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}} + while (test "X"`$SHELL $0 --fallback-echo "X$teststring" 2>/dev/null` \ + = "XX$teststring") >/dev/null 2>&1 && + new_result=`expr "X$teststring" : ".*" 2>&1` && + lt_cv_sys_max_cmd_len=$new_result && + test $i != 17 # 1/2 MB should be enough + do + i=`expr $i + 1` + teststring=$teststring$teststring + done + teststring= + # Add a significant safety factor because C++ compilers can tack on massive + # amounts of additional arguments before passing them to the linker. + # It appears as though 1/2 is a usable value. + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` + fi + ;; + esac + +fi + +if test -n $lt_cv_sys_max_cmd_len ; then + { echo "$as_me:$LINENO: result: $lt_cv_sys_max_cmd_len" >&5 +echo "${ECHO_T}$lt_cv_sys_max_cmd_len" >&6; } +else + { echo "$as_me:$LINENO: result: none" >&5 +echo "${ECHO_T}none" >&6; } +fi + + + + + +# Check for command to grab the raw symbol name followed by C symbol from nm. +{ echo "$as_me:$LINENO: checking command to parse $NM output from $compiler object" >&5 +echo $ECHO_N "checking command to parse $NM output from $compiler object... $ECHO_C" >&6; } +if test "${lt_cv_sys_global_symbol_pipe+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + +# These are sane defaults that work on at least a few old systems. +# [They come from Ultrix. What could be older than Ultrix?!! ;)] + +# Character class describing NM global symbol codes. +symcode='[BCDEGRST]' + +# Regexp to match symbols that can be accessed directly from C. +sympat='\([_A-Za-z][_A-Za-z0-9]*\)' + +# Transform an extracted symbol line into a proper C declaration +lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^. .* \(.*\)$/extern int \1;/p'" + +# Transform an extracted symbol line into symbol name and symbol address +lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([^ ]*\) $/ {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode \([^ ]*\) \([^ ]*\)$/ {\"\2\", (lt_ptr) \&\2},/p'" + +# Define system-specific variables. +case $host_os in +aix*) + symcode='[BCDT]' + ;; +cygwin* | mingw* | pw32*) + symcode='[ABCDGISTW]' + ;; +hpux*) # Its linker distinguishes data from code symbols + if test "$host_cpu" = ia64; then + symcode='[ABCDEGRST]' + fi + lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'" + lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([^ ]*\) $/ {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/ {\"\2\", (lt_ptr) \&\2},/p'" + ;; +linux* | k*bsd*-gnu) + if test "$host_cpu" = ia64; then + symcode='[ABCDGIRSTW]' + lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'" + lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([^ ]*\) $/ {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/ {\"\2\", (lt_ptr) \&\2},/p'" + fi + ;; +irix* | nonstopux*) + symcode='[BCDEGRST]' + ;; +osf*) + symcode='[BCDEGQRST]' + ;; +solaris*) + symcode='[BDRT]' + ;; +sco3.2v5*) + symcode='[DT]' + ;; +sysv4.2uw2*) + symcode='[DT]' + ;; +sysv5* | sco5v6* | unixware* | OpenUNIX*) + symcode='[ABDT]' + ;; +sysv4) + symcode='[DFNSTU]' + ;; +esac + +# Handle CRLF in mingw tool chain +opt_cr= +case $build_os in +mingw*) + opt_cr=`echo 'x\{0,1\}' | tr x '\015'` # option cr in regexp + ;; +esac + +# If we're using GNU nm, then use its standard symbol codes. +case `$NM -V 2>&1` in +*GNU* | *'with BFD'*) + symcode='[ABCDGIRSTW]' ;; +esac + +# Try without a prefix undercore, then with it. +for ac_symprfx in "" "_"; do + + # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol. + symxfrm="\\1 $ac_symprfx\\2 \\2" + + # Write the raw and C identifiers. + lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[ ]\($symcode$symcode*\)[ ][ ]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'" + + # Check to see that the pipe works correctly. + pipe_works=no + + rm -f conftest* + cat > conftest.$ac_ext <&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + # Now try to grab the symbols. + nlist=conftest.nm + if { (eval echo "$as_me:$LINENO: \"$NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $nlist\"") >&5 + (eval $NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $nlist) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && test -s "$nlist"; then + # Try sorting and uniquifying the output. + if sort "$nlist" | uniq > "$nlist"T; then + mv -f "$nlist"T "$nlist" + else + rm -f "$nlist"T + fi + + # Make sure that we snagged all the symbols we need. + if grep ' nm_test_var$' "$nlist" >/dev/null; then + if grep ' nm_test_func$' "$nlist" >/dev/null; then + cat < conftest.$ac_ext +#ifdef __cplusplus +extern "C" { +#endif + +EOF + # Now generate the symbol file. + eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | grep -v main >> conftest.$ac_ext' + + cat <> conftest.$ac_ext +#if defined (__STDC__) && __STDC__ +# define lt_ptr_t void * +#else +# define lt_ptr_t char * +# define const +#endif + +/* The mapping between symbol names and symbols. */ +const struct { + const char *name; + lt_ptr_t address; +} +lt_preloaded_symbols[] = +{ +EOF + $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/ {\"\2\", (lt_ptr_t) \&\2},/" < "$nlist" | grep -v main >> conftest.$ac_ext + cat <<\EOF >> conftest.$ac_ext + {0, (lt_ptr_t) 0} +}; + +#ifdef __cplusplus +} +#endif +EOF + # Now try linking the two files. + mv conftest.$ac_objext conftstm.$ac_objext + lt_save_LIBS="$LIBS" + lt_save_CFLAGS="$CFLAGS" + LIBS="conftstm.$ac_objext" + CFLAGS="$CFLAGS$lt_prog_compiler_no_builtin_flag" + if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && test -s conftest${ac_exeext}; then + pipe_works=yes + fi + LIBS="$lt_save_LIBS" + CFLAGS="$lt_save_CFLAGS" + else + echo "cannot find nm_test_func in $nlist" >&5 + fi + else + echo "cannot find nm_test_var in $nlist" >&5 + fi + else + echo "cannot run $lt_cv_sys_global_symbol_pipe" >&5 + fi + else + echo "$progname: failed program was:" >&5 + cat conftest.$ac_ext >&5 + fi + rm -f conftest* conftst* + + # Do not use the global_symbol_pipe unless it works. + if test "$pipe_works" = yes; then + break + else + lt_cv_sys_global_symbol_pipe= + fi +done + +fi + +if test -z "$lt_cv_sys_global_symbol_pipe"; then + lt_cv_sys_global_symbol_to_cdecl= +fi +if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then + { echo "$as_me:$LINENO: result: failed" >&5 +echo "${ECHO_T}failed" >&6; } +else + { echo "$as_me:$LINENO: result: ok" >&5 +echo "${ECHO_T}ok" >&6; } +fi + +{ echo "$as_me:$LINENO: checking for objdir" >&5 +echo $ECHO_N "checking for objdir... $ECHO_C" >&6; } +if test "${lt_cv_objdir+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + rm -f .libs 2>/dev/null +mkdir .libs 2>/dev/null +if test -d .libs; then + lt_cv_objdir=.libs +else + # MS-DOS does not allow filenames that begin with a dot. + lt_cv_objdir=_libs +fi +rmdir .libs 2>/dev/null +fi +{ echo "$as_me:$LINENO: result: $lt_cv_objdir" >&5 +echo "${ECHO_T}$lt_cv_objdir" >&6; } +objdir=$lt_cv_objdir + + + + + +case $host_os in +aix3*) + # AIX sometimes has problems with the GCC collect2 program. For some + # reason, if we set the COLLECT_NAMES environment variable, the problems + # vanish in a puff of smoke. + if test "X${COLLECT_NAMES+set}" != Xset; then + COLLECT_NAMES= + export COLLECT_NAMES + fi + ;; +esac + +# Sed substitution that helps us do robust quoting. It backslashifies +# metacharacters that are still active within double-quoted strings. +Xsed='sed -e 1s/^X//' +sed_quote_subst='s/\([\\"\\`$\\\\]\)/\\\1/g' + +# Same as above, but do not quote variable references. +double_quote_subst='s/\([\\"\\`\\\\]\)/\\\1/g' + +# Sed substitution to delay expansion of an escaped shell variable in a +# double_quote_subst'ed string. +delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' + +# Sed substitution to avoid accidental globbing in evaled expressions +no_glob_subst='s/\*/\\\*/g' + +# Constants: +rm="rm -f" + +# Global variables: +default_ofile=libtool +can_build_shared=yes + +# All known linkers require a `.a' archive for static linking (except MSVC, +# which needs '.lib'). +libext=a +ltmain="$ac_aux_dir/ltmain.sh" +ofile="$default_ofile" +with_gnu_ld="$lt_cv_prog_gnu_ld" + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}ar", so it can be a program name with args. +set dummy ${ac_tool_prefix}ar; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_AR+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$AR"; then + ac_cv_prog_AR="$AR" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_AR="${ac_tool_prefix}ar" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +AR=$ac_cv_prog_AR +if test -n "$AR"; then + { echo "$as_me:$LINENO: result: $AR" >&5 +echo "${ECHO_T}$AR" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_AR"; then + ac_ct_AR=$AR + # Extract the first word of "ar", so it can be a program name with args. +set dummy ar; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_ac_ct_AR+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$ac_ct_AR"; then + ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_AR="ar" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +ac_ct_AR=$ac_cv_prog_ac_ct_AR +if test -n "$ac_ct_AR"; then + { echo "$as_me:$LINENO: result: $ac_ct_AR" >&5 +echo "${ECHO_T}$ac_ct_AR" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + if test "x$ac_ct_AR" = x; then + AR="false" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf at gnu.org." >&5 +echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf at gnu.org." >&2;} +ac_tool_warned=yes ;; +esac + AR=$ac_ct_AR + fi +else + AR="$ac_cv_prog_AR" +fi + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. +set dummy ${ac_tool_prefix}ranlib; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_RANLIB+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$RANLIB"; then + ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +RANLIB=$ac_cv_prog_RANLIB +if test -n "$RANLIB"; then + { echo "$as_me:$LINENO: result: $RANLIB" >&5 +echo "${ECHO_T}$RANLIB" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_RANLIB"; then + ac_ct_RANLIB=$RANLIB + # Extract the first word of "ranlib", so it can be a program name with args. +set dummy ranlib; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_ac_ct_RANLIB+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$ac_ct_RANLIB"; then + ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_RANLIB="ranlib" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB +if test -n "$ac_ct_RANLIB"; then + { echo "$as_me:$LINENO: result: $ac_ct_RANLIB" >&5 +echo "${ECHO_T}$ac_ct_RANLIB" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + if test "x$ac_ct_RANLIB" = x; then + RANLIB=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf at gnu.org." >&5 +echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf at gnu.org." >&2;} +ac_tool_warned=yes ;; +esac + RANLIB=$ac_ct_RANLIB + fi +else + RANLIB="$ac_cv_prog_RANLIB" +fi + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. +set dummy ${ac_tool_prefix}strip; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_STRIP+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$STRIP"; then + ac_cv_prog_STRIP="$STRIP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_STRIP="${ac_tool_prefix}strip" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +STRIP=$ac_cv_prog_STRIP +if test -n "$STRIP"; then + { echo "$as_me:$LINENO: result: $STRIP" >&5 +echo "${ECHO_T}$STRIP" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_STRIP"; then + ac_ct_STRIP=$STRIP + # Extract the first word of "strip", so it can be a program name with args. +set dummy strip; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_ac_ct_STRIP+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$ac_ct_STRIP"; then + ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_STRIP="strip" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP +if test -n "$ac_ct_STRIP"; then + { echo "$as_me:$LINENO: result: $ac_ct_STRIP" >&5 +echo "${ECHO_T}$ac_ct_STRIP" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + if test "x$ac_ct_STRIP" = x; then + STRIP=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf at gnu.org." >&5 +echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf at gnu.org." >&2;} +ac_tool_warned=yes ;; +esac + STRIP=$ac_ct_STRIP + fi +else + STRIP="$ac_cv_prog_STRIP" +fi + + +old_CC="$CC" +old_CFLAGS="$CFLAGS" + +# Set sane defaults for various variables +test -z "$AR" && AR=ar +test -z "$AR_FLAGS" && AR_FLAGS=cru +test -z "$AS" && AS=as +test -z "$CC" && CC=cc +test -z "$LTCC" && LTCC=$CC +test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS +test -z "$DLLTOOL" && DLLTOOL=dlltool +test -z "$LD" && LD=ld +test -z "$LN_S" && LN_S="ln -s" +test -z "$MAGIC_CMD" && MAGIC_CMD=file +test -z "$NM" && NM=nm +test -z "$SED" && SED=sed +test -z "$OBJDUMP" && OBJDUMP=objdump +test -z "$RANLIB" && RANLIB=: +test -z "$STRIP" && STRIP=: +test -z "$ac_objext" && ac_objext=o + +# Determine commands to create old-style static archives. +old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs' +old_postinstall_cmds='chmod 644 $oldlib' +old_postuninstall_cmds= + +if test -n "$RANLIB"; then + case $host_os in + openbsd*) + old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$oldlib" + ;; + *) + old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$oldlib" + ;; + esac + old_archive_cmds="$old_archive_cmds~\$RANLIB \$oldlib" +fi + +for cc_temp in $compiler""; do + case $cc_temp in + compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; + distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; + \-*) ;; + *) break;; + esac +done +cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"` + + +# Only perform the check for file, if the check method requires it +case $deplibs_check_method in +file_magic*) + if test "$file_magic_cmd" = '$MAGIC_CMD'; then + { echo "$as_me:$LINENO: checking for ${ac_tool_prefix}file" >&5 +echo $ECHO_N "checking for ${ac_tool_prefix}file... $ECHO_C" >&6; } +if test "${lt_cv_path_MAGIC_CMD+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + case $MAGIC_CMD in +[\\/*] | ?:[\\/]*) + lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. + ;; +*) + lt_save_MAGIC_CMD="$MAGIC_CMD" + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" + for ac_dir in $ac_dummy; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + if test -f $ac_dir/${ac_tool_prefix}file; then + lt_cv_path_MAGIC_CMD="$ac_dir/${ac_tool_prefix}file" + if test -n "$file_magic_test_file"; then + case $deplibs_check_method in + "file_magic "*) + file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` + MAGIC_CMD="$lt_cv_path_MAGIC_CMD" + if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | + $EGREP "$file_magic_regex" > /dev/null; then + : + else + cat <&2 + +*** Warning: the command libtool uses to detect shared libraries, +*** $file_magic_cmd, produces output that libtool cannot recognize. +*** The result is that libtool may fail to recognize shared libraries +*** as such. This will affect the creation of libtool libraries that +*** depend on shared libraries, but programs linked with such libtool +*** libraries will work regardless of this problem. Nevertheless, you +*** may want to report the problem to your system manager and/or to +*** bug-libtool at gnu.org + +EOF + fi ;; + esac + fi + break + fi + done + IFS="$lt_save_ifs" + MAGIC_CMD="$lt_save_MAGIC_CMD" + ;; +esac +fi + +MAGIC_CMD="$lt_cv_path_MAGIC_CMD" +if test -n "$MAGIC_CMD"; then + { echo "$as_me:$LINENO: result: $MAGIC_CMD" >&5 +echo "${ECHO_T}$MAGIC_CMD" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + +if test -z "$lt_cv_path_MAGIC_CMD"; then + if test -n "$ac_tool_prefix"; then + { echo "$as_me:$LINENO: checking for file" >&5 +echo $ECHO_N "checking for file... $ECHO_C" >&6; } +if test "${lt_cv_path_MAGIC_CMD+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + case $MAGIC_CMD in +[\\/*] | ?:[\\/]*) + lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. + ;; +*) + lt_save_MAGIC_CMD="$MAGIC_CMD" + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" + for ac_dir in $ac_dummy; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + if test -f $ac_dir/file; then + lt_cv_path_MAGIC_CMD="$ac_dir/file" + if test -n "$file_magic_test_file"; then + case $deplibs_check_method in + "file_magic "*) + file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` + MAGIC_CMD="$lt_cv_path_MAGIC_CMD" + if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | + $EGREP "$file_magic_regex" > /dev/null; then + : + else + cat <&2 + +*** Warning: the command libtool uses to detect shared libraries, +*** $file_magic_cmd, produces output that libtool cannot recognize. +*** The result is that libtool may fail to recognize shared libraries +*** as such. This will affect the creation of libtool libraries that +*** depend on shared libraries, but programs linked with such libtool +*** libraries will work regardless of this problem. Nevertheless, you +*** may want to report the problem to your system manager and/or to +*** bug-libtool at gnu.org + +EOF + fi ;; + esac + fi + break + fi + done + IFS="$lt_save_ifs" + MAGIC_CMD="$lt_save_MAGIC_CMD" + ;; +esac +fi + +MAGIC_CMD="$lt_cv_path_MAGIC_CMD" +if test -n "$MAGIC_CMD"; then + { echo "$as_me:$LINENO: result: $MAGIC_CMD" >&5 +echo "${ECHO_T}$MAGIC_CMD" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + else + MAGIC_CMD=: + fi +fi + + fi + ;; +esac + +enable_dlopen=no +enable_win32_dll=no + +# Check whether --enable-libtool-lock was given. +if test "${enable_libtool_lock+set}" = set; then + enableval=$enable_libtool_lock; +fi + +test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes + + +# Check whether --with-pic was given. +if test "${with_pic+set}" = set; then + withval=$with_pic; pic_mode="$withval" +else + pic_mode=default +fi + +test -z "$pic_mode" && pic_mode=default + +# Use C for the default configuration in the libtool script +tagname= +lt_save_CC="$CC" +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + +# Source file extension for C test sources. +ac_ext=c + +# Object file extension for compiled C test sources. +objext=o +objext=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code="int some_variable = 0;" + +# Code to be used in simple link tests +lt_simple_link_test_code='int main(){return(0);}' + + +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} + +# If no C compiler flags were specified, use CFLAGS. +LTCFLAGS=${LTCFLAGS-"$CFLAGS"} + +# Allow CC to be a program name with arguments. +compiler=$CC + + +# save warnings/boilerplate of simple test code +ac_outfile=conftest.$ac_objext +echo "$lt_simple_compile_test_code" >conftest.$ac_ext +eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_compiler_boilerplate=`cat conftest.err` +$rm conftest* + +ac_outfile=conftest.$ac_objext +echo "$lt_simple_link_test_code" >conftest.$ac_ext +eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_linker_boilerplate=`cat conftest.err` +$rm conftest* + + + +lt_prog_compiler_no_builtin_flag= + +if test "$GCC" = yes; then + lt_prog_compiler_no_builtin_flag=' -fno-builtin' + + +{ echo "$as_me:$LINENO: checking if $compiler supports -fno-rtti -fno-exceptions" >&5 +echo $ECHO_N "checking if $compiler supports -fno-rtti -fno-exceptions... $ECHO_C" >&6; } +if test "${lt_cv_prog_compiler_rtti_exceptions+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_cv_prog_compiler_rtti_exceptions=no + ac_outfile=conftest.$ac_objext + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="-fno-rtti -fno-exceptions" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:7436: $lt_compile\"" >&5) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&5 + echo "$as_me:7440: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings other than the usual output. + $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then + lt_cv_prog_compiler_rtti_exceptions=yes + fi + fi + $rm conftest* + +fi +{ echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_rtti_exceptions" >&5 +echo "${ECHO_T}$lt_cv_prog_compiler_rtti_exceptions" >&6; } + +if test x"$lt_cv_prog_compiler_rtti_exceptions" = xyes; then + lt_prog_compiler_no_builtin_flag="$lt_prog_compiler_no_builtin_flag -fno-rtti -fno-exceptions" +else + : +fi + +fi + +lt_prog_compiler_wl= +lt_prog_compiler_pic= +lt_prog_compiler_static= + +{ echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5 +echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6; } + + if test "$GCC" = yes; then + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_static='-static' + + case $host_os in + aix*) + # All AIX code is PIC. + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static='-Bstatic' + fi + ;; + + amigaos*) + # FIXME: we need at least 68020 code to build shared libraries, but + # adding the `-m68020' flag to GCC prevents building anything better, + # like `-m68040'. + lt_prog_compiler_pic='-m68020 -resident32 -malways-restore-a4' + ;; + + beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) + # PIC is the default for these OSes. + ;; + + mingw* | cygwin* | pw32* | os2*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + # Although the cygwin gcc ignores -fPIC, still need this for old-style + # (--disable-auto-import) libraries + lt_prog_compiler_pic='-DDLL_EXPORT' + ;; + + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + lt_prog_compiler_pic='-fno-common' + ;; + + interix[3-9]*) + # Interix 3.x gcc -fpic/-fPIC options generate broken code. + # Instead, we relocate shared libraries at runtime. + ;; + + msdosdjgpp*) + # Just because we use GCC doesn't mean we suddenly get shared libraries + # on systems that don't support them. + lt_prog_compiler_can_build_shared=no + enable_shared=no + ;; + + sysv4*MP*) + if test -d /usr/nec; then + lt_prog_compiler_pic=-Kconform_pic + fi + ;; + + hpux*) + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case $host_cpu in + hppa*64*|ia64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic='-fPIC' + ;; + esac + ;; + + *) + lt_prog_compiler_pic='-fPIC' + ;; + esac + else + # PORTME Check for flag to pass linker flags through the system compiler. + case $host_os in + aix*) + lt_prog_compiler_wl='-Wl,' + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static='-Bstatic' + else + lt_prog_compiler_static='-bnso -bI:/lib/syscalls.exp' + fi + ;; + darwin*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + case $cc_basename in + xlc*) + lt_prog_compiler_pic='-qnocommon' + lt_prog_compiler_wl='-Wl,' + ;; + esac + ;; + + mingw* | cygwin* | pw32* | os2*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + lt_prog_compiler_pic='-DDLL_EXPORT' + ;; + + hpux9* | hpux10* | hpux11*) + lt_prog_compiler_wl='-Wl,' + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case $host_cpu in + hppa*64*|ia64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic='+Z' + ;; + esac + # Is there a better lt_prog_compiler_static that works with the bundled CC? + lt_prog_compiler_static='${wl}-a ${wl}archive' + ;; + + irix5* | irix6* | nonstopux*) + lt_prog_compiler_wl='-Wl,' + # PIC (with -KPIC) is the default. + lt_prog_compiler_static='-non_shared' + ;; + + newsos6) + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + ;; + + linux* | k*bsd*-gnu) + case $cc_basename in + icc* | ecc*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-static' + ;; + pgcc* | pgf77* | pgf90* | pgf95*) + # Portland Group compilers (*not* the Pentium gcc compiler, + # which looks to be a dead project) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-fpic' + lt_prog_compiler_static='-Bstatic' + ;; + ccc*) + lt_prog_compiler_wl='-Wl,' + # All Alpha code is PIC. + lt_prog_compiler_static='-non_shared' + ;; + *) + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) + # Sun C 5.9 + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + lt_prog_compiler_wl='-Wl,' + ;; + *Sun\ F*) + # Sun Fortran 8.3 passes all unrecognized flags to the linker + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + lt_prog_compiler_wl='' + ;; + esac + ;; + esac + ;; + + osf3* | osf4* | osf5*) + lt_prog_compiler_wl='-Wl,' + # All OSF/1 code is PIC. + lt_prog_compiler_static='-non_shared' + ;; + + rdos*) + lt_prog_compiler_static='-non_shared' + ;; + + solaris*) + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + case $cc_basename in + f77* | f90* | f95*) + lt_prog_compiler_wl='-Qoption ld ';; + *) + lt_prog_compiler_wl='-Wl,';; + esac + ;; + + sunos4*) + lt_prog_compiler_wl='-Qoption ld ' + lt_prog_compiler_pic='-PIC' + lt_prog_compiler_static='-Bstatic' + ;; + + sysv4 | sysv4.2uw2* | sysv4.3*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + ;; + + sysv4*MP*) + if test -d /usr/nec ;then + lt_prog_compiler_pic='-Kconform_pic' + lt_prog_compiler_static='-Bstatic' + fi + ;; + + sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + ;; + + unicos*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_can_build_shared=no + ;; + + uts4*) + lt_prog_compiler_pic='-pic' + lt_prog_compiler_static='-Bstatic' + ;; + + *) + lt_prog_compiler_can_build_shared=no + ;; + esac + fi + +{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic" >&5 +echo "${ECHO_T}$lt_prog_compiler_pic" >&6; } + +# +# Check to make sure the PIC flag actually works. +# +if test -n "$lt_prog_compiler_pic"; then + +{ echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_pic works" >&5 +echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic works... $ECHO_C" >&6; } +if test "${lt_prog_compiler_pic_works+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_prog_compiler_pic_works=no + ac_outfile=conftest.$ac_objext + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="$lt_prog_compiler_pic -DPIC" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:7726: $lt_compile\"" >&5) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&5 + echo "$as_me:7730: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings other than the usual output. + $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then + lt_prog_compiler_pic_works=yes + fi + fi + $rm conftest* + +fi +{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works" >&5 +echo "${ECHO_T}$lt_prog_compiler_pic_works" >&6; } + +if test x"$lt_prog_compiler_pic_works" = xyes; then + case $lt_prog_compiler_pic in + "" | " "*) ;; + *) lt_prog_compiler_pic=" $lt_prog_compiler_pic" ;; + esac +else + lt_prog_compiler_pic= + lt_prog_compiler_can_build_shared=no +fi + +fi +case $host_os in + # For platforms which do not support PIC, -DPIC is meaningless: + *djgpp*) + lt_prog_compiler_pic= + ;; + *) + lt_prog_compiler_pic="$lt_prog_compiler_pic -DPIC" + ;; +esac + +# +# Check to make sure the static flag actually works. +# +wl=$lt_prog_compiler_wl eval lt_tmp_static_flag=\"$lt_prog_compiler_static\" +{ echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_flag works" >&5 +echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works... $ECHO_C" >&6; } +if test "${lt_prog_compiler_static_works+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_prog_compiler_static_works=no + save_LDFLAGS="$LDFLAGS" + LDFLAGS="$LDFLAGS $lt_tmp_static_flag" + echo "$lt_simple_link_test_code" > conftest.$ac_ext + if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then + # The linker can only warn and ignore the option if not recognized + # So say no if there are warnings + if test -s conftest.err; then + # Append any errors to the config.log. + cat conftest.err 1>&5 + $echo "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if diff conftest.exp conftest.er2 >/dev/null; then + lt_prog_compiler_static_works=yes + fi + else + lt_prog_compiler_static_works=yes + fi + fi + $rm conftest* + LDFLAGS="$save_LDFLAGS" + +fi +{ echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works" >&5 +echo "${ECHO_T}$lt_prog_compiler_static_works" >&6; } + +if test x"$lt_prog_compiler_static_works" = xyes; then + : +else + lt_prog_compiler_static= +fi + + +{ echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5 +echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6; } +if test "${lt_cv_prog_compiler_c_o+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_cv_prog_compiler_c_o=no + $rm -r conftest 2>/dev/null + mkdir conftest + cd conftest + mkdir out + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + lt_compiler_flag="-o out/conftest2.$ac_objext" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:7830: $lt_compile\"" >&5) + (eval "$lt_compile" 2>out/conftest.err) + ac_status=$? + cat out/conftest.err >&5 + echo "$as_me:7834: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s out/conftest2.$ac_objext + then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp + $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 + if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then + lt_cv_prog_compiler_c_o=yes + fi + fi + chmod u+w . 2>&5 + $rm conftest* + # SGI C++ compiler will create directory out/ii_files/ for + # template instantiation + test -d out/ii_files && $rm out/ii_files/* && rmdir out/ii_files + $rm out/* && rmdir out + cd .. + rmdir conftest + $rm conftest* + +fi +{ echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o" >&5 +echo "${ECHO_T}$lt_cv_prog_compiler_c_o" >&6; } + + +hard_links="nottested" +if test "$lt_cv_prog_compiler_c_o" = no && test "$need_locks" != no; then + # do not overwrite the value of need_locks provided by the user + { echo "$as_me:$LINENO: checking if we can lock with hard links" >&5 +echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6; } + hard_links=yes + $rm conftest* + ln conftest.a conftest.b 2>/dev/null && hard_links=no + touch conftest.a + ln conftest.a conftest.b 2>&5 || hard_links=no + ln conftest.a conftest.b 2>/dev/null && hard_links=no + { echo "$as_me:$LINENO: result: $hard_links" >&5 +echo "${ECHO_T}$hard_links" >&6; } + if test "$hard_links" = no; then + { echo "$as_me:$LINENO: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5 +echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;} + need_locks=warn + fi +else + need_locks=no +fi + +{ echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5 +echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6; } + + runpath_var= + allow_undefined_flag= + enable_shared_with_static_runtimes=no + archive_cmds= + archive_expsym_cmds= + old_archive_From_new_cmds= + old_archive_from_expsyms_cmds= + export_dynamic_flag_spec= + whole_archive_flag_spec= + thread_safe_flag_spec= + hardcode_libdir_flag_spec= + hardcode_libdir_flag_spec_ld= + hardcode_libdir_separator= + hardcode_direct=no + hardcode_minus_L=no + hardcode_shlibpath_var=unsupported + link_all_deplibs=unknown + hardcode_automatic=no + module_cmds= + module_expsym_cmds= + always_export_symbols=no + export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + # include_expsyms should be a list of space-separated symbols to be *always* + # included in the symbol list + include_expsyms= + # exclude_expsyms can be an extended regexp of symbols to exclude + # it will be wrapped by ` (' and `)$', so one must not match beginning or + # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc', + # as well as any symbol that contains `d'. + exclude_expsyms="_GLOBAL_OFFSET_TABLE_" + # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out + # platforms (ab)use it in PIC code, but their linkers get confused if + # the symbol is explicitly referenced. Since portable code cannot + # rely on this symbol name, it's probably fine to never include it in + # preloaded symbol tables. + extract_expsyms_cmds= + # Just being paranoid about ensuring that cc_basename is set. + for cc_temp in $compiler""; do + case $cc_temp in + compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; + distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; + \-*) ;; + *) break;; + esac +done +cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"` + + case $host_os in + cygwin* | mingw* | pw32*) + # FIXME: the MSVC++ port hasn't been tested in a loooong time + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + if test "$GCC" != yes; then + with_gnu_ld=no + fi + ;; + interix*) + # we just hope/assume this is gcc and not c89 (= MSVC++) + with_gnu_ld=yes + ;; + openbsd*) + with_gnu_ld=no + ;; + esac + + ld_shlibs=yes + if test "$with_gnu_ld" = yes; then + # If archive_cmds runs LD, not CC, wlarc should be empty + wlarc='${wl}' + + # Set some defaults for GNU ld with shared library support. These + # are reset later if shared libraries are not supported. Putting them + # here allows them to be overridden if necessary. + runpath_var=LD_RUN_PATH + hardcode_libdir_flag_spec='${wl}--rpath ${wl}$libdir' + export_dynamic_flag_spec='${wl}--export-dynamic' + # ancient GNU ld didn't support --whole-archive et. al. + if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then + whole_archive_flag_spec="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' + else + whole_archive_flag_spec= + fi + supports_anon_versioning=no + case `$LD -v 2>/dev/null` in + *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11 + *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... + *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... + *\ 2.11.*) ;; # other 2.11 versions + *) supports_anon_versioning=yes ;; + esac + + # See if GNU ld supports shared libraries. + case $host_os in + aix3* | aix4* | aix5*) + # On AIX/PPC, the GNU linker is very broken + if test "$host_cpu" != ia64; then + ld_shlibs=no + cat <&2 + +*** Warning: the GNU linker, at least up to release 2.9.1, is reported +*** to be unable to reliably create shared libraries on AIX. +*** Therefore, libtool is disabling shared libraries support. If you +*** really care for shared libraries, you may want to modify your PATH +*** so that a non-GNU linker is found, and then restart. + +EOF + fi + ;; + + amigaos*) + archive_cmds='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + hardcode_libdir_flag_spec='-L$libdir' + hardcode_minus_L=yes + + # Samuel A. Falvo II reports + # that the semantics of dynamic libraries on AmigaOS, at least up + # to version 4, is to share data among multiple programs linked + # with the same dynamic library. Since this doesn't match the + # behavior of shared libraries on other platforms, we can't use + # them. + ld_shlibs=no + ;; + + beos*) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + allow_undefined_flag=unsupported + # Joseph Beckenbach says some releases of gcc + # support --undefined. This deserves some investigation. FIXME + archive_cmds='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + else + ld_shlibs=no + fi + ;; + + cygwin* | mingw* | pw32*) + # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, ) is actually meaningless, + # as there is no search path for DLLs. + hardcode_libdir_flag_spec='-L$libdir' + allow_undefined_flag=unsupported + always_export_symbols=no + enable_shared_with_static_runtimes=yes + export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/'\'' -e '\''/^[AITW][ ]/s/.*[ ]//'\'' | sort | uniq > $export_symbols' + + if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + # If the export-symbols file already is a .def file (1st line + # is EXPORTS), use it as is; otherwise, prepend... + archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then + cp $export_symbols $output_objdir/$soname.def; + else + echo EXPORTS > $output_objdir/$soname.def; + cat $export_symbols >> $output_objdir/$soname.def; + fi~ + $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + else + ld_shlibs=no + fi + ;; + + interix[3-9]*) + hardcode_direct=no + hardcode_shlibpath_var=no + hardcode_libdir_flag_spec='${wl}-rpath,$libdir' + export_dynamic_flag_spec='${wl}-E' + # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. + # Instead, shared libraries are loaded at an image base (0x10000000 by + # default) and relocated if they conflict, which is a slow very memory + # consuming and fragmenting process. To avoid this, we pick a random, + # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link + # time. Moving up from 0x10000000 also allows more sbrk(2) space. + archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + archive_expsym_cmds='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + ;; + + gnu* | linux* | k*bsd*-gnu) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + tmp_addflag= + case $cc_basename,$host_cpu in + pgcc*) # Portland Group C compiler + whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive' + tmp_addflag=' $pic_flag' + ;; + pgf77* | pgf90* | pgf95*) # Portland Group f77 and f90 compilers + whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive' + tmp_addflag=' $pic_flag -Mnomain' ;; + ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 + tmp_addflag=' -i_dynamic' ;; + efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 + tmp_addflag=' -i_dynamic -nofor_main' ;; + ifc* | ifort*) # Intel Fortran compiler + tmp_addflag=' -nofor_main' ;; + esac + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) # Sun C 5.9 + whole_archive_flag_spec='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive' + tmp_sharedflag='-G' ;; + *Sun\ F*) # Sun Fortran 8.3 + tmp_sharedflag='-G' ;; + *) + tmp_sharedflag='-shared' ;; + esac + archive_cmds='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + + if test $supports_anon_versioning = yes; then + archive_expsym_cmds='$echo "{ global:" > $output_objdir/$libname.ver~ + cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ + $echo "local: *; };" >> $output_objdir/$libname.ver~ + $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' + fi + else + ld_shlibs=no + fi + ;; + + netbsd*) + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + archive_cmds='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' + wlarc= + else + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + fi + ;; + + solaris*) + if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then + ld_shlibs=no + cat <&2 + +*** Warning: The releases 2.8.* of the GNU linker cannot reliably +*** create shared libraries on Solaris systems. Therefore, libtool +*** is disabling shared libraries support. We urge you to upgrade GNU +*** binutils to release 2.9.1 or newer. Another option is to modify +*** your PATH or compiler configuration so that the native linker is +*** used, and then restart. + +EOF + elif $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + ld_shlibs=no + fi + ;; + + sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) + case `$LD -v 2>&1` in + *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*) + ld_shlibs=no + cat <<_LT_EOF 1>&2 + +*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not +*** reliably create shared libraries on SCO systems. Therefore, libtool +*** is disabling shared libraries support. We urge you to upgrade GNU +*** binutils to release 2.16.91.0.3 or newer. Another option is to modify +*** your PATH or compiler configuration so that the native linker is +*** used, and then restart. + +_LT_EOF + ;; + *) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + hardcode_libdir_flag_spec='`test -z "$SCOABSPATH" && echo ${wl}-rpath,$libdir`' + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib' + archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname,-retain-symbols-file,$export_symbols -o $lib' + else + ld_shlibs=no + fi + ;; + esac + ;; + + sunos4*) + archive_cmds='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' + wlarc= + hardcode_direct=yes + hardcode_shlibpath_var=no + ;; + + *) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + ld_shlibs=no + fi + ;; + esac + + if test "$ld_shlibs" = no; then + runpath_var= + hardcode_libdir_flag_spec= + export_dynamic_flag_spec= + whole_archive_flag_spec= + fi + else + # PORTME fill in a description of your system's linker (not GNU ld) + case $host_os in + aix3*) + allow_undefined_flag=unsupported + always_export_symbols=yes + archive_expsym_cmds='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' + # Note: this linker hardcodes the directories in LIBPATH if there + # are no directories specified by -L. + hardcode_minus_L=yes + if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then + # Neither direct hardcoding nor static linking is supported with a + # broken collect2. + hardcode_direct=unsupported + fi + ;; + + aix4* | aix5*) + if test "$host_cpu" = ia64; then + # On IA64, the linker does run time linking by default, so we don't + # have to do anything special. + aix_use_runtimelinking=no + exp_sym_flag='-Bexport' + no_entry_flag="" + else + # If we're using GNU nm, then we don't want the "-C" option. + # -C means demangle to AIX nm, but means don't demangle with GNU nm + if $NM -V 2>&1 | grep 'GNU' > /dev/null; then + export_symbols_cmds='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols' + else + export_symbols_cmds='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols' + fi + aix_use_runtimelinking=no + + # Test if we are trying to use run time linking or normal + # AIX style linking. If -brtl is somewhere in LDFLAGS, we + # need to do runtime linking. + case $host_os in aix4.[23]|aix4.[23].*|aix5*) + for ld_flag in $LDFLAGS; do + if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then + aix_use_runtimelinking=yes + break + fi + done + ;; + esac + + exp_sym_flag='-bexport' + no_entry_flag='-bnoentry' + fi + + # When large executables or shared objects are built, AIX ld can + # have problems creating the table of contents. If linking a library + # or program results in "error TOC overflow" add -mminimal-toc to + # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not + # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. + + archive_cmds='' + hardcode_direct=yes + hardcode_libdir_separator=':' + link_all_deplibs=yes + + if test "$GCC" = yes; then + case $host_os in aix4.[012]|aix4.[012].*) + # We only want to do this on AIX 4.2 and lower, the check + # below for broken collect2 doesn't work under 4.3+ + collect2name=`${CC} -print-prog-name=collect2` + if test -f "$collect2name" && \ + strings "$collect2name" | grep resolve_lib_name >/dev/null + then + # We have reworked collect2 + : + else + # We have old collect2 + hardcode_direct=unsupported + # It fails to find uninstalled libraries when the uninstalled + # path is not listed in the libpath. Setting hardcode_minus_L + # to unsupported forces relinking + hardcode_minus_L=yes + hardcode_libdir_flag_spec='-L$libdir' + hardcode_libdir_separator= + fi + ;; + esac + shared_flag='-shared' + if test "$aix_use_runtimelinking" = yes; then + shared_flag="$shared_flag "'${wl}-G' + fi + else + # not using gcc + if test "$host_cpu" = ia64; then + # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release + # chokes on -Wl,-G. The following line is correct: + shared_flag='-G' + else + if test "$aix_use_runtimelinking" = yes; then + shared_flag='${wl}-G' + else + shared_flag='${wl}-bM:SRE' + fi + fi + fi + + # It seems that -bexpall does not export symbols beginning with + # underscore (_), so it is better to generate a list of symbols to export. + always_export_symbols=yes + if test "$aix_use_runtimelinking" = yes; then + # Warning - without using the other runtime loading flags (-brtl), + # -berok will link without error, but may produce a broken library. + allow_undefined_flag='-berok' + # Determine the default libpath from the value encoded in an empty executable. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + +lt_aix_libpath_sed=' + /Import File Strings/,/^$/ { + /^0/ { + s/^0 *\(.*\)$/\1/ + p + } + }' +aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +# Check for a 64-bit object if we didn't find anything. +if test -z "$aix_libpath"; then + aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +fi +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi + + hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath" + archive_expsym_cmds="\$CC"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" + else + if test "$host_cpu" = ia64; then + hardcode_libdir_flag_spec='${wl}-R $libdir:/usr/lib:/lib' + allow_undefined_flag="-z nodefs" + archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" + else + # Determine the default libpath from the value encoded in an empty executable. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + +lt_aix_libpath_sed=' + /Import File Strings/,/^$/ { + /^0/ { + s/^0 *\(.*\)$/\1/ + p + } + }' +aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +# Check for a 64-bit object if we didn't find anything. +if test -z "$aix_libpath"; then + aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +fi +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi + + hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath" + # Warning - without using the other run time loading flags, + # -berok will link without error, but may produce a broken library. + no_undefined_flag=' ${wl}-bernotok' + allow_undefined_flag=' ${wl}-berok' + # Exported symbols can be pulled into shared objects from archives + whole_archive_flag_spec='$convenience' + archive_cmds_need_lc=yes + # This is similar to how AIX traditionally builds its shared libraries. + archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' + fi + fi + ;; + + amigaos*) + archive_cmds='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + hardcode_libdir_flag_spec='-L$libdir' + hardcode_minus_L=yes + # see comment about different semantics on the GNU ld section + ld_shlibs=no + ;; + + bsdi[45]*) + export_dynamic_flag_spec=-rdynamic + ;; + + cygwin* | mingw* | pw32*) + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + # hardcode_libdir_flag_spec is actually meaningless, as there is + # no search path for DLLs. + hardcode_libdir_flag_spec=' ' + allow_undefined_flag=unsupported + # Tell ltmain to make .lib files, not .a files. + libext=lib + # Tell ltmain to make .dll files, not .so files. + shrext_cmds=".dll" + # FIXME: Setting linknames here is a bad hack. + archive_cmds='$CC -o $lib $libobjs $compiler_flags `echo "$deplibs" | $SED -e '\''s/ -lc$//'\''` -link -dll~linknames=' + # The linker will automatically build a .lib file if we build a DLL. + old_archive_From_new_cmds='true' + # FIXME: Should let the user specify the lib program. + old_archive_cmds='lib -OUT:$oldlib$oldobjs$old_deplibs' + fix_srcfile_path='`cygpath -w "$srcfile"`' + enable_shared_with_static_runtimes=yes + ;; + + darwin* | rhapsody*) + case $host_os in + rhapsody* | darwin1.[012]) + allow_undefined_flag='${wl}-undefined ${wl}suppress' + ;; + *) # Darwin 1.3 on + if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then + allow_undefined_flag='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' + else + case ${MACOSX_DEPLOYMENT_TARGET} in + 10.[012]) + allow_undefined_flag='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' + ;; + 10.*) + allow_undefined_flag='${wl}-undefined ${wl}dynamic_lookup' + ;; + esac + fi + ;; + esac + archive_cmds_need_lc=no + hardcode_direct=no + hardcode_automatic=yes + hardcode_shlibpath_var=unsupported + whole_archive_flag_spec='' + link_all_deplibs=yes + if test "$GCC" = yes ; then + output_verbose_link_cmd='echo' + archive_cmds='$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring' + module_cmds='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags' + # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds + archive_expsym_cmds='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + module_expsym_cmds='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + else + case $cc_basename in + xlc*) + output_verbose_link_cmd='echo' + archive_cmds='$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$soname` $xlcverstring' + module_cmds='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags' + # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds + archive_expsym_cmds='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}$rpath/$soname $xlcverstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + module_expsym_cmds='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + ;; + *) + ld_shlibs=no + ;; + esac + fi + ;; + + dgux*) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec='-L$libdir' + hardcode_shlibpath_var=no + ;; + + freebsd1*) + ld_shlibs=no + ;; + + # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor + # support. Future versions do this automatically, but an explicit c++rt0.o + # does not break anything, and helps significantly (at the cost of a little + # extra space). + freebsd2.2*) + archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' + hardcode_libdir_flag_spec='-R$libdir' + hardcode_direct=yes + hardcode_shlibpath_var=no + ;; + + # Unfortunately, older versions of FreeBSD 2 do not have this feature. + freebsd2*) + archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct=yes + hardcode_minus_L=yes + hardcode_shlibpath_var=no + ;; + + # FreeBSD 3 and greater uses gcc -shared to do shared libraries. + freebsd* | dragonfly*) + archive_cmds='$CC -shared -o $lib $libobjs $deplibs $compiler_flags' + hardcode_libdir_flag_spec='-R$libdir' + hardcode_direct=yes + hardcode_shlibpath_var=no + ;; + + hpux9*) + if test "$GCC" = yes; then + archive_cmds='$rm $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + else + archive_cmds='$rm $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + fi + hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' + hardcode_libdir_separator=: + hardcode_direct=yes + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L=yes + export_dynamic_flag_spec='${wl}-E' + ;; + + hpux10*) + if test "$GCC" = yes -a "$with_gnu_ld" = no; then + archive_cmds='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' + fi + if test "$with_gnu_ld" = no; then + hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' + hardcode_libdir_separator=: + + hardcode_direct=yes + export_dynamic_flag_spec='${wl}-E' + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L=yes + fi + ;; + + hpux11*) + if test "$GCC" = yes -a "$with_gnu_ld" = no; then + case $host_cpu in + hppa*64*) + archive_cmds='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + ia64*) + archive_cmds='$CC -shared ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + archive_cmds='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + else + case $host_cpu in + hppa*64*) + archive_cmds='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + ia64*) + archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + fi + if test "$with_gnu_ld" = no; then + hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' + hardcode_libdir_separator=: + + case $host_cpu in + hppa*64*|ia64*) + hardcode_libdir_flag_spec_ld='+b $libdir' + hardcode_direct=no + hardcode_shlibpath_var=no + ;; + *) + hardcode_direct=yes + export_dynamic_flag_spec='${wl}-E' + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L=yes + ;; + esac + fi + ;; + + irix5* | irix6* | nonstopux*) + if test "$GCC" = yes; then + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + else + archive_cmds='$LD -shared $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + hardcode_libdir_flag_spec_ld='-rpath $libdir' + fi + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator=: + link_all_deplibs=yes + ;; + + netbsd*) + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out + else + archive_cmds='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF + fi + hardcode_libdir_flag_spec='-R$libdir' + hardcode_direct=yes + hardcode_shlibpath_var=no + ;; + + newsos6) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct=yes + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator=: + hardcode_shlibpath_var=no + ;; + + openbsd*) + if test -f /usr/libexec/ld.so; then + hardcode_direct=yes + hardcode_shlibpath_var=no + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols' + hardcode_libdir_flag_spec='${wl}-rpath,$libdir' + export_dynamic_flag_spec='${wl}-E' + else + case $host_os in + openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*) + archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec='-R$libdir' + ;; + *) + archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + hardcode_libdir_flag_spec='${wl}-rpath,$libdir' + ;; + esac + fi + else + ld_shlibs=no + fi + ;; + + os2*) + hardcode_libdir_flag_spec='-L$libdir' + hardcode_minus_L=yes + allow_undefined_flag=unsupported + archive_cmds='$echo "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$echo "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~$echo DATA >> $output_objdir/$libname.def~$echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~$echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def' + old_archive_From_new_cmds='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def' + ;; + + osf3*) + if test "$GCC" = yes; then + allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*' + archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + else + allow_undefined_flag=' -expect_unresolved \*' + archive_cmds='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + fi + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator=: + ;; + + osf4* | osf5*) # as osf3* with the addition of -msym flag + if test "$GCC" = yes; then + allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*' + archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + else + allow_undefined_flag=' -expect_unresolved \*' + archive_cmds='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + archive_expsym_cmds='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; echo "-hidden">> $lib.exp~ + $LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib~$rm $lib.exp' + + # Both c and cxx compiler support -rpath directly + hardcode_libdir_flag_spec='-rpath $libdir' + fi + hardcode_libdir_separator=: + ;; + + solaris*) + no_undefined_flag=' -z text' + if test "$GCC" = yes; then + wlarc='${wl}' + archive_cmds='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $CC -shared ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$rm $lib.exp' + else + wlarc='' + archive_cmds='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' + archive_expsym_cmds='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp' + fi + hardcode_libdir_flag_spec='-R$libdir' + hardcode_shlibpath_var=no + case $host_os in + solaris2.[0-5] | solaris2.[0-5].*) ;; + *) + # The compiler driver will combine and reorder linker options, + # but understands `-z linker_flag'. GCC discards it without `$wl', + # but is careful enough not to reorder. + # Supported since Solaris 2.6 (maybe 2.5.1?) + if test "$GCC" = yes; then + whole_archive_flag_spec='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' + else + whole_archive_flag_spec='-z allextract$convenience -z defaultextract' + fi + ;; + esac + link_all_deplibs=yes + ;; + + sunos4*) + if test "x$host_vendor" = xsequent; then + # Use $CC to link under sequent, because it throws in some extra .o + # files that make .init and .fini sections work. + archive_cmds='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' + fi + hardcode_libdir_flag_spec='-L$libdir' + hardcode_direct=yes + hardcode_minus_L=yes + hardcode_shlibpath_var=no + ;; + + sysv4) + case $host_vendor in + sni) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct=yes # is this really true??? + ;; + siemens) + ## LD is ld it makes a PLAMLIB + ## CC just makes a GrossModule. + archive_cmds='$LD -G -o $lib $libobjs $deplibs $linker_flags' + reload_cmds='$CC -r -o $output$reload_objs' + hardcode_direct=no + ;; + motorola) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct=no #Motorola manual says yes, but my tests say they lie + ;; + esac + runpath_var='LD_RUN_PATH' + hardcode_shlibpath_var=no + ;; + + sysv4.3*) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_shlibpath_var=no + export_dynamic_flag_spec='-Bexport' + ;; + + sysv4*MP*) + if test -d /usr/nec; then + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_shlibpath_var=no + runpath_var=LD_RUN_PATH + hardcode_runpath_var=yes + ld_shlibs=yes + fi + ;; + + sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*) + no_undefined_flag='${wl}-z,text' + archive_cmds_need_lc=no + hardcode_shlibpath_var=no + runpath_var='LD_RUN_PATH' + + if test "$GCC" = yes; then + archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + fi + ;; + + sysv5* | sco3.2v5* | sco5v6*) + # Note: We can NOT use -z defs as we might desire, because we do not + # link with -lc, and that would cause any symbols used from libc to + # always be unresolved, which means just about no library would + # ever link correctly. If we're not using GNU ld we use -z text + # though, which does catch some bad symbols but isn't as heavy-handed + # as -z defs. + no_undefined_flag='${wl}-z,text' + allow_undefined_flag='${wl}-z,nodefs' + archive_cmds_need_lc=no + hardcode_shlibpath_var=no + hardcode_libdir_flag_spec='`test -z "$SCOABSPATH" && echo ${wl}-R,$libdir`' + hardcode_libdir_separator=':' + link_all_deplibs=yes + export_dynamic_flag_spec='${wl}-Bexport' + runpath_var='LD_RUN_PATH' + + if test "$GCC" = yes; then + archive_cmds='$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds='$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + fi + ;; + + uts4*) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec='-L$libdir' + hardcode_shlibpath_var=no + ;; + + *) + ld_shlibs=no + ;; + esac + fi + +{ echo "$as_me:$LINENO: result: $ld_shlibs" >&5 +echo "${ECHO_T}$ld_shlibs" >&6; } +test "$ld_shlibs" = no && can_build_shared=no + +# +# Do we need to explicitly link libc? +# +case "x$archive_cmds_need_lc" in +x|xyes) + # Assume -lc should be added + archive_cmds_need_lc=yes + + if test "$enable_shared" = yes && test "$GCC" = yes; then + case $archive_cmds in + *'~'*) + # FIXME: we may have to deal with multi-command sequences. + ;; + '$CC '*) + # Test whether the compiler implicitly links with -lc since on some + # systems, -lgcc has to come before -lc. If gcc already passes -lc + # to ld, don't add -lc before -lgcc. + { echo "$as_me:$LINENO: checking whether -lc should be explicitly linked in" >&5 +echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO_C" >&6; } + $rm conftest* + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } 2>conftest.err; then + soname=conftest + lib=conftest + libobjs=conftest.$ac_objext + deplibs= + wl=$lt_prog_compiler_wl + pic_flag=$lt_prog_compiler_pic + compiler_flags=-v + linker_flags=-v + verstring= + output_objdir=. + libname=conftest + lt_save_allow_undefined_flag=$allow_undefined_flag + allow_undefined_flag= + if { (eval echo "$as_me:$LINENO: \"$archive_cmds 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1\"") >&5 + (eval $archive_cmds 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } + then + archive_cmds_need_lc=no + else + archive_cmds_need_lc=yes + fi + allow_undefined_flag=$lt_save_allow_undefined_flag + else + cat conftest.err 1>&5 + fi + $rm conftest* + { echo "$as_me:$LINENO: result: $archive_cmds_need_lc" >&5 +echo "${ECHO_T}$archive_cmds_need_lc" >&6; } + ;; + esac + fi + ;; +esac + +{ echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5 +echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6; } +library_names_spec= +libname_spec='lib$name' +soname_spec= +shrext_cmds=".so" +postinstall_cmds= +postuninstall_cmds= +finish_cmds= +finish_eval= +shlibpath_var= +shlibpath_overrides_runpath=unknown +version_type=none +dynamic_linker="$host_os ld.so" +sys_lib_dlsearch_path_spec="/lib /usr/lib" + +if test "$GCC" = yes; then + case $host_os in + darwin*) lt_awk_arg="/^libraries:/,/LR/" ;; + *) lt_awk_arg="/^libraries:/" ;; + esac + lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e "s,=/,/,g"` + if echo "$lt_search_path_spec" | grep ';' >/dev/null ; then + # if the path contains ";" then we assume it to be the separator + # otherwise default to the standard path separator (i.e. ":") - it is + # assumed that no part of a normal pathname contains ";" but that should + # okay in the real world where ";" in dirpaths is itself problematic. + lt_search_path_spec=`echo "$lt_search_path_spec" | $SED -e 's/;/ /g'` + else + lt_search_path_spec=`echo "$lt_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi + # Ok, now we have the path, separated by spaces, we can step through it + # and add multilib dir if necessary. + lt_tmp_lt_search_path_spec= + lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null` + for lt_sys_path in $lt_search_path_spec; do + if test -d "$lt_sys_path/$lt_multi_os_dir"; then + lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir" + else + test -d "$lt_sys_path" && \ + lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path" + fi + done + lt_search_path_spec=`echo $lt_tmp_lt_search_path_spec | awk ' +BEGIN {RS=" "; FS="/|\n";} { + lt_foo=""; + lt_count=0; + for (lt_i = NF; lt_i > 0; lt_i--) { + if ($lt_i != "" && $lt_i != ".") { + if ($lt_i == "..") { + lt_count++; + } else { + if (lt_count == 0) { + lt_foo="/" $lt_i lt_foo; + } else { + lt_count--; + } + } + } + } + if (lt_foo != "") { lt_freq[lt_foo]++; } + if (lt_freq[lt_foo] == 1) { print lt_foo; } +}'` + sys_lib_search_path_spec=`echo $lt_search_path_spec` +else + sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" +fi +need_lib_prefix=unknown +hardcode_into_libs=no + +# when you set need_version to no, make sure it does not cause -set_version +# flags to be left without arguments +need_version=unknown + +case $host_os in +aix3*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' + shlibpath_var=LIBPATH + + # AIX 3 has no versioning support, so we append a major version to the name. + soname_spec='${libname}${release}${shared_ext}$major' + ;; + +aix4* | aix5*) + version_type=linux + need_lib_prefix=no + need_version=no + hardcode_into_libs=yes + if test "$host_cpu" = ia64; then + # AIX 5 supports IA64 + library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + else + # With GCC up to 2.95.x, collect2 would create an import file + # for dependence libraries. The import file would start with + # the line `#! .'. This would cause the generated library to + # depend on `.', always an invalid library. This was fixed in + # development snapshots of GCC prior to 3.0. + case $host_os in + aix4 | aix4.[01] | aix4.[01].*) + if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' + echo ' yes ' + echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then + : + else + can_build_shared=no + fi + ;; + esac + # AIX (on Power*) has no versioning support, so currently we can not hardcode correct + # soname into executable. Probably we can add versioning support to + # collect2, so additional links can be useful in future. + if test "$aix_use_runtimelinking" = yes; then + # If using run time linking (on AIX 4.2 or later) use lib.so + # instead of lib.a to let people know that these are not + # typical AIX shared libraries. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + else + # We preserve .a as extension for shared libraries through AIX4.2 + # and later when we are not doing run time linking. + library_names_spec='${libname}${release}.a $libname.a' + soname_spec='${libname}${release}${shared_ext}$major' + fi + shlibpath_var=LIBPATH + fi + ;; + +amigaos*) + library_names_spec='$libname.ixlibrary $libname.a' + # Create ${libname}_ixlibrary.a entries in /sys/libs. + finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$echo "X$lib" | $Xsed -e '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' + ;; + +beos*) + library_names_spec='${libname}${shared_ext}' + dynamic_linker="$host_os ld.so" + shlibpath_var=LIBRARY_PATH + ;; + +bsdi[45]*) + version_type=linux + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" + sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" + # the default ld.so.conf also contains /usr/contrib/lib and + # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow + # libtool to hard-code these into programs + ;; + +cygwin* | mingw* | pw32*) + version_type=windows + shrext_cmds=".dll" + need_version=no + need_lib_prefix=no + + case $GCC,$host_os in + yes,cygwin* | yes,mingw* | yes,pw32*) + library_names_spec='$libname.dll.a' + # DLL is installed to $(libdir)/../bin by postinstall_cmds + postinstall_cmds='base_file=`basename \${file}`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname~ + chmod a+x \$dldir/$dlname' + postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ + dlpath=$dir/\$dldll~ + $rm \$dlpath' + shlibpath_overrides_runpath=yes + + case $host_os in + cygwin*) + # Cygwin DLLs use 'cyg' prefix rather than 'lib' + soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib" + ;; + mingw*) + # MinGW DLLs use traditional 'lib' prefix + soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"` + if echo "$sys_lib_search_path_spec" | grep ';[c-zC-Z]:/' >/dev/null; then + # It is most probably a Windows format PATH printed by + # mingw gcc, but we are running on Cygwin. Gcc prints its search + # path with ; separators, and with drive letters. We can handle the + # drive letters (cygwin fileutils understands them), so leave them, + # especially as we might pass files found there to a mingw objdump, + # which wouldn't understand a cygwinified path. Ahh. + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` + else + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi + ;; + pw32*) + # pw32 DLLs use 'pw' prefix rather than 'lib' + library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + ;; + esac + ;; + + *) + library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib' + ;; + esac + dynamic_linker='Win32 ld.exe' + # FIXME: first we should search . and the directory the executable is in + shlibpath_var=PATH + ;; + +darwin* | rhapsody*) + dynamic_linker="$host_os dyld" + version_type=darwin + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${versuffix}$shared_ext ${libname}${release}${major}$shared_ext ${libname}$shared_ext' + soname_spec='${libname}${release}${major}$shared_ext' + shlibpath_overrides_runpath=yes + shlibpath_var=DYLD_LIBRARY_PATH + shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' + + sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib" + sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' + ;; + +dgux*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +freebsd1*) + dynamic_linker=no + ;; + +freebsd* | dragonfly*) + # DragonFly does not have aout. When/if they implement a new + # versioning mechanism, adjust this. + if test -x /usr/bin/objformat; then + objformat=`/usr/bin/objformat` + else + case $host_os in + freebsd[123]*) objformat=aout ;; + *) objformat=elf ;; + esac + fi + version_type=freebsd-$objformat + case $version_type in + freebsd-elf*) + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' + need_version=no + need_lib_prefix=no + ;; + freebsd-*) + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' + need_version=yes + ;; + esac + shlibpath_var=LD_LIBRARY_PATH + case $host_os in + freebsd2*) + shlibpath_overrides_runpath=yes + ;; + freebsd3.[01]* | freebsdelf3.[01]*) + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + freebsd3.[2-9]* | freebsdelf3.[2-9]* | \ + freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1) + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + *) # from 4.6 on, and DragonFly + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + esac + ;; + +gnu*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + hardcode_into_libs=yes + ;; + +hpux9* | hpux10* | hpux11*) + # Give a soname corresponding to the major version so that dld.sl refuses to + # link against other versions. + version_type=sunos + need_lib_prefix=no + need_version=no + case $host_cpu in + ia64*) + shrext_cmds='.so' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.so" + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + if test "X$HPUX_IA64_MODE" = X32; then + sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" + else + sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" + fi + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + hppa*64*) + shrext_cmds='.sl' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.sl" + shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + *) + shrext_cmds='.sl' + dynamic_linker="$host_os dld.sl" + shlibpath_var=SHLIB_PATH + shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + ;; + esac + # HP-UX runs *really* slowly unless shared libraries are mode 555. + postinstall_cmds='chmod 555 $lib' + ;; + +interix[3-9]*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + +irix5* | irix6* | nonstopux*) + case $host_os in + nonstopux*) version_type=nonstopux ;; + *) + if test "$lt_cv_prog_gnu_ld" = yes; then + version_type=linux + else + version_type=irix + fi ;; + esac + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' + case $host_os in + irix5* | nonstopux*) + libsuff= shlibsuff= + ;; + *) + case $LD in # libtool.m4 will add one of these switches to LD + *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") + libsuff= shlibsuff= libmagic=32-bit;; + *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") + libsuff=32 shlibsuff=N32 libmagic=N32;; + *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") + libsuff=64 shlibsuff=64 libmagic=64-bit;; + *) libsuff= shlibsuff= libmagic=never-match;; + esac + ;; + esac + shlibpath_var=LD_LIBRARY${shlibsuff}_PATH + shlibpath_overrides_runpath=no + sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" + sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" + hardcode_into_libs=yes + ;; + +# No shared lib support for Linux oldld, aout, or coff. +linux*oldld* | linux*aout* | linux*coff*) + dynamic_linker=no + ;; + +# This must be Linux ELF. +linux* | k*bsd*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + # This implies no fast_install, which is unacceptable. + # Some rework will be needed to allow for fast_install + # before this can be enabled. + hardcode_into_libs=yes + sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" + sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" + + # Append ld.so.conf contents to the search path + if test -f /etc/ld.so.conf; then + lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` + sys_lib_dlsearch_path_spec="$sys_lib_dlsearch_path_spec $lt_ld_extra" + fi + + # We used to test for /lib/ld.so.1 and disable shared libraries on + # powerpc, because MkLinux only supported shared libraries with the + # GNU dynamic linker. Since this was broken with cross compilers, + # most powerpc-linux boxes support dynamic linking these days and + # people can always --disable-shared, the test was removed, and we + # assume the GNU/Linux dynamic linker is in use. + dynamic_linker='GNU/Linux ld.so' + ;; + +netbsd*) + version_type=sunos + need_lib_prefix=no + need_version=no + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + dynamic_linker='NetBSD (a.out) ld.so' + else + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + dynamic_linker='NetBSD ld.elf_so' + fi + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + +newsos6) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +nto-qnx*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +openbsd*) + version_type=sunos + sys_lib_dlsearch_path_spec="/usr/lib" + need_lib_prefix=no + # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs. + case $host_os in + openbsd3.3 | openbsd3.3.*) need_version=yes ;; + *) need_version=no ;; + esac + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + shlibpath_var=LD_LIBRARY_PATH + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + case $host_os in + openbsd2.[89] | openbsd2.[89].*) + shlibpath_overrides_runpath=no + ;; + *) + shlibpath_overrides_runpath=yes + ;; + esac + else + shlibpath_overrides_runpath=yes + fi + ;; + +os2*) + libname_spec='$name' + shrext_cmds=".dll" + need_lib_prefix=no + library_names_spec='$libname${shared_ext} $libname.a' + dynamic_linker='OS/2 ld.exe' + shlibpath_var=LIBPATH + ;; + +osf3* | osf4* | osf5*) + version_type=osf + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" + sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" + ;; + +rdos*) + dynamic_linker=no + ;; + +solaris*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + # ldd complains unless libraries are executable + postinstall_cmds='chmod +x $lib' + ;; + +sunos4*) + version_type=sunos + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + if test "$with_gnu_ld" = yes; then + need_lib_prefix=no + fi + need_version=yes + ;; + +sysv4 | sysv4.3*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + case $host_vendor in + sni) + shlibpath_overrides_runpath=no + need_lib_prefix=no + export_dynamic_flag_spec='${wl}-Blargedynsym' + runpath_var=LD_RUN_PATH + ;; + siemens) + need_lib_prefix=no + ;; + motorola) + need_lib_prefix=no + need_version=no + shlibpath_overrides_runpath=no + sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' + ;; + esac + ;; + +sysv4*MP*) + if test -d /usr/nec ;then + version_type=linux + library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' + soname_spec='$libname${shared_ext}.$major' + shlibpath_var=LD_LIBRARY_PATH + fi + ;; + +sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) + version_type=freebsd-elf + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + hardcode_into_libs=yes + if test "$with_gnu_ld" = yes; then + sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' + shlibpath_overrides_runpath=no + else + sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' + shlibpath_overrides_runpath=yes + case $host_os in + sco3.2v5*) + sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" + ;; + esac + fi + sys_lib_dlsearch_path_spec='/usr/lib' + ;; + +uts4*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +*) + dynamic_linker=no + ;; +esac +{ echo "$as_me:$LINENO: result: $dynamic_linker" >&5 +echo "${ECHO_T}$dynamic_linker" >&6; } +test "$dynamic_linker" = no && can_build_shared=no + +variables_saved_for_relink="PATH $shlibpath_var $runpath_var" +if test "$GCC" = yes; then + variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" +fi + +{ echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5 +echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6; } +hardcode_action= +if test -n "$hardcode_libdir_flag_spec" || \ + test -n "$runpath_var" || \ + test "X$hardcode_automatic" = "Xyes" ; then + + # We can hardcode non-existant directories. + if test "$hardcode_direct" != no && + # If the only mechanism to avoid hardcoding is shlibpath_var, we + # have to relink, otherwise we might link with an installed library + # when we should be linking with a yet-to-be-installed one + ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, )" != no && + test "$hardcode_minus_L" != no; then + # Linking always hardcodes the temporary library directory. + hardcode_action=relink + else + # We can link without hardcoding, and we can hardcode nonexisting dirs. + hardcode_action=immediate + fi +else + # We cannot hardcode anything, or else we can only hardcode existing + # directories. + hardcode_action=unsupported +fi +{ echo "$as_me:$LINENO: result: $hardcode_action" >&5 +echo "${ECHO_T}$hardcode_action" >&6; } + +if test "$hardcode_action" = relink; then + # Fast installation is not supported + enable_fast_install=no +elif test "$shlibpath_overrides_runpath" = yes || + test "$enable_shared" = no; then + # Fast installation is not necessary + enable_fast_install=needless +fi + +striplib= +old_striplib= +{ echo "$as_me:$LINENO: checking whether stripping libraries is possible" >&5 +echo $ECHO_N "checking whether stripping libraries is possible... $ECHO_C" >&6; } +if test -n "$STRIP" && $STRIP -V 2>&1 | grep "GNU strip" >/dev/null; then + test -z "$old_striplib" && old_striplib="$STRIP --strip-debug" + test -z "$striplib" && striplib="$STRIP --strip-unneeded" + { echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6; } +else +# FIXME - insert some real tests, host_os isn't really good enough + case $host_os in + darwin*) + if test -n "$STRIP" ; then + striplib="$STRIP -x" + old_striplib="$STRIP -S" + { echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6; } + else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + ;; + *) + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } + ;; + esac +fi + +if test "x$enable_dlopen" != xyes; then + enable_dlopen=unknown + enable_dlopen_self=unknown + enable_dlopen_self_static=unknown +else + lt_cv_dlopen=no + lt_cv_dlopen_libs= + + case $host_os in + beos*) + lt_cv_dlopen="load_add_on" + lt_cv_dlopen_libs= + lt_cv_dlopen_self=yes + ;; + + mingw* | pw32*) + lt_cv_dlopen="LoadLibrary" + lt_cv_dlopen_libs= + ;; + + cygwin*) + lt_cv_dlopen="dlopen" + lt_cv_dlopen_libs= + ;; + + darwin*) + # if libdl is installed we need to link against it + { echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5 +echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6; } +if test "${ac_cv_lib_dl_dlopen+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldl $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char dlopen (); +int +main () +{ +return dlopen (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + ac_cv_lib_dl_dlopen=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_lib_dl_dlopen=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5 +echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6; } +if test $ac_cv_lib_dl_dlopen = yes; then + lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" +else + + lt_cv_dlopen="dyld" + lt_cv_dlopen_libs= + lt_cv_dlopen_self=yes + +fi + + ;; + + *) + { echo "$as_me:$LINENO: checking for shl_load" >&5 +echo $ECHO_N "checking for shl_load... $ECHO_C" >&6; } +if test "${ac_cv_func_shl_load+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +/* Define shl_load to an innocuous variant, in case declares shl_load. + For example, HP-UX 11i declares gettimeofday. */ +#define shl_load innocuous_shl_load + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char shl_load (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef shl_load + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char shl_load (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_shl_load || defined __stub___shl_load +choke me +#endif + +int +main () +{ +return shl_load (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + ac_cv_func_shl_load=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_func_shl_load=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $ac_cv_func_shl_load" >&5 +echo "${ECHO_T}$ac_cv_func_shl_load" >&6; } +if test $ac_cv_func_shl_load = yes; then + lt_cv_dlopen="shl_load" +else + { echo "$as_me:$LINENO: checking for shl_load in -ldld" >&5 +echo $ECHO_N "checking for shl_load in -ldld... $ECHO_C" >&6; } +if test "${ac_cv_lib_dld_shl_load+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldld $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char shl_load (); +int +main () +{ +return shl_load (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + ac_cv_lib_dld_shl_load=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_lib_dld_shl_load=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ echo "$as_me:$LINENO: result: $ac_cv_lib_dld_shl_load" >&5 +echo "${ECHO_T}$ac_cv_lib_dld_shl_load" >&6; } +if test $ac_cv_lib_dld_shl_load = yes; then + lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-dld" +else + { echo "$as_me:$LINENO: checking for dlopen" >&5 +echo $ECHO_N "checking for dlopen... $ECHO_C" >&6; } +if test "${ac_cv_func_dlopen+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +/* Define dlopen to an innocuous variant, in case declares dlopen. + For example, HP-UX 11i declares gettimeofday. */ +#define dlopen innocuous_dlopen + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char dlopen (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef dlopen + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char dlopen (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_dlopen || defined __stub___dlopen +choke me +#endif + +int +main () +{ +return dlopen (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + ac_cv_func_dlopen=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_func_dlopen=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $ac_cv_func_dlopen" >&5 +echo "${ECHO_T}$ac_cv_func_dlopen" >&6; } +if test $ac_cv_func_dlopen = yes; then + lt_cv_dlopen="dlopen" +else + { echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5 +echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6; } +if test "${ac_cv_lib_dl_dlopen+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldl $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char dlopen (); +int +main () +{ +return dlopen (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + ac_cv_lib_dl_dlopen=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_lib_dl_dlopen=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5 +echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6; } +if test $ac_cv_lib_dl_dlopen = yes; then + lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" +else + { echo "$as_me:$LINENO: checking for dlopen in -lsvld" >&5 +echo $ECHO_N "checking for dlopen in -lsvld... $ECHO_C" >&6; } +if test "${ac_cv_lib_svld_dlopen+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lsvld $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char dlopen (); +int +main () +{ +return dlopen (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + ac_cv_lib_svld_dlopen=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_lib_svld_dlopen=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ echo "$as_me:$LINENO: result: $ac_cv_lib_svld_dlopen" >&5 +echo "${ECHO_T}$ac_cv_lib_svld_dlopen" >&6; } +if test $ac_cv_lib_svld_dlopen = yes; then + lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld" +else + { echo "$as_me:$LINENO: checking for dld_link in -ldld" >&5 +echo $ECHO_N "checking for dld_link in -ldld... $ECHO_C" >&6; } +if test "${ac_cv_lib_dld_dld_link+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldld $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char dld_link (); +int +main () +{ +return dld_link (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + ac_cv_lib_dld_dld_link=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_lib_dld_dld_link=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ echo "$as_me:$LINENO: result: $ac_cv_lib_dld_dld_link" >&5 +echo "${ECHO_T}$ac_cv_lib_dld_dld_link" >&6; } +if test $ac_cv_lib_dld_dld_link = yes; then + lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-dld" +fi + + +fi + + +fi + + +fi + + +fi + + +fi + + ;; + esac + + if test "x$lt_cv_dlopen" != xno; then + enable_dlopen=yes + else + enable_dlopen=no + fi + + case $lt_cv_dlopen in + dlopen) + save_CPPFLAGS="$CPPFLAGS" + test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" + + save_LDFLAGS="$LDFLAGS" + wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" + + save_LIBS="$LIBS" + LIBS="$lt_cv_dlopen_libs $LIBS" + + { echo "$as_me:$LINENO: checking whether a program can dlopen itself" >&5 +echo $ECHO_N "checking whether a program can dlopen itself... $ECHO_C" >&6; } +if test "${lt_cv_dlopen_self+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test "$cross_compiling" = yes; then : + lt_cv_dlopen_self=cross +else + lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 + lt_status=$lt_dlunknown + cat > conftest.$ac_ext < +#endif + +#include + +#ifdef RTLD_GLOBAL +# define LT_DLGLOBAL RTLD_GLOBAL +#else +# ifdef DL_GLOBAL +# define LT_DLGLOBAL DL_GLOBAL +# else +# define LT_DLGLOBAL 0 +# endif +#endif + +/* We may have to define LT_DLLAZY_OR_NOW in the command line if we + find out it does not work in some platform. */ +#ifndef LT_DLLAZY_OR_NOW +# ifdef RTLD_LAZY +# define LT_DLLAZY_OR_NOW RTLD_LAZY +# else +# ifdef DL_LAZY +# define LT_DLLAZY_OR_NOW DL_LAZY +# else +# ifdef RTLD_NOW +# define LT_DLLAZY_OR_NOW RTLD_NOW +# else +# ifdef DL_NOW +# define LT_DLLAZY_OR_NOW DL_NOW +# else +# define LT_DLLAZY_OR_NOW 0 +# endif +# endif +# endif +# endif +#endif + +#ifdef __cplusplus +extern "C" void exit (int); +#endif + +void fnord() { int i=42;} +int main () +{ + void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); + int status = $lt_dlunknown; + + if (self) + { + if (dlsym (self,"fnord")) status = $lt_dlno_uscore; + else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; + /* dlclose (self); */ + } + else + puts (dlerror ()); + + exit (status); +} +EOF + if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && test -s conftest${ac_exeext} 2>/dev/null; then + (./conftest; exit; ) >&5 2>/dev/null + lt_status=$? + case x$lt_status in + x$lt_dlno_uscore) lt_cv_dlopen_self=yes ;; + x$lt_dlneed_uscore) lt_cv_dlopen_self=yes ;; + x$lt_dlunknown|x*) lt_cv_dlopen_self=no ;; + esac + else : + # compilation failed + lt_cv_dlopen_self=no + fi +fi +rm -fr conftest* + + +fi +{ echo "$as_me:$LINENO: result: $lt_cv_dlopen_self" >&5 +echo "${ECHO_T}$lt_cv_dlopen_self" >&6; } + + if test "x$lt_cv_dlopen_self" = xyes; then + wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\" + { echo "$as_me:$LINENO: checking whether a statically linked program can dlopen itself" >&5 +echo $ECHO_N "checking whether a statically linked program can dlopen itself... $ECHO_C" >&6; } +if test "${lt_cv_dlopen_self_static+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test "$cross_compiling" = yes; then : + lt_cv_dlopen_self_static=cross +else + lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 + lt_status=$lt_dlunknown + cat > conftest.$ac_ext < +#endif + +#include + +#ifdef RTLD_GLOBAL +# define LT_DLGLOBAL RTLD_GLOBAL +#else +# ifdef DL_GLOBAL +# define LT_DLGLOBAL DL_GLOBAL +# else +# define LT_DLGLOBAL 0 +# endif +#endif + +/* We may have to define LT_DLLAZY_OR_NOW in the command line if we + find out it does not work in some platform. */ +#ifndef LT_DLLAZY_OR_NOW +# ifdef RTLD_LAZY +# define LT_DLLAZY_OR_NOW RTLD_LAZY +# else +# ifdef DL_LAZY +# define LT_DLLAZY_OR_NOW DL_LAZY +# else +# ifdef RTLD_NOW +# define LT_DLLAZY_OR_NOW RTLD_NOW +# else +# ifdef DL_NOW +# define LT_DLLAZY_OR_NOW DL_NOW +# else +# define LT_DLLAZY_OR_NOW 0 +# endif +# endif +# endif +# endif +#endif + +#ifdef __cplusplus +extern "C" void exit (int); +#endif + +void fnord() { int i=42;} +int main () +{ + void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); + int status = $lt_dlunknown; + + if (self) + { + if (dlsym (self,"fnord")) status = $lt_dlno_uscore; + else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; + /* dlclose (self); */ + } + else + puts (dlerror ()); + + exit (status); +} +EOF + if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && test -s conftest${ac_exeext} 2>/dev/null; then + (./conftest; exit; ) >&5 2>/dev/null + lt_status=$? + case x$lt_status in + x$lt_dlno_uscore) lt_cv_dlopen_self_static=yes ;; + x$lt_dlneed_uscore) lt_cv_dlopen_self_static=yes ;; + x$lt_dlunknown|x*) lt_cv_dlopen_self_static=no ;; + esac + else : + # compilation failed + lt_cv_dlopen_self_static=no + fi +fi +rm -fr conftest* + + +fi +{ echo "$as_me:$LINENO: result: $lt_cv_dlopen_self_static" >&5 +echo "${ECHO_T}$lt_cv_dlopen_self_static" >&6; } + fi + + CPPFLAGS="$save_CPPFLAGS" + LDFLAGS="$save_LDFLAGS" + LIBS="$save_LIBS" + ;; + esac + + case $lt_cv_dlopen_self in + yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; + *) enable_dlopen_self=unknown ;; + esac + + case $lt_cv_dlopen_self_static in + yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; + *) enable_dlopen_self_static=unknown ;; + esac +fi + + +# Report which library types will actually be built +{ echo "$as_me:$LINENO: checking if libtool supports shared libraries" >&5 +echo $ECHO_N "checking if libtool supports shared libraries... $ECHO_C" >&6; } +{ echo "$as_me:$LINENO: result: $can_build_shared" >&5 +echo "${ECHO_T}$can_build_shared" >&6; } + +{ echo "$as_me:$LINENO: checking whether to build shared libraries" >&5 +echo $ECHO_N "checking whether to build shared libraries... $ECHO_C" >&6; } +test "$can_build_shared" = "no" && enable_shared=no + +# On AIX, shared libraries and static libraries use the same namespace, and +# are all built from PIC. +case $host_os in +aix3*) + test "$enable_shared" = yes && enable_static=no + if test -n "$RANLIB"; then + archive_cmds="$archive_cmds~\$RANLIB \$lib" + postinstall_cmds='$RANLIB $lib' + fi + ;; + +aix4* | aix5*) + if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then + test "$enable_shared" = yes && enable_static=no + fi + ;; +esac +{ echo "$as_me:$LINENO: result: $enable_shared" >&5 +echo "${ECHO_T}$enable_shared" >&6; } + +{ echo "$as_me:$LINENO: checking whether to build static libraries" >&5 +echo $ECHO_N "checking whether to build static libraries... $ECHO_C" >&6; } +# Make sure either enable_shared or enable_static is yes. +test "$enable_shared" = yes || enable_static=yes +{ echo "$as_me:$LINENO: result: $enable_static" >&5 +echo "${ECHO_T}$enable_static" >&6; } + +# The else clause should only fire when bootstrapping the +# libtool distribution, otherwise you forgot to ship ltmain.sh +# with your package, and you will get complaints that there are +# no rules to generate ltmain.sh. +if test -f "$ltmain"; then + # See if we are running on zsh, and set the options which allow our commands through + # without removal of \ escapes. + if test -n "${ZSH_VERSION+set}" ; then + setopt NO_GLOB_SUBST + fi + # Now quote all the things that may contain metacharacters while being + # careful not to overquote the AC_SUBSTed values. We take copies of the + # variables and quote the copies for generation of the libtool script. + for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTCFLAGS NM \ + SED SHELL STRIP \ + libname_spec library_names_spec soname_spec extract_expsyms_cmds \ + old_striplib striplib file_magic_cmd finish_cmds finish_eval \ + deplibs_check_method reload_flag reload_cmds need_locks \ + lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \ + lt_cv_sys_global_symbol_to_c_name_address \ + sys_lib_search_path_spec sys_lib_dlsearch_path_spec \ + old_postinstall_cmds old_postuninstall_cmds \ + compiler \ + CC \ + LD \ + lt_prog_compiler_wl \ + lt_prog_compiler_pic \ + lt_prog_compiler_static \ + lt_prog_compiler_no_builtin_flag \ + export_dynamic_flag_spec \ + thread_safe_flag_spec \ + whole_archive_flag_spec \ + enable_shared_with_static_runtimes \ + old_archive_cmds \ + old_archive_from_new_cmds \ + predep_objects \ + postdep_objects \ + predeps \ + postdeps \ + compiler_lib_search_path \ + archive_cmds \ + archive_expsym_cmds \ + postinstall_cmds \ + postuninstall_cmds \ + old_archive_from_expsyms_cmds \ + allow_undefined_flag \ + no_undefined_flag \ + export_symbols_cmds \ + hardcode_libdir_flag_spec \ + hardcode_libdir_flag_spec_ld \ + hardcode_libdir_separator \ + hardcode_automatic \ + module_cmds \ + module_expsym_cmds \ + lt_cv_prog_compiler_c_o \ + fix_srcfile_path \ + exclude_expsyms \ + include_expsyms; do + + case $var in + old_archive_cmds | \ + old_archive_from_new_cmds | \ + archive_cmds | \ + archive_expsym_cmds | \ + module_cmds | \ + module_expsym_cmds | \ + old_archive_from_expsyms_cmds | \ + export_symbols_cmds | \ + extract_expsyms_cmds | reload_cmds | finish_cmds | \ + postinstall_cmds | postuninstall_cmds | \ + old_postinstall_cmds | old_postuninstall_cmds | \ + sys_lib_search_path_spec | sys_lib_dlsearch_path_spec) + # Double-quote double-evaled strings. + eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\"" + ;; + *) + eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`\\\"" + ;; + esac + done + + case $lt_echo in + *'\$0 --fallback-echo"') + lt_echo=`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$/$0 --fallback-echo"/'` + ;; + esac + +cfgfile="${ofile}T" + trap "$rm \"$cfgfile\"; exit 1" 1 2 15 + $rm -f "$cfgfile" + { echo "$as_me:$LINENO: creating $ofile" >&5 +echo "$as_me: creating $ofile" >&6;} + + cat <<__EOF__ >> "$cfgfile" +#! $SHELL + +# `$echo "$cfgfile" | sed 's%^.*/%%'` - Provide generalized library-building support services. +# Generated automatically by $PROGRAM (GNU $PACKAGE $VERSION$TIMESTAMP) +# NOTE: Changes made to this file will be lost: look at ltmain.sh. +# +# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 +# Free Software Foundation, Inc. +# +# This file is part of GNU Libtool: +# Originally by Gordon Matzigkeit , 1996 +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# A sed program that does not truncate output. +SED=$lt_SED + +# Sed that helps us avoid accidentally triggering echo(1) options like -n. +Xsed="$SED -e 1s/^X//" + +# The HP-UX ksh and POSIX shell print the target directory to stdout +# if CDPATH is set. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + +# The names of the tagged configurations supported by this script. +available_tags= + +# ### BEGIN LIBTOOL CONFIG + +# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: + +# Shell to use when invoking shell scripts. +SHELL=$lt_SHELL + +# Whether or not to build shared libraries. +build_libtool_libs=$enable_shared + +# Whether or not to build static libraries. +build_old_libs=$enable_static + +# Whether or not to add -lc for building shared libraries. +build_libtool_need_lc=$archive_cmds_need_lc + +# Whether or not to disallow shared libs when runtime libs are static +allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes + +# Whether or not to optimize for fast installation. +fast_install=$enable_fast_install + +# The host system. +host_alias=$host_alias +host=$host +host_os=$host_os + +# The build system. +build_alias=$build_alias +build=$build +build_os=$build_os + +# An echo program that does not interpret backslashes. +echo=$lt_echo + +# The archiver. +AR=$lt_AR +AR_FLAGS=$lt_AR_FLAGS + +# A C compiler. +LTCC=$lt_LTCC + +# LTCC compiler flags. +LTCFLAGS=$lt_LTCFLAGS + +# A language-specific compiler. +CC=$lt_compiler + +# Is the compiler the GNU C compiler? +with_gcc=$GCC + +# An ERE matcher. +EGREP=$lt_EGREP + +# The linker used to build libraries. +LD=$lt_LD + +# Whether we need hard or soft links. +LN_S=$lt_LN_S + +# A BSD-compatible nm program. +NM=$lt_NM + +# A symbol stripping program +STRIP=$lt_STRIP + +# Used to examine libraries when file_magic_cmd begins "file" +MAGIC_CMD=$MAGIC_CMD + +# Used on cygwin: DLL creation program. +DLLTOOL="$DLLTOOL" + +# Used on cygwin: object dumper. +OBJDUMP="$OBJDUMP" + +# Used on cygwin: assembler. +AS="$AS" + +# The name of the directory that contains temporary libtool files. +objdir=$objdir + +# How to create reloadable object files. +reload_flag=$lt_reload_flag +reload_cmds=$lt_reload_cmds + +# How to pass a linker flag through the compiler. +wl=$lt_lt_prog_compiler_wl + +# Object file suffix (normally "o"). +objext="$ac_objext" + +# Old archive suffix (normally "a"). +libext="$libext" + +# Shared library suffix (normally ".so"). +shrext_cmds='$shrext_cmds' + +# Executable file suffix (normally ""). +exeext="$exeext" + +# Additional compiler flags for building library objects. +pic_flag=$lt_lt_prog_compiler_pic +pic_mode=$pic_mode + +# What is the maximum length of a command? +max_cmd_len=$lt_cv_sys_max_cmd_len + +# Does compiler simultaneously support -c and -o options? +compiler_c_o=$lt_lt_cv_prog_compiler_c_o + +# Must we lock files when doing compilation? +need_locks=$lt_need_locks + +# Do we need the lib prefix for modules? +need_lib_prefix=$need_lib_prefix + +# Do we need a version for libraries? +need_version=$need_version + +# Whether dlopen is supported. +dlopen_support=$enable_dlopen + +# Whether dlopen of programs is supported. +dlopen_self=$enable_dlopen_self + +# Whether dlopen of statically linked programs is supported. +dlopen_self_static=$enable_dlopen_self_static + +# Compiler flag to prevent dynamic linking. +link_static_flag=$lt_lt_prog_compiler_static + +# Compiler flag to turn off builtin functions. +no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag + +# Compiler flag to allow reflexive dlopens. +export_dynamic_flag_spec=$lt_export_dynamic_flag_spec + +# Compiler flag to generate shared objects directly from archives. +whole_archive_flag_spec=$lt_whole_archive_flag_spec + +# Compiler flag to generate thread-safe objects. +thread_safe_flag_spec=$lt_thread_safe_flag_spec + +# Library versioning type. +version_type=$version_type + +# Format of library name prefix. +libname_spec=$lt_libname_spec + +# List of archive names. First name is the real one, the rest are links. +# The last name is the one that the linker finds with -lNAME. +library_names_spec=$lt_library_names_spec + +# The coded name of the library, if different from the real name. +soname_spec=$lt_soname_spec + +# Commands used to build and install an old-style archive. +RANLIB=$lt_RANLIB +old_archive_cmds=$lt_old_archive_cmds +old_postinstall_cmds=$lt_old_postinstall_cmds +old_postuninstall_cmds=$lt_old_postuninstall_cmds + +# Create an old-style archive from a shared archive. +old_archive_from_new_cmds=$lt_old_archive_from_new_cmds + +# Create a temporary old-style archive to link instead of a shared archive. +old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds + +# Commands used to build and install a shared archive. +archive_cmds=$lt_archive_cmds +archive_expsym_cmds=$lt_archive_expsym_cmds +postinstall_cmds=$lt_postinstall_cmds +postuninstall_cmds=$lt_postuninstall_cmds + +# Commands used to build a loadable module (assumed same as above if empty) +module_cmds=$lt_module_cmds +module_expsym_cmds=$lt_module_expsym_cmds + +# Commands to strip libraries. +old_striplib=$lt_old_striplib +striplib=$lt_striplib + +# Dependencies to place before the objects being linked to create a +# shared library. +predep_objects=$lt_predep_objects + +# Dependencies to place after the objects being linked to create a +# shared library. +postdep_objects=$lt_postdep_objects + +# Dependencies to place before the objects being linked to create a +# shared library. +predeps=$lt_predeps + +# Dependencies to place after the objects being linked to create a +# shared library. +postdeps=$lt_postdeps + +# The library search path used internally by the compiler when linking +# a shared library. +compiler_lib_search_path=$lt_compiler_lib_search_path + +# Method to check whether dependent libraries are shared objects. +deplibs_check_method=$lt_deplibs_check_method + +# Command to use when deplibs_check_method == file_magic. +file_magic_cmd=$lt_file_magic_cmd + +# Flag that allows shared libraries with undefined symbols to be built. +allow_undefined_flag=$lt_allow_undefined_flag + +# Flag that forces no undefined symbols. +no_undefined_flag=$lt_no_undefined_flag + +# Commands used to finish a libtool library installation in a directory. +finish_cmds=$lt_finish_cmds + +# Same as above, but a single script fragment to be evaled but not shown. +finish_eval=$lt_finish_eval + +# Take the output of nm and produce a listing of raw symbols and C names. +global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe + +# Transform the output of nm in a proper C declaration +global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl + +# Transform the output of nm in a C name address pair +global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address + +# This is the shared library runtime path variable. +runpath_var=$runpath_var + +# This is the shared library path variable. +shlibpath_var=$shlibpath_var + +# Is shlibpath searched before the hard-coded library search path? +shlibpath_overrides_runpath=$shlibpath_overrides_runpath + +# How to hardcode a shared library path into an executable. +hardcode_action=$hardcode_action + +# Whether we should hardcode library paths into libraries. +hardcode_into_libs=$hardcode_into_libs + +# Flag to hardcode \$libdir into a binary during linking. +# This must work even if \$libdir does not exist. +hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec + +# If ld is used when linking, flag to hardcode \$libdir into +# a binary during linking. This must work even if \$libdir does +# not exist. +hardcode_libdir_flag_spec_ld=$lt_hardcode_libdir_flag_spec_ld + +# Whether we need a single -rpath flag with a separated argument. +hardcode_libdir_separator=$lt_hardcode_libdir_separator + +# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the +# resulting binary. +hardcode_direct=$hardcode_direct + +# Set to yes if using the -LDIR flag during linking hardcodes DIR into the +# resulting binary. +hardcode_minus_L=$hardcode_minus_L + +# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into +# the resulting binary. +hardcode_shlibpath_var=$hardcode_shlibpath_var + +# Set to yes if building a shared library automatically hardcodes DIR into the library +# and all subsequent libraries and executables linked against it. +hardcode_automatic=$hardcode_automatic + +# Variables whose values should be saved in libtool wrapper scripts and +# restored at relink time. +variables_saved_for_relink="$variables_saved_for_relink" + +# Whether libtool must link a program against all its dependency libraries. +link_all_deplibs=$link_all_deplibs + +# Compile-time system search path for libraries +sys_lib_search_path_spec=$lt_sys_lib_search_path_spec + +# Run-time system search path for libraries +sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec + +# Fix the shell variable \$srcfile for the compiler. +fix_srcfile_path=$lt_fix_srcfile_path + +# Set to yes if exported symbols are required. +always_export_symbols=$always_export_symbols + +# The commands to list exported symbols. +export_symbols_cmds=$lt_export_symbols_cmds + +# The commands to extract the exported symbol list from a shared archive. +extract_expsyms_cmds=$lt_extract_expsyms_cmds + +# Symbols that should not be listed in the preloaded symbols. +exclude_expsyms=$lt_exclude_expsyms + +# Symbols that must always be exported. +include_expsyms=$lt_include_expsyms + +# ### END LIBTOOL CONFIG + +__EOF__ + + + case $host_os in + aix3*) + cat <<\EOF >> "$cfgfile" + +# AIX sometimes has problems with the GCC collect2 program. For some +# reason, if we set the COLLECT_NAMES environment variable, the problems +# vanish in a puff of smoke. +if test "X${COLLECT_NAMES+set}" != Xset; then + COLLECT_NAMES= + export COLLECT_NAMES +fi +EOF + ;; + esac + + # We use sed instead of cat because bash on DJGPP gets confused if + # if finds mixed CR/LF and LF-only lines. Since sed operates in + # text mode, it properly converts lines to CR/LF. This bash problem + # is reportedly fixed, but why not run on old versions too? + sed '$q' "$ltmain" >> "$cfgfile" || (rm -f "$cfgfile"; exit 1) + + mv -f "$cfgfile" "$ofile" || \ + (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") + chmod +x "$ofile" + +else + # If there is no Makefile yet, we rely on a make rule to execute + # `config.status --recheck' to rerun these tests and create the + # libtool script then. + ltmain_in=`echo $ltmain | sed -e 's/\.sh$/.in/'` + if test -f "$ltmain_in"; then + test -f Makefile && make "$ltmain" + fi +fi + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +CC="$lt_save_CC" + + +# Check whether --with-tags was given. +if test "${with_tags+set}" = set; then + withval=$with_tags; tagnames="$withval" +fi + + +if test -f "$ltmain" && test -n "$tagnames"; then + if test ! -f "${ofile}"; then + { echo "$as_me:$LINENO: WARNING: output file \`$ofile' does not exist" >&5 +echo "$as_me: WARNING: output file \`$ofile' does not exist" >&2;} + fi + + if test -z "$LTCC"; then + eval "`$SHELL ${ofile} --config | grep '^LTCC='`" + if test -z "$LTCC"; then + { echo "$as_me:$LINENO: WARNING: output file \`$ofile' does not look like a libtool script" >&5 +echo "$as_me: WARNING: output file \`$ofile' does not look like a libtool script" >&2;} + else + { echo "$as_me:$LINENO: WARNING: using \`LTCC=$LTCC', extracted from \`$ofile'" >&5 +echo "$as_me: WARNING: using \`LTCC=$LTCC', extracted from \`$ofile'" >&2;} + fi + fi + if test -z "$LTCFLAGS"; then + eval "`$SHELL ${ofile} --config | grep '^LTCFLAGS='`" + fi + + # Extract list of available tagged configurations in $ofile. + # Note that this assumes the entire list is on one line. + available_tags=`grep "^available_tags=" "${ofile}" | $SED -e 's/available_tags=\(.*$\)/\1/' -e 's/\"//g'` + + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for tagname in $tagnames; do + IFS="$lt_save_ifs" + # Check whether tagname contains only valid characters + case `$echo "X$tagname" | $Xsed -e 's:[-_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890,/]::g'` in + "") ;; + *) { { echo "$as_me:$LINENO: error: invalid tag name: $tagname" >&5 +echo "$as_me: error: invalid tag name: $tagname" >&2;} + { (exit 1); exit 1; }; } + ;; + esac + + if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$" < "${ofile}" > /dev/null + then + { { echo "$as_me:$LINENO: error: tag name \"$tagname\" already exists" >&5 +echo "$as_me: error: tag name \"$tagname\" already exists" >&2;} + { (exit 1); exit 1; }; } + fi + + # Update the list of available tags. + if test -n "$tagname"; then + echo appending configuration tag \"$tagname\" to $ofile + + case $tagname in + CXX) + if test -n "$CXX" && ( test "X$CXX" != "Xno" && + ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) || + (test "X$CXX" != "Xg++"))) ; then + ac_ext=cpp +ac_cpp='$CXXCPP $CPPFLAGS' +ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_cxx_compiler_gnu + + + + +archive_cmds_need_lc_CXX=no +allow_undefined_flag_CXX= +always_export_symbols_CXX=no +archive_expsym_cmds_CXX= +export_dynamic_flag_spec_CXX= +hardcode_direct_CXX=no +hardcode_libdir_flag_spec_CXX= +hardcode_libdir_flag_spec_ld_CXX= +hardcode_libdir_separator_CXX= +hardcode_minus_L_CXX=no +hardcode_shlibpath_var_CXX=unsupported +hardcode_automatic_CXX=no +module_cmds_CXX= +module_expsym_cmds_CXX= +link_all_deplibs_CXX=unknown +old_archive_cmds_CXX=$old_archive_cmds +no_undefined_flag_CXX= +whole_archive_flag_spec_CXX= +enable_shared_with_static_runtimes_CXX=no + +# Dependencies to place before and after the object being linked: +predep_objects_CXX= +postdep_objects_CXX= +predeps_CXX= +postdeps_CXX= +compiler_lib_search_path_CXX= + +# Source file extension for C++ test sources. +ac_ext=cpp + +# Object file extension for compiled C++ test sources. +objext=o +objext_CXX=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code="int some_variable = 0;" + +# Code to be used in simple link tests +lt_simple_link_test_code='int main(int, char *[]) { return(0); }' + +# ltmain only uses $CC for tagged configurations so make sure $CC is set. + +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} + +# If no C compiler flags were specified, use CFLAGS. +LTCFLAGS=${LTCFLAGS-"$CFLAGS"} + +# Allow CC to be a program name with arguments. +compiler=$CC + + +# save warnings/boilerplate of simple test code +ac_outfile=conftest.$ac_objext +echo "$lt_simple_compile_test_code" >conftest.$ac_ext +eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_compiler_boilerplate=`cat conftest.err` +$rm conftest* + +ac_outfile=conftest.$ac_objext +echo "$lt_simple_link_test_code" >conftest.$ac_ext +eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_linker_boilerplate=`cat conftest.err` +$rm conftest* + + +# Allow CC to be a program name with arguments. +lt_save_CC=$CC +lt_save_LD=$LD +lt_save_GCC=$GCC +GCC=$GXX +lt_save_with_gnu_ld=$with_gnu_ld +lt_save_path_LD=$lt_cv_path_LD +if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then + lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx +else + $as_unset lt_cv_prog_gnu_ld +fi +if test -n "${lt_cv_path_LDCXX+set}"; then + lt_cv_path_LD=$lt_cv_path_LDCXX +else + $as_unset lt_cv_path_LD +fi +test -z "${LDCXX+set}" || LD=$LDCXX +CC=${CXX-"c++"} +compiler=$CC +compiler_CXX=$CC +for cc_temp in $compiler""; do + case $cc_temp in + compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; + distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; + \-*) ;; + *) break;; + esac +done +cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"` + + +# We don't want -fno-exception wen compiling C++ code, so set the +# no_builtin_flag separately +if test "$GXX" = yes; then + lt_prog_compiler_no_builtin_flag_CXX=' -fno-builtin' +else + lt_prog_compiler_no_builtin_flag_CXX= +fi + +if test "$GXX" = yes; then + # Set up default GNU C++ configuration + + +# Check whether --with-gnu-ld was given. +if test "${with_gnu_ld+set}" = set; then + withval=$with_gnu_ld; test "$withval" = no || with_gnu_ld=yes +else + with_gnu_ld=no +fi + +ac_prog=ld +if test "$GCC" = yes; then + # Check if gcc -print-prog-name=ld gives a path. + { echo "$as_me:$LINENO: checking for ld used by $CC" >&5 +echo $ECHO_N "checking for ld used by $CC... $ECHO_C" >&6; } + case $host in + *-*-mingw*) + # gcc leaves a trailing carriage return which upsets mingw + ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; + *) + ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; + esac + case $ac_prog in + # Accept absolute paths. + [\\/]* | ?:[\\/]*) + re_direlt='/[^/][^/]*/\.\./' + # Canonicalize the pathname of ld + ac_prog=`echo $ac_prog| $SED 's%\\\\%/%g'` + while echo $ac_prog | grep "$re_direlt" > /dev/null 2>&1; do + ac_prog=`echo $ac_prog| $SED "s%$re_direlt%/%"` + done + test -z "$LD" && LD="$ac_prog" + ;; + "") + # If it fails, then pretend we aren't using GCC. + ac_prog=ld + ;; + *) + # If it is relative, then search for the first ld in PATH. + with_gnu_ld=unknown + ;; + esac +elif test "$with_gnu_ld" = yes; then + { echo "$as_me:$LINENO: checking for GNU ld" >&5 +echo $ECHO_N "checking for GNU ld... $ECHO_C" >&6; } +else + { echo "$as_me:$LINENO: checking for non-GNU ld" >&5 +echo $ECHO_N "checking for non-GNU ld... $ECHO_C" >&6; } +fi +if test "${lt_cv_path_LD+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -z "$LD"; then + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + for ac_dir in $PATH; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then + lt_cv_path_LD="$ac_dir/$ac_prog" + # Check to see if the program is GNU ld. I'd rather use --version, + # but apparently some variants of GNU ld only accept -v. + # Break only if it was the GNU/non-GNU ld that we prefer. + case `"$lt_cv_path_LD" -v 2>&1 &5 +echo "${ECHO_T}$LD" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi +test -z "$LD" && { { echo "$as_me:$LINENO: error: no acceptable ld found in \$PATH" >&5 +echo "$as_me: error: no acceptable ld found in \$PATH" >&2;} + { (exit 1); exit 1; }; } +{ echo "$as_me:$LINENO: checking if the linker ($LD) is GNU ld" >&5 +echo $ECHO_N "checking if the linker ($LD) is GNU ld... $ECHO_C" >&6; } +if test "${lt_cv_prog_gnu_ld+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + # I'd rather use --version here, but apparently some GNU lds only accept -v. +case `$LD -v 2>&1 &5 +echo "${ECHO_T}$lt_cv_prog_gnu_ld" >&6; } +with_gnu_ld=$lt_cv_prog_gnu_ld + + + + # Check if GNU C++ uses GNU ld as the underlying linker, since the + # archiving commands below assume that GNU ld is being used. + if test "$with_gnu_ld" = yes; then + archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + + hardcode_libdir_flag_spec_CXX='${wl}--rpath ${wl}$libdir' + export_dynamic_flag_spec_CXX='${wl}--export-dynamic' + + # If archive_cmds runs LD, not CC, wlarc should be empty + # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to + # investigate it a little bit more. (MM) + wlarc='${wl}' + + # ancient GNU ld didn't support --whole-archive et. al. + if eval "`$CC -print-prog-name=ld` --help 2>&1" | \ + grep 'no-whole-archive' > /dev/null; then + whole_archive_flag_spec_CXX="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' + else + whole_archive_flag_spec_CXX= + fi + else + with_gnu_ld=no + wlarc= + + # A generic and very simple default shared library creation + # command for GNU C++ for the case where it uses the native + # linker, instead of GNU ld. If possible, this setting should + # overridden to take advantage of the native linker features on + # the platform it is being used on. + archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' + fi + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "\-L"' + +else + GXX=no + with_gnu_ld=no + wlarc= +fi + +# PORTME: fill in a description of your system's C++ link characteristics +{ echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5 +echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6; } +ld_shlibs_CXX=yes +case $host_os in + aix3*) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + aix4* | aix5*) + if test "$host_cpu" = ia64; then + # On IA64, the linker does run time linking by default, so we don't + # have to do anything special. + aix_use_runtimelinking=no + exp_sym_flag='-Bexport' + no_entry_flag="" + else + aix_use_runtimelinking=no + + # Test if we are trying to use run time linking or normal + # AIX style linking. If -brtl is somewhere in LDFLAGS, we + # need to do runtime linking. + case $host_os in aix4.[23]|aix4.[23].*|aix5*) + for ld_flag in $LDFLAGS; do + case $ld_flag in + *-brtl*) + aix_use_runtimelinking=yes + break + ;; + esac + done + ;; + esac + + exp_sym_flag='-bexport' + no_entry_flag='-bnoentry' + fi + + # When large executables or shared objects are built, AIX ld can + # have problems creating the table of contents. If linking a library + # or program results in "error TOC overflow" add -mminimal-toc to + # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not + # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. + + archive_cmds_CXX='' + hardcode_direct_CXX=yes + hardcode_libdir_separator_CXX=':' + link_all_deplibs_CXX=yes + + if test "$GXX" = yes; then + case $host_os in aix4.[012]|aix4.[012].*) + # We only want to do this on AIX 4.2 and lower, the check + # below for broken collect2 doesn't work under 4.3+ + collect2name=`${CC} -print-prog-name=collect2` + if test -f "$collect2name" && \ + strings "$collect2name" | grep resolve_lib_name >/dev/null + then + # We have reworked collect2 + : + else + # We have old collect2 + hardcode_direct_CXX=unsupported + # It fails to find uninstalled libraries when the uninstalled + # path is not listed in the libpath. Setting hardcode_minus_L + # to unsupported forces relinking + hardcode_minus_L_CXX=yes + hardcode_libdir_flag_spec_CXX='-L$libdir' + hardcode_libdir_separator_CXX= + fi + ;; + esac + shared_flag='-shared' + if test "$aix_use_runtimelinking" = yes; then + shared_flag="$shared_flag "'${wl}-G' + fi + else + # not using gcc + if test "$host_cpu" = ia64; then + # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release + # chokes on -Wl,-G. The following line is correct: + shared_flag='-G' + else + if test "$aix_use_runtimelinking" = yes; then + shared_flag='${wl}-G' + else + shared_flag='${wl}-bM:SRE' + fi + fi + fi + + # It seems that -bexpall does not export symbols beginning with + # underscore (_), so it is better to generate a list of symbols to export. + always_export_symbols_CXX=yes + if test "$aix_use_runtimelinking" = yes; then + # Warning - without using the other runtime loading flags (-brtl), + # -berok will link without error, but may produce a broken library. + allow_undefined_flag_CXX='-berok' + # Determine the default libpath from the value encoded in an empty executable. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_cxx_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + +lt_aix_libpath_sed=' + /Import File Strings/,/^$/ { + /^0/ { + s/^0 *\(.*\)$/\1/ + p + } + }' +aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +# Check for a 64-bit object if we didn't find anything. +if test -z "$aix_libpath"; then + aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +fi +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi + + hardcode_libdir_flag_spec_CXX='${wl}-blibpath:$libdir:'"$aix_libpath" + + archive_expsym_cmds_CXX="\$CC"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" + else + if test "$host_cpu" = ia64; then + hardcode_libdir_flag_spec_CXX='${wl}-R $libdir:/usr/lib:/lib' + allow_undefined_flag_CXX="-z nodefs" + archive_expsym_cmds_CXX="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" + else + # Determine the default libpath from the value encoded in an empty executable. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_cxx_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + +lt_aix_libpath_sed=' + /Import File Strings/,/^$/ { + /^0/ { + s/^0 *\(.*\)$/\1/ + p + } + }' +aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +# Check for a 64-bit object if we didn't find anything. +if test -z "$aix_libpath"; then + aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +fi +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi + + hardcode_libdir_flag_spec_CXX='${wl}-blibpath:$libdir:'"$aix_libpath" + # Warning - without using the other run time loading flags, + # -berok will link without error, but may produce a broken library. + no_undefined_flag_CXX=' ${wl}-bernotok' + allow_undefined_flag_CXX=' ${wl}-berok' + # Exported symbols can be pulled into shared objects from archives + whole_archive_flag_spec_CXX='$convenience' + archive_cmds_need_lc_CXX=yes + # This is similar to how AIX traditionally builds its shared libraries. + archive_expsym_cmds_CXX="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' + fi + fi + ;; + + beos*) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + allow_undefined_flag_CXX=unsupported + # Joseph Beckenbach says some releases of gcc + # support --undefined. This deserves some investigation. FIXME + archive_cmds_CXX='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + else + ld_shlibs_CXX=no + fi + ;; + + chorus*) + case $cc_basename in + *) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + esac + ;; + + cygwin* | mingw* | pw32*) + # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, CXX) is actually meaningless, + # as there is no search path for DLLs. + hardcode_libdir_flag_spec_CXX='-L$libdir' + allow_undefined_flag_CXX=unsupported + always_export_symbols_CXX=no + enable_shared_with_static_runtimes_CXX=yes + + if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then + archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + # If the export-symbols file already is a .def file (1st line + # is EXPORTS), use it as is; otherwise, prepend... + archive_expsym_cmds_CXX='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then + cp $export_symbols $output_objdir/$soname.def; + else + echo EXPORTS > $output_objdir/$soname.def; + cat $export_symbols >> $output_objdir/$soname.def; + fi~ + $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + else + ld_shlibs_CXX=no + fi + ;; + darwin* | rhapsody*) + case $host_os in + rhapsody* | darwin1.[012]) + allow_undefined_flag_CXX='${wl}-undefined ${wl}suppress' + ;; + *) # Darwin 1.3 on + if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then + allow_undefined_flag_CXX='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' + else + case ${MACOSX_DEPLOYMENT_TARGET} in + 10.[012]) + allow_undefined_flag_CXX='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' + ;; + 10.*) + allow_undefined_flag_CXX='${wl}-undefined ${wl}dynamic_lookup' + ;; + esac + fi + ;; + esac + archive_cmds_need_lc_CXX=no + hardcode_direct_CXX=no + hardcode_automatic_CXX=yes + hardcode_shlibpath_var_CXX=unsupported + whole_archive_flag_spec_CXX='' + link_all_deplibs_CXX=yes + + if test "$GXX" = yes ; then + lt_int_apple_cc_single_mod=no + output_verbose_link_cmd='echo' + if $CC -dumpspecs 2>&1 | $EGREP 'single_module' >/dev/null ; then + lt_int_apple_cc_single_mod=yes + fi + if test "X$lt_int_apple_cc_single_mod" = Xyes ; then + archive_cmds_CXX='$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring' + else + archive_cmds_CXX='$CC -r -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring' + fi + module_cmds_CXX='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags' + # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds + if test "X$lt_int_apple_cc_single_mod" = Xyes ; then + archive_expsym_cmds_CXX='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + else + archive_expsym_cmds_CXX='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -r -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + fi + module_expsym_cmds_CXX='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + else + case $cc_basename in + xlc*) + output_verbose_link_cmd='echo' + archive_cmds_CXX='$CC -qmkshrobj ${wl}-single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$soname` $xlcverstring' + module_cmds_CXX='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags' + # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds + archive_expsym_cmds_CXX='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -qmkshrobj ${wl}-single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}$rpath/$soname $xlcverstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + module_expsym_cmds_CXX='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + ;; + *) + ld_shlibs_CXX=no + ;; + esac + fi + ;; + + dgux*) + case $cc_basename in + ec++*) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + ghcx*) + # Green Hills C++ Compiler + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + *) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + esac + ;; + freebsd[12]*) + # C++ shared libraries reported to be fairly broken before switch to ELF + ld_shlibs_CXX=no + ;; + freebsd-elf*) + archive_cmds_need_lc_CXX=no + ;; + freebsd* | dragonfly*) + # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF + # conventions + ld_shlibs_CXX=yes + ;; + gnu*) + ;; + hpux9*) + hardcode_libdir_flag_spec_CXX='${wl}+b ${wl}$libdir' + hardcode_libdir_separator_CXX=: + export_dynamic_flag_spec_CXX='${wl}-E' + hardcode_direct_CXX=yes + hardcode_minus_L_CXX=yes # Not in the search PATH, + # but as the default + # location of the library. + + case $cc_basename in + CC*) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + aCC*) + archive_cmds_CXX='$rm $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | grep "[-]L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + ;; + *) + if test "$GXX" = yes; then + archive_cmds_CXX='$rm $output_objdir/$soname~$CC -shared -nostdlib -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + else + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + fi + ;; + esac + ;; + hpux10*|hpux11*) + if test $with_gnu_ld = no; then + hardcode_libdir_flag_spec_CXX='${wl}+b ${wl}$libdir' + hardcode_libdir_separator_CXX=: + + case $host_cpu in + hppa*64*|ia64*) ;; + *) + export_dynamic_flag_spec_CXX='${wl}-E' + ;; + esac + fi + case $host_cpu in + hppa*64*|ia64*) + hardcode_direct_CXX=no + hardcode_shlibpath_var_CXX=no + ;; + *) + hardcode_direct_CXX=yes + hardcode_minus_L_CXX=yes # Not in the search PATH, + # but as the default + # location of the library. + ;; + esac + + case $cc_basename in + CC*) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + aCC*) + case $host_cpu in + hppa*64*) + archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + ia64*) + archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + *) + archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + esac + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | grep "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + ;; + *) + if test "$GXX" = yes; then + if test $with_gnu_ld = no; then + case $host_cpu in + hppa*64*) + archive_cmds_CXX='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + ia64*) + archive_cmds_CXX='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + *) + archive_cmds_CXX='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + esac + fi + else + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + fi + ;; + esac + ;; + interix[3-9]*) + hardcode_direct_CXX=no + hardcode_shlibpath_var_CXX=no + hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' + export_dynamic_flag_spec_CXX='${wl}-E' + # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. + # Instead, shared libraries are loaded at an image base (0x10000000 by + # default) and relocated if they conflict, which is a slow very memory + # consuming and fragmenting process. To avoid this, we pick a random, + # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link + # time. Moving up from 0x10000000 also allows more sbrk(2) space. + archive_cmds_CXX='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + archive_expsym_cmds_CXX='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + ;; + irix5* | irix6*) + case $cc_basename in + CC*) + # SGI C++ + archive_cmds_CXX='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + + # Archives containing C++ object files must be created using + # "CC -ar", where "CC" is the IRIX C++ compiler. This is + # necessary to make sure instantiated templates are included + # in the archive. + old_archive_cmds_CXX='$CC -ar -WR,-u -o $oldlib $oldobjs' + ;; + *) + if test "$GXX" = yes; then + if test "$with_gnu_ld" = no; then + archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + else + archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` -o $lib' + fi + fi + link_all_deplibs_CXX=yes + ;; + esac + hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator_CXX=: + ;; + linux* | k*bsd*-gnu) + case $cc_basename in + KCC*) + # Kuck and Associates, Inc. (KAI) C++ Compiler + + # KCC will only create a shared library if the output file + # ends with ".so" (or ".sl" for HP-UX), so rename the library + # to its proper name (with version) after linking. + archive_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' + archive_expsym_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib' + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | grep "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + + hardcode_libdir_flag_spec_CXX='${wl}--rpath,$libdir' + export_dynamic_flag_spec_CXX='${wl}--export-dynamic' + + # Archives containing C++ object files must be created using + # "CC -Bstatic", where "CC" is the KAI C++ compiler. + old_archive_cmds_CXX='$CC -Bstatic -o $oldlib $oldobjs' + ;; + icpc*) + # Intel C++ + with_gnu_ld=yes + # version 8.0 and above of icpc choke on multiply defined symbols + # if we add $predep_objects and $postdep_objects, however 7.1 and + # earlier do not add the objects themselves. + case `$CC -V 2>&1` in + *"Version 7."*) + archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + ;; + *) # Version 8.0 or newer + tmp_idyn= + case $host_cpu in + ia64*) tmp_idyn=' -i_dynamic';; + esac + archive_cmds_CXX='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds_CXX='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + ;; + esac + archive_cmds_need_lc_CXX=no + hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' + export_dynamic_flag_spec_CXX='${wl}--export-dynamic' + whole_archive_flag_spec_CXX='${wl}--whole-archive$convenience ${wl}--no-whole-archive' + ;; + pgCC*) + # Portland Group C++ compiler + archive_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib' + archive_expsym_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib' + + hardcode_libdir_flag_spec_CXX='${wl}--rpath ${wl}$libdir' + export_dynamic_flag_spec_CXX='${wl}--export-dynamic' + whole_archive_flag_spec_CXX='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive' + ;; + cxx*) + # Compaq C++ + archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib ${wl}-retain-symbols-file $wl$export_symbols' + + runpath_var=LD_RUN_PATH + hardcode_libdir_flag_spec_CXX='-rpath $libdir' + hardcode_libdir_separator_CXX=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "ld"`; templist=`echo $templist | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + ;; + *) + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) + # Sun C++ 5.9 + no_undefined_flag_CXX=' -zdefs' + archive_cmds_CXX='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + archive_expsym_cmds_CXX='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file ${wl}$export_symbols' + hardcode_libdir_flag_spec_CXX='-R$libdir' + whole_archive_flag_spec_CXX='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive' + + # Not sure whether something based on + # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 + # would be better. + output_verbose_link_cmd='echo' + + # Archives containing C++ object files must be created using + # "CC -xar", where "CC" is the Sun C++ compiler. This is + # necessary to make sure instantiated templates are included + # in the archive. + old_archive_cmds_CXX='$CC -xar -o $oldlib $oldobjs' + ;; + esac + ;; + esac + ;; + lynxos*) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + m88k*) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + mvs*) + case $cc_basename in + cxx*) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + *) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + esac + ;; + netbsd*) + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + archive_cmds_CXX='$LD -Bshareable -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags' + wlarc= + hardcode_libdir_flag_spec_CXX='-R$libdir' + hardcode_direct_CXX=yes + hardcode_shlibpath_var_CXX=no + fi + # Workaround some broken pre-1.5 toolchains + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"' + ;; + openbsd2*) + # C++ shared libraries are fairly broken + ld_shlibs_CXX=no + ;; + openbsd*) + if test -f /usr/libexec/ld.so; then + hardcode_direct_CXX=yes + hardcode_shlibpath_var_CXX=no + archive_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' + hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + archive_expsym_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib' + export_dynamic_flag_spec_CXX='${wl}-E' + whole_archive_flag_spec_CXX="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' + fi + output_verbose_link_cmd='echo' + else + ld_shlibs_CXX=no + fi + ;; + osf3*) + case $cc_basename in + KCC*) + # Kuck and Associates, Inc. (KAI) C++ Compiler + + # KCC will only create a shared library if the output file + # ends with ".so" (or ".sl" for HP-UX), so rename the library + # to its proper name (with version) after linking. + archive_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' + + hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' + hardcode_libdir_separator_CXX=: + + # Archives containing C++ object files must be created using + # "CC -Bstatic", where "CC" is the KAI C++ compiler. + old_archive_cmds_CXX='$CC -Bstatic -o $oldlib $oldobjs' + + ;; + RCC*) + # Rational C++ 2.4.1 + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + cxx*) + allow_undefined_flag_CXX=' ${wl}-expect_unresolved ${wl}\*' + archive_cmds_CXX='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && echo ${wl}-set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + + hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator_CXX=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "ld" | grep -v "ld:"`; templist=`echo $templist | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + ;; + *) + if test "$GXX" = yes && test "$with_gnu_ld" = no; then + allow_undefined_flag_CXX=' ${wl}-expect_unresolved ${wl}\*' + archive_cmds_CXX='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + + hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator_CXX=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "\-L"' + + else + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + fi + ;; + esac + ;; + osf4* | osf5*) + case $cc_basename in + KCC*) + # Kuck and Associates, Inc. (KAI) C++ Compiler + + # KCC will only create a shared library if the output file + # ends with ".so" (or ".sl" for HP-UX), so rename the library + # to its proper name (with version) after linking. + archive_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' + + hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' + hardcode_libdir_separator_CXX=: + + # Archives containing C++ object files must be created using + # the KAI C++ compiler. + old_archive_cmds_CXX='$CC -o $oldlib $oldobjs' + ;; + RCC*) + # Rational C++ 2.4.1 + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + cxx*) + allow_undefined_flag_CXX=' -expect_unresolved \*' + archive_cmds_CXX='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + archive_expsym_cmds_CXX='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~ + echo "-hidden">> $lib.exp~ + $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname -Wl,-input -Wl,$lib.exp `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib~ + $rm $lib.exp' + + hardcode_libdir_flag_spec_CXX='-rpath $libdir' + hardcode_libdir_separator_CXX=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "ld" | grep -v "ld:"`; templist=`echo $templist | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + ;; + *) + if test "$GXX" = yes && test "$with_gnu_ld" = no; then + allow_undefined_flag_CXX=' ${wl}-expect_unresolved ${wl}\*' + archive_cmds_CXX='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + + hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator_CXX=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "\-L"' + + else + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + fi + ;; + esac + ;; + psos*) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + sunos4*) + case $cc_basename in + CC*) + # Sun C++ 4.x + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + lcc*) + # Lucid + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + *) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + esac + ;; + solaris*) + case $cc_basename in + CC*) + # Sun C++ 4.2, 5.x and Centerline C++ + archive_cmds_need_lc_CXX=yes + no_undefined_flag_CXX=' -zdefs' + archive_cmds_CXX='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + archive_expsym_cmds_CXX='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp' + + hardcode_libdir_flag_spec_CXX='-R$libdir' + hardcode_shlibpath_var_CXX=no + case $host_os in + solaris2.[0-5] | solaris2.[0-5].*) ;; + *) + # The compiler driver will combine and reorder linker options, + # but understands `-z linker_flag'. + # Supported since Solaris 2.6 (maybe 2.5.1?) + whole_archive_flag_spec_CXX='-z allextract$convenience -z defaultextract' + ;; + esac + link_all_deplibs_CXX=yes + + output_verbose_link_cmd='echo' + + # Archives containing C++ object files must be created using + # "CC -xar", where "CC" is the Sun C++ compiler. This is + # necessary to make sure instantiated templates are included + # in the archive. + old_archive_cmds_CXX='$CC -xar -o $oldlib $oldobjs' + ;; + gcx*) + # Green Hills C++ Compiler + archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' + + # The C++ compiler must be used to create the archive. + old_archive_cmds_CXX='$CC $LDFLAGS -archive -o $oldlib $oldobjs' + ;; + *) + # GNU C++ compiler with Solaris linker + if test "$GXX" = yes && test "$with_gnu_ld" = no; then + no_undefined_flag_CXX=' ${wl}-z ${wl}defs' + if $CC --version | grep -v '^2\.7' > /dev/null; then + archive_cmds_CXX='$CC -shared -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' + archive_expsym_cmds_CXX='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $CC -shared -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp' + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd="$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep \"\-L\"" + else + # g++ 2.7 appears to require `-G' NOT `-shared' on this + # platform. + archive_cmds_CXX='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' + archive_expsym_cmds_CXX='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp' + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd="$CC -G $CFLAGS -v conftest.$objext 2>&1 | grep \"\-L\"" + fi + + hardcode_libdir_flag_spec_CXX='${wl}-R $wl$libdir' + case $host_os in + solaris2.[0-5] | solaris2.[0-5].*) ;; + *) + whole_archive_flag_spec_CXX='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' + ;; + esac + fi + ;; + esac + ;; + sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*) + no_undefined_flag_CXX='${wl}-z,text' + archive_cmds_need_lc_CXX=no + hardcode_shlibpath_var_CXX=no + runpath_var='LD_RUN_PATH' + + case $cc_basename in + CC*) + archive_cmds_CXX='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds_CXX='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + archive_cmds_CXX='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds_CXX='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + ;; + sysv5* | sco3.2v5* | sco5v6*) + # Note: We can NOT use -z defs as we might desire, because we do not + # link with -lc, and that would cause any symbols used from libc to + # always be unresolved, which means just about no library would + # ever link correctly. If we're not using GNU ld we use -z text + # though, which does catch some bad symbols but isn't as heavy-handed + # as -z defs. + # For security reasons, it is highly recommended that you always + # use absolute paths for naming shared libraries, and exclude the + # DT_RUNPATH tag from executables and libraries. But doing so + # requires that you compile everything twice, which is a pain. + # So that behaviour is only enabled if SCOABSPATH is set to a + # non-empty value in the environment. Most likely only useful for + # creating official distributions of packages. + # This is a hack until libtool officially supports absolute path + # names for shared libraries. + no_undefined_flag_CXX='${wl}-z,text' + allow_undefined_flag_CXX='${wl}-z,nodefs' + archive_cmds_need_lc_CXX=no + hardcode_shlibpath_var_CXX=no + hardcode_libdir_flag_spec_CXX='`test -z "$SCOABSPATH" && echo ${wl}-R,$libdir`' + hardcode_libdir_separator_CXX=':' + link_all_deplibs_CXX=yes + export_dynamic_flag_spec_CXX='${wl}-Bexport' + runpath_var='LD_RUN_PATH' + + case $cc_basename in + CC*) + archive_cmds_CXX='$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds_CXX='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + archive_cmds_CXX='$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds_CXX='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + ;; + tandem*) + case $cc_basename in + NCC*) + # NonStop-UX NCC 3.20 + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + *) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + esac + ;; + vxworks*) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + *) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; +esac +{ echo "$as_me:$LINENO: result: $ld_shlibs_CXX" >&5 +echo "${ECHO_T}$ld_shlibs_CXX" >&6; } +test "$ld_shlibs_CXX" = no && can_build_shared=no + +GCC_CXX="$GXX" +LD_CXX="$LD" + + +cat > conftest.$ac_ext <&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + # Parse the compiler output and extract the necessary + # objects, libraries and library flags. + + # Sentinel used to keep track of whether or not we are before + # the conftest object file. + pre_test_object_deps_done=no + + # The `*' in the case matches for architectures that use `case' in + # $output_verbose_cmd can trigger glob expansion during the loop + # eval without this substitution. + output_verbose_link_cmd=`$echo "X$output_verbose_link_cmd" | $Xsed -e "$no_glob_subst"` + + for p in `eval $output_verbose_link_cmd`; do + case $p in + + -L* | -R* | -l*) + # Some compilers place space between "-{L,R}" and the path. + # Remove the space. + if test $p = "-L" \ + || test $p = "-R"; then + prev=$p + continue + else + prev= + fi + + if test "$pre_test_object_deps_done" = no; then + case $p in + -L* | -R*) + # Internal compiler library paths should come after those + # provided the user. The postdeps already come after the + # user supplied libs so there is no need to process them. + if test -z "$compiler_lib_search_path_CXX"; then + compiler_lib_search_path_CXX="${prev}${p}" + else + compiler_lib_search_path_CXX="${compiler_lib_search_path_CXX} ${prev}${p}" + fi + ;; + # The "-l" case would never come before the object being + # linked, so don't bother handling this case. + esac + else + if test -z "$postdeps_CXX"; then + postdeps_CXX="${prev}${p}" + else + postdeps_CXX="${postdeps_CXX} ${prev}${p}" + fi + fi + ;; + + *.$objext) + # This assumes that the test object file only shows up + # once in the compiler output. + if test "$p" = "conftest.$objext"; then + pre_test_object_deps_done=yes + continue + fi + + if test "$pre_test_object_deps_done" = no; then + if test -z "$predep_objects_CXX"; then + predep_objects_CXX="$p" + else + predep_objects_CXX="$predep_objects_CXX $p" + fi + else + if test -z "$postdep_objects_CXX"; then + postdep_objects_CXX="$p" + else + postdep_objects_CXX="$postdep_objects_CXX $p" + fi + fi + ;; + + *) ;; # Ignore the rest. + + esac + done + + # Clean up. + rm -f a.out a.exe +else + echo "libtool.m4: error: problem compiling CXX test program" +fi + +$rm -f confest.$objext + +# PORTME: override above test on systems where it is broken +case $host_os in +interix[3-9]*) + # Interix 3.5 installs completely hosed .la files for C++, so rather than + # hack all around it, let's just trust "g++" to DTRT. + predep_objects_CXX= + postdep_objects_CXX= + postdeps_CXX= + ;; + +linux*) + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) + # Sun C++ 5.9 + # + # The more standards-conforming stlport4 library is + # incompatible with the Cstd library. Avoid specifying + # it if it's in CXXFLAGS. Ignore libCrun as + # -library=stlport4 depends on it. + case " $CXX $CXXFLAGS " in + *" -library=stlport4 "*) + solaris_use_stlport4=yes + ;; + esac + if test "$solaris_use_stlport4" != yes; then + postdeps_CXX='-library=Cstd -library=Crun' + fi + ;; + esac + ;; + +solaris*) + case $cc_basename in + CC*) + # The more standards-conforming stlport4 library is + # incompatible with the Cstd library. Avoid specifying + # it if it's in CXXFLAGS. Ignore libCrun as + # -library=stlport4 depends on it. + case " $CXX $CXXFLAGS " in + *" -library=stlport4 "*) + solaris_use_stlport4=yes + ;; + esac + + # Adding this requires a known-good setup of shared libraries for + # Sun compiler versions before 5.6, else PIC objects from an old + # archive will be linked into the output, leading to subtle bugs. + if test "$solaris_use_stlport4" != yes; then + postdeps_CXX='-library=Cstd -library=Crun' + fi + ;; + esac + ;; +esac + + +case " $postdeps_CXX " in +*" -lc "*) archive_cmds_need_lc_CXX=no ;; +esac + +lt_prog_compiler_wl_CXX= +lt_prog_compiler_pic_CXX= +lt_prog_compiler_static_CXX= + +{ echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5 +echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6; } + + # C++ specific cases for pic, static, wl, etc. + if test "$GXX" = yes; then + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_static_CXX='-static' + + case $host_os in + aix*) + # All AIX code is PIC. + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static_CXX='-Bstatic' + fi + ;; + amigaos*) + # FIXME: we need at least 68020 code to build shared libraries, but + # adding the `-m68020' flag to GCC prevents building anything better, + # like `-m68040'. + lt_prog_compiler_pic_CXX='-m68020 -resident32 -malways-restore-a4' + ;; + beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) + # PIC is the default for these OSes. + ;; + mingw* | cygwin* | os2* | pw32*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + # Although the cygwin gcc ignores -fPIC, still need this for old-style + # (--disable-auto-import) libraries + lt_prog_compiler_pic_CXX='-DDLL_EXPORT' + ;; + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + lt_prog_compiler_pic_CXX='-fno-common' + ;; + *djgpp*) + # DJGPP does not support shared libraries at all + lt_prog_compiler_pic_CXX= + ;; + interix[3-9]*) + # Interix 3.x gcc -fpic/-fPIC options generate broken code. + # Instead, we relocate shared libraries at runtime. + ;; + sysv4*MP*) + if test -d /usr/nec; then + lt_prog_compiler_pic_CXX=-Kconform_pic + fi + ;; + hpux*) + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case $host_cpu in + hppa*64*|ia64*) + ;; + *) + lt_prog_compiler_pic_CXX='-fPIC' + ;; + esac + ;; + *) + lt_prog_compiler_pic_CXX='-fPIC' + ;; + esac + else + case $host_os in + aix4* | aix5*) + # All AIX code is PIC. + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static_CXX='-Bstatic' + else + lt_prog_compiler_static_CXX='-bnso -bI:/lib/syscalls.exp' + fi + ;; + chorus*) + case $cc_basename in + cxch68*) + # Green Hills C++ Compiler + # _LT_AC_TAGVAR(lt_prog_compiler_static, CXX)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a" + ;; + esac + ;; + darwin*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + case $cc_basename in + xlc*) + lt_prog_compiler_pic_CXX='-qnocommon' + lt_prog_compiler_wl_CXX='-Wl,' + ;; + esac + ;; + dgux*) + case $cc_basename in + ec++*) + lt_prog_compiler_pic_CXX='-KPIC' + ;; + ghcx*) + # Green Hills C++ Compiler + lt_prog_compiler_pic_CXX='-pic' + ;; + *) + ;; + esac + ;; + freebsd* | dragonfly*) + # FreeBSD uses GNU C++ + ;; + hpux9* | hpux10* | hpux11*) + case $cc_basename in + CC*) + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_static_CXX='${wl}-a ${wl}archive' + if test "$host_cpu" != ia64; then + lt_prog_compiler_pic_CXX='+Z' + fi + ;; + aCC*) + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_static_CXX='${wl}-a ${wl}archive' + case $host_cpu in + hppa*64*|ia64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic_CXX='+Z' + ;; + esac + ;; + *) + ;; + esac + ;; + interix*) + # This is c89, which is MS Visual C++ (no shared libs) + # Anyone wants to do a port? + ;; + irix5* | irix6* | nonstopux*) + case $cc_basename in + CC*) + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_static_CXX='-non_shared' + # CC pic flag -KPIC is the default. + ;; + *) + ;; + esac + ;; + linux* | k*bsd*-gnu) + case $cc_basename in + KCC*) + # KAI C++ Compiler + lt_prog_compiler_wl_CXX='--backend -Wl,' + lt_prog_compiler_pic_CXX='-fPIC' + ;; + icpc* | ecpc*) + # Intel C++ + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_pic_CXX='-KPIC' + lt_prog_compiler_static_CXX='-static' + ;; + pgCC*) + # Portland Group C++ compiler. + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_pic_CXX='-fpic' + lt_prog_compiler_static_CXX='-Bstatic' + ;; + cxx*) + # Compaq C++ + # Make sure the PIC flag is empty. It appears that all Alpha + # Linux and Compaq Tru64 Unix objects are PIC. + lt_prog_compiler_pic_CXX= + lt_prog_compiler_static_CXX='-non_shared' + ;; + *) + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) + # Sun C++ 5.9 + lt_prog_compiler_pic_CXX='-KPIC' + lt_prog_compiler_static_CXX='-Bstatic' + lt_prog_compiler_wl_CXX='-Qoption ld ' + ;; + esac + ;; + esac + ;; + lynxos*) + ;; + m88k*) + ;; + mvs*) + case $cc_basename in + cxx*) + lt_prog_compiler_pic_CXX='-W c,exportall' + ;; + *) + ;; + esac + ;; + netbsd*) + ;; + osf3* | osf4* | osf5*) + case $cc_basename in + KCC*) + lt_prog_compiler_wl_CXX='--backend -Wl,' + ;; + RCC*) + # Rational C++ 2.4.1 + lt_prog_compiler_pic_CXX='-pic' + ;; + cxx*) + # Digital/Compaq C++ + lt_prog_compiler_wl_CXX='-Wl,' + # Make sure the PIC flag is empty. It appears that all Alpha + # Linux and Compaq Tru64 Unix objects are PIC. + lt_prog_compiler_pic_CXX= + lt_prog_compiler_static_CXX='-non_shared' + ;; + *) + ;; + esac + ;; + psos*) + ;; + solaris*) + case $cc_basename in + CC*) + # Sun C++ 4.2, 5.x and Centerline C++ + lt_prog_compiler_pic_CXX='-KPIC' + lt_prog_compiler_static_CXX='-Bstatic' + lt_prog_compiler_wl_CXX='-Qoption ld ' + ;; + gcx*) + # Green Hills C++ Compiler + lt_prog_compiler_pic_CXX='-PIC' + ;; + *) + ;; + esac + ;; + sunos4*) + case $cc_basename in + CC*) + # Sun C++ 4.x + lt_prog_compiler_pic_CXX='-pic' + lt_prog_compiler_static_CXX='-Bstatic' + ;; + lcc*) + # Lucid + lt_prog_compiler_pic_CXX='-pic' + ;; + *) + ;; + esac + ;; + tandem*) + case $cc_basename in + NCC*) + # NonStop-UX NCC 3.20 + lt_prog_compiler_pic_CXX='-KPIC' + ;; + *) + ;; + esac + ;; + sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) + case $cc_basename in + CC*) + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_pic_CXX='-KPIC' + lt_prog_compiler_static_CXX='-Bstatic' + ;; + esac + ;; + vxworks*) + ;; + *) + lt_prog_compiler_can_build_shared_CXX=no + ;; + esac + fi + +{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_CXX" >&5 +echo "${ECHO_T}$lt_prog_compiler_pic_CXX" >&6; } + +# +# Check to make sure the PIC flag actually works. +# +if test -n "$lt_prog_compiler_pic_CXX"; then + +{ echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_pic_CXX works" >&5 +echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic_CXX works... $ECHO_C" >&6; } +if test "${lt_prog_compiler_pic_works_CXX+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_prog_compiler_pic_works_CXX=no + ac_outfile=conftest.$ac_objext + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="$lt_prog_compiler_pic_CXX -DPIC" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:12701: $lt_compile\"" >&5) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&5 + echo "$as_me:12705: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings other than the usual output. + $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then + lt_prog_compiler_pic_works_CXX=yes + fi + fi + $rm conftest* + +fi +{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works_CXX" >&5 +echo "${ECHO_T}$lt_prog_compiler_pic_works_CXX" >&6; } + +if test x"$lt_prog_compiler_pic_works_CXX" = xyes; then + case $lt_prog_compiler_pic_CXX in + "" | " "*) ;; + *) lt_prog_compiler_pic_CXX=" $lt_prog_compiler_pic_CXX" ;; + esac +else + lt_prog_compiler_pic_CXX= + lt_prog_compiler_can_build_shared_CXX=no +fi + +fi +case $host_os in + # For platforms which do not support PIC, -DPIC is meaningless: + *djgpp*) + lt_prog_compiler_pic_CXX= + ;; + *) + lt_prog_compiler_pic_CXX="$lt_prog_compiler_pic_CXX -DPIC" + ;; +esac + +# +# Check to make sure the static flag actually works. +# +wl=$lt_prog_compiler_wl_CXX eval lt_tmp_static_flag=\"$lt_prog_compiler_static_CXX\" +{ echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_flag works" >&5 +echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works... $ECHO_C" >&6; } +if test "${lt_prog_compiler_static_works_CXX+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_prog_compiler_static_works_CXX=no + save_LDFLAGS="$LDFLAGS" + LDFLAGS="$LDFLAGS $lt_tmp_static_flag" + echo "$lt_simple_link_test_code" > conftest.$ac_ext + if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then + # The linker can only warn and ignore the option if not recognized + # So say no if there are warnings + if test -s conftest.err; then + # Append any errors to the config.log. + cat conftest.err 1>&5 + $echo "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if diff conftest.exp conftest.er2 >/dev/null; then + lt_prog_compiler_static_works_CXX=yes + fi + else + lt_prog_compiler_static_works_CXX=yes + fi + fi + $rm conftest* + LDFLAGS="$save_LDFLAGS" + +fi +{ echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works_CXX" >&5 +echo "${ECHO_T}$lt_prog_compiler_static_works_CXX" >&6; } + +if test x"$lt_prog_compiler_static_works_CXX" = xyes; then + : +else + lt_prog_compiler_static_CXX= +fi + + +{ echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5 +echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6; } +if test "${lt_cv_prog_compiler_c_o_CXX+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_cv_prog_compiler_c_o_CXX=no + $rm -r conftest 2>/dev/null + mkdir conftest + cd conftest + mkdir out + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + lt_compiler_flag="-o out/conftest2.$ac_objext" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:12805: $lt_compile\"" >&5) + (eval "$lt_compile" 2>out/conftest.err) + ac_status=$? + cat out/conftest.err >&5 + echo "$as_me:12809: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s out/conftest2.$ac_objext + then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp + $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 + if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then + lt_cv_prog_compiler_c_o_CXX=yes + fi + fi + chmod u+w . 2>&5 + $rm conftest* + # SGI C++ compiler will create directory out/ii_files/ for + # template instantiation + test -d out/ii_files && $rm out/ii_files/* && rmdir out/ii_files + $rm out/* && rmdir out + cd .. + rmdir conftest + $rm conftest* + +fi +{ echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o_CXX" >&5 +echo "${ECHO_T}$lt_cv_prog_compiler_c_o_CXX" >&6; } + + +hard_links="nottested" +if test "$lt_cv_prog_compiler_c_o_CXX" = no && test "$need_locks" != no; then + # do not overwrite the value of need_locks provided by the user + { echo "$as_me:$LINENO: checking if we can lock with hard links" >&5 +echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6; } + hard_links=yes + $rm conftest* + ln conftest.a conftest.b 2>/dev/null && hard_links=no + touch conftest.a + ln conftest.a conftest.b 2>&5 || hard_links=no + ln conftest.a conftest.b 2>/dev/null && hard_links=no + { echo "$as_me:$LINENO: result: $hard_links" >&5 +echo "${ECHO_T}$hard_links" >&6; } + if test "$hard_links" = no; then + { echo "$as_me:$LINENO: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5 +echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;} + need_locks=warn + fi +else + need_locks=no +fi + +{ echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5 +echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6; } + + export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + case $host_os in + aix4* | aix5*) + # If we're using GNU nm, then we don't want the "-C" option. + # -C means demangle to AIX nm, but means don't demangle with GNU nm + if $NM -V 2>&1 | grep 'GNU' > /dev/null; then + export_symbols_cmds_CXX='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols' + else + export_symbols_cmds_CXX='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols' + fi + ;; + pw32*) + export_symbols_cmds_CXX="$ltdll_cmds" + ;; + cygwin* | mingw*) + export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/;/^.*[ ]__nm__/s/^.*[ ]__nm__\([^ ]*\)[ ][^ ]*/\1 DATA/;/^I[ ]/d;/^[AITW][ ]/s/.*[ ]//'\'' | sort | uniq > $export_symbols' + ;; + *) + export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + ;; + esac + +{ echo "$as_me:$LINENO: result: $ld_shlibs_CXX" >&5 +echo "${ECHO_T}$ld_shlibs_CXX" >&6; } +test "$ld_shlibs_CXX" = no && can_build_shared=no + +# +# Do we need to explicitly link libc? +# +case "x$archive_cmds_need_lc_CXX" in +x|xyes) + # Assume -lc should be added + archive_cmds_need_lc_CXX=yes + + if test "$enable_shared" = yes && test "$GCC" = yes; then + case $archive_cmds_CXX in + *'~'*) + # FIXME: we may have to deal with multi-command sequences. + ;; + '$CC '*) + # Test whether the compiler implicitly links with -lc since on some + # systems, -lgcc has to come before -lc. If gcc already passes -lc + # to ld, don't add -lc before -lgcc. + { echo "$as_me:$LINENO: checking whether -lc should be explicitly linked in" >&5 +echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO_C" >&6; } + $rm conftest* + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } 2>conftest.err; then + soname=conftest + lib=conftest + libobjs=conftest.$ac_objext + deplibs= + wl=$lt_prog_compiler_wl_CXX + pic_flag=$lt_prog_compiler_pic_CXX + compiler_flags=-v + linker_flags=-v + verstring= + output_objdir=. + libname=conftest + lt_save_allow_undefined_flag=$allow_undefined_flag_CXX + allow_undefined_flag_CXX= + if { (eval echo "$as_me:$LINENO: \"$archive_cmds_CXX 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1\"") >&5 + (eval $archive_cmds_CXX 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } + then + archive_cmds_need_lc_CXX=no + else + archive_cmds_need_lc_CXX=yes + fi + allow_undefined_flag_CXX=$lt_save_allow_undefined_flag + else + cat conftest.err 1>&5 + fi + $rm conftest* + { echo "$as_me:$LINENO: result: $archive_cmds_need_lc_CXX" >&5 +echo "${ECHO_T}$archive_cmds_need_lc_CXX" >&6; } + ;; + esac + fi + ;; +esac + +{ echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5 +echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6; } +library_names_spec= +libname_spec='lib$name' +soname_spec= +shrext_cmds=".so" +postinstall_cmds= +postuninstall_cmds= +finish_cmds= +finish_eval= +shlibpath_var= +shlibpath_overrides_runpath=unknown +version_type=none +dynamic_linker="$host_os ld.so" +sys_lib_dlsearch_path_spec="/lib /usr/lib" + +need_lib_prefix=unknown +hardcode_into_libs=no + +# when you set need_version to no, make sure it does not cause -set_version +# flags to be left without arguments +need_version=unknown + +case $host_os in +aix3*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' + shlibpath_var=LIBPATH + + # AIX 3 has no versioning support, so we append a major version to the name. + soname_spec='${libname}${release}${shared_ext}$major' + ;; + +aix4* | aix5*) + version_type=linux + need_lib_prefix=no + need_version=no + hardcode_into_libs=yes + if test "$host_cpu" = ia64; then + # AIX 5 supports IA64 + library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + else + # With GCC up to 2.95.x, collect2 would create an import file + # for dependence libraries. The import file would start with + # the line `#! .'. This would cause the generated library to + # depend on `.', always an invalid library. This was fixed in + # development snapshots of GCC prior to 3.0. + case $host_os in + aix4 | aix4.[01] | aix4.[01].*) + if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' + echo ' yes ' + echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then + : + else + can_build_shared=no + fi + ;; + esac + # AIX (on Power*) has no versioning support, so currently we can not hardcode correct + # soname into executable. Probably we can add versioning support to + # collect2, so additional links can be useful in future. + if test "$aix_use_runtimelinking" = yes; then + # If using run time linking (on AIX 4.2 or later) use lib.so + # instead of lib.a to let people know that these are not + # typical AIX shared libraries. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + else + # We preserve .a as extension for shared libraries through AIX4.2 + # and later when we are not doing run time linking. + library_names_spec='${libname}${release}.a $libname.a' + soname_spec='${libname}${release}${shared_ext}$major' + fi + shlibpath_var=LIBPATH + fi + ;; + +amigaos*) + library_names_spec='$libname.ixlibrary $libname.a' + # Create ${libname}_ixlibrary.a entries in /sys/libs. + finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$echo "X$lib" | $Xsed -e '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' + ;; + +beos*) + library_names_spec='${libname}${shared_ext}' + dynamic_linker="$host_os ld.so" + shlibpath_var=LIBRARY_PATH + ;; + +bsdi[45]*) + version_type=linux + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" + sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" + # the default ld.so.conf also contains /usr/contrib/lib and + # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow + # libtool to hard-code these into programs + ;; + +cygwin* | mingw* | pw32*) + version_type=windows + shrext_cmds=".dll" + need_version=no + need_lib_prefix=no + + case $GCC,$host_os in + yes,cygwin* | yes,mingw* | yes,pw32*) + library_names_spec='$libname.dll.a' + # DLL is installed to $(libdir)/../bin by postinstall_cmds + postinstall_cmds='base_file=`basename \${file}`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname~ + chmod a+x \$dldir/$dlname' + postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ + dlpath=$dir/\$dldll~ + $rm \$dlpath' + shlibpath_overrides_runpath=yes + + case $host_os in + cygwin*) + # Cygwin DLLs use 'cyg' prefix rather than 'lib' + soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib" + ;; + mingw*) + # MinGW DLLs use traditional 'lib' prefix + soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"` + if echo "$sys_lib_search_path_spec" | grep ';[c-zC-Z]:/' >/dev/null; then + # It is most probably a Windows format PATH printed by + # mingw gcc, but we are running on Cygwin. Gcc prints its search + # path with ; separators, and with drive letters. We can handle the + # drive letters (cygwin fileutils understands them), so leave them, + # especially as we might pass files found there to a mingw objdump, + # which wouldn't understand a cygwinified path. Ahh. + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` + else + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi + ;; + pw32*) + # pw32 DLLs use 'pw' prefix rather than 'lib' + library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + ;; + esac + ;; + + *) + library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib' + ;; + esac + dynamic_linker='Win32 ld.exe' + # FIXME: first we should search . and the directory the executable is in + shlibpath_var=PATH + ;; + +darwin* | rhapsody*) + dynamic_linker="$host_os dyld" + version_type=darwin + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${versuffix}$shared_ext ${libname}${release}${major}$shared_ext ${libname}$shared_ext' + soname_spec='${libname}${release}${major}$shared_ext' + shlibpath_overrides_runpath=yes + shlibpath_var=DYLD_LIBRARY_PATH + shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' + + sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' + ;; + +dgux*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +freebsd1*) + dynamic_linker=no + ;; + +freebsd* | dragonfly*) + # DragonFly does not have aout. When/if they implement a new + # versioning mechanism, adjust this. + if test -x /usr/bin/objformat; then + objformat=`/usr/bin/objformat` + else + case $host_os in + freebsd[123]*) objformat=aout ;; + *) objformat=elf ;; + esac + fi + version_type=freebsd-$objformat + case $version_type in + freebsd-elf*) + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' + need_version=no + need_lib_prefix=no + ;; + freebsd-*) + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' + need_version=yes + ;; + esac + shlibpath_var=LD_LIBRARY_PATH + case $host_os in + freebsd2*) + shlibpath_overrides_runpath=yes + ;; + freebsd3.[01]* | freebsdelf3.[01]*) + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + freebsd3.[2-9]* | freebsdelf3.[2-9]* | \ + freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1) + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + *) # from 4.6 on, and DragonFly + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + esac + ;; + +gnu*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + hardcode_into_libs=yes + ;; + +hpux9* | hpux10* | hpux11*) + # Give a soname corresponding to the major version so that dld.sl refuses to + # link against other versions. + version_type=sunos + need_lib_prefix=no + need_version=no + case $host_cpu in + ia64*) + shrext_cmds='.so' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.so" + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + if test "X$HPUX_IA64_MODE" = X32; then + sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" + else + sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" + fi + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + hppa*64*) + shrext_cmds='.sl' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.sl" + shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + *) + shrext_cmds='.sl' + dynamic_linker="$host_os dld.sl" + shlibpath_var=SHLIB_PATH + shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + ;; + esac + # HP-UX runs *really* slowly unless shared libraries are mode 555. + postinstall_cmds='chmod 555 $lib' + ;; + +interix[3-9]*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + +irix5* | irix6* | nonstopux*) + case $host_os in + nonstopux*) version_type=nonstopux ;; + *) + if test "$lt_cv_prog_gnu_ld" = yes; then + version_type=linux + else + version_type=irix + fi ;; + esac + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' + case $host_os in + irix5* | nonstopux*) + libsuff= shlibsuff= + ;; + *) + case $LD in # libtool.m4 will add one of these switches to LD + *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") + libsuff= shlibsuff= libmagic=32-bit;; + *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") + libsuff=32 shlibsuff=N32 libmagic=N32;; + *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") + libsuff=64 shlibsuff=64 libmagic=64-bit;; + *) libsuff= shlibsuff= libmagic=never-match;; + esac + ;; + esac + shlibpath_var=LD_LIBRARY${shlibsuff}_PATH + shlibpath_overrides_runpath=no + sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" + sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" + hardcode_into_libs=yes + ;; + +# No shared lib support for Linux oldld, aout, or coff. +linux*oldld* | linux*aout* | linux*coff*) + dynamic_linker=no + ;; + +# This must be Linux ELF. +linux* | k*bsd*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + # This implies no fast_install, which is unacceptable. + # Some rework will be needed to allow for fast_install + # before this can be enabled. + hardcode_into_libs=yes + sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" + sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" + + # Append ld.so.conf contents to the search path + if test -f /etc/ld.so.conf; then + lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` + sys_lib_dlsearch_path_spec="$sys_lib_dlsearch_path_spec $lt_ld_extra" + fi + + # We used to test for /lib/ld.so.1 and disable shared libraries on + # powerpc, because MkLinux only supported shared libraries with the + # GNU dynamic linker. Since this was broken with cross compilers, + # most powerpc-linux boxes support dynamic linking these days and + # people can always --disable-shared, the test was removed, and we + # assume the GNU/Linux dynamic linker is in use. + dynamic_linker='GNU/Linux ld.so' + ;; + +netbsd*) + version_type=sunos + need_lib_prefix=no + need_version=no + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + dynamic_linker='NetBSD (a.out) ld.so' + else + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + dynamic_linker='NetBSD ld.elf_so' + fi + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + +newsos6) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +nto-qnx*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +openbsd*) + version_type=sunos + sys_lib_dlsearch_path_spec="/usr/lib" + need_lib_prefix=no + # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs. + case $host_os in + openbsd3.3 | openbsd3.3.*) need_version=yes ;; + *) need_version=no ;; + esac + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + shlibpath_var=LD_LIBRARY_PATH + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + case $host_os in + openbsd2.[89] | openbsd2.[89].*) + shlibpath_overrides_runpath=no + ;; + *) + shlibpath_overrides_runpath=yes + ;; + esac + else + shlibpath_overrides_runpath=yes + fi + ;; + +os2*) + libname_spec='$name' + shrext_cmds=".dll" + need_lib_prefix=no + library_names_spec='$libname${shared_ext} $libname.a' + dynamic_linker='OS/2 ld.exe' + shlibpath_var=LIBPATH + ;; + +osf3* | osf4* | osf5*) + version_type=osf + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" + sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" + ;; + +rdos*) + dynamic_linker=no + ;; + +solaris*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + # ldd complains unless libraries are executable + postinstall_cmds='chmod +x $lib' + ;; + +sunos4*) + version_type=sunos + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + if test "$with_gnu_ld" = yes; then + need_lib_prefix=no + fi + need_version=yes + ;; + +sysv4 | sysv4.3*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + case $host_vendor in + sni) + shlibpath_overrides_runpath=no + need_lib_prefix=no + export_dynamic_flag_spec='${wl}-Blargedynsym' + runpath_var=LD_RUN_PATH + ;; + siemens) + need_lib_prefix=no + ;; + motorola) + need_lib_prefix=no + need_version=no + shlibpath_overrides_runpath=no + sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' + ;; + esac + ;; + +sysv4*MP*) + if test -d /usr/nec ;then + version_type=linux + library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' + soname_spec='$libname${shared_ext}.$major' + shlibpath_var=LD_LIBRARY_PATH + fi + ;; + +sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) + version_type=freebsd-elf + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + hardcode_into_libs=yes + if test "$with_gnu_ld" = yes; then + sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' + shlibpath_overrides_runpath=no + else + sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' + shlibpath_overrides_runpath=yes + case $host_os in + sco3.2v5*) + sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" + ;; + esac + fi + sys_lib_dlsearch_path_spec='/usr/lib' + ;; + +uts4*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +*) + dynamic_linker=no + ;; +esac +{ echo "$as_me:$LINENO: result: $dynamic_linker" >&5 +echo "${ECHO_T}$dynamic_linker" >&6; } +test "$dynamic_linker" = no && can_build_shared=no + +variables_saved_for_relink="PATH $shlibpath_var $runpath_var" +if test "$GCC" = yes; then + variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" +fi + +{ echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5 +echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6; } +hardcode_action_CXX= +if test -n "$hardcode_libdir_flag_spec_CXX" || \ + test -n "$runpath_var_CXX" || \ + test "X$hardcode_automatic_CXX" = "Xyes" ; then + + # We can hardcode non-existant directories. + if test "$hardcode_direct_CXX" != no && + # If the only mechanism to avoid hardcoding is shlibpath_var, we + # have to relink, otherwise we might link with an installed library + # when we should be linking with a yet-to-be-installed one + ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, CXX)" != no && + test "$hardcode_minus_L_CXX" != no; then + # Linking always hardcodes the temporary library directory. + hardcode_action_CXX=relink + else + # We can link without hardcoding, and we can hardcode nonexisting dirs. + hardcode_action_CXX=immediate + fi +else + # We cannot hardcode anything, or else we can only hardcode existing + # directories. + hardcode_action_CXX=unsupported +fi +{ echo "$as_me:$LINENO: result: $hardcode_action_CXX" >&5 +echo "${ECHO_T}$hardcode_action_CXX" >&6; } + +if test "$hardcode_action_CXX" = relink; then + # Fast installation is not supported + enable_fast_install=no +elif test "$shlibpath_overrides_runpath" = yes || + test "$enable_shared" = no; then + # Fast installation is not necessary + enable_fast_install=needless +fi + + +# The else clause should only fire when bootstrapping the +# libtool distribution, otherwise you forgot to ship ltmain.sh +# with your package, and you will get complaints that there are +# no rules to generate ltmain.sh. +if test -f "$ltmain"; then + # See if we are running on zsh, and set the options which allow our commands through + # without removal of \ escapes. + if test -n "${ZSH_VERSION+set}" ; then + setopt NO_GLOB_SUBST + fi + # Now quote all the things that may contain metacharacters while being + # careful not to overquote the AC_SUBSTed values. We take copies of the + # variables and quote the copies for generation of the libtool script. + for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTCFLAGS NM \ + SED SHELL STRIP \ + libname_spec library_names_spec soname_spec extract_expsyms_cmds \ + old_striplib striplib file_magic_cmd finish_cmds finish_eval \ + deplibs_check_method reload_flag reload_cmds need_locks \ + lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \ + lt_cv_sys_global_symbol_to_c_name_address \ + sys_lib_search_path_spec sys_lib_dlsearch_path_spec \ + old_postinstall_cmds old_postuninstall_cmds \ + compiler_CXX \ + CC_CXX \ + LD_CXX \ + lt_prog_compiler_wl_CXX \ + lt_prog_compiler_pic_CXX \ + lt_prog_compiler_static_CXX \ + lt_prog_compiler_no_builtin_flag_CXX \ + export_dynamic_flag_spec_CXX \ + thread_safe_flag_spec_CXX \ + whole_archive_flag_spec_CXX \ + enable_shared_with_static_runtimes_CXX \ + old_archive_cmds_CXX \ + old_archive_from_new_cmds_CXX \ + predep_objects_CXX \ + postdep_objects_CXX \ + predeps_CXX \ + postdeps_CXX \ + compiler_lib_search_path_CXX \ + archive_cmds_CXX \ + archive_expsym_cmds_CXX \ + postinstall_cmds_CXX \ + postuninstall_cmds_CXX \ + old_archive_from_expsyms_cmds_CXX \ + allow_undefined_flag_CXX \ + no_undefined_flag_CXX \ + export_symbols_cmds_CXX \ + hardcode_libdir_flag_spec_CXX \ + hardcode_libdir_flag_spec_ld_CXX \ + hardcode_libdir_separator_CXX \ + hardcode_automatic_CXX \ + module_cmds_CXX \ + module_expsym_cmds_CXX \ + lt_cv_prog_compiler_c_o_CXX \ + fix_srcfile_path_CXX \ + exclude_expsyms_CXX \ + include_expsyms_CXX; do + + case $var in + old_archive_cmds_CXX | \ + old_archive_from_new_cmds_CXX | \ + archive_cmds_CXX | \ + archive_expsym_cmds_CXX | \ + module_cmds_CXX | \ + module_expsym_cmds_CXX | \ + old_archive_from_expsyms_cmds_CXX | \ + export_symbols_cmds_CXX | \ + extract_expsyms_cmds | reload_cmds | finish_cmds | \ + postinstall_cmds | postuninstall_cmds | \ + old_postinstall_cmds | old_postuninstall_cmds | \ + sys_lib_search_path_spec | sys_lib_dlsearch_path_spec) + # Double-quote double-evaled strings. + eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\"" + ;; + *) + eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`\\\"" + ;; + esac + done + + case $lt_echo in + *'\$0 --fallback-echo"') + lt_echo=`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$/$0 --fallback-echo"/'` + ;; + esac + +cfgfile="$ofile" + + cat <<__EOF__ >> "$cfgfile" +# ### BEGIN LIBTOOL TAG CONFIG: $tagname + +# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: + +# Shell to use when invoking shell scripts. +SHELL=$lt_SHELL + +# Whether or not to build shared libraries. +build_libtool_libs=$enable_shared + +# Whether or not to build static libraries. +build_old_libs=$enable_static + +# Whether or not to add -lc for building shared libraries. +build_libtool_need_lc=$archive_cmds_need_lc_CXX + +# Whether or not to disallow shared libs when runtime libs are static +allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes_CXX + +# Whether or not to optimize for fast installation. +fast_install=$enable_fast_install + +# The host system. +host_alias=$host_alias +host=$host +host_os=$host_os + +# The build system. +build_alias=$build_alias +build=$build +build_os=$build_os + +# An echo program that does not interpret backslashes. +echo=$lt_echo + +# The archiver. +AR=$lt_AR +AR_FLAGS=$lt_AR_FLAGS + +# A C compiler. +LTCC=$lt_LTCC + +# LTCC compiler flags. +LTCFLAGS=$lt_LTCFLAGS + +# A language-specific compiler. +CC=$lt_compiler_CXX + +# Is the compiler the GNU C compiler? +with_gcc=$GCC_CXX + +# An ERE matcher. +EGREP=$lt_EGREP + +# The linker used to build libraries. +LD=$lt_LD_CXX + +# Whether we need hard or soft links. +LN_S=$lt_LN_S + +# A BSD-compatible nm program. +NM=$lt_NM + +# A symbol stripping program +STRIP=$lt_STRIP + +# Used to examine libraries when file_magic_cmd begins "file" +MAGIC_CMD=$MAGIC_CMD + +# Used on cygwin: DLL creation program. +DLLTOOL="$DLLTOOL" + +# Used on cygwin: object dumper. +OBJDUMP="$OBJDUMP" + +# Used on cygwin: assembler. +AS="$AS" + +# The name of the directory that contains temporary libtool files. +objdir=$objdir + +# How to create reloadable object files. +reload_flag=$lt_reload_flag +reload_cmds=$lt_reload_cmds + +# How to pass a linker flag through the compiler. +wl=$lt_lt_prog_compiler_wl_CXX + +# Object file suffix (normally "o"). +objext="$ac_objext" + +# Old archive suffix (normally "a"). +libext="$libext" + +# Shared library suffix (normally ".so"). +shrext_cmds='$shrext_cmds' + +# Executable file suffix (normally ""). +exeext="$exeext" + +# Additional compiler flags for building library objects. +pic_flag=$lt_lt_prog_compiler_pic_CXX +pic_mode=$pic_mode + +# What is the maximum length of a command? +max_cmd_len=$lt_cv_sys_max_cmd_len + +# Does compiler simultaneously support -c and -o options? +compiler_c_o=$lt_lt_cv_prog_compiler_c_o_CXX + +# Must we lock files when doing compilation? +need_locks=$lt_need_locks + +# Do we need the lib prefix for modules? +need_lib_prefix=$need_lib_prefix + +# Do we need a version for libraries? +need_version=$need_version + +# Whether dlopen is supported. +dlopen_support=$enable_dlopen + +# Whether dlopen of programs is supported. +dlopen_self=$enable_dlopen_self + +# Whether dlopen of statically linked programs is supported. +dlopen_self_static=$enable_dlopen_self_static + +# Compiler flag to prevent dynamic linking. +link_static_flag=$lt_lt_prog_compiler_static_CXX + +# Compiler flag to turn off builtin functions. +no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag_CXX + +# Compiler flag to allow reflexive dlopens. +export_dynamic_flag_spec=$lt_export_dynamic_flag_spec_CXX + +# Compiler flag to generate shared objects directly from archives. +whole_archive_flag_spec=$lt_whole_archive_flag_spec_CXX + +# Compiler flag to generate thread-safe objects. +thread_safe_flag_spec=$lt_thread_safe_flag_spec_CXX + +# Library versioning type. +version_type=$version_type + +# Format of library name prefix. +libname_spec=$lt_libname_spec + +# List of archive names. First name is the real one, the rest are links. +# The last name is the one that the linker finds with -lNAME. +library_names_spec=$lt_library_names_spec + +# The coded name of the library, if different from the real name. +soname_spec=$lt_soname_spec + +# Commands used to build and install an old-style archive. +RANLIB=$lt_RANLIB +old_archive_cmds=$lt_old_archive_cmds_CXX +old_postinstall_cmds=$lt_old_postinstall_cmds +old_postuninstall_cmds=$lt_old_postuninstall_cmds + +# Create an old-style archive from a shared archive. +old_archive_from_new_cmds=$lt_old_archive_from_new_cmds_CXX + +# Create a temporary old-style archive to link instead of a shared archive. +old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds_CXX + +# Commands used to build and install a shared archive. +archive_cmds=$lt_archive_cmds_CXX +archive_expsym_cmds=$lt_archive_expsym_cmds_CXX +postinstall_cmds=$lt_postinstall_cmds +postuninstall_cmds=$lt_postuninstall_cmds + +# Commands used to build a loadable module (assumed same as above if empty) +module_cmds=$lt_module_cmds_CXX +module_expsym_cmds=$lt_module_expsym_cmds_CXX + +# Commands to strip libraries. +old_striplib=$lt_old_striplib +striplib=$lt_striplib + +# Dependencies to place before the objects being linked to create a +# shared library. +predep_objects=$lt_predep_objects_CXX + +# Dependencies to place after the objects being linked to create a +# shared library. +postdep_objects=$lt_postdep_objects_CXX + +# Dependencies to place before the objects being linked to create a +# shared library. +predeps=$lt_predeps_CXX + +# Dependencies to place after the objects being linked to create a +# shared library. +postdeps=$lt_postdeps_CXX + +# The library search path used internally by the compiler when linking +# a shared library. +compiler_lib_search_path=$lt_compiler_lib_search_path_CXX + +# Method to check whether dependent libraries are shared objects. +deplibs_check_method=$lt_deplibs_check_method + +# Command to use when deplibs_check_method == file_magic. +file_magic_cmd=$lt_file_magic_cmd + +# Flag that allows shared libraries with undefined symbols to be built. +allow_undefined_flag=$lt_allow_undefined_flag_CXX + +# Flag that forces no undefined symbols. +no_undefined_flag=$lt_no_undefined_flag_CXX + +# Commands used to finish a libtool library installation in a directory. +finish_cmds=$lt_finish_cmds + +# Same as above, but a single script fragment to be evaled but not shown. +finish_eval=$lt_finish_eval + +# Take the output of nm and produce a listing of raw symbols and C names. +global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe + +# Transform the output of nm in a proper C declaration +global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl + +# Transform the output of nm in a C name address pair +global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address + +# This is the shared library runtime path variable. +runpath_var=$runpath_var + +# This is the shared library path variable. +shlibpath_var=$shlibpath_var + +# Is shlibpath searched before the hard-coded library search path? +shlibpath_overrides_runpath=$shlibpath_overrides_runpath + +# How to hardcode a shared library path into an executable. +hardcode_action=$hardcode_action_CXX + +# Whether we should hardcode library paths into libraries. +hardcode_into_libs=$hardcode_into_libs + +# Flag to hardcode \$libdir into a binary during linking. +# This must work even if \$libdir does not exist. +hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec_CXX + +# If ld is used when linking, flag to hardcode \$libdir into +# a binary during linking. This must work even if \$libdir does +# not exist. +hardcode_libdir_flag_spec_ld=$lt_hardcode_libdir_flag_spec_ld_CXX + +# Whether we need a single -rpath flag with a separated argument. +hardcode_libdir_separator=$lt_hardcode_libdir_separator_CXX + +# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the +# resulting binary. +hardcode_direct=$hardcode_direct_CXX + +# Set to yes if using the -LDIR flag during linking hardcodes DIR into the +# resulting binary. +hardcode_minus_L=$hardcode_minus_L_CXX + +# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into +# the resulting binary. +hardcode_shlibpath_var=$hardcode_shlibpath_var_CXX + +# Set to yes if building a shared library automatically hardcodes DIR into the library +# and all subsequent libraries and executables linked against it. +hardcode_automatic=$hardcode_automatic_CXX + +# Variables whose values should be saved in libtool wrapper scripts and +# restored at relink time. +variables_saved_for_relink="$variables_saved_for_relink" + +# Whether libtool must link a program against all its dependency libraries. +link_all_deplibs=$link_all_deplibs_CXX + +# Compile-time system search path for libraries +sys_lib_search_path_spec=$lt_sys_lib_search_path_spec + +# Run-time system search path for libraries +sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec + +# Fix the shell variable \$srcfile for the compiler. +fix_srcfile_path=$lt_fix_srcfile_path + +# Set to yes if exported symbols are required. +always_export_symbols=$always_export_symbols_CXX + +# The commands to list exported symbols. +export_symbols_cmds=$lt_export_symbols_cmds_CXX + +# The commands to extract the exported symbol list from a shared archive. +extract_expsyms_cmds=$lt_extract_expsyms_cmds + +# Symbols that should not be listed in the preloaded symbols. +exclude_expsyms=$lt_exclude_expsyms_CXX + +# Symbols that must always be exported. +include_expsyms=$lt_include_expsyms_CXX + +# ### END LIBTOOL TAG CONFIG: $tagname + +__EOF__ + + +else + # If there is no Makefile yet, we rely on a make rule to execute + # `config.status --recheck' to rerun these tests and create the + # libtool script then. + ltmain_in=`echo $ltmain | sed -e 's/\.sh$/.in/'` + if test -f "$ltmain_in"; then + test -f Makefile && make "$ltmain" + fi +fi + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +CC=$lt_save_CC +LDCXX=$LD +LD=$lt_save_LD +GCC=$lt_save_GCC +with_gnu_ldcxx=$with_gnu_ld +with_gnu_ld=$lt_save_with_gnu_ld +lt_cv_path_LDCXX=$lt_cv_path_LD +lt_cv_path_LD=$lt_save_path_LD +lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld +lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld + + else + tagname="" + fi + ;; + + F77) + if test -n "$F77" && test "X$F77" != "Xno"; then + +ac_ext=f +ac_compile='$F77 -c $FFLAGS conftest.$ac_ext >&5' +ac_link='$F77 -o conftest$ac_exeext $FFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_f77_compiler_gnu + + +archive_cmds_need_lc_F77=no +allow_undefined_flag_F77= +always_export_symbols_F77=no +archive_expsym_cmds_F77= +export_dynamic_flag_spec_F77= +hardcode_direct_F77=no +hardcode_libdir_flag_spec_F77= +hardcode_libdir_flag_spec_ld_F77= +hardcode_libdir_separator_F77= +hardcode_minus_L_F77=no +hardcode_automatic_F77=no +module_cmds_F77= +module_expsym_cmds_F77= +link_all_deplibs_F77=unknown +old_archive_cmds_F77=$old_archive_cmds +no_undefined_flag_F77= +whole_archive_flag_spec_F77= +enable_shared_with_static_runtimes_F77=no + +# Source file extension for f77 test sources. +ac_ext=f + +# Object file extension for compiled f77 test sources. +objext=o +objext_F77=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code="\ + subroutine t + return + end +" + +# Code to be used in simple link tests +lt_simple_link_test_code="\ + program t + end +" + +# ltmain only uses $CC for tagged configurations so make sure $CC is set. + +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} + +# If no C compiler flags were specified, use CFLAGS. +LTCFLAGS=${LTCFLAGS-"$CFLAGS"} + +# Allow CC to be a program name with arguments. +compiler=$CC + + +# save warnings/boilerplate of simple test code +ac_outfile=conftest.$ac_objext +echo "$lt_simple_compile_test_code" >conftest.$ac_ext +eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_compiler_boilerplate=`cat conftest.err` +$rm conftest* + +ac_outfile=conftest.$ac_objext +echo "$lt_simple_link_test_code" >conftest.$ac_ext +eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_linker_boilerplate=`cat conftest.err` +$rm conftest* + + +# Allow CC to be a program name with arguments. +lt_save_CC="$CC" +CC=${F77-"f77"} +compiler=$CC +compiler_F77=$CC +for cc_temp in $compiler""; do + case $cc_temp in + compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; + distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; + \-*) ;; + *) break;; + esac +done +cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"` + + +{ echo "$as_me:$LINENO: checking if libtool supports shared libraries" >&5 +echo $ECHO_N "checking if libtool supports shared libraries... $ECHO_C" >&6; } +{ echo "$as_me:$LINENO: result: $can_build_shared" >&5 +echo "${ECHO_T}$can_build_shared" >&6; } + +{ echo "$as_me:$LINENO: checking whether to build shared libraries" >&5 +echo $ECHO_N "checking whether to build shared libraries... $ECHO_C" >&6; } +test "$can_build_shared" = "no" && enable_shared=no + +# On AIX, shared libraries and static libraries use the same namespace, and +# are all built from PIC. +case $host_os in +aix3*) + test "$enable_shared" = yes && enable_static=no + if test -n "$RANLIB"; then + archive_cmds="$archive_cmds~\$RANLIB \$lib" + postinstall_cmds='$RANLIB $lib' + fi + ;; +aix4* | aix5*) + if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then + test "$enable_shared" = yes && enable_static=no + fi + ;; +esac +{ echo "$as_me:$LINENO: result: $enable_shared" >&5 +echo "${ECHO_T}$enable_shared" >&6; } + +{ echo "$as_me:$LINENO: checking whether to build static libraries" >&5 +echo $ECHO_N "checking whether to build static libraries... $ECHO_C" >&6; } +# Make sure either enable_shared or enable_static is yes. +test "$enable_shared" = yes || enable_static=yes +{ echo "$as_me:$LINENO: result: $enable_static" >&5 +echo "${ECHO_T}$enable_static" >&6; } + +GCC_F77="$G77" +LD_F77="$LD" + +lt_prog_compiler_wl_F77= +lt_prog_compiler_pic_F77= +lt_prog_compiler_static_F77= + +{ echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5 +echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6; } + + if test "$GCC" = yes; then + lt_prog_compiler_wl_F77='-Wl,' + lt_prog_compiler_static_F77='-static' + + case $host_os in + aix*) + # All AIX code is PIC. + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static_F77='-Bstatic' + fi + ;; + + amigaos*) + # FIXME: we need at least 68020 code to build shared libraries, but + # adding the `-m68020' flag to GCC prevents building anything better, + # like `-m68040'. + lt_prog_compiler_pic_F77='-m68020 -resident32 -malways-restore-a4' + ;; + + beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) + # PIC is the default for these OSes. + ;; + + mingw* | cygwin* | pw32* | os2*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + # Although the cygwin gcc ignores -fPIC, still need this for old-style + # (--disable-auto-import) libraries + lt_prog_compiler_pic_F77='-DDLL_EXPORT' + ;; + + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + lt_prog_compiler_pic_F77='-fno-common' + ;; + + interix[3-9]*) + # Interix 3.x gcc -fpic/-fPIC options generate broken code. + # Instead, we relocate shared libraries at runtime. + ;; + + msdosdjgpp*) + # Just because we use GCC doesn't mean we suddenly get shared libraries + # on systems that don't support them. + lt_prog_compiler_can_build_shared_F77=no + enable_shared=no + ;; + + sysv4*MP*) + if test -d /usr/nec; then + lt_prog_compiler_pic_F77=-Kconform_pic + fi + ;; + + hpux*) + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case $host_cpu in + hppa*64*|ia64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic_F77='-fPIC' + ;; + esac + ;; + + *) + lt_prog_compiler_pic_F77='-fPIC' + ;; + esac + else + # PORTME Check for flag to pass linker flags through the system compiler. + case $host_os in + aix*) + lt_prog_compiler_wl_F77='-Wl,' + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static_F77='-Bstatic' + else + lt_prog_compiler_static_F77='-bnso -bI:/lib/syscalls.exp' + fi + ;; + darwin*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + case $cc_basename in + xlc*) + lt_prog_compiler_pic_F77='-qnocommon' + lt_prog_compiler_wl_F77='-Wl,' + ;; + esac + ;; + + mingw* | cygwin* | pw32* | os2*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + lt_prog_compiler_pic_F77='-DDLL_EXPORT' + ;; + + hpux9* | hpux10* | hpux11*) + lt_prog_compiler_wl_F77='-Wl,' + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case $host_cpu in + hppa*64*|ia64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic_F77='+Z' + ;; + esac + # Is there a better lt_prog_compiler_static that works with the bundled CC? + lt_prog_compiler_static_F77='${wl}-a ${wl}archive' + ;; + + irix5* | irix6* | nonstopux*) + lt_prog_compiler_wl_F77='-Wl,' + # PIC (with -KPIC) is the default. + lt_prog_compiler_static_F77='-non_shared' + ;; + + newsos6) + lt_prog_compiler_pic_F77='-KPIC' + lt_prog_compiler_static_F77='-Bstatic' + ;; + + linux* | k*bsd*-gnu) + case $cc_basename in + icc* | ecc*) + lt_prog_compiler_wl_F77='-Wl,' + lt_prog_compiler_pic_F77='-KPIC' + lt_prog_compiler_static_F77='-static' + ;; + pgcc* | pgf77* | pgf90* | pgf95*) + # Portland Group compilers (*not* the Pentium gcc compiler, + # which looks to be a dead project) + lt_prog_compiler_wl_F77='-Wl,' + lt_prog_compiler_pic_F77='-fpic' + lt_prog_compiler_static_F77='-Bstatic' + ;; + ccc*) + lt_prog_compiler_wl_F77='-Wl,' + # All Alpha code is PIC. + lt_prog_compiler_static_F77='-non_shared' + ;; + *) + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) + # Sun C 5.9 + lt_prog_compiler_pic_F77='-KPIC' + lt_prog_compiler_static_F77='-Bstatic' + lt_prog_compiler_wl_F77='-Wl,' + ;; + *Sun\ F*) + # Sun Fortran 8.3 passes all unrecognized flags to the linker + lt_prog_compiler_pic_F77='-KPIC' + lt_prog_compiler_static_F77='-Bstatic' + lt_prog_compiler_wl_F77='' + ;; + esac + ;; + esac + ;; + + osf3* | osf4* | osf5*) + lt_prog_compiler_wl_F77='-Wl,' + # All OSF/1 code is PIC. + lt_prog_compiler_static_F77='-non_shared' + ;; + + rdos*) + lt_prog_compiler_static_F77='-non_shared' + ;; + + solaris*) + lt_prog_compiler_pic_F77='-KPIC' + lt_prog_compiler_static_F77='-Bstatic' + case $cc_basename in + f77* | f90* | f95*) + lt_prog_compiler_wl_F77='-Qoption ld ';; + *) + lt_prog_compiler_wl_F77='-Wl,';; + esac + ;; + + sunos4*) + lt_prog_compiler_wl_F77='-Qoption ld ' + lt_prog_compiler_pic_F77='-PIC' + lt_prog_compiler_static_F77='-Bstatic' + ;; + + sysv4 | sysv4.2uw2* | sysv4.3*) + lt_prog_compiler_wl_F77='-Wl,' + lt_prog_compiler_pic_F77='-KPIC' + lt_prog_compiler_static_F77='-Bstatic' + ;; + + sysv4*MP*) + if test -d /usr/nec ;then + lt_prog_compiler_pic_F77='-Kconform_pic' + lt_prog_compiler_static_F77='-Bstatic' + fi + ;; + + sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) + lt_prog_compiler_wl_F77='-Wl,' + lt_prog_compiler_pic_F77='-KPIC' + lt_prog_compiler_static_F77='-Bstatic' + ;; + + unicos*) + lt_prog_compiler_wl_F77='-Wl,' + lt_prog_compiler_can_build_shared_F77=no + ;; + + uts4*) + lt_prog_compiler_pic_F77='-pic' + lt_prog_compiler_static_F77='-Bstatic' + ;; + + *) + lt_prog_compiler_can_build_shared_F77=no + ;; + esac + fi + +{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_F77" >&5 +echo "${ECHO_T}$lt_prog_compiler_pic_F77" >&6; } + +# +# Check to make sure the PIC flag actually works. +# +if test -n "$lt_prog_compiler_pic_F77"; then + +{ echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_pic_F77 works" >&5 +echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic_F77 works... $ECHO_C" >&6; } +if test "${lt_prog_compiler_pic_works_F77+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_prog_compiler_pic_works_F77=no + ac_outfile=conftest.$ac_objext + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="$lt_prog_compiler_pic_F77" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:14369: $lt_compile\"" >&5) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&5 + echo "$as_me:14373: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings other than the usual output. + $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then + lt_prog_compiler_pic_works_F77=yes + fi + fi + $rm conftest* + +fi +{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works_F77" >&5 +echo "${ECHO_T}$lt_prog_compiler_pic_works_F77" >&6; } + +if test x"$lt_prog_compiler_pic_works_F77" = xyes; then + case $lt_prog_compiler_pic_F77 in + "" | " "*) ;; + *) lt_prog_compiler_pic_F77=" $lt_prog_compiler_pic_F77" ;; + esac +else + lt_prog_compiler_pic_F77= + lt_prog_compiler_can_build_shared_F77=no +fi + +fi +case $host_os in + # For platforms which do not support PIC, -DPIC is meaningless: + *djgpp*) + lt_prog_compiler_pic_F77= + ;; + *) + lt_prog_compiler_pic_F77="$lt_prog_compiler_pic_F77" + ;; +esac + +# +# Check to make sure the static flag actually works. +# +wl=$lt_prog_compiler_wl_F77 eval lt_tmp_static_flag=\"$lt_prog_compiler_static_F77\" +{ echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_flag works" >&5 +echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works... $ECHO_C" >&6; } +if test "${lt_prog_compiler_static_works_F77+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_prog_compiler_static_works_F77=no + save_LDFLAGS="$LDFLAGS" + LDFLAGS="$LDFLAGS $lt_tmp_static_flag" + echo "$lt_simple_link_test_code" > conftest.$ac_ext + if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then + # The linker can only warn and ignore the option if not recognized + # So say no if there are warnings + if test -s conftest.err; then + # Append any errors to the config.log. + cat conftest.err 1>&5 + $echo "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if diff conftest.exp conftest.er2 >/dev/null; then + lt_prog_compiler_static_works_F77=yes + fi + else + lt_prog_compiler_static_works_F77=yes + fi + fi + $rm conftest* + LDFLAGS="$save_LDFLAGS" + +fi +{ echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works_F77" >&5 +echo "${ECHO_T}$lt_prog_compiler_static_works_F77" >&6; } + +if test x"$lt_prog_compiler_static_works_F77" = xyes; then + : +else + lt_prog_compiler_static_F77= +fi + + +{ echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5 +echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6; } +if test "${lt_cv_prog_compiler_c_o_F77+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_cv_prog_compiler_c_o_F77=no + $rm -r conftest 2>/dev/null + mkdir conftest + cd conftest + mkdir out + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + lt_compiler_flag="-o out/conftest2.$ac_objext" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:14473: $lt_compile\"" >&5) + (eval "$lt_compile" 2>out/conftest.err) + ac_status=$? + cat out/conftest.err >&5 + echo "$as_me:14477: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s out/conftest2.$ac_objext + then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp + $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 + if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then + lt_cv_prog_compiler_c_o_F77=yes + fi + fi + chmod u+w . 2>&5 + $rm conftest* + # SGI C++ compiler will create directory out/ii_files/ for + # template instantiation + test -d out/ii_files && $rm out/ii_files/* && rmdir out/ii_files + $rm out/* && rmdir out + cd .. + rmdir conftest + $rm conftest* + +fi +{ echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o_F77" >&5 +echo "${ECHO_T}$lt_cv_prog_compiler_c_o_F77" >&6; } + + +hard_links="nottested" +if test "$lt_cv_prog_compiler_c_o_F77" = no && test "$need_locks" != no; then + # do not overwrite the value of need_locks provided by the user + { echo "$as_me:$LINENO: checking if we can lock with hard links" >&5 +echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6; } + hard_links=yes + $rm conftest* + ln conftest.a conftest.b 2>/dev/null && hard_links=no + touch conftest.a + ln conftest.a conftest.b 2>&5 || hard_links=no + ln conftest.a conftest.b 2>/dev/null && hard_links=no + { echo "$as_me:$LINENO: result: $hard_links" >&5 +echo "${ECHO_T}$hard_links" >&6; } + if test "$hard_links" = no; then + { echo "$as_me:$LINENO: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5 +echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;} + need_locks=warn + fi +else + need_locks=no +fi + +{ echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5 +echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6; } + + runpath_var= + allow_undefined_flag_F77= + enable_shared_with_static_runtimes_F77=no + archive_cmds_F77= + archive_expsym_cmds_F77= + old_archive_From_new_cmds_F77= + old_archive_from_expsyms_cmds_F77= + export_dynamic_flag_spec_F77= + whole_archive_flag_spec_F77= + thread_safe_flag_spec_F77= + hardcode_libdir_flag_spec_F77= + hardcode_libdir_flag_spec_ld_F77= + hardcode_libdir_separator_F77= + hardcode_direct_F77=no + hardcode_minus_L_F77=no + hardcode_shlibpath_var_F77=unsupported + link_all_deplibs_F77=unknown + hardcode_automatic_F77=no + module_cmds_F77= + module_expsym_cmds_F77= + always_export_symbols_F77=no + export_symbols_cmds_F77='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + # include_expsyms should be a list of space-separated symbols to be *always* + # included in the symbol list + include_expsyms_F77= + # exclude_expsyms can be an extended regexp of symbols to exclude + # it will be wrapped by ` (' and `)$', so one must not match beginning or + # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc', + # as well as any symbol that contains `d'. + exclude_expsyms_F77="_GLOBAL_OFFSET_TABLE_" + # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out + # platforms (ab)use it in PIC code, but their linkers get confused if + # the symbol is explicitly referenced. Since portable code cannot + # rely on this symbol name, it's probably fine to never include it in + # preloaded symbol tables. + extract_expsyms_cmds= + # Just being paranoid about ensuring that cc_basename is set. + for cc_temp in $compiler""; do + case $cc_temp in + compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; + distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; + \-*) ;; + *) break;; + esac +done +cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"` + + case $host_os in + cygwin* | mingw* | pw32*) + # FIXME: the MSVC++ port hasn't been tested in a loooong time + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + if test "$GCC" != yes; then + with_gnu_ld=no + fi + ;; + interix*) + # we just hope/assume this is gcc and not c89 (= MSVC++) + with_gnu_ld=yes + ;; + openbsd*) + with_gnu_ld=no + ;; + esac + + ld_shlibs_F77=yes + if test "$with_gnu_ld" = yes; then + # If archive_cmds runs LD, not CC, wlarc should be empty + wlarc='${wl}' + + # Set some defaults for GNU ld with shared library support. These + # are reset later if shared libraries are not supported. Putting them + # here allows them to be overridden if necessary. + runpath_var=LD_RUN_PATH + hardcode_libdir_flag_spec_F77='${wl}--rpath ${wl}$libdir' + export_dynamic_flag_spec_F77='${wl}--export-dynamic' + # ancient GNU ld didn't support --whole-archive et. al. + if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then + whole_archive_flag_spec_F77="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' + else + whole_archive_flag_spec_F77= + fi + supports_anon_versioning=no + case `$LD -v 2>/dev/null` in + *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11 + *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... + *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... + *\ 2.11.*) ;; # other 2.11 versions + *) supports_anon_versioning=yes ;; + esac + + # See if GNU ld supports shared libraries. + case $host_os in + aix3* | aix4* | aix5*) + # On AIX/PPC, the GNU linker is very broken + if test "$host_cpu" != ia64; then + ld_shlibs_F77=no + cat <&2 + +*** Warning: the GNU linker, at least up to release 2.9.1, is reported +*** to be unable to reliably create shared libraries on AIX. +*** Therefore, libtool is disabling shared libraries support. If you +*** really care for shared libraries, you may want to modify your PATH +*** so that a non-GNU linker is found, and then restart. + +EOF + fi + ;; + + amigaos*) + archive_cmds_F77='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + hardcode_libdir_flag_spec_F77='-L$libdir' + hardcode_minus_L_F77=yes + + # Samuel A. Falvo II reports + # that the semantics of dynamic libraries on AmigaOS, at least up + # to version 4, is to share data among multiple programs linked + # with the same dynamic library. Since this doesn't match the + # behavior of shared libraries on other platforms, we can't use + # them. + ld_shlibs_F77=no + ;; + + beos*) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + allow_undefined_flag_F77=unsupported + # Joseph Beckenbach says some releases of gcc + # support --undefined. This deserves some investigation. FIXME + archive_cmds_F77='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + else + ld_shlibs_F77=no + fi + ;; + + cygwin* | mingw* | pw32*) + # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, F77) is actually meaningless, + # as there is no search path for DLLs. + hardcode_libdir_flag_spec_F77='-L$libdir' + allow_undefined_flag_F77=unsupported + always_export_symbols_F77=no + enable_shared_with_static_runtimes_F77=yes + export_symbols_cmds_F77='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/'\'' -e '\''/^[AITW][ ]/s/.*[ ]//'\'' | sort | uniq > $export_symbols' + + if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then + archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + # If the export-symbols file already is a .def file (1st line + # is EXPORTS), use it as is; otherwise, prepend... + archive_expsym_cmds_F77='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then + cp $export_symbols $output_objdir/$soname.def; + else + echo EXPORTS > $output_objdir/$soname.def; + cat $export_symbols >> $output_objdir/$soname.def; + fi~ + $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + else + ld_shlibs_F77=no + fi + ;; + + interix[3-9]*) + hardcode_direct_F77=no + hardcode_shlibpath_var_F77=no + hardcode_libdir_flag_spec_F77='${wl}-rpath,$libdir' + export_dynamic_flag_spec_F77='${wl}-E' + # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. + # Instead, shared libraries are loaded at an image base (0x10000000 by + # default) and relocated if they conflict, which is a slow very memory + # consuming and fragmenting process. To avoid this, we pick a random, + # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link + # time. Moving up from 0x10000000 also allows more sbrk(2) space. + archive_cmds_F77='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + archive_expsym_cmds_F77='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + ;; + + gnu* | linux* | k*bsd*-gnu) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + tmp_addflag= + case $cc_basename,$host_cpu in + pgcc*) # Portland Group C compiler + whole_archive_flag_spec_F77='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive' + tmp_addflag=' $pic_flag' + ;; + pgf77* | pgf90* | pgf95*) # Portland Group f77 and f90 compilers + whole_archive_flag_spec_F77='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive' + tmp_addflag=' $pic_flag -Mnomain' ;; + ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 + tmp_addflag=' -i_dynamic' ;; + efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 + tmp_addflag=' -i_dynamic -nofor_main' ;; + ifc* | ifort*) # Intel Fortran compiler + tmp_addflag=' -nofor_main' ;; + esac + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) # Sun C 5.9 + whole_archive_flag_spec_F77='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive' + tmp_sharedflag='-G' ;; + *Sun\ F*) # Sun Fortran 8.3 + tmp_sharedflag='-G' ;; + *) + tmp_sharedflag='-shared' ;; + esac + archive_cmds_F77='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + + if test $supports_anon_versioning = yes; then + archive_expsym_cmds_F77='$echo "{ global:" > $output_objdir/$libname.ver~ + cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ + $echo "local: *; };" >> $output_objdir/$libname.ver~ + $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' + fi + else + ld_shlibs_F77=no + fi + ;; + + netbsd*) + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + archive_cmds_F77='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' + wlarc= + else + archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + fi + ;; + + solaris*) + if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then + ld_shlibs_F77=no + cat <&2 + +*** Warning: The releases 2.8.* of the GNU linker cannot reliably +*** create shared libraries on Solaris systems. Therefore, libtool +*** is disabling shared libraries support. We urge you to upgrade GNU +*** binutils to release 2.9.1 or newer. Another option is to modify +*** your PATH or compiler configuration so that the native linker is +*** used, and then restart. + +EOF + elif $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + ld_shlibs_F77=no + fi + ;; + + sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) + case `$LD -v 2>&1` in + *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*) + ld_shlibs_F77=no + cat <<_LT_EOF 1>&2 + +*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not +*** reliably create shared libraries on SCO systems. Therefore, libtool +*** is disabling shared libraries support. We urge you to upgrade GNU +*** binutils to release 2.16.91.0.3 or newer. Another option is to modify +*** your PATH or compiler configuration so that the native linker is +*** used, and then restart. + +_LT_EOF + ;; + *) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + hardcode_libdir_flag_spec_F77='`test -z "$SCOABSPATH" && echo ${wl}-rpath,$libdir`' + archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib' + archive_expsym_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname,-retain-symbols-file,$export_symbols -o $lib' + else + ld_shlibs_F77=no + fi + ;; + esac + ;; + + sunos4*) + archive_cmds_F77='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' + wlarc= + hardcode_direct_F77=yes + hardcode_shlibpath_var_F77=no + ;; + + *) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + ld_shlibs_F77=no + fi + ;; + esac + + if test "$ld_shlibs_F77" = no; then + runpath_var= + hardcode_libdir_flag_spec_F77= + export_dynamic_flag_spec_F77= + whole_archive_flag_spec_F77= + fi + else + # PORTME fill in a description of your system's linker (not GNU ld) + case $host_os in + aix3*) + allow_undefined_flag_F77=unsupported + always_export_symbols_F77=yes + archive_expsym_cmds_F77='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' + # Note: this linker hardcodes the directories in LIBPATH if there + # are no directories specified by -L. + hardcode_minus_L_F77=yes + if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then + # Neither direct hardcoding nor static linking is supported with a + # broken collect2. + hardcode_direct_F77=unsupported + fi + ;; + + aix4* | aix5*) + if test "$host_cpu" = ia64; then + # On IA64, the linker does run time linking by default, so we don't + # have to do anything special. + aix_use_runtimelinking=no + exp_sym_flag='-Bexport' + no_entry_flag="" + else + # If we're using GNU nm, then we don't want the "-C" option. + # -C means demangle to AIX nm, but means don't demangle with GNU nm + if $NM -V 2>&1 | grep 'GNU' > /dev/null; then + export_symbols_cmds_F77='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols' + else + export_symbols_cmds_F77='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols' + fi + aix_use_runtimelinking=no + + # Test if we are trying to use run time linking or normal + # AIX style linking. If -brtl is somewhere in LDFLAGS, we + # need to do runtime linking. + case $host_os in aix4.[23]|aix4.[23].*|aix5*) + for ld_flag in $LDFLAGS; do + if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then + aix_use_runtimelinking=yes + break + fi + done + ;; + esac + + exp_sym_flag='-bexport' + no_entry_flag='-bnoentry' + fi + + # When large executables or shared objects are built, AIX ld can + # have problems creating the table of contents. If linking a library + # or program results in "error TOC overflow" add -mminimal-toc to + # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not + # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. + + archive_cmds_F77='' + hardcode_direct_F77=yes + hardcode_libdir_separator_F77=':' + link_all_deplibs_F77=yes + + if test "$GCC" = yes; then + case $host_os in aix4.[012]|aix4.[012].*) + # We only want to do this on AIX 4.2 and lower, the check + # below for broken collect2 doesn't work under 4.3+ + collect2name=`${CC} -print-prog-name=collect2` + if test -f "$collect2name" && \ + strings "$collect2name" | grep resolve_lib_name >/dev/null + then + # We have reworked collect2 + : + else + # We have old collect2 + hardcode_direct_F77=unsupported + # It fails to find uninstalled libraries when the uninstalled + # path is not listed in the libpath. Setting hardcode_minus_L + # to unsupported forces relinking + hardcode_minus_L_F77=yes + hardcode_libdir_flag_spec_F77='-L$libdir' + hardcode_libdir_separator_F77= + fi + ;; + esac + shared_flag='-shared' + if test "$aix_use_runtimelinking" = yes; then + shared_flag="$shared_flag "'${wl}-G' + fi + else + # not using gcc + if test "$host_cpu" = ia64; then + # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release + # chokes on -Wl,-G. The following line is correct: + shared_flag='-G' + else + if test "$aix_use_runtimelinking" = yes; then + shared_flag='${wl}-G' + else + shared_flag='${wl}-bM:SRE' + fi + fi + fi + + # It seems that -bexpall does not export symbols beginning with + # underscore (_), so it is better to generate a list of symbols to export. + always_export_symbols_F77=yes + if test "$aix_use_runtimelinking" = yes; then + # Warning - without using the other runtime loading flags (-brtl), + # -berok will link without error, but may produce a broken library. + allow_undefined_flag_F77='-berok' + # Determine the default libpath from the value encoded in an empty executable. + cat >conftest.$ac_ext <<_ACEOF + program main + + end +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_f77_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + +lt_aix_libpath_sed=' + /Import File Strings/,/^$/ { + /^0/ { + s/^0 *\(.*\)$/\1/ + p + } + }' +aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +# Check for a 64-bit object if we didn't find anything. +if test -z "$aix_libpath"; then + aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +fi +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi + + hardcode_libdir_flag_spec_F77='${wl}-blibpath:$libdir:'"$aix_libpath" + archive_expsym_cmds_F77="\$CC"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" + else + if test "$host_cpu" = ia64; then + hardcode_libdir_flag_spec_F77='${wl}-R $libdir:/usr/lib:/lib' + allow_undefined_flag_F77="-z nodefs" + archive_expsym_cmds_F77="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" + else + # Determine the default libpath from the value encoded in an empty executable. + cat >conftest.$ac_ext <<_ACEOF + program main + + end +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_f77_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + +lt_aix_libpath_sed=' + /Import File Strings/,/^$/ { + /^0/ { + s/^0 *\(.*\)$/\1/ + p + } + }' +aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +# Check for a 64-bit object if we didn't find anything. +if test -z "$aix_libpath"; then + aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +fi +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi + + hardcode_libdir_flag_spec_F77='${wl}-blibpath:$libdir:'"$aix_libpath" + # Warning - without using the other run time loading flags, + # -berok will link without error, but may produce a broken library. + no_undefined_flag_F77=' ${wl}-bernotok' + allow_undefined_flag_F77=' ${wl}-berok' + # Exported symbols can be pulled into shared objects from archives + whole_archive_flag_spec_F77='$convenience' + archive_cmds_need_lc_F77=yes + # This is similar to how AIX traditionally builds its shared libraries. + archive_expsym_cmds_F77="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' + fi + fi + ;; + + amigaos*) + archive_cmds_F77='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + hardcode_libdir_flag_spec_F77='-L$libdir' + hardcode_minus_L_F77=yes + # see comment about different semantics on the GNU ld section + ld_shlibs_F77=no + ;; + + bsdi[45]*) + export_dynamic_flag_spec_F77=-rdynamic + ;; + + cygwin* | mingw* | pw32*) + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + # hardcode_libdir_flag_spec is actually meaningless, as there is + # no search path for DLLs. + hardcode_libdir_flag_spec_F77=' ' + allow_undefined_flag_F77=unsupported + # Tell ltmain to make .lib files, not .a files. + libext=lib + # Tell ltmain to make .dll files, not .so files. + shrext_cmds=".dll" + # FIXME: Setting linknames here is a bad hack. + archive_cmds_F77='$CC -o $lib $libobjs $compiler_flags `echo "$deplibs" | $SED -e '\''s/ -lc$//'\''` -link -dll~linknames=' + # The linker will automatically build a .lib file if we build a DLL. + old_archive_From_new_cmds_F77='true' + # FIXME: Should let the user specify the lib program. + old_archive_cmds_F77='lib -OUT:$oldlib$oldobjs$old_deplibs' + fix_srcfile_path_F77='`cygpath -w "$srcfile"`' + enable_shared_with_static_runtimes_F77=yes + ;; + + darwin* | rhapsody*) + case $host_os in + rhapsody* | darwin1.[012]) + allow_undefined_flag_F77='${wl}-undefined ${wl}suppress' + ;; + *) # Darwin 1.3 on + if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then + allow_undefined_flag_F77='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' + else + case ${MACOSX_DEPLOYMENT_TARGET} in + 10.[012]) + allow_undefined_flag_F77='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' + ;; + 10.*) + allow_undefined_flag_F77='${wl}-undefined ${wl}dynamic_lookup' + ;; + esac + fi + ;; + esac + archive_cmds_need_lc_F77=no + hardcode_direct_F77=no + hardcode_automatic_F77=yes + hardcode_shlibpath_var_F77=unsupported + whole_archive_flag_spec_F77='' + link_all_deplibs_F77=yes + if test "$GCC" = yes ; then + output_verbose_link_cmd='echo' + archive_cmds_F77='$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring' + module_cmds_F77='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags' + # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds + archive_expsym_cmds_F77='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + module_expsym_cmds_F77='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + else + case $cc_basename in + xlc*) + output_verbose_link_cmd='echo' + archive_cmds_F77='$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$soname` $xlcverstring' + module_cmds_F77='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags' + # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds + archive_expsym_cmds_F77='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}$rpath/$soname $xlcverstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + module_expsym_cmds_F77='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + ;; + *) + ld_shlibs_F77=no + ;; + esac + fi + ;; + + dgux*) + archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec_F77='-L$libdir' + hardcode_shlibpath_var_F77=no + ;; + + freebsd1*) + ld_shlibs_F77=no + ;; + + # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor + # support. Future versions do this automatically, but an explicit c++rt0.o + # does not break anything, and helps significantly (at the cost of a little + # extra space). + freebsd2.2*) + archive_cmds_F77='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' + hardcode_libdir_flag_spec_F77='-R$libdir' + hardcode_direct_F77=yes + hardcode_shlibpath_var_F77=no + ;; + + # Unfortunately, older versions of FreeBSD 2 do not have this feature. + freebsd2*) + archive_cmds_F77='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct_F77=yes + hardcode_minus_L_F77=yes + hardcode_shlibpath_var_F77=no + ;; + + # FreeBSD 3 and greater uses gcc -shared to do shared libraries. + freebsd* | dragonfly*) + archive_cmds_F77='$CC -shared -o $lib $libobjs $deplibs $compiler_flags' + hardcode_libdir_flag_spec_F77='-R$libdir' + hardcode_direct_F77=yes + hardcode_shlibpath_var_F77=no + ;; + + hpux9*) + if test "$GCC" = yes; then + archive_cmds_F77='$rm $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + else + archive_cmds_F77='$rm $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + fi + hardcode_libdir_flag_spec_F77='${wl}+b ${wl}$libdir' + hardcode_libdir_separator_F77=: + hardcode_direct_F77=yes + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L_F77=yes + export_dynamic_flag_spec_F77='${wl}-E' + ;; + + hpux10*) + if test "$GCC" = yes -a "$with_gnu_ld" = no; then + archive_cmds_F77='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds_F77='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' + fi + if test "$with_gnu_ld" = no; then + hardcode_libdir_flag_spec_F77='${wl}+b ${wl}$libdir' + hardcode_libdir_separator_F77=: + + hardcode_direct_F77=yes + export_dynamic_flag_spec_F77='${wl}-E' + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L_F77=yes + fi + ;; + + hpux11*) + if test "$GCC" = yes -a "$with_gnu_ld" = no; then + case $host_cpu in + hppa*64*) + archive_cmds_F77='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + ia64*) + archive_cmds_F77='$CC -shared ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + archive_cmds_F77='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + else + case $host_cpu in + hppa*64*) + archive_cmds_F77='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + ia64*) + archive_cmds_F77='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + archive_cmds_F77='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + fi + if test "$with_gnu_ld" = no; then + hardcode_libdir_flag_spec_F77='${wl}+b ${wl}$libdir' + hardcode_libdir_separator_F77=: + + case $host_cpu in + hppa*64*|ia64*) + hardcode_libdir_flag_spec_ld_F77='+b $libdir' + hardcode_direct_F77=no + hardcode_shlibpath_var_F77=no + ;; + *) + hardcode_direct_F77=yes + export_dynamic_flag_spec_F77='${wl}-E' + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L_F77=yes + ;; + esac + fi + ;; + + irix5* | irix6* | nonstopux*) + if test "$GCC" = yes; then + archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + else + archive_cmds_F77='$LD -shared $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + hardcode_libdir_flag_spec_ld_F77='-rpath $libdir' + fi + hardcode_libdir_flag_spec_F77='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator_F77=: + link_all_deplibs_F77=yes + ;; + + netbsd*) + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + archive_cmds_F77='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out + else + archive_cmds_F77='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF + fi + hardcode_libdir_flag_spec_F77='-R$libdir' + hardcode_direct_F77=yes + hardcode_shlibpath_var_F77=no + ;; + + newsos6) + archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct_F77=yes + hardcode_libdir_flag_spec_F77='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator_F77=: + hardcode_shlibpath_var_F77=no + ;; + + openbsd*) + if test -f /usr/libexec/ld.so; then + hardcode_direct_F77=yes + hardcode_shlibpath_var_F77=no + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + archive_cmds_F77='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds_F77='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols' + hardcode_libdir_flag_spec_F77='${wl}-rpath,$libdir' + export_dynamic_flag_spec_F77='${wl}-E' + else + case $host_os in + openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*) + archive_cmds_F77='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec_F77='-R$libdir' + ;; + *) + archive_cmds_F77='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + hardcode_libdir_flag_spec_F77='${wl}-rpath,$libdir' + ;; + esac + fi + else + ld_shlibs_F77=no + fi + ;; + + os2*) + hardcode_libdir_flag_spec_F77='-L$libdir' + hardcode_minus_L_F77=yes + allow_undefined_flag_F77=unsupported + archive_cmds_F77='$echo "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$echo "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~$echo DATA >> $output_objdir/$libname.def~$echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~$echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def' + old_archive_From_new_cmds_F77='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def' + ;; + + osf3*) + if test "$GCC" = yes; then + allow_undefined_flag_F77=' ${wl}-expect_unresolved ${wl}\*' + archive_cmds_F77='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + else + allow_undefined_flag_F77=' -expect_unresolved \*' + archive_cmds_F77='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + fi + hardcode_libdir_flag_spec_F77='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator_F77=: + ;; + + osf4* | osf5*) # as osf3* with the addition of -msym flag + if test "$GCC" = yes; then + allow_undefined_flag_F77=' ${wl}-expect_unresolved ${wl}\*' + archive_cmds_F77='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + hardcode_libdir_flag_spec_F77='${wl}-rpath ${wl}$libdir' + else + allow_undefined_flag_F77=' -expect_unresolved \*' + archive_cmds_F77='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + archive_expsym_cmds_F77='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; echo "-hidden">> $lib.exp~ + $LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib~$rm $lib.exp' + + # Both c and cxx compiler support -rpath directly + hardcode_libdir_flag_spec_F77='-rpath $libdir' + fi + hardcode_libdir_separator_F77=: + ;; + + solaris*) + no_undefined_flag_F77=' -z text' + if test "$GCC" = yes; then + wlarc='${wl}' + archive_cmds_F77='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds_F77='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $CC -shared ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$rm $lib.exp' + else + wlarc='' + archive_cmds_F77='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' + archive_expsym_cmds_F77='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp' + fi + hardcode_libdir_flag_spec_F77='-R$libdir' + hardcode_shlibpath_var_F77=no + case $host_os in + solaris2.[0-5] | solaris2.[0-5].*) ;; + *) + # The compiler driver will combine and reorder linker options, + # but understands `-z linker_flag'. GCC discards it without `$wl', + # but is careful enough not to reorder. + # Supported since Solaris 2.6 (maybe 2.5.1?) + if test "$GCC" = yes; then + whole_archive_flag_spec_F77='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' + else + whole_archive_flag_spec_F77='-z allextract$convenience -z defaultextract' + fi + ;; + esac + link_all_deplibs_F77=yes + ;; + + sunos4*) + if test "x$host_vendor" = xsequent; then + # Use $CC to link under sequent, because it throws in some extra .o + # files that make .init and .fini sections work. + archive_cmds_F77='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds_F77='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' + fi + hardcode_libdir_flag_spec_F77='-L$libdir' + hardcode_direct_F77=yes + hardcode_minus_L_F77=yes + hardcode_shlibpath_var_F77=no + ;; + + sysv4) + case $host_vendor in + sni) + archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct_F77=yes # is this really true??? + ;; + siemens) + ## LD is ld it makes a PLAMLIB + ## CC just makes a GrossModule. + archive_cmds_F77='$LD -G -o $lib $libobjs $deplibs $linker_flags' + reload_cmds_F77='$CC -r -o $output$reload_objs' + hardcode_direct_F77=no + ;; + motorola) + archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct_F77=no #Motorola manual says yes, but my tests say they lie + ;; + esac + runpath_var='LD_RUN_PATH' + hardcode_shlibpath_var_F77=no + ;; + + sysv4.3*) + archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_shlibpath_var_F77=no + export_dynamic_flag_spec_F77='-Bexport' + ;; + + sysv4*MP*) + if test -d /usr/nec; then + archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_shlibpath_var_F77=no + runpath_var=LD_RUN_PATH + hardcode_runpath_var=yes + ld_shlibs_F77=yes + fi + ;; + + sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*) + no_undefined_flag_F77='${wl}-z,text' + archive_cmds_need_lc_F77=no + hardcode_shlibpath_var_F77=no + runpath_var='LD_RUN_PATH' + + if test "$GCC" = yes; then + archive_cmds_F77='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds_F77='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds_F77='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds_F77='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + fi + ;; + + sysv5* | sco3.2v5* | sco5v6*) + # Note: We can NOT use -z defs as we might desire, because we do not + # link with -lc, and that would cause any symbols used from libc to + # always be unresolved, which means just about no library would + # ever link correctly. If we're not using GNU ld we use -z text + # though, which does catch some bad symbols but isn't as heavy-handed + # as -z defs. + no_undefined_flag_F77='${wl}-z,text' + allow_undefined_flag_F77='${wl}-z,nodefs' + archive_cmds_need_lc_F77=no + hardcode_shlibpath_var_F77=no + hardcode_libdir_flag_spec_F77='`test -z "$SCOABSPATH" && echo ${wl}-R,$libdir`' + hardcode_libdir_separator_F77=':' + link_all_deplibs_F77=yes + export_dynamic_flag_spec_F77='${wl}-Bexport' + runpath_var='LD_RUN_PATH' + + if test "$GCC" = yes; then + archive_cmds_F77='$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds_F77='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds_F77='$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds_F77='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + fi + ;; + + uts4*) + archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec_F77='-L$libdir' + hardcode_shlibpath_var_F77=no + ;; + + *) + ld_shlibs_F77=no + ;; + esac + fi + +{ echo "$as_me:$LINENO: result: $ld_shlibs_F77" >&5 +echo "${ECHO_T}$ld_shlibs_F77" >&6; } +test "$ld_shlibs_F77" = no && can_build_shared=no + +# +# Do we need to explicitly link libc? +# +case "x$archive_cmds_need_lc_F77" in +x|xyes) + # Assume -lc should be added + archive_cmds_need_lc_F77=yes + + if test "$enable_shared" = yes && test "$GCC" = yes; then + case $archive_cmds_F77 in + *'~'*) + # FIXME: we may have to deal with multi-command sequences. + ;; + '$CC '*) + # Test whether the compiler implicitly links with -lc since on some + # systems, -lgcc has to come before -lc. If gcc already passes -lc + # to ld, don't add -lc before -lgcc. + { echo "$as_me:$LINENO: checking whether -lc should be explicitly linked in" >&5 +echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO_C" >&6; } + $rm conftest* + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } 2>conftest.err; then + soname=conftest + lib=conftest + libobjs=conftest.$ac_objext + deplibs= + wl=$lt_prog_compiler_wl_F77 + pic_flag=$lt_prog_compiler_pic_F77 + compiler_flags=-v + linker_flags=-v + verstring= + output_objdir=. + libname=conftest + lt_save_allow_undefined_flag=$allow_undefined_flag_F77 + allow_undefined_flag_F77= + if { (eval echo "$as_me:$LINENO: \"$archive_cmds_F77 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1\"") >&5 + (eval $archive_cmds_F77 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } + then + archive_cmds_need_lc_F77=no + else + archive_cmds_need_lc_F77=yes + fi + allow_undefined_flag_F77=$lt_save_allow_undefined_flag + else + cat conftest.err 1>&5 + fi + $rm conftest* + { echo "$as_me:$LINENO: result: $archive_cmds_need_lc_F77" >&5 +echo "${ECHO_T}$archive_cmds_need_lc_F77" >&6; } + ;; + esac + fi + ;; +esac + +{ echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5 +echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6; } +library_names_spec= +libname_spec='lib$name' +soname_spec= +shrext_cmds=".so" +postinstall_cmds= +postuninstall_cmds= +finish_cmds= +finish_eval= +shlibpath_var= +shlibpath_overrides_runpath=unknown +version_type=none +dynamic_linker="$host_os ld.so" +sys_lib_dlsearch_path_spec="/lib /usr/lib" + +need_lib_prefix=unknown +hardcode_into_libs=no + +# when you set need_version to no, make sure it does not cause -set_version +# flags to be left without arguments +need_version=unknown + +case $host_os in +aix3*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' + shlibpath_var=LIBPATH + + # AIX 3 has no versioning support, so we append a major version to the name. + soname_spec='${libname}${release}${shared_ext}$major' + ;; + +aix4* | aix5*) + version_type=linux + need_lib_prefix=no + need_version=no + hardcode_into_libs=yes + if test "$host_cpu" = ia64; then + # AIX 5 supports IA64 + library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + else + # With GCC up to 2.95.x, collect2 would create an import file + # for dependence libraries. The import file would start with + # the line `#! .'. This would cause the generated library to + # depend on `.', always an invalid library. This was fixed in + # development snapshots of GCC prior to 3.0. + case $host_os in + aix4 | aix4.[01] | aix4.[01].*) + if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' + echo ' yes ' + echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then + : + else + can_build_shared=no + fi + ;; + esac + # AIX (on Power*) has no versioning support, so currently we can not hardcode correct + # soname into executable. Probably we can add versioning support to + # collect2, so additional links can be useful in future. + if test "$aix_use_runtimelinking" = yes; then + # If using run time linking (on AIX 4.2 or later) use lib.so + # instead of lib.a to let people know that these are not + # typical AIX shared libraries. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + else + # We preserve .a as extension for shared libraries through AIX4.2 + # and later when we are not doing run time linking. + library_names_spec='${libname}${release}.a $libname.a' + soname_spec='${libname}${release}${shared_ext}$major' + fi + shlibpath_var=LIBPATH + fi + ;; + +amigaos*) + library_names_spec='$libname.ixlibrary $libname.a' + # Create ${libname}_ixlibrary.a entries in /sys/libs. + finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$echo "X$lib" | $Xsed -e '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' + ;; + +beos*) + library_names_spec='${libname}${shared_ext}' + dynamic_linker="$host_os ld.so" + shlibpath_var=LIBRARY_PATH + ;; + +bsdi[45]*) + version_type=linux + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" + sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" + # the default ld.so.conf also contains /usr/contrib/lib and + # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow + # libtool to hard-code these into programs + ;; + +cygwin* | mingw* | pw32*) + version_type=windows + shrext_cmds=".dll" + need_version=no + need_lib_prefix=no + + case $GCC,$host_os in + yes,cygwin* | yes,mingw* | yes,pw32*) + library_names_spec='$libname.dll.a' + # DLL is installed to $(libdir)/../bin by postinstall_cmds + postinstall_cmds='base_file=`basename \${file}`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname~ + chmod a+x \$dldir/$dlname' + postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ + dlpath=$dir/\$dldll~ + $rm \$dlpath' + shlibpath_overrides_runpath=yes + + case $host_os in + cygwin*) + # Cygwin DLLs use 'cyg' prefix rather than 'lib' + soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib" + ;; + mingw*) + # MinGW DLLs use traditional 'lib' prefix + soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"` + if echo "$sys_lib_search_path_spec" | grep ';[c-zC-Z]:/' >/dev/null; then + # It is most probably a Windows format PATH printed by + # mingw gcc, but we are running on Cygwin. Gcc prints its search + # path with ; separators, and with drive letters. We can handle the + # drive letters (cygwin fileutils understands them), so leave them, + # especially as we might pass files found there to a mingw objdump, + # which wouldn't understand a cygwinified path. Ahh. + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` + else + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi + ;; + pw32*) + # pw32 DLLs use 'pw' prefix rather than 'lib' + library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + ;; + esac + ;; + + *) + library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib' + ;; + esac + dynamic_linker='Win32 ld.exe' + # FIXME: first we should search . and the directory the executable is in + shlibpath_var=PATH + ;; + +darwin* | rhapsody*) + dynamic_linker="$host_os dyld" + version_type=darwin + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${versuffix}$shared_ext ${libname}${release}${major}$shared_ext ${libname}$shared_ext' + soname_spec='${libname}${release}${major}$shared_ext' + shlibpath_overrides_runpath=yes + shlibpath_var=DYLD_LIBRARY_PATH + shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' + + sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' + ;; + +dgux*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +freebsd1*) + dynamic_linker=no + ;; + +freebsd* | dragonfly*) + # DragonFly does not have aout. When/if they implement a new + # versioning mechanism, adjust this. + if test -x /usr/bin/objformat; then + objformat=`/usr/bin/objformat` + else + case $host_os in + freebsd[123]*) objformat=aout ;; + *) objformat=elf ;; + esac + fi + version_type=freebsd-$objformat + case $version_type in + freebsd-elf*) + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' + need_version=no + need_lib_prefix=no + ;; + freebsd-*) + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' + need_version=yes + ;; + esac + shlibpath_var=LD_LIBRARY_PATH + case $host_os in + freebsd2*) + shlibpath_overrides_runpath=yes + ;; + freebsd3.[01]* | freebsdelf3.[01]*) + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + freebsd3.[2-9]* | freebsdelf3.[2-9]* | \ + freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1) + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + *) # from 4.6 on, and DragonFly + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + esac + ;; + +gnu*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + hardcode_into_libs=yes + ;; + +hpux9* | hpux10* | hpux11*) + # Give a soname corresponding to the major version so that dld.sl refuses to + # link against other versions. + version_type=sunos + need_lib_prefix=no + need_version=no + case $host_cpu in + ia64*) + shrext_cmds='.so' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.so" + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + if test "X$HPUX_IA64_MODE" = X32; then + sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" + else + sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" + fi + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + hppa*64*) + shrext_cmds='.sl' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.sl" + shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + *) + shrext_cmds='.sl' + dynamic_linker="$host_os dld.sl" + shlibpath_var=SHLIB_PATH + shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + ;; + esac + # HP-UX runs *really* slowly unless shared libraries are mode 555. + postinstall_cmds='chmod 555 $lib' + ;; + +interix[3-9]*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + +irix5* | irix6* | nonstopux*) + case $host_os in + nonstopux*) version_type=nonstopux ;; + *) + if test "$lt_cv_prog_gnu_ld" = yes; then + version_type=linux + else + version_type=irix + fi ;; + esac + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' + case $host_os in + irix5* | nonstopux*) + libsuff= shlibsuff= + ;; + *) + case $LD in # libtool.m4 will add one of these switches to LD + *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") + libsuff= shlibsuff= libmagic=32-bit;; + *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") + libsuff=32 shlibsuff=N32 libmagic=N32;; + *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") + libsuff=64 shlibsuff=64 libmagic=64-bit;; + *) libsuff= shlibsuff= libmagic=never-match;; + esac + ;; + esac + shlibpath_var=LD_LIBRARY${shlibsuff}_PATH + shlibpath_overrides_runpath=no + sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" + sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" + hardcode_into_libs=yes + ;; + +# No shared lib support for Linux oldld, aout, or coff. +linux*oldld* | linux*aout* | linux*coff*) + dynamic_linker=no + ;; + +# This must be Linux ELF. +linux* | k*bsd*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + # This implies no fast_install, which is unacceptable. + # Some rework will be needed to allow for fast_install + # before this can be enabled. + hardcode_into_libs=yes + sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" + sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" + + # Append ld.so.conf contents to the search path + if test -f /etc/ld.so.conf; then + lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` + sys_lib_dlsearch_path_spec="$sys_lib_dlsearch_path_spec $lt_ld_extra" + fi + + # We used to test for /lib/ld.so.1 and disable shared libraries on + # powerpc, because MkLinux only supported shared libraries with the + # GNU dynamic linker. Since this was broken with cross compilers, + # most powerpc-linux boxes support dynamic linking these days and + # people can always --disable-shared, the test was removed, and we + # assume the GNU/Linux dynamic linker is in use. + dynamic_linker='GNU/Linux ld.so' + ;; + +netbsd*) + version_type=sunos + need_lib_prefix=no + need_version=no + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + dynamic_linker='NetBSD (a.out) ld.so' + else + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + dynamic_linker='NetBSD ld.elf_so' + fi + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + +newsos6) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +nto-qnx*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +openbsd*) + version_type=sunos + sys_lib_dlsearch_path_spec="/usr/lib" + need_lib_prefix=no + # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs. + case $host_os in + openbsd3.3 | openbsd3.3.*) need_version=yes ;; + *) need_version=no ;; + esac + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + shlibpath_var=LD_LIBRARY_PATH + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + case $host_os in + openbsd2.[89] | openbsd2.[89].*) + shlibpath_overrides_runpath=no + ;; + *) + shlibpath_overrides_runpath=yes + ;; + esac + else + shlibpath_overrides_runpath=yes + fi + ;; + +os2*) + libname_spec='$name' + shrext_cmds=".dll" + need_lib_prefix=no + library_names_spec='$libname${shared_ext} $libname.a' + dynamic_linker='OS/2 ld.exe' + shlibpath_var=LIBPATH + ;; + +osf3* | osf4* | osf5*) + version_type=osf + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" + sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" + ;; + +rdos*) + dynamic_linker=no + ;; + +solaris*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + # ldd complains unless libraries are executable + postinstall_cmds='chmod +x $lib' + ;; + +sunos4*) + version_type=sunos + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + if test "$with_gnu_ld" = yes; then + need_lib_prefix=no + fi + need_version=yes + ;; + +sysv4 | sysv4.3*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + case $host_vendor in + sni) + shlibpath_overrides_runpath=no + need_lib_prefix=no + export_dynamic_flag_spec='${wl}-Blargedynsym' + runpath_var=LD_RUN_PATH + ;; + siemens) + need_lib_prefix=no + ;; + motorola) + need_lib_prefix=no + need_version=no + shlibpath_overrides_runpath=no + sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' + ;; + esac + ;; + +sysv4*MP*) + if test -d /usr/nec ;then + version_type=linux + library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' + soname_spec='$libname${shared_ext}.$major' + shlibpath_var=LD_LIBRARY_PATH + fi + ;; + +sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) + version_type=freebsd-elf + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + hardcode_into_libs=yes + if test "$with_gnu_ld" = yes; then + sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' + shlibpath_overrides_runpath=no + else + sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' + shlibpath_overrides_runpath=yes + case $host_os in + sco3.2v5*) + sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" + ;; + esac + fi + sys_lib_dlsearch_path_spec='/usr/lib' + ;; + +uts4*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +*) + dynamic_linker=no + ;; +esac +{ echo "$as_me:$LINENO: result: $dynamic_linker" >&5 +echo "${ECHO_T}$dynamic_linker" >&6; } +test "$dynamic_linker" = no && can_build_shared=no + +variables_saved_for_relink="PATH $shlibpath_var $runpath_var" +if test "$GCC" = yes; then + variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" +fi + +{ echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5 +echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6; } +hardcode_action_F77= +if test -n "$hardcode_libdir_flag_spec_F77" || \ + test -n "$runpath_var_F77" || \ + test "X$hardcode_automatic_F77" = "Xyes" ; then + + # We can hardcode non-existant directories. + if test "$hardcode_direct_F77" != no && + # If the only mechanism to avoid hardcoding is shlibpath_var, we + # have to relink, otherwise we might link with an installed library + # when we should be linking with a yet-to-be-installed one + ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, F77)" != no && + test "$hardcode_minus_L_F77" != no; then + # Linking always hardcodes the temporary library directory. + hardcode_action_F77=relink + else + # We can link without hardcoding, and we can hardcode nonexisting dirs. + hardcode_action_F77=immediate + fi +else + # We cannot hardcode anything, or else we can only hardcode existing + # directories. + hardcode_action_F77=unsupported +fi +{ echo "$as_me:$LINENO: result: $hardcode_action_F77" >&5 +echo "${ECHO_T}$hardcode_action_F77" >&6; } + +if test "$hardcode_action_F77" = relink; then + # Fast installation is not supported + enable_fast_install=no +elif test "$shlibpath_overrides_runpath" = yes || + test "$enable_shared" = no; then + # Fast installation is not necessary + enable_fast_install=needless +fi + + +# The else clause should only fire when bootstrapping the +# libtool distribution, otherwise you forgot to ship ltmain.sh +# with your package, and you will get complaints that there are +# no rules to generate ltmain.sh. +if test -f "$ltmain"; then + # See if we are running on zsh, and set the options which allow our commands through + # without removal of \ escapes. + if test -n "${ZSH_VERSION+set}" ; then + setopt NO_GLOB_SUBST + fi + # Now quote all the things that may contain metacharacters while being + # careful not to overquote the AC_SUBSTed values. We take copies of the + # variables and quote the copies for generation of the libtool script. + for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTCFLAGS NM \ + SED SHELL STRIP \ + libname_spec library_names_spec soname_spec extract_expsyms_cmds \ + old_striplib striplib file_magic_cmd finish_cmds finish_eval \ + deplibs_check_method reload_flag reload_cmds need_locks \ + lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \ + lt_cv_sys_global_symbol_to_c_name_address \ + sys_lib_search_path_spec sys_lib_dlsearch_path_spec \ + old_postinstall_cmds old_postuninstall_cmds \ + compiler_F77 \ + CC_F77 \ + LD_F77 \ + lt_prog_compiler_wl_F77 \ + lt_prog_compiler_pic_F77 \ + lt_prog_compiler_static_F77 \ + lt_prog_compiler_no_builtin_flag_F77 \ + export_dynamic_flag_spec_F77 \ + thread_safe_flag_spec_F77 \ + whole_archive_flag_spec_F77 \ + enable_shared_with_static_runtimes_F77 \ + old_archive_cmds_F77 \ + old_archive_from_new_cmds_F77 \ + predep_objects_F77 \ + postdep_objects_F77 \ + predeps_F77 \ + postdeps_F77 \ + compiler_lib_search_path_F77 \ + archive_cmds_F77 \ + archive_expsym_cmds_F77 \ + postinstall_cmds_F77 \ + postuninstall_cmds_F77 \ + old_archive_from_expsyms_cmds_F77 \ + allow_undefined_flag_F77 \ + no_undefined_flag_F77 \ + export_symbols_cmds_F77 \ + hardcode_libdir_flag_spec_F77 \ + hardcode_libdir_flag_spec_ld_F77 \ + hardcode_libdir_separator_F77 \ + hardcode_automatic_F77 \ + module_cmds_F77 \ + module_expsym_cmds_F77 \ + lt_cv_prog_compiler_c_o_F77 \ + fix_srcfile_path_F77 \ + exclude_expsyms_F77 \ + include_expsyms_F77; do + + case $var in + old_archive_cmds_F77 | \ + old_archive_from_new_cmds_F77 | \ + archive_cmds_F77 | \ + archive_expsym_cmds_F77 | \ + module_cmds_F77 | \ + module_expsym_cmds_F77 | \ + old_archive_from_expsyms_cmds_F77 | \ + export_symbols_cmds_F77 | \ + extract_expsyms_cmds | reload_cmds | finish_cmds | \ + postinstall_cmds | postuninstall_cmds | \ + old_postinstall_cmds | old_postuninstall_cmds | \ + sys_lib_search_path_spec | sys_lib_dlsearch_path_spec) + # Double-quote double-evaled strings. + eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\"" + ;; + *) + eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`\\\"" + ;; + esac + done + + case $lt_echo in + *'\$0 --fallback-echo"') + lt_echo=`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$/$0 --fallback-echo"/'` + ;; + esac + +cfgfile="$ofile" + + cat <<__EOF__ >> "$cfgfile" +# ### BEGIN LIBTOOL TAG CONFIG: $tagname + +# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: + +# Shell to use when invoking shell scripts. +SHELL=$lt_SHELL + +# Whether or not to build shared libraries. +build_libtool_libs=$enable_shared + +# Whether or not to build static libraries. +build_old_libs=$enable_static + +# Whether or not to add -lc for building shared libraries. +build_libtool_need_lc=$archive_cmds_need_lc_F77 + +# Whether or not to disallow shared libs when runtime libs are static +allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes_F77 + +# Whether or not to optimize for fast installation. +fast_install=$enable_fast_install + +# The host system. +host_alias=$host_alias +host=$host +host_os=$host_os + +# The build system. +build_alias=$build_alias +build=$build +build_os=$build_os + +# An echo program that does not interpret backslashes. +echo=$lt_echo + +# The archiver. +AR=$lt_AR +AR_FLAGS=$lt_AR_FLAGS + +# A C compiler. +LTCC=$lt_LTCC + +# LTCC compiler flags. +LTCFLAGS=$lt_LTCFLAGS + +# A language-specific compiler. +CC=$lt_compiler_F77 + +# Is the compiler the GNU C compiler? +with_gcc=$GCC_F77 + +# An ERE matcher. +EGREP=$lt_EGREP + +# The linker used to build libraries. +LD=$lt_LD_F77 + +# Whether we need hard or soft links. +LN_S=$lt_LN_S + +# A BSD-compatible nm program. +NM=$lt_NM + +# A symbol stripping program +STRIP=$lt_STRIP + +# Used to examine libraries when file_magic_cmd begins "file" +MAGIC_CMD=$MAGIC_CMD + +# Used on cygwin: DLL creation program. +DLLTOOL="$DLLTOOL" + +# Used on cygwin: object dumper. +OBJDUMP="$OBJDUMP" + +# Used on cygwin: assembler. +AS="$AS" + +# The name of the directory that contains temporary libtool files. +objdir=$objdir + +# How to create reloadable object files. +reload_flag=$lt_reload_flag +reload_cmds=$lt_reload_cmds + +# How to pass a linker flag through the compiler. +wl=$lt_lt_prog_compiler_wl_F77 + +# Object file suffix (normally "o"). +objext="$ac_objext" + +# Old archive suffix (normally "a"). +libext="$libext" + +# Shared library suffix (normally ".so"). +shrext_cmds='$shrext_cmds' + +# Executable file suffix (normally ""). +exeext="$exeext" + +# Additional compiler flags for building library objects. +pic_flag=$lt_lt_prog_compiler_pic_F77 +pic_mode=$pic_mode + +# What is the maximum length of a command? +max_cmd_len=$lt_cv_sys_max_cmd_len + +# Does compiler simultaneously support -c and -o options? +compiler_c_o=$lt_lt_cv_prog_compiler_c_o_F77 + +# Must we lock files when doing compilation? +need_locks=$lt_need_locks + +# Do we need the lib prefix for modules? +need_lib_prefix=$need_lib_prefix + +# Do we need a version for libraries? +need_version=$need_version + +# Whether dlopen is supported. +dlopen_support=$enable_dlopen + +# Whether dlopen of programs is supported. +dlopen_self=$enable_dlopen_self + +# Whether dlopen of statically linked programs is supported. +dlopen_self_static=$enable_dlopen_self_static + +# Compiler flag to prevent dynamic linking. +link_static_flag=$lt_lt_prog_compiler_static_F77 + +# Compiler flag to turn off builtin functions. +no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag_F77 + +# Compiler flag to allow reflexive dlopens. +export_dynamic_flag_spec=$lt_export_dynamic_flag_spec_F77 + +# Compiler flag to generate shared objects directly from archives. +whole_archive_flag_spec=$lt_whole_archive_flag_spec_F77 + +# Compiler flag to generate thread-safe objects. +thread_safe_flag_spec=$lt_thread_safe_flag_spec_F77 + +# Library versioning type. +version_type=$version_type + +# Format of library name prefix. +libname_spec=$lt_libname_spec + +# List of archive names. First name is the real one, the rest are links. +# The last name is the one that the linker finds with -lNAME. +library_names_spec=$lt_library_names_spec + +# The coded name of the library, if different from the real name. +soname_spec=$lt_soname_spec + +# Commands used to build and install an old-style archive. +RANLIB=$lt_RANLIB +old_archive_cmds=$lt_old_archive_cmds_F77 +old_postinstall_cmds=$lt_old_postinstall_cmds +old_postuninstall_cmds=$lt_old_postuninstall_cmds + +# Create an old-style archive from a shared archive. +old_archive_from_new_cmds=$lt_old_archive_from_new_cmds_F77 + +# Create a temporary old-style archive to link instead of a shared archive. +old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds_F77 + +# Commands used to build and install a shared archive. +archive_cmds=$lt_archive_cmds_F77 +archive_expsym_cmds=$lt_archive_expsym_cmds_F77 +postinstall_cmds=$lt_postinstall_cmds +postuninstall_cmds=$lt_postuninstall_cmds + +# Commands used to build a loadable module (assumed same as above if empty) +module_cmds=$lt_module_cmds_F77 +module_expsym_cmds=$lt_module_expsym_cmds_F77 + +# Commands to strip libraries. +old_striplib=$lt_old_striplib +striplib=$lt_striplib + +# Dependencies to place before the objects being linked to create a +# shared library. +predep_objects=$lt_predep_objects_F77 + +# Dependencies to place after the objects being linked to create a +# shared library. +postdep_objects=$lt_postdep_objects_F77 + +# Dependencies to place before the objects being linked to create a +# shared library. +predeps=$lt_predeps_F77 + +# Dependencies to place after the objects being linked to create a +# shared library. +postdeps=$lt_postdeps_F77 + +# The library search path used internally by the compiler when linking +# a shared library. +compiler_lib_search_path=$lt_compiler_lib_search_path_F77 + +# Method to check whether dependent libraries are shared objects. +deplibs_check_method=$lt_deplibs_check_method + +# Command to use when deplibs_check_method == file_magic. +file_magic_cmd=$lt_file_magic_cmd + +# Flag that allows shared libraries with undefined symbols to be built. +allow_undefined_flag=$lt_allow_undefined_flag_F77 + +# Flag that forces no undefined symbols. +no_undefined_flag=$lt_no_undefined_flag_F77 + +# Commands used to finish a libtool library installation in a directory. +finish_cmds=$lt_finish_cmds + +# Same as above, but a single script fragment to be evaled but not shown. +finish_eval=$lt_finish_eval + +# Take the output of nm and produce a listing of raw symbols and C names. +global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe + +# Transform the output of nm in a proper C declaration +global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl + +# Transform the output of nm in a C name address pair +global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address + +# This is the shared library runtime path variable. +runpath_var=$runpath_var + +# This is the shared library path variable. +shlibpath_var=$shlibpath_var + +# Is shlibpath searched before the hard-coded library search path? +shlibpath_overrides_runpath=$shlibpath_overrides_runpath + +# How to hardcode a shared library path into an executable. +hardcode_action=$hardcode_action_F77 + +# Whether we should hardcode library paths into libraries. +hardcode_into_libs=$hardcode_into_libs + +# Flag to hardcode \$libdir into a binary during linking. +# This must work even if \$libdir does not exist. +hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec_F77 + +# If ld is used when linking, flag to hardcode \$libdir into +# a binary during linking. This must work even if \$libdir does +# not exist. +hardcode_libdir_flag_spec_ld=$lt_hardcode_libdir_flag_spec_ld_F77 + +# Whether we need a single -rpath flag with a separated argument. +hardcode_libdir_separator=$lt_hardcode_libdir_separator_F77 + +# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the +# resulting binary. +hardcode_direct=$hardcode_direct_F77 + +# Set to yes if using the -LDIR flag during linking hardcodes DIR into the +# resulting binary. +hardcode_minus_L=$hardcode_minus_L_F77 + +# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into +# the resulting binary. +hardcode_shlibpath_var=$hardcode_shlibpath_var_F77 + +# Set to yes if building a shared library automatically hardcodes DIR into the library +# and all subsequent libraries and executables linked against it. +hardcode_automatic=$hardcode_automatic_F77 + +# Variables whose values should be saved in libtool wrapper scripts and +# restored at relink time. +variables_saved_for_relink="$variables_saved_for_relink" + +# Whether libtool must link a program against all its dependency libraries. +link_all_deplibs=$link_all_deplibs_F77 + +# Compile-time system search path for libraries +sys_lib_search_path_spec=$lt_sys_lib_search_path_spec + +# Run-time system search path for libraries +sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec + +# Fix the shell variable \$srcfile for the compiler. +fix_srcfile_path=$lt_fix_srcfile_path + +# Set to yes if exported symbols are required. +always_export_symbols=$always_export_symbols_F77 + +# The commands to list exported symbols. +export_symbols_cmds=$lt_export_symbols_cmds_F77 + +# The commands to extract the exported symbol list from a shared archive. +extract_expsyms_cmds=$lt_extract_expsyms_cmds + +# Symbols that should not be listed in the preloaded symbols. +exclude_expsyms=$lt_exclude_expsyms_F77 + +# Symbols that must always be exported. +include_expsyms=$lt_include_expsyms_F77 + +# ### END LIBTOOL TAG CONFIG: $tagname + +__EOF__ + + +else + # If there is no Makefile yet, we rely on a make rule to execute + # `config.status --recheck' to rerun these tests and create the + # libtool script then. + ltmain_in=`echo $ltmain | sed -e 's/\.sh$/.in/'` + if test -f "$ltmain_in"; then + test -f Makefile && make "$ltmain" + fi +fi + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +CC="$lt_save_CC" + + else + tagname="" + fi + ;; + + GCJ) + if test -n "$GCJ" && test "X$GCJ" != "Xno"; then + + +# Source file extension for Java test sources. +ac_ext=java + +# Object file extension for compiled Java test sources. +objext=o +objext_GCJ=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code="class foo {}" + +# Code to be used in simple link tests +lt_simple_link_test_code='public class conftest { public static void main(String[] argv) {}; }' + +# ltmain only uses $CC for tagged configurations so make sure $CC is set. + +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} + +# If no C compiler flags were specified, use CFLAGS. +LTCFLAGS=${LTCFLAGS-"$CFLAGS"} + +# Allow CC to be a program name with arguments. +compiler=$CC + + +# save warnings/boilerplate of simple test code +ac_outfile=conftest.$ac_objext +echo "$lt_simple_compile_test_code" >conftest.$ac_ext +eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_compiler_boilerplate=`cat conftest.err` +$rm conftest* + +ac_outfile=conftest.$ac_objext +echo "$lt_simple_link_test_code" >conftest.$ac_ext +eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_linker_boilerplate=`cat conftest.err` +$rm conftest* + + +# Allow CC to be a program name with arguments. +lt_save_CC="$CC" +CC=${GCJ-"gcj"} +compiler=$CC +compiler_GCJ=$CC +for cc_temp in $compiler""; do + case $cc_temp in + compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; + distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; + \-*) ;; + *) break;; + esac +done +cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"` + + +# GCJ did not exist at the time GCC didn't implicitly link libc in. +archive_cmds_need_lc_GCJ=no + +old_archive_cmds_GCJ=$old_archive_cmds + + +lt_prog_compiler_no_builtin_flag_GCJ= + +if test "$GCC" = yes; then + lt_prog_compiler_no_builtin_flag_GCJ=' -fno-builtin' + + +{ echo "$as_me:$LINENO: checking if $compiler supports -fno-rtti -fno-exceptions" >&5 +echo $ECHO_N "checking if $compiler supports -fno-rtti -fno-exceptions... $ECHO_C" >&6; } +if test "${lt_cv_prog_compiler_rtti_exceptions+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_cv_prog_compiler_rtti_exceptions=no + ac_outfile=conftest.$ac_objext + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="-fno-rtti -fno-exceptions" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:16662: $lt_compile\"" >&5) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&5 + echo "$as_me:16666: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings other than the usual output. + $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then + lt_cv_prog_compiler_rtti_exceptions=yes + fi + fi + $rm conftest* + +fi +{ echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_rtti_exceptions" >&5 +echo "${ECHO_T}$lt_cv_prog_compiler_rtti_exceptions" >&6; } + +if test x"$lt_cv_prog_compiler_rtti_exceptions" = xyes; then + lt_prog_compiler_no_builtin_flag_GCJ="$lt_prog_compiler_no_builtin_flag_GCJ -fno-rtti -fno-exceptions" +else + : +fi + +fi + +lt_prog_compiler_wl_GCJ= +lt_prog_compiler_pic_GCJ= +lt_prog_compiler_static_GCJ= + +{ echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5 +echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6; } + + if test "$GCC" = yes; then + lt_prog_compiler_wl_GCJ='-Wl,' + lt_prog_compiler_static_GCJ='-static' + + case $host_os in + aix*) + # All AIX code is PIC. + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static_GCJ='-Bstatic' + fi + ;; + + amigaos*) + # FIXME: we need at least 68020 code to build shared libraries, but + # adding the `-m68020' flag to GCC prevents building anything better, + # like `-m68040'. + lt_prog_compiler_pic_GCJ='-m68020 -resident32 -malways-restore-a4' + ;; + + beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) + # PIC is the default for these OSes. + ;; + + mingw* | cygwin* | pw32* | os2*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + # Although the cygwin gcc ignores -fPIC, still need this for old-style + # (--disable-auto-import) libraries + lt_prog_compiler_pic_GCJ='-DDLL_EXPORT' + ;; + + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + lt_prog_compiler_pic_GCJ='-fno-common' + ;; + + interix[3-9]*) + # Interix 3.x gcc -fpic/-fPIC options generate broken code. + # Instead, we relocate shared libraries at runtime. + ;; + + msdosdjgpp*) + # Just because we use GCC doesn't mean we suddenly get shared libraries + # on systems that don't support them. + lt_prog_compiler_can_build_shared_GCJ=no + enable_shared=no + ;; + + sysv4*MP*) + if test -d /usr/nec; then + lt_prog_compiler_pic_GCJ=-Kconform_pic + fi + ;; + + hpux*) + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case $host_cpu in + hppa*64*|ia64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic_GCJ='-fPIC' + ;; + esac + ;; + + *) + lt_prog_compiler_pic_GCJ='-fPIC' + ;; + esac + else + # PORTME Check for flag to pass linker flags through the system compiler. + case $host_os in + aix*) + lt_prog_compiler_wl_GCJ='-Wl,' + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static_GCJ='-Bstatic' + else + lt_prog_compiler_static_GCJ='-bnso -bI:/lib/syscalls.exp' + fi + ;; + darwin*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + case $cc_basename in + xlc*) + lt_prog_compiler_pic_GCJ='-qnocommon' + lt_prog_compiler_wl_GCJ='-Wl,' + ;; + esac + ;; + + mingw* | cygwin* | pw32* | os2*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + lt_prog_compiler_pic_GCJ='-DDLL_EXPORT' + ;; + + hpux9* | hpux10* | hpux11*) + lt_prog_compiler_wl_GCJ='-Wl,' + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case $host_cpu in + hppa*64*|ia64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic_GCJ='+Z' + ;; + esac + # Is there a better lt_prog_compiler_static that works with the bundled CC? + lt_prog_compiler_static_GCJ='${wl}-a ${wl}archive' + ;; + + irix5* | irix6* | nonstopux*) + lt_prog_compiler_wl_GCJ='-Wl,' + # PIC (with -KPIC) is the default. + lt_prog_compiler_static_GCJ='-non_shared' + ;; + + newsos6) + lt_prog_compiler_pic_GCJ='-KPIC' + lt_prog_compiler_static_GCJ='-Bstatic' + ;; + + linux* | k*bsd*-gnu) + case $cc_basename in + icc* | ecc*) + lt_prog_compiler_wl_GCJ='-Wl,' + lt_prog_compiler_pic_GCJ='-KPIC' + lt_prog_compiler_static_GCJ='-static' + ;; + pgcc* | pgf77* | pgf90* | pgf95*) + # Portland Group compilers (*not* the Pentium gcc compiler, + # which looks to be a dead project) + lt_prog_compiler_wl_GCJ='-Wl,' + lt_prog_compiler_pic_GCJ='-fpic' + lt_prog_compiler_static_GCJ='-Bstatic' + ;; + ccc*) + lt_prog_compiler_wl_GCJ='-Wl,' + # All Alpha code is PIC. + lt_prog_compiler_static_GCJ='-non_shared' + ;; + *) + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) + # Sun C 5.9 + lt_prog_compiler_pic_GCJ='-KPIC' + lt_prog_compiler_static_GCJ='-Bstatic' + lt_prog_compiler_wl_GCJ='-Wl,' + ;; + *Sun\ F*) + # Sun Fortran 8.3 passes all unrecognized flags to the linker + lt_prog_compiler_pic_GCJ='-KPIC' + lt_prog_compiler_static_GCJ='-Bstatic' + lt_prog_compiler_wl_GCJ='' + ;; + esac + ;; + esac + ;; + + osf3* | osf4* | osf5*) + lt_prog_compiler_wl_GCJ='-Wl,' + # All OSF/1 code is PIC. + lt_prog_compiler_static_GCJ='-non_shared' + ;; + + rdos*) + lt_prog_compiler_static_GCJ='-non_shared' + ;; + + solaris*) + lt_prog_compiler_pic_GCJ='-KPIC' + lt_prog_compiler_static_GCJ='-Bstatic' + case $cc_basename in + f77* | f90* | f95*) + lt_prog_compiler_wl_GCJ='-Qoption ld ';; + *) + lt_prog_compiler_wl_GCJ='-Wl,';; + esac + ;; + + sunos4*) + lt_prog_compiler_wl_GCJ='-Qoption ld ' + lt_prog_compiler_pic_GCJ='-PIC' + lt_prog_compiler_static_GCJ='-Bstatic' + ;; + + sysv4 | sysv4.2uw2* | sysv4.3*) + lt_prog_compiler_wl_GCJ='-Wl,' + lt_prog_compiler_pic_GCJ='-KPIC' + lt_prog_compiler_static_GCJ='-Bstatic' + ;; + + sysv4*MP*) + if test -d /usr/nec ;then + lt_prog_compiler_pic_GCJ='-Kconform_pic' + lt_prog_compiler_static_GCJ='-Bstatic' + fi + ;; + + sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) + lt_prog_compiler_wl_GCJ='-Wl,' + lt_prog_compiler_pic_GCJ='-KPIC' + lt_prog_compiler_static_GCJ='-Bstatic' + ;; + + unicos*) + lt_prog_compiler_wl_GCJ='-Wl,' + lt_prog_compiler_can_build_shared_GCJ=no + ;; + + uts4*) + lt_prog_compiler_pic_GCJ='-pic' + lt_prog_compiler_static_GCJ='-Bstatic' + ;; + + *) + lt_prog_compiler_can_build_shared_GCJ=no + ;; + esac + fi + +{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_GCJ" >&5 +echo "${ECHO_T}$lt_prog_compiler_pic_GCJ" >&6; } + +# +# Check to make sure the PIC flag actually works. +# +if test -n "$lt_prog_compiler_pic_GCJ"; then + +{ echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_pic_GCJ works" >&5 +echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic_GCJ works... $ECHO_C" >&6; } +if test "${lt_prog_compiler_pic_works_GCJ+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_prog_compiler_pic_works_GCJ=no + ac_outfile=conftest.$ac_objext + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="$lt_prog_compiler_pic_GCJ" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:16952: $lt_compile\"" >&5) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&5 + echo "$as_me:16956: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings other than the usual output. + $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then + lt_prog_compiler_pic_works_GCJ=yes + fi + fi + $rm conftest* + +fi +{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works_GCJ" >&5 +echo "${ECHO_T}$lt_prog_compiler_pic_works_GCJ" >&6; } + +if test x"$lt_prog_compiler_pic_works_GCJ" = xyes; then + case $lt_prog_compiler_pic_GCJ in + "" | " "*) ;; + *) lt_prog_compiler_pic_GCJ=" $lt_prog_compiler_pic_GCJ" ;; + esac +else + lt_prog_compiler_pic_GCJ= + lt_prog_compiler_can_build_shared_GCJ=no +fi + +fi +case $host_os in + # For platforms which do not support PIC, -DPIC is meaningless: + *djgpp*) + lt_prog_compiler_pic_GCJ= + ;; + *) + lt_prog_compiler_pic_GCJ="$lt_prog_compiler_pic_GCJ" + ;; +esac + +# +# Check to make sure the static flag actually works. +# +wl=$lt_prog_compiler_wl_GCJ eval lt_tmp_static_flag=\"$lt_prog_compiler_static_GCJ\" +{ echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_flag works" >&5 +echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works... $ECHO_C" >&6; } +if test "${lt_prog_compiler_static_works_GCJ+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_prog_compiler_static_works_GCJ=no + save_LDFLAGS="$LDFLAGS" + LDFLAGS="$LDFLAGS $lt_tmp_static_flag" + echo "$lt_simple_link_test_code" > conftest.$ac_ext + if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then + # The linker can only warn and ignore the option if not recognized + # So say no if there are warnings + if test -s conftest.err; then + # Append any errors to the config.log. + cat conftest.err 1>&5 + $echo "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if diff conftest.exp conftest.er2 >/dev/null; then + lt_prog_compiler_static_works_GCJ=yes + fi + else + lt_prog_compiler_static_works_GCJ=yes + fi + fi + $rm conftest* + LDFLAGS="$save_LDFLAGS" + +fi +{ echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works_GCJ" >&5 +echo "${ECHO_T}$lt_prog_compiler_static_works_GCJ" >&6; } + +if test x"$lt_prog_compiler_static_works_GCJ" = xyes; then + : +else + lt_prog_compiler_static_GCJ= +fi + + +{ echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5 +echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6; } +if test "${lt_cv_prog_compiler_c_o_GCJ+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_cv_prog_compiler_c_o_GCJ=no + $rm -r conftest 2>/dev/null + mkdir conftest + cd conftest + mkdir out + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + lt_compiler_flag="-o out/conftest2.$ac_objext" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:17056: $lt_compile\"" >&5) + (eval "$lt_compile" 2>out/conftest.err) + ac_status=$? + cat out/conftest.err >&5 + echo "$as_me:17060: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s out/conftest2.$ac_objext + then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp + $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 + if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then + lt_cv_prog_compiler_c_o_GCJ=yes + fi + fi + chmod u+w . 2>&5 + $rm conftest* + # SGI C++ compiler will create directory out/ii_files/ for + # template instantiation + test -d out/ii_files && $rm out/ii_files/* && rmdir out/ii_files + $rm out/* && rmdir out + cd .. + rmdir conftest + $rm conftest* + +fi +{ echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o_GCJ" >&5 +echo "${ECHO_T}$lt_cv_prog_compiler_c_o_GCJ" >&6; } + + +hard_links="nottested" +if test "$lt_cv_prog_compiler_c_o_GCJ" = no && test "$need_locks" != no; then + # do not overwrite the value of need_locks provided by the user + { echo "$as_me:$LINENO: checking if we can lock with hard links" >&5 +echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6; } + hard_links=yes + $rm conftest* + ln conftest.a conftest.b 2>/dev/null && hard_links=no + touch conftest.a + ln conftest.a conftest.b 2>&5 || hard_links=no + ln conftest.a conftest.b 2>/dev/null && hard_links=no + { echo "$as_me:$LINENO: result: $hard_links" >&5 +echo "${ECHO_T}$hard_links" >&6; } + if test "$hard_links" = no; then + { echo "$as_me:$LINENO: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5 +echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;} + need_locks=warn + fi +else + need_locks=no +fi + +{ echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5 +echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6; } + + runpath_var= + allow_undefined_flag_GCJ= + enable_shared_with_static_runtimes_GCJ=no + archive_cmds_GCJ= + archive_expsym_cmds_GCJ= + old_archive_From_new_cmds_GCJ= + old_archive_from_expsyms_cmds_GCJ= + export_dynamic_flag_spec_GCJ= + whole_archive_flag_spec_GCJ= + thread_safe_flag_spec_GCJ= + hardcode_libdir_flag_spec_GCJ= + hardcode_libdir_flag_spec_ld_GCJ= + hardcode_libdir_separator_GCJ= + hardcode_direct_GCJ=no + hardcode_minus_L_GCJ=no + hardcode_shlibpath_var_GCJ=unsupported + link_all_deplibs_GCJ=unknown + hardcode_automatic_GCJ=no + module_cmds_GCJ= + module_expsym_cmds_GCJ= + always_export_symbols_GCJ=no + export_symbols_cmds_GCJ='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + # include_expsyms should be a list of space-separated symbols to be *always* + # included in the symbol list + include_expsyms_GCJ= + # exclude_expsyms can be an extended regexp of symbols to exclude + # it will be wrapped by ` (' and `)$', so one must not match beginning or + # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc', + # as well as any symbol that contains `d'. + exclude_expsyms_GCJ="_GLOBAL_OFFSET_TABLE_" + # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out + # platforms (ab)use it in PIC code, but their linkers get confused if + # the symbol is explicitly referenced. Since portable code cannot + # rely on this symbol name, it's probably fine to never include it in + # preloaded symbol tables. + extract_expsyms_cmds= + # Just being paranoid about ensuring that cc_basename is set. + for cc_temp in $compiler""; do + case $cc_temp in + compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; + distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; + \-*) ;; + *) break;; + esac +done +cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"` + + case $host_os in + cygwin* | mingw* | pw32*) + # FIXME: the MSVC++ port hasn't been tested in a loooong time + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + if test "$GCC" != yes; then + with_gnu_ld=no + fi + ;; + interix*) + # we just hope/assume this is gcc and not c89 (= MSVC++) + with_gnu_ld=yes + ;; + openbsd*) + with_gnu_ld=no + ;; + esac + + ld_shlibs_GCJ=yes + if test "$with_gnu_ld" = yes; then + # If archive_cmds runs LD, not CC, wlarc should be empty + wlarc='${wl}' + + # Set some defaults for GNU ld with shared library support. These + # are reset later if shared libraries are not supported. Putting them + # here allows them to be overridden if necessary. + runpath_var=LD_RUN_PATH + hardcode_libdir_flag_spec_GCJ='${wl}--rpath ${wl}$libdir' + export_dynamic_flag_spec_GCJ='${wl}--export-dynamic' + # ancient GNU ld didn't support --whole-archive et. al. + if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then + whole_archive_flag_spec_GCJ="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' + else + whole_archive_flag_spec_GCJ= + fi + supports_anon_versioning=no + case `$LD -v 2>/dev/null` in + *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11 + *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... + *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... + *\ 2.11.*) ;; # other 2.11 versions + *) supports_anon_versioning=yes ;; + esac + + # See if GNU ld supports shared libraries. + case $host_os in + aix3* | aix4* | aix5*) + # On AIX/PPC, the GNU linker is very broken + if test "$host_cpu" != ia64; then + ld_shlibs_GCJ=no + cat <&2 + +*** Warning: the GNU linker, at least up to release 2.9.1, is reported +*** to be unable to reliably create shared libraries on AIX. +*** Therefore, libtool is disabling shared libraries support. If you +*** really care for shared libraries, you may want to modify your PATH +*** so that a non-GNU linker is found, and then restart. + +EOF + fi + ;; + + amigaos*) + archive_cmds_GCJ='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + hardcode_libdir_flag_spec_GCJ='-L$libdir' + hardcode_minus_L_GCJ=yes + + # Samuel A. Falvo II reports + # that the semantics of dynamic libraries on AmigaOS, at least up + # to version 4, is to share data among multiple programs linked + # with the same dynamic library. Since this doesn't match the + # behavior of shared libraries on other platforms, we can't use + # them. + ld_shlibs_GCJ=no + ;; + + beos*) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + allow_undefined_flag_GCJ=unsupported + # Joseph Beckenbach says some releases of gcc + # support --undefined. This deserves some investigation. FIXME + archive_cmds_GCJ='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + else + ld_shlibs_GCJ=no + fi + ;; + + cygwin* | mingw* | pw32*) + # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, GCJ) is actually meaningless, + # as there is no search path for DLLs. + hardcode_libdir_flag_spec_GCJ='-L$libdir' + allow_undefined_flag_GCJ=unsupported + always_export_symbols_GCJ=no + enable_shared_with_static_runtimes_GCJ=yes + export_symbols_cmds_GCJ='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/'\'' -e '\''/^[AITW][ ]/s/.*[ ]//'\'' | sort | uniq > $export_symbols' + + if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then + archive_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + # If the export-symbols file already is a .def file (1st line + # is EXPORTS), use it as is; otherwise, prepend... + archive_expsym_cmds_GCJ='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then + cp $export_symbols $output_objdir/$soname.def; + else + echo EXPORTS > $output_objdir/$soname.def; + cat $export_symbols >> $output_objdir/$soname.def; + fi~ + $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + else + ld_shlibs_GCJ=no + fi + ;; + + interix[3-9]*) + hardcode_direct_GCJ=no + hardcode_shlibpath_var_GCJ=no + hardcode_libdir_flag_spec_GCJ='${wl}-rpath,$libdir' + export_dynamic_flag_spec_GCJ='${wl}-E' + # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. + # Instead, shared libraries are loaded at an image base (0x10000000 by + # default) and relocated if they conflict, which is a slow very memory + # consuming and fragmenting process. To avoid this, we pick a random, + # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link + # time. Moving up from 0x10000000 also allows more sbrk(2) space. + archive_cmds_GCJ='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + archive_expsym_cmds_GCJ='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + ;; + + gnu* | linux* | k*bsd*-gnu) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + tmp_addflag= + case $cc_basename,$host_cpu in + pgcc*) # Portland Group C compiler + whole_archive_flag_spec_GCJ='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive' + tmp_addflag=' $pic_flag' + ;; + pgf77* | pgf90* | pgf95*) # Portland Group f77 and f90 compilers + whole_archive_flag_spec_GCJ='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive' + tmp_addflag=' $pic_flag -Mnomain' ;; + ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 + tmp_addflag=' -i_dynamic' ;; + efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 + tmp_addflag=' -i_dynamic -nofor_main' ;; + ifc* | ifort*) # Intel Fortran compiler + tmp_addflag=' -nofor_main' ;; + esac + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) # Sun C 5.9 + whole_archive_flag_spec_GCJ='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive' + tmp_sharedflag='-G' ;; + *Sun\ F*) # Sun Fortran 8.3 + tmp_sharedflag='-G' ;; + *) + tmp_sharedflag='-shared' ;; + esac + archive_cmds_GCJ='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + + if test $supports_anon_versioning = yes; then + archive_expsym_cmds_GCJ='$echo "{ global:" > $output_objdir/$libname.ver~ + cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ + $echo "local: *; };" >> $output_objdir/$libname.ver~ + $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' + fi + else + ld_shlibs_GCJ=no + fi + ;; + + netbsd*) + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + archive_cmds_GCJ='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' + wlarc= + else + archive_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + fi + ;; + + solaris*) + if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then + ld_shlibs_GCJ=no + cat <&2 + +*** Warning: The releases 2.8.* of the GNU linker cannot reliably +*** create shared libraries on Solaris systems. Therefore, libtool +*** is disabling shared libraries support. We urge you to upgrade GNU +*** binutils to release 2.9.1 or newer. Another option is to modify +*** your PATH or compiler configuration so that the native linker is +*** used, and then restart. + +EOF + elif $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + archive_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + ld_shlibs_GCJ=no + fi + ;; + + sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) + case `$LD -v 2>&1` in + *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*) + ld_shlibs_GCJ=no + cat <<_LT_EOF 1>&2 + +*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not +*** reliably create shared libraries on SCO systems. Therefore, libtool +*** is disabling shared libraries support. We urge you to upgrade GNU +*** binutils to release 2.16.91.0.3 or newer. Another option is to modify +*** your PATH or compiler configuration so that the native linker is +*** used, and then restart. + +_LT_EOF + ;; + *) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + hardcode_libdir_flag_spec_GCJ='`test -z "$SCOABSPATH" && echo ${wl}-rpath,$libdir`' + archive_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib' + archive_expsym_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname,-retain-symbols-file,$export_symbols -o $lib' + else + ld_shlibs_GCJ=no + fi + ;; + esac + ;; + + sunos4*) + archive_cmds_GCJ='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' + wlarc= + hardcode_direct_GCJ=yes + hardcode_shlibpath_var_GCJ=no + ;; + + *) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + archive_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + ld_shlibs_GCJ=no + fi + ;; + esac + + if test "$ld_shlibs_GCJ" = no; then + runpath_var= + hardcode_libdir_flag_spec_GCJ= + export_dynamic_flag_spec_GCJ= + whole_archive_flag_spec_GCJ= + fi + else + # PORTME fill in a description of your system's linker (not GNU ld) + case $host_os in + aix3*) + allow_undefined_flag_GCJ=unsupported + always_export_symbols_GCJ=yes + archive_expsym_cmds_GCJ='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' + # Note: this linker hardcodes the directories in LIBPATH if there + # are no directories specified by -L. + hardcode_minus_L_GCJ=yes + if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then + # Neither direct hardcoding nor static linking is supported with a + # broken collect2. + hardcode_direct_GCJ=unsupported + fi + ;; + + aix4* | aix5*) + if test "$host_cpu" = ia64; then + # On IA64, the linker does run time linking by default, so we don't + # have to do anything special. + aix_use_runtimelinking=no + exp_sym_flag='-Bexport' + no_entry_flag="" + else + # If we're using GNU nm, then we don't want the "-C" option. + # -C means demangle to AIX nm, but means don't demangle with GNU nm + if $NM -V 2>&1 | grep 'GNU' > /dev/null; then + export_symbols_cmds_GCJ='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols' + else + export_symbols_cmds_GCJ='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols' + fi + aix_use_runtimelinking=no + + # Test if we are trying to use run time linking or normal + # AIX style linking. If -brtl is somewhere in LDFLAGS, we + # need to do runtime linking. + case $host_os in aix4.[23]|aix4.[23].*|aix5*) + for ld_flag in $LDFLAGS; do + if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then + aix_use_runtimelinking=yes + break + fi + done + ;; + esac + + exp_sym_flag='-bexport' + no_entry_flag='-bnoentry' + fi + + # When large executables or shared objects are built, AIX ld can + # have problems creating the table of contents. If linking a library + # or program results in "error TOC overflow" add -mminimal-toc to + # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not + # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. + + archive_cmds_GCJ='' + hardcode_direct_GCJ=yes + hardcode_libdir_separator_GCJ=':' + link_all_deplibs_GCJ=yes + + if test "$GCC" = yes; then + case $host_os in aix4.[012]|aix4.[012].*) + # We only want to do this on AIX 4.2 and lower, the check + # below for broken collect2 doesn't work under 4.3+ + collect2name=`${CC} -print-prog-name=collect2` + if test -f "$collect2name" && \ + strings "$collect2name" | grep resolve_lib_name >/dev/null + then + # We have reworked collect2 + : + else + # We have old collect2 + hardcode_direct_GCJ=unsupported + # It fails to find uninstalled libraries when the uninstalled + # path is not listed in the libpath. Setting hardcode_minus_L + # to unsupported forces relinking + hardcode_minus_L_GCJ=yes + hardcode_libdir_flag_spec_GCJ='-L$libdir' + hardcode_libdir_separator_GCJ= + fi + ;; + esac + shared_flag='-shared' + if test "$aix_use_runtimelinking" = yes; then + shared_flag="$shared_flag "'${wl}-G' + fi + else + # not using gcc + if test "$host_cpu" = ia64; then + # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release + # chokes on -Wl,-G. The following line is correct: + shared_flag='-G' + else + if test "$aix_use_runtimelinking" = yes; then + shared_flag='${wl}-G' + else + shared_flag='${wl}-bM:SRE' + fi + fi + fi + + # It seems that -bexpall does not export symbols beginning with + # underscore (_), so it is better to generate a list of symbols to export. + always_export_symbols_GCJ=yes + if test "$aix_use_runtimelinking" = yes; then + # Warning - without using the other runtime loading flags (-brtl), + # -berok will link without error, but may produce a broken library. + allow_undefined_flag_GCJ='-berok' + # Determine the default libpath from the value encoded in an empty executable. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + +lt_aix_libpath_sed=' + /Import File Strings/,/^$/ { + /^0/ { + s/^0 *\(.*\)$/\1/ + p + } + }' +aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +# Check for a 64-bit object if we didn't find anything. +if test -z "$aix_libpath"; then + aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +fi +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi + + hardcode_libdir_flag_spec_GCJ='${wl}-blibpath:$libdir:'"$aix_libpath" + archive_expsym_cmds_GCJ="\$CC"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" + else + if test "$host_cpu" = ia64; then + hardcode_libdir_flag_spec_GCJ='${wl}-R $libdir:/usr/lib:/lib' + allow_undefined_flag_GCJ="-z nodefs" + archive_expsym_cmds_GCJ="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" + else + # Determine the default libpath from the value encoded in an empty executable. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + +lt_aix_libpath_sed=' + /Import File Strings/,/^$/ { + /^0/ { + s/^0 *\(.*\)$/\1/ + p + } + }' +aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +# Check for a 64-bit object if we didn't find anything. +if test -z "$aix_libpath"; then + aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +fi +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi + + hardcode_libdir_flag_spec_GCJ='${wl}-blibpath:$libdir:'"$aix_libpath" + # Warning - without using the other run time loading flags, + # -berok will link without error, but may produce a broken library. + no_undefined_flag_GCJ=' ${wl}-bernotok' + allow_undefined_flag_GCJ=' ${wl}-berok' + # Exported symbols can be pulled into shared objects from archives + whole_archive_flag_spec_GCJ='$convenience' + archive_cmds_need_lc_GCJ=yes + # This is similar to how AIX traditionally builds its shared libraries. + archive_expsym_cmds_GCJ="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' + fi + fi + ;; + + amigaos*) + archive_cmds_GCJ='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + hardcode_libdir_flag_spec_GCJ='-L$libdir' + hardcode_minus_L_GCJ=yes + # see comment about different semantics on the GNU ld section + ld_shlibs_GCJ=no + ;; + + bsdi[45]*) + export_dynamic_flag_spec_GCJ=-rdynamic + ;; + + cygwin* | mingw* | pw32*) + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + # hardcode_libdir_flag_spec is actually meaningless, as there is + # no search path for DLLs. + hardcode_libdir_flag_spec_GCJ=' ' + allow_undefined_flag_GCJ=unsupported + # Tell ltmain to make .lib files, not .a files. + libext=lib + # Tell ltmain to make .dll files, not .so files. + shrext_cmds=".dll" + # FIXME: Setting linknames here is a bad hack. + archive_cmds_GCJ='$CC -o $lib $libobjs $compiler_flags `echo "$deplibs" | $SED -e '\''s/ -lc$//'\''` -link -dll~linknames=' + # The linker will automatically build a .lib file if we build a DLL. + old_archive_From_new_cmds_GCJ='true' + # FIXME: Should let the user specify the lib program. + old_archive_cmds_GCJ='lib -OUT:$oldlib$oldobjs$old_deplibs' + fix_srcfile_path_GCJ='`cygpath -w "$srcfile"`' + enable_shared_with_static_runtimes_GCJ=yes + ;; + + darwin* | rhapsody*) + case $host_os in + rhapsody* | darwin1.[012]) + allow_undefined_flag_GCJ='${wl}-undefined ${wl}suppress' + ;; + *) # Darwin 1.3 on + if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then + allow_undefined_flag_GCJ='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' + else + case ${MACOSX_DEPLOYMENT_TARGET} in + 10.[012]) + allow_undefined_flag_GCJ='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' + ;; + 10.*) + allow_undefined_flag_GCJ='${wl}-undefined ${wl}dynamic_lookup' + ;; + esac + fi + ;; + esac + archive_cmds_need_lc_GCJ=no + hardcode_direct_GCJ=no + hardcode_automatic_GCJ=yes + hardcode_shlibpath_var_GCJ=unsupported + whole_archive_flag_spec_GCJ='' + link_all_deplibs_GCJ=yes + if test "$GCC" = yes ; then + output_verbose_link_cmd='echo' + archive_cmds_GCJ='$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring' + module_cmds_GCJ='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags' + # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds + archive_expsym_cmds_GCJ='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + module_expsym_cmds_GCJ='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + else + case $cc_basename in + xlc*) + output_verbose_link_cmd='echo' + archive_cmds_GCJ='$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$soname` $xlcverstring' + module_cmds_GCJ='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags' + # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds + archive_expsym_cmds_GCJ='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}$rpath/$soname $xlcverstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + module_expsym_cmds_GCJ='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + ;; + *) + ld_shlibs_GCJ=no + ;; + esac + fi + ;; + + dgux*) + archive_cmds_GCJ='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec_GCJ='-L$libdir' + hardcode_shlibpath_var_GCJ=no + ;; + + freebsd1*) + ld_shlibs_GCJ=no + ;; + + # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor + # support. Future versions do this automatically, but an explicit c++rt0.o + # does not break anything, and helps significantly (at the cost of a little + # extra space). + freebsd2.2*) + archive_cmds_GCJ='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' + hardcode_libdir_flag_spec_GCJ='-R$libdir' + hardcode_direct_GCJ=yes + hardcode_shlibpath_var_GCJ=no + ;; + + # Unfortunately, older versions of FreeBSD 2 do not have this feature. + freebsd2*) + archive_cmds_GCJ='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct_GCJ=yes + hardcode_minus_L_GCJ=yes + hardcode_shlibpath_var_GCJ=no + ;; + + # FreeBSD 3 and greater uses gcc -shared to do shared libraries. + freebsd* | dragonfly*) + archive_cmds_GCJ='$CC -shared -o $lib $libobjs $deplibs $compiler_flags' + hardcode_libdir_flag_spec_GCJ='-R$libdir' + hardcode_direct_GCJ=yes + hardcode_shlibpath_var_GCJ=no + ;; + + hpux9*) + if test "$GCC" = yes; then + archive_cmds_GCJ='$rm $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + else + archive_cmds_GCJ='$rm $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + fi + hardcode_libdir_flag_spec_GCJ='${wl}+b ${wl}$libdir' + hardcode_libdir_separator_GCJ=: + hardcode_direct_GCJ=yes + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L_GCJ=yes + export_dynamic_flag_spec_GCJ='${wl}-E' + ;; + + hpux10*) + if test "$GCC" = yes -a "$with_gnu_ld" = no; then + archive_cmds_GCJ='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds_GCJ='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' + fi + if test "$with_gnu_ld" = no; then + hardcode_libdir_flag_spec_GCJ='${wl}+b ${wl}$libdir' + hardcode_libdir_separator_GCJ=: + + hardcode_direct_GCJ=yes + export_dynamic_flag_spec_GCJ='${wl}-E' + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L_GCJ=yes + fi + ;; + + hpux11*) + if test "$GCC" = yes -a "$with_gnu_ld" = no; then + case $host_cpu in + hppa*64*) + archive_cmds_GCJ='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + ia64*) + archive_cmds_GCJ='$CC -shared ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + archive_cmds_GCJ='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + else + case $host_cpu in + hppa*64*) + archive_cmds_GCJ='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + ia64*) + archive_cmds_GCJ='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + archive_cmds_GCJ='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + fi + if test "$with_gnu_ld" = no; then + hardcode_libdir_flag_spec_GCJ='${wl}+b ${wl}$libdir' + hardcode_libdir_separator_GCJ=: + + case $host_cpu in + hppa*64*|ia64*) + hardcode_libdir_flag_spec_ld_GCJ='+b $libdir' + hardcode_direct_GCJ=no + hardcode_shlibpath_var_GCJ=no + ;; + *) + hardcode_direct_GCJ=yes + export_dynamic_flag_spec_GCJ='${wl}-E' + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L_GCJ=yes + ;; + esac + fi + ;; + + irix5* | irix6* | nonstopux*) + if test "$GCC" = yes; then + archive_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + else + archive_cmds_GCJ='$LD -shared $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + hardcode_libdir_flag_spec_ld_GCJ='-rpath $libdir' + fi + hardcode_libdir_flag_spec_GCJ='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator_GCJ=: + link_all_deplibs_GCJ=yes + ;; + + netbsd*) + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + archive_cmds_GCJ='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out + else + archive_cmds_GCJ='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF + fi + hardcode_libdir_flag_spec_GCJ='-R$libdir' + hardcode_direct_GCJ=yes + hardcode_shlibpath_var_GCJ=no + ;; + + newsos6) + archive_cmds_GCJ='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct_GCJ=yes + hardcode_libdir_flag_spec_GCJ='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator_GCJ=: + hardcode_shlibpath_var_GCJ=no + ;; + + openbsd*) + if test -f /usr/libexec/ld.so; then + hardcode_direct_GCJ=yes + hardcode_shlibpath_var_GCJ=no + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + archive_cmds_GCJ='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds_GCJ='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols' + hardcode_libdir_flag_spec_GCJ='${wl}-rpath,$libdir' + export_dynamic_flag_spec_GCJ='${wl}-E' + else + case $host_os in + openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*) + archive_cmds_GCJ='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec_GCJ='-R$libdir' + ;; + *) + archive_cmds_GCJ='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + hardcode_libdir_flag_spec_GCJ='${wl}-rpath,$libdir' + ;; + esac + fi + else + ld_shlibs_GCJ=no + fi + ;; + + os2*) + hardcode_libdir_flag_spec_GCJ='-L$libdir' + hardcode_minus_L_GCJ=yes + allow_undefined_flag_GCJ=unsupported + archive_cmds_GCJ='$echo "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$echo "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~$echo DATA >> $output_objdir/$libname.def~$echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~$echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def' + old_archive_From_new_cmds_GCJ='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def' + ;; + + osf3*) + if test "$GCC" = yes; then + allow_undefined_flag_GCJ=' ${wl}-expect_unresolved ${wl}\*' + archive_cmds_GCJ='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + else + allow_undefined_flag_GCJ=' -expect_unresolved \*' + archive_cmds_GCJ='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + fi + hardcode_libdir_flag_spec_GCJ='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator_GCJ=: + ;; + + osf4* | osf5*) # as osf3* with the addition of -msym flag + if test "$GCC" = yes; then + allow_undefined_flag_GCJ=' ${wl}-expect_unresolved ${wl}\*' + archive_cmds_GCJ='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + hardcode_libdir_flag_spec_GCJ='${wl}-rpath ${wl}$libdir' + else + allow_undefined_flag_GCJ=' -expect_unresolved \*' + archive_cmds_GCJ='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + archive_expsym_cmds_GCJ='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; echo "-hidden">> $lib.exp~ + $LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib~$rm $lib.exp' + + # Both c and cxx compiler support -rpath directly + hardcode_libdir_flag_spec_GCJ='-rpath $libdir' + fi + hardcode_libdir_separator_GCJ=: + ;; + + solaris*) + no_undefined_flag_GCJ=' -z text' + if test "$GCC" = yes; then + wlarc='${wl}' + archive_cmds_GCJ='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds_GCJ='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $CC -shared ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$rm $lib.exp' + else + wlarc='' + archive_cmds_GCJ='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' + archive_expsym_cmds_GCJ='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp' + fi + hardcode_libdir_flag_spec_GCJ='-R$libdir' + hardcode_shlibpath_var_GCJ=no + case $host_os in + solaris2.[0-5] | solaris2.[0-5].*) ;; + *) + # The compiler driver will combine and reorder linker options, + # but understands `-z linker_flag'. GCC discards it without `$wl', + # but is careful enough not to reorder. + # Supported since Solaris 2.6 (maybe 2.5.1?) + if test "$GCC" = yes; then + whole_archive_flag_spec_GCJ='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' + else + whole_archive_flag_spec_GCJ='-z allextract$convenience -z defaultextract' + fi + ;; + esac + link_all_deplibs_GCJ=yes + ;; + + sunos4*) + if test "x$host_vendor" = xsequent; then + # Use $CC to link under sequent, because it throws in some extra .o + # files that make .init and .fini sections work. + archive_cmds_GCJ='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds_GCJ='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' + fi + hardcode_libdir_flag_spec_GCJ='-L$libdir' + hardcode_direct_GCJ=yes + hardcode_minus_L_GCJ=yes + hardcode_shlibpath_var_GCJ=no + ;; + + sysv4) + case $host_vendor in + sni) + archive_cmds_GCJ='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct_GCJ=yes # is this really true??? + ;; + siemens) + ## LD is ld it makes a PLAMLIB + ## CC just makes a GrossModule. + archive_cmds_GCJ='$LD -G -o $lib $libobjs $deplibs $linker_flags' + reload_cmds_GCJ='$CC -r -o $output$reload_objs' + hardcode_direct_GCJ=no + ;; + motorola) + archive_cmds_GCJ='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct_GCJ=no #Motorola manual says yes, but my tests say they lie + ;; + esac + runpath_var='LD_RUN_PATH' + hardcode_shlibpath_var_GCJ=no + ;; + + sysv4.3*) + archive_cmds_GCJ='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_shlibpath_var_GCJ=no + export_dynamic_flag_spec_GCJ='-Bexport' + ;; + + sysv4*MP*) + if test -d /usr/nec; then + archive_cmds_GCJ='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_shlibpath_var_GCJ=no + runpath_var=LD_RUN_PATH + hardcode_runpath_var=yes + ld_shlibs_GCJ=yes + fi + ;; + + sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*) + no_undefined_flag_GCJ='${wl}-z,text' + archive_cmds_need_lc_GCJ=no + hardcode_shlibpath_var_GCJ=no + runpath_var='LD_RUN_PATH' + + if test "$GCC" = yes; then + archive_cmds_GCJ='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds_GCJ='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds_GCJ='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds_GCJ='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + fi + ;; + + sysv5* | sco3.2v5* | sco5v6*) + # Note: We can NOT use -z defs as we might desire, because we do not + # link with -lc, and that would cause any symbols used from libc to + # always be unresolved, which means just about no library would + # ever link correctly. If we're not using GNU ld we use -z text + # though, which does catch some bad symbols but isn't as heavy-handed + # as -z defs. + no_undefined_flag_GCJ='${wl}-z,text' + allow_undefined_flag_GCJ='${wl}-z,nodefs' + archive_cmds_need_lc_GCJ=no + hardcode_shlibpath_var_GCJ=no + hardcode_libdir_flag_spec_GCJ='`test -z "$SCOABSPATH" && echo ${wl}-R,$libdir`' + hardcode_libdir_separator_GCJ=':' + link_all_deplibs_GCJ=yes + export_dynamic_flag_spec_GCJ='${wl}-Bexport' + runpath_var='LD_RUN_PATH' + + if test "$GCC" = yes; then + archive_cmds_GCJ='$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds_GCJ='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds_GCJ='$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds_GCJ='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags' + fi + ;; + + uts4*) + archive_cmds_GCJ='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec_GCJ='-L$libdir' + hardcode_shlibpath_var_GCJ=no + ;; + + *) + ld_shlibs_GCJ=no + ;; + esac + fi + +{ echo "$as_me:$LINENO: result: $ld_shlibs_GCJ" >&5 +echo "${ECHO_T}$ld_shlibs_GCJ" >&6; } +test "$ld_shlibs_GCJ" = no && can_build_shared=no + +# +# Do we need to explicitly link libc? +# +case "x$archive_cmds_need_lc_GCJ" in +x|xyes) + # Assume -lc should be added + archive_cmds_need_lc_GCJ=yes + + if test "$enable_shared" = yes && test "$GCC" = yes; then + case $archive_cmds_GCJ in + *'~'*) + # FIXME: we may have to deal with multi-command sequences. + ;; + '$CC '*) + # Test whether the compiler implicitly links with -lc since on some + # systems, -lgcc has to come before -lc. If gcc already passes -lc + # to ld, don't add -lc before -lgcc. + { echo "$as_me:$LINENO: checking whether -lc should be explicitly linked in" >&5 +echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO_C" >&6; } + $rm conftest* + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } 2>conftest.err; then + soname=conftest + lib=conftest + libobjs=conftest.$ac_objext + deplibs= + wl=$lt_prog_compiler_wl_GCJ + pic_flag=$lt_prog_compiler_pic_GCJ + compiler_flags=-v + linker_flags=-v + verstring= + output_objdir=. + libname=conftest + lt_save_allow_undefined_flag=$allow_undefined_flag_GCJ + allow_undefined_flag_GCJ= + if { (eval echo "$as_me:$LINENO: \"$archive_cmds_GCJ 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1\"") >&5 + (eval $archive_cmds_GCJ 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } + then + archive_cmds_need_lc_GCJ=no + else + archive_cmds_need_lc_GCJ=yes + fi + allow_undefined_flag_GCJ=$lt_save_allow_undefined_flag + else + cat conftest.err 1>&5 + fi + $rm conftest* + { echo "$as_me:$LINENO: result: $archive_cmds_need_lc_GCJ" >&5 +echo "${ECHO_T}$archive_cmds_need_lc_GCJ" >&6; } + ;; + esac + fi + ;; +esac + +{ echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5 +echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6; } +library_names_spec= +libname_spec='lib$name' +soname_spec= +shrext_cmds=".so" +postinstall_cmds= +postuninstall_cmds= +finish_cmds= +finish_eval= +shlibpath_var= +shlibpath_overrides_runpath=unknown +version_type=none +dynamic_linker="$host_os ld.so" +sys_lib_dlsearch_path_spec="/lib /usr/lib" + +need_lib_prefix=unknown +hardcode_into_libs=no + +# when you set need_version to no, make sure it does not cause -set_version +# flags to be left without arguments +need_version=unknown + +case $host_os in +aix3*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' + shlibpath_var=LIBPATH + + # AIX 3 has no versioning support, so we append a major version to the name. + soname_spec='${libname}${release}${shared_ext}$major' + ;; + +aix4* | aix5*) + version_type=linux + need_lib_prefix=no + need_version=no + hardcode_into_libs=yes + if test "$host_cpu" = ia64; then + # AIX 5 supports IA64 + library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + else + # With GCC up to 2.95.x, collect2 would create an import file + # for dependence libraries. The import file would start with + # the line `#! .'. This would cause the generated library to + # depend on `.', always an invalid library. This was fixed in + # development snapshots of GCC prior to 3.0. + case $host_os in + aix4 | aix4.[01] | aix4.[01].*) + if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' + echo ' yes ' + echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then + : + else + can_build_shared=no + fi + ;; + esac + # AIX (on Power*) has no versioning support, so currently we can not hardcode correct + # soname into executable. Probably we can add versioning support to + # collect2, so additional links can be useful in future. + if test "$aix_use_runtimelinking" = yes; then + # If using run time linking (on AIX 4.2 or later) use lib.so + # instead of lib.a to let people know that these are not + # typical AIX shared libraries. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + else + # We preserve .a as extension for shared libraries through AIX4.2 + # and later when we are not doing run time linking. + library_names_spec='${libname}${release}.a $libname.a' + soname_spec='${libname}${release}${shared_ext}$major' + fi + shlibpath_var=LIBPATH + fi + ;; + +amigaos*) + library_names_spec='$libname.ixlibrary $libname.a' + # Create ${libname}_ixlibrary.a entries in /sys/libs. + finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$echo "X$lib" | $Xsed -e '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' + ;; + +beos*) + library_names_spec='${libname}${shared_ext}' + dynamic_linker="$host_os ld.so" + shlibpath_var=LIBRARY_PATH + ;; + +bsdi[45]*) + version_type=linux + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" + sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" + # the default ld.so.conf also contains /usr/contrib/lib and + # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow + # libtool to hard-code these into programs + ;; + +cygwin* | mingw* | pw32*) + version_type=windows + shrext_cmds=".dll" + need_version=no + need_lib_prefix=no + + case $GCC,$host_os in + yes,cygwin* | yes,mingw* | yes,pw32*) + library_names_spec='$libname.dll.a' + # DLL is installed to $(libdir)/../bin by postinstall_cmds + postinstall_cmds='base_file=`basename \${file}`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname~ + chmod a+x \$dldir/$dlname' + postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ + dlpath=$dir/\$dldll~ + $rm \$dlpath' + shlibpath_overrides_runpath=yes + + case $host_os in + cygwin*) + # Cygwin DLLs use 'cyg' prefix rather than 'lib' + soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib" + ;; + mingw*) + # MinGW DLLs use traditional 'lib' prefix + soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"` + if echo "$sys_lib_search_path_spec" | grep ';[c-zC-Z]:/' >/dev/null; then + # It is most probably a Windows format PATH printed by + # mingw gcc, but we are running on Cygwin. Gcc prints its search + # path with ; separators, and with drive letters. We can handle the + # drive letters (cygwin fileutils understands them), so leave them, + # especially as we might pass files found there to a mingw objdump, + # which wouldn't understand a cygwinified path. Ahh. + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` + else + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi + ;; + pw32*) + # pw32 DLLs use 'pw' prefix rather than 'lib' + library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + ;; + esac + ;; + + *) + library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib' + ;; + esac + dynamic_linker='Win32 ld.exe' + # FIXME: first we should search . and the directory the executable is in + shlibpath_var=PATH + ;; + +darwin* | rhapsody*) + dynamic_linker="$host_os dyld" + version_type=darwin + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${versuffix}$shared_ext ${libname}${release}${major}$shared_ext ${libname}$shared_ext' + soname_spec='${libname}${release}${major}$shared_ext' + shlibpath_overrides_runpath=yes + shlibpath_var=DYLD_LIBRARY_PATH + shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' + + sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' + ;; + +dgux*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +freebsd1*) + dynamic_linker=no + ;; + +freebsd* | dragonfly*) + # DragonFly does not have aout. When/if they implement a new + # versioning mechanism, adjust this. + if test -x /usr/bin/objformat; then + objformat=`/usr/bin/objformat` + else + case $host_os in + freebsd[123]*) objformat=aout ;; + *) objformat=elf ;; + esac + fi + version_type=freebsd-$objformat + case $version_type in + freebsd-elf*) + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' + need_version=no + need_lib_prefix=no + ;; + freebsd-*) + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' + need_version=yes + ;; + esac + shlibpath_var=LD_LIBRARY_PATH + case $host_os in + freebsd2*) + shlibpath_overrides_runpath=yes + ;; + freebsd3.[01]* | freebsdelf3.[01]*) + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + freebsd3.[2-9]* | freebsdelf3.[2-9]* | \ + freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1) + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + *) # from 4.6 on, and DragonFly + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + esac + ;; + +gnu*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + hardcode_into_libs=yes + ;; + +hpux9* | hpux10* | hpux11*) + # Give a soname corresponding to the major version so that dld.sl refuses to + # link against other versions. + version_type=sunos + need_lib_prefix=no + need_version=no + case $host_cpu in + ia64*) + shrext_cmds='.so' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.so" + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + if test "X$HPUX_IA64_MODE" = X32; then + sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" + else + sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" + fi + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + hppa*64*) + shrext_cmds='.sl' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.sl" + shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + *) + shrext_cmds='.sl' + dynamic_linker="$host_os dld.sl" + shlibpath_var=SHLIB_PATH + shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + ;; + esac + # HP-UX runs *really* slowly unless shared libraries are mode 555. + postinstall_cmds='chmod 555 $lib' + ;; + +interix[3-9]*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + +irix5* | irix6* | nonstopux*) + case $host_os in + nonstopux*) version_type=nonstopux ;; + *) + if test "$lt_cv_prog_gnu_ld" = yes; then + version_type=linux + else + version_type=irix + fi ;; + esac + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' + case $host_os in + irix5* | nonstopux*) + libsuff= shlibsuff= + ;; + *) + case $LD in # libtool.m4 will add one of these switches to LD + *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") + libsuff= shlibsuff= libmagic=32-bit;; + *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") + libsuff=32 shlibsuff=N32 libmagic=N32;; + *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") + libsuff=64 shlibsuff=64 libmagic=64-bit;; + *) libsuff= shlibsuff= libmagic=never-match;; + esac + ;; + esac + shlibpath_var=LD_LIBRARY${shlibsuff}_PATH + shlibpath_overrides_runpath=no + sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" + sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" + hardcode_into_libs=yes + ;; + +# No shared lib support for Linux oldld, aout, or coff. +linux*oldld* | linux*aout* | linux*coff*) + dynamic_linker=no + ;; + +# This must be Linux ELF. +linux* | k*bsd*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + # This implies no fast_install, which is unacceptable. + # Some rework will be needed to allow for fast_install + # before this can be enabled. + hardcode_into_libs=yes + sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" + sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" + + # Append ld.so.conf contents to the search path + if test -f /etc/ld.so.conf; then + lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` + sys_lib_dlsearch_path_spec="$sys_lib_dlsearch_path_spec $lt_ld_extra" + fi + + # We used to test for /lib/ld.so.1 and disable shared libraries on + # powerpc, because MkLinux only supported shared libraries with the + # GNU dynamic linker. Since this was broken with cross compilers, + # most powerpc-linux boxes support dynamic linking these days and + # people can always --disable-shared, the test was removed, and we + # assume the GNU/Linux dynamic linker is in use. + dynamic_linker='GNU/Linux ld.so' + ;; + +netbsd*) + version_type=sunos + need_lib_prefix=no + need_version=no + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + dynamic_linker='NetBSD (a.out) ld.so' + else + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + dynamic_linker='NetBSD ld.elf_so' + fi + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + +newsos6) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +nto-qnx*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +openbsd*) + version_type=sunos + sys_lib_dlsearch_path_spec="/usr/lib" + need_lib_prefix=no + # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs. + case $host_os in + openbsd3.3 | openbsd3.3.*) need_version=yes ;; + *) need_version=no ;; + esac + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + shlibpath_var=LD_LIBRARY_PATH + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + case $host_os in + openbsd2.[89] | openbsd2.[89].*) + shlibpath_overrides_runpath=no + ;; + *) + shlibpath_overrides_runpath=yes + ;; + esac + else + shlibpath_overrides_runpath=yes + fi + ;; + +os2*) + libname_spec='$name' + shrext_cmds=".dll" + need_lib_prefix=no + library_names_spec='$libname${shared_ext} $libname.a' + dynamic_linker='OS/2 ld.exe' + shlibpath_var=LIBPATH + ;; + +osf3* | osf4* | osf5*) + version_type=osf + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" + sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" + ;; + +rdos*) + dynamic_linker=no + ;; + +solaris*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + # ldd complains unless libraries are executable + postinstall_cmds='chmod +x $lib' + ;; + +sunos4*) + version_type=sunos + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + if test "$with_gnu_ld" = yes; then + need_lib_prefix=no + fi + need_version=yes + ;; + +sysv4 | sysv4.3*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + case $host_vendor in + sni) + shlibpath_overrides_runpath=no + need_lib_prefix=no + export_dynamic_flag_spec='${wl}-Blargedynsym' + runpath_var=LD_RUN_PATH + ;; + siemens) + need_lib_prefix=no + ;; + motorola) + need_lib_prefix=no + need_version=no + shlibpath_overrides_runpath=no + sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' + ;; + esac + ;; + +sysv4*MP*) + if test -d /usr/nec ;then + version_type=linux + library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' + soname_spec='$libname${shared_ext}.$major' + shlibpath_var=LD_LIBRARY_PATH + fi + ;; + +sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) + version_type=freebsd-elf + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + hardcode_into_libs=yes + if test "$with_gnu_ld" = yes; then + sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' + shlibpath_overrides_runpath=no + else + sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' + shlibpath_overrides_runpath=yes + case $host_os in + sco3.2v5*) + sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" + ;; + esac + fi + sys_lib_dlsearch_path_spec='/usr/lib' + ;; + +uts4*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +*) + dynamic_linker=no + ;; +esac +{ echo "$as_me:$LINENO: result: $dynamic_linker" >&5 +echo "${ECHO_T}$dynamic_linker" >&6; } +test "$dynamic_linker" = no && can_build_shared=no + +variables_saved_for_relink="PATH $shlibpath_var $runpath_var" +if test "$GCC" = yes; then + variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" +fi + +{ echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5 +echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6; } +hardcode_action_GCJ= +if test -n "$hardcode_libdir_flag_spec_GCJ" || \ + test -n "$runpath_var_GCJ" || \ + test "X$hardcode_automatic_GCJ" = "Xyes" ; then + + # We can hardcode non-existant directories. + if test "$hardcode_direct_GCJ" != no && + # If the only mechanism to avoid hardcoding is shlibpath_var, we + # have to relink, otherwise we might link with an installed library + # when we should be linking with a yet-to-be-installed one + ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, GCJ)" != no && + test "$hardcode_minus_L_GCJ" != no; then + # Linking always hardcodes the temporary library directory. + hardcode_action_GCJ=relink + else + # We can link without hardcoding, and we can hardcode nonexisting dirs. + hardcode_action_GCJ=immediate + fi +else + # We cannot hardcode anything, or else we can only hardcode existing + # directories. + hardcode_action_GCJ=unsupported +fi +{ echo "$as_me:$LINENO: result: $hardcode_action_GCJ" >&5 +echo "${ECHO_T}$hardcode_action_GCJ" >&6; } + +if test "$hardcode_action_GCJ" = relink; then + # Fast installation is not supported + enable_fast_install=no +elif test "$shlibpath_overrides_runpath" = yes || + test "$enable_shared" = no; then + # Fast installation is not necessary + enable_fast_install=needless +fi + + +# The else clause should only fire when bootstrapping the +# libtool distribution, otherwise you forgot to ship ltmain.sh +# with your package, and you will get complaints that there are +# no rules to generate ltmain.sh. +if test -f "$ltmain"; then + # See if we are running on zsh, and set the options which allow our commands through + # without removal of \ escapes. + if test -n "${ZSH_VERSION+set}" ; then + setopt NO_GLOB_SUBST + fi + # Now quote all the things that may contain metacharacters while being + # careful not to overquote the AC_SUBSTed values. We take copies of the + # variables and quote the copies for generation of the libtool script. + for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTCFLAGS NM \ + SED SHELL STRIP \ + libname_spec library_names_spec soname_spec extract_expsyms_cmds \ + old_striplib striplib file_magic_cmd finish_cmds finish_eval \ + deplibs_check_method reload_flag reload_cmds need_locks \ + lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \ + lt_cv_sys_global_symbol_to_c_name_address \ + sys_lib_search_path_spec sys_lib_dlsearch_path_spec \ + old_postinstall_cmds old_postuninstall_cmds \ + compiler_GCJ \ + CC_GCJ \ + LD_GCJ \ + lt_prog_compiler_wl_GCJ \ + lt_prog_compiler_pic_GCJ \ + lt_prog_compiler_static_GCJ \ + lt_prog_compiler_no_builtin_flag_GCJ \ + export_dynamic_flag_spec_GCJ \ + thread_safe_flag_spec_GCJ \ + whole_archive_flag_spec_GCJ \ + enable_shared_with_static_runtimes_GCJ \ + old_archive_cmds_GCJ \ + old_archive_from_new_cmds_GCJ \ + predep_objects_GCJ \ + postdep_objects_GCJ \ + predeps_GCJ \ + postdeps_GCJ \ + compiler_lib_search_path_GCJ \ + archive_cmds_GCJ \ + archive_expsym_cmds_GCJ \ + postinstall_cmds_GCJ \ + postuninstall_cmds_GCJ \ + old_archive_from_expsyms_cmds_GCJ \ + allow_undefined_flag_GCJ \ + no_undefined_flag_GCJ \ + export_symbols_cmds_GCJ \ + hardcode_libdir_flag_spec_GCJ \ + hardcode_libdir_flag_spec_ld_GCJ \ + hardcode_libdir_separator_GCJ \ + hardcode_automatic_GCJ \ + module_cmds_GCJ \ + module_expsym_cmds_GCJ \ + lt_cv_prog_compiler_c_o_GCJ \ + fix_srcfile_path_GCJ \ + exclude_expsyms_GCJ \ + include_expsyms_GCJ; do + + case $var in + old_archive_cmds_GCJ | \ + old_archive_from_new_cmds_GCJ | \ + archive_cmds_GCJ | \ + archive_expsym_cmds_GCJ | \ + module_cmds_GCJ | \ + module_expsym_cmds_GCJ | \ + old_archive_from_expsyms_cmds_GCJ | \ + export_symbols_cmds_GCJ | \ + extract_expsyms_cmds | reload_cmds | finish_cmds | \ + postinstall_cmds | postuninstall_cmds | \ + old_postinstall_cmds | old_postuninstall_cmds | \ + sys_lib_search_path_spec | sys_lib_dlsearch_path_spec) + # Double-quote double-evaled strings. + eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\"" + ;; + *) + eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`\\\"" + ;; + esac + done + + case $lt_echo in + *'\$0 --fallback-echo"') + lt_echo=`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$/$0 --fallback-echo"/'` + ;; + esac + +cfgfile="$ofile" + + cat <<__EOF__ >> "$cfgfile" +# ### BEGIN LIBTOOL TAG CONFIG: $tagname + +# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: + +# Shell to use when invoking shell scripts. +SHELL=$lt_SHELL + +# Whether or not to build shared libraries. +build_libtool_libs=$enable_shared + +# Whether or not to build static libraries. +build_old_libs=$enable_static + +# Whether or not to add -lc for building shared libraries. +build_libtool_need_lc=$archive_cmds_need_lc_GCJ + +# Whether or not to disallow shared libs when runtime libs are static +allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes_GCJ + +# Whether or not to optimize for fast installation. +fast_install=$enable_fast_install + +# The host system. +host_alias=$host_alias +host=$host +host_os=$host_os + +# The build system. +build_alias=$build_alias +build=$build +build_os=$build_os + +# An echo program that does not interpret backslashes. +echo=$lt_echo + +# The archiver. +AR=$lt_AR +AR_FLAGS=$lt_AR_FLAGS + +# A C compiler. +LTCC=$lt_LTCC + +# LTCC compiler flags. +LTCFLAGS=$lt_LTCFLAGS + +# A language-specific compiler. +CC=$lt_compiler_GCJ + +# Is the compiler the GNU C compiler? +with_gcc=$GCC_GCJ + +# An ERE matcher. +EGREP=$lt_EGREP + +# The linker used to build libraries. +LD=$lt_LD_GCJ + +# Whether we need hard or soft links. +LN_S=$lt_LN_S + +# A BSD-compatible nm program. +NM=$lt_NM + +# A symbol stripping program +STRIP=$lt_STRIP + +# Used to examine libraries when file_magic_cmd begins "file" +MAGIC_CMD=$MAGIC_CMD + +# Used on cygwin: DLL creation program. +DLLTOOL="$DLLTOOL" + +# Used on cygwin: object dumper. +OBJDUMP="$OBJDUMP" + +# Used on cygwin: assembler. +AS="$AS" + +# The name of the directory that contains temporary libtool files. +objdir=$objdir + +# How to create reloadable object files. +reload_flag=$lt_reload_flag +reload_cmds=$lt_reload_cmds + +# How to pass a linker flag through the compiler. +wl=$lt_lt_prog_compiler_wl_GCJ + +# Object file suffix (normally "o"). +objext="$ac_objext" + +# Old archive suffix (normally "a"). +libext="$libext" + +# Shared library suffix (normally ".so"). +shrext_cmds='$shrext_cmds' + +# Executable file suffix (normally ""). +exeext="$exeext" + +# Additional compiler flags for building library objects. +pic_flag=$lt_lt_prog_compiler_pic_GCJ +pic_mode=$pic_mode + +# What is the maximum length of a command? +max_cmd_len=$lt_cv_sys_max_cmd_len + +# Does compiler simultaneously support -c and -o options? +compiler_c_o=$lt_lt_cv_prog_compiler_c_o_GCJ + +# Must we lock files when doing compilation? +need_locks=$lt_need_locks + +# Do we need the lib prefix for modules? +need_lib_prefix=$need_lib_prefix + +# Do we need a version for libraries? +need_version=$need_version + +# Whether dlopen is supported. +dlopen_support=$enable_dlopen + +# Whether dlopen of programs is supported. +dlopen_self=$enable_dlopen_self + +# Whether dlopen of statically linked programs is supported. +dlopen_self_static=$enable_dlopen_self_static + +# Compiler flag to prevent dynamic linking. +link_static_flag=$lt_lt_prog_compiler_static_GCJ + +# Compiler flag to turn off builtin functions. +no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag_GCJ + +# Compiler flag to allow reflexive dlopens. +export_dynamic_flag_spec=$lt_export_dynamic_flag_spec_GCJ + +# Compiler flag to generate shared objects directly from archives. +whole_archive_flag_spec=$lt_whole_archive_flag_spec_GCJ + +# Compiler flag to generate thread-safe objects. +thread_safe_flag_spec=$lt_thread_safe_flag_spec_GCJ + +# Library versioning type. +version_type=$version_type + +# Format of library name prefix. +libname_spec=$lt_libname_spec + +# List of archive names. First name is the real one, the rest are links. +# The last name is the one that the linker finds with -lNAME. +library_names_spec=$lt_library_names_spec + +# The coded name of the library, if different from the real name. +soname_spec=$lt_soname_spec + +# Commands used to build and install an old-style archive. +RANLIB=$lt_RANLIB +old_archive_cmds=$lt_old_archive_cmds_GCJ +old_postinstall_cmds=$lt_old_postinstall_cmds +old_postuninstall_cmds=$lt_old_postuninstall_cmds + +# Create an old-style archive from a shared archive. +old_archive_from_new_cmds=$lt_old_archive_from_new_cmds_GCJ + +# Create a temporary old-style archive to link instead of a shared archive. +old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds_GCJ + +# Commands used to build and install a shared archive. +archive_cmds=$lt_archive_cmds_GCJ +archive_expsym_cmds=$lt_archive_expsym_cmds_GCJ +postinstall_cmds=$lt_postinstall_cmds +postuninstall_cmds=$lt_postuninstall_cmds + +# Commands used to build a loadable module (assumed same as above if empty) +module_cmds=$lt_module_cmds_GCJ +module_expsym_cmds=$lt_module_expsym_cmds_GCJ + +# Commands to strip libraries. +old_striplib=$lt_old_striplib +striplib=$lt_striplib + +# Dependencies to place before the objects being linked to create a +# shared library. +predep_objects=$lt_predep_objects_GCJ + +# Dependencies to place after the objects being linked to create a +# shared library. +postdep_objects=$lt_postdep_objects_GCJ + +# Dependencies to place before the objects being linked to create a +# shared library. +predeps=$lt_predeps_GCJ + +# Dependencies to place after the objects being linked to create a +# shared library. +postdeps=$lt_postdeps_GCJ + +# The library search path used internally by the compiler when linking +# a shared library. +compiler_lib_search_path=$lt_compiler_lib_search_path_GCJ + +# Method to check whether dependent libraries are shared objects. +deplibs_check_method=$lt_deplibs_check_method + +# Command to use when deplibs_check_method == file_magic. +file_magic_cmd=$lt_file_magic_cmd + +# Flag that allows shared libraries with undefined symbols to be built. +allow_undefined_flag=$lt_allow_undefined_flag_GCJ + +# Flag that forces no undefined symbols. +no_undefined_flag=$lt_no_undefined_flag_GCJ + +# Commands used to finish a libtool library installation in a directory. +finish_cmds=$lt_finish_cmds + +# Same as above, but a single script fragment to be evaled but not shown. +finish_eval=$lt_finish_eval + +# Take the output of nm and produce a listing of raw symbols and C names. +global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe + +# Transform the output of nm in a proper C declaration +global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl + +# Transform the output of nm in a C name address pair +global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address + +# This is the shared library runtime path variable. +runpath_var=$runpath_var + +# This is the shared library path variable. +shlibpath_var=$shlibpath_var + +# Is shlibpath searched before the hard-coded library search path? +shlibpath_overrides_runpath=$shlibpath_overrides_runpath + +# How to hardcode a shared library path into an executable. +hardcode_action=$hardcode_action_GCJ + +# Whether we should hardcode library paths into libraries. +hardcode_into_libs=$hardcode_into_libs + +# Flag to hardcode \$libdir into a binary during linking. +# This must work even if \$libdir does not exist. +hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec_GCJ + +# If ld is used when linking, flag to hardcode \$libdir into +# a binary during linking. This must work even if \$libdir does +# not exist. +hardcode_libdir_flag_spec_ld=$lt_hardcode_libdir_flag_spec_ld_GCJ + +# Whether we need a single -rpath flag with a separated argument. +hardcode_libdir_separator=$lt_hardcode_libdir_separator_GCJ + +# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the +# resulting binary. +hardcode_direct=$hardcode_direct_GCJ + +# Set to yes if using the -LDIR flag during linking hardcodes DIR into the +# resulting binary. +hardcode_minus_L=$hardcode_minus_L_GCJ + +# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into +# the resulting binary. +hardcode_shlibpath_var=$hardcode_shlibpath_var_GCJ + +# Set to yes if building a shared library automatically hardcodes DIR into the library +# and all subsequent libraries and executables linked against it. +hardcode_automatic=$hardcode_automatic_GCJ + +# Variables whose values should be saved in libtool wrapper scripts and +# restored at relink time. +variables_saved_for_relink="$variables_saved_for_relink" + +# Whether libtool must link a program against all its dependency libraries. +link_all_deplibs=$link_all_deplibs_GCJ + +# Compile-time system search path for libraries +sys_lib_search_path_spec=$lt_sys_lib_search_path_spec + +# Run-time system search path for libraries +sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec + +# Fix the shell variable \$srcfile for the compiler. +fix_srcfile_path=$lt_fix_srcfile_path + +# Set to yes if exported symbols are required. +always_export_symbols=$always_export_symbols_GCJ + +# The commands to list exported symbols. +export_symbols_cmds=$lt_export_symbols_cmds_GCJ + +# The commands to extract the exported symbol list from a shared archive. +extract_expsyms_cmds=$lt_extract_expsyms_cmds + +# Symbols that should not be listed in the preloaded symbols. +exclude_expsyms=$lt_exclude_expsyms_GCJ + +# Symbols that must always be exported. +include_expsyms=$lt_include_expsyms_GCJ + +# ### END LIBTOOL TAG CONFIG: $tagname + +__EOF__ + + +else + # If there is no Makefile yet, we rely on a make rule to execute + # `config.status --recheck' to rerun these tests and create the + # libtool script then. + ltmain_in=`echo $ltmain | sed -e 's/\.sh$/.in/'` + if test -f "$ltmain_in"; then + test -f Makefile && make "$ltmain" + fi +fi + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +CC="$lt_save_CC" + + else + tagname="" + fi + ;; + + RC) + + +# Source file extension for RC test sources. +ac_ext=rc + +# Object file extension for compiled RC test sources. +objext=o +objext_RC=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }' + +# Code to be used in simple link tests +lt_simple_link_test_code="$lt_simple_compile_test_code" + +# ltmain only uses $CC for tagged configurations so make sure $CC is set. + +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} + +# If no C compiler flags were specified, use CFLAGS. +LTCFLAGS=${LTCFLAGS-"$CFLAGS"} + +# Allow CC to be a program name with arguments. +compiler=$CC + + +# save warnings/boilerplate of simple test code +ac_outfile=conftest.$ac_objext +echo "$lt_simple_compile_test_code" >conftest.$ac_ext +eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_compiler_boilerplate=`cat conftest.err` +$rm conftest* + +ac_outfile=conftest.$ac_objext +echo "$lt_simple_link_test_code" >conftest.$ac_ext +eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_linker_boilerplate=`cat conftest.err` +$rm conftest* + + +# Allow CC to be a program name with arguments. +lt_save_CC="$CC" +CC=${RC-"windres"} +compiler=$CC +compiler_RC=$CC +for cc_temp in $compiler""; do + case $cc_temp in + compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; + distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; + \-*) ;; + *) break;; + esac +done +cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"` + +lt_cv_prog_compiler_c_o_RC=yes + +# The else clause should only fire when bootstrapping the +# libtool distribution, otherwise you forgot to ship ltmain.sh +# with your package, and you will get complaints that there are +# no rules to generate ltmain.sh. +if test -f "$ltmain"; then + # See if we are running on zsh, and set the options which allow our commands through + # without removal of \ escapes. + if test -n "${ZSH_VERSION+set}" ; then + setopt NO_GLOB_SUBST + fi + # Now quote all the things that may contain metacharacters while being + # careful not to overquote the AC_SUBSTed values. We take copies of the + # variables and quote the copies for generation of the libtool script. + for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTCFLAGS NM \ + SED SHELL STRIP \ + libname_spec library_names_spec soname_spec extract_expsyms_cmds \ + old_striplib striplib file_magic_cmd finish_cmds finish_eval \ + deplibs_check_method reload_flag reload_cmds need_locks \ + lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \ + lt_cv_sys_global_symbol_to_c_name_address \ + sys_lib_search_path_spec sys_lib_dlsearch_path_spec \ + old_postinstall_cmds old_postuninstall_cmds \ + compiler_RC \ + CC_RC \ + LD_RC \ + lt_prog_compiler_wl_RC \ + lt_prog_compiler_pic_RC \ + lt_prog_compiler_static_RC \ + lt_prog_compiler_no_builtin_flag_RC \ + export_dynamic_flag_spec_RC \ + thread_safe_flag_spec_RC \ + whole_archive_flag_spec_RC \ + enable_shared_with_static_runtimes_RC \ + old_archive_cmds_RC \ + old_archive_from_new_cmds_RC \ + predep_objects_RC \ + postdep_objects_RC \ + predeps_RC \ + postdeps_RC \ + compiler_lib_search_path_RC \ + archive_cmds_RC \ + archive_expsym_cmds_RC \ + postinstall_cmds_RC \ + postuninstall_cmds_RC \ + old_archive_from_expsyms_cmds_RC \ + allow_undefined_flag_RC \ + no_undefined_flag_RC \ + export_symbols_cmds_RC \ + hardcode_libdir_flag_spec_RC \ + hardcode_libdir_flag_spec_ld_RC \ + hardcode_libdir_separator_RC \ + hardcode_automatic_RC \ + module_cmds_RC \ + module_expsym_cmds_RC \ + lt_cv_prog_compiler_c_o_RC \ + fix_srcfile_path_RC \ + exclude_expsyms_RC \ + include_expsyms_RC; do + + case $var in + old_archive_cmds_RC | \ + old_archive_from_new_cmds_RC | \ + archive_cmds_RC | \ + archive_expsym_cmds_RC | \ + module_cmds_RC | \ + module_expsym_cmds_RC | \ + old_archive_from_expsyms_cmds_RC | \ + export_symbols_cmds_RC | \ + extract_expsyms_cmds | reload_cmds | finish_cmds | \ + postinstall_cmds | postuninstall_cmds | \ + old_postinstall_cmds | old_postuninstall_cmds | \ + sys_lib_search_path_spec | sys_lib_dlsearch_path_spec) + # Double-quote double-evaled strings. + eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\"" + ;; + *) + eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`\\\"" + ;; + esac + done + + case $lt_echo in + *'\$0 --fallback-echo"') + lt_echo=`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$/$0 --fallback-echo"/'` + ;; + esac + +cfgfile="$ofile" + + cat <<__EOF__ >> "$cfgfile" +# ### BEGIN LIBTOOL TAG CONFIG: $tagname + +# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: + +# Shell to use when invoking shell scripts. +SHELL=$lt_SHELL + +# Whether or not to build shared libraries. +build_libtool_libs=$enable_shared + +# Whether or not to build static libraries. +build_old_libs=$enable_static + +# Whether or not to add -lc for building shared libraries. +build_libtool_need_lc=$archive_cmds_need_lc_RC + +# Whether or not to disallow shared libs when runtime libs are static +allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes_RC + +# Whether or not to optimize for fast installation. +fast_install=$enable_fast_install + +# The host system. +host_alias=$host_alias +host=$host +host_os=$host_os + +# The build system. +build_alias=$build_alias +build=$build +build_os=$build_os + +# An echo program that does not interpret backslashes. +echo=$lt_echo + +# The archiver. +AR=$lt_AR +AR_FLAGS=$lt_AR_FLAGS + +# A C compiler. +LTCC=$lt_LTCC + +# LTCC compiler flags. +LTCFLAGS=$lt_LTCFLAGS + +# A language-specific compiler. +CC=$lt_compiler_RC + +# Is the compiler the GNU C compiler? +with_gcc=$GCC_RC + +# An ERE matcher. +EGREP=$lt_EGREP + +# The linker used to build libraries. +LD=$lt_LD_RC + +# Whether we need hard or soft links. +LN_S=$lt_LN_S + +# A BSD-compatible nm program. +NM=$lt_NM + +# A symbol stripping program +STRIP=$lt_STRIP + +# Used to examine libraries when file_magic_cmd begins "file" +MAGIC_CMD=$MAGIC_CMD + +# Used on cygwin: DLL creation program. +DLLTOOL="$DLLTOOL" + +# Used on cygwin: object dumper. +OBJDUMP="$OBJDUMP" + +# Used on cygwin: assembler. +AS="$AS" + +# The name of the directory that contains temporary libtool files. +objdir=$objdir + +# How to create reloadable object files. +reload_flag=$lt_reload_flag +reload_cmds=$lt_reload_cmds + +# How to pass a linker flag through the compiler. +wl=$lt_lt_prog_compiler_wl_RC + +# Object file suffix (normally "o"). +objext="$ac_objext" + +# Old archive suffix (normally "a"). +libext="$libext" + +# Shared library suffix (normally ".so"). +shrext_cmds='$shrext_cmds' + +# Executable file suffix (normally ""). +exeext="$exeext" + +# Additional compiler flags for building library objects. +pic_flag=$lt_lt_prog_compiler_pic_RC +pic_mode=$pic_mode + +# What is the maximum length of a command? +max_cmd_len=$lt_cv_sys_max_cmd_len + +# Does compiler simultaneously support -c and -o options? +compiler_c_o=$lt_lt_cv_prog_compiler_c_o_RC + +# Must we lock files when doing compilation? +need_locks=$lt_need_locks + +# Do we need the lib prefix for modules? +need_lib_prefix=$need_lib_prefix + +# Do we need a version for libraries? +need_version=$need_version + +# Whether dlopen is supported. +dlopen_support=$enable_dlopen + +# Whether dlopen of programs is supported. +dlopen_self=$enable_dlopen_self + +# Whether dlopen of statically linked programs is supported. +dlopen_self_static=$enable_dlopen_self_static + +# Compiler flag to prevent dynamic linking. +link_static_flag=$lt_lt_prog_compiler_static_RC + +# Compiler flag to turn off builtin functions. +no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag_RC + +# Compiler flag to allow reflexive dlopens. +export_dynamic_flag_spec=$lt_export_dynamic_flag_spec_RC + +# Compiler flag to generate shared objects directly from archives. +whole_archive_flag_spec=$lt_whole_archive_flag_spec_RC + +# Compiler flag to generate thread-safe objects. +thread_safe_flag_spec=$lt_thread_safe_flag_spec_RC + +# Library versioning type. +version_type=$version_type + +# Format of library name prefix. +libname_spec=$lt_libname_spec + +# List of archive names. First name is the real one, the rest are links. +# The last name is the one that the linker finds with -lNAME. +library_names_spec=$lt_library_names_spec + +# The coded name of the library, if different from the real name. +soname_spec=$lt_soname_spec + +# Commands used to build and install an old-style archive. +RANLIB=$lt_RANLIB +old_archive_cmds=$lt_old_archive_cmds_RC +old_postinstall_cmds=$lt_old_postinstall_cmds +old_postuninstall_cmds=$lt_old_postuninstall_cmds + +# Create an old-style archive from a shared archive. +old_archive_from_new_cmds=$lt_old_archive_from_new_cmds_RC + +# Create a temporary old-style archive to link instead of a shared archive. +old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds_RC + +# Commands used to build and install a shared archive. +archive_cmds=$lt_archive_cmds_RC +archive_expsym_cmds=$lt_archive_expsym_cmds_RC +postinstall_cmds=$lt_postinstall_cmds +postuninstall_cmds=$lt_postuninstall_cmds + +# Commands used to build a loadable module (assumed same as above if empty) +module_cmds=$lt_module_cmds_RC +module_expsym_cmds=$lt_module_expsym_cmds_RC + +# Commands to strip libraries. +old_striplib=$lt_old_striplib +striplib=$lt_striplib + +# Dependencies to place before the objects being linked to create a +# shared library. +predep_objects=$lt_predep_objects_RC + +# Dependencies to place after the objects being linked to create a +# shared library. +postdep_objects=$lt_postdep_objects_RC + +# Dependencies to place before the objects being linked to create a +# shared library. +predeps=$lt_predeps_RC + +# Dependencies to place after the objects being linked to create a +# shared library. +postdeps=$lt_postdeps_RC + +# The library search path used internally by the compiler when linking +# a shared library. +compiler_lib_search_path=$lt_compiler_lib_search_path_RC + +# Method to check whether dependent libraries are shared objects. +deplibs_check_method=$lt_deplibs_check_method + +# Command to use when deplibs_check_method == file_magic. +file_magic_cmd=$lt_file_magic_cmd + +# Flag that allows shared libraries with undefined symbols to be built. +allow_undefined_flag=$lt_allow_undefined_flag_RC + +# Flag that forces no undefined symbols. +no_undefined_flag=$lt_no_undefined_flag_RC + +# Commands used to finish a libtool library installation in a directory. +finish_cmds=$lt_finish_cmds + +# Same as above, but a single script fragment to be evaled but not shown. +finish_eval=$lt_finish_eval + +# Take the output of nm and produce a listing of raw symbols and C names. +global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe + +# Transform the output of nm in a proper C declaration +global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl + +# Transform the output of nm in a C name address pair +global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address + +# This is the shared library runtime path variable. +runpath_var=$runpath_var + +# This is the shared library path variable. +shlibpath_var=$shlibpath_var + +# Is shlibpath searched before the hard-coded library search path? +shlibpath_overrides_runpath=$shlibpath_overrides_runpath + +# How to hardcode a shared library path into an executable. +hardcode_action=$hardcode_action_RC + +# Whether we should hardcode library paths into libraries. +hardcode_into_libs=$hardcode_into_libs + +# Flag to hardcode \$libdir into a binary during linking. +# This must work even if \$libdir does not exist. +hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec_RC + +# If ld is used when linking, flag to hardcode \$libdir into +# a binary during linking. This must work even if \$libdir does +# not exist. +hardcode_libdir_flag_spec_ld=$lt_hardcode_libdir_flag_spec_ld_RC + +# Whether we need a single -rpath flag with a separated argument. +hardcode_libdir_separator=$lt_hardcode_libdir_separator_RC + +# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the +# resulting binary. +hardcode_direct=$hardcode_direct_RC + +# Set to yes if using the -LDIR flag during linking hardcodes DIR into the +# resulting binary. +hardcode_minus_L=$hardcode_minus_L_RC + +# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into +# the resulting binary. +hardcode_shlibpath_var=$hardcode_shlibpath_var_RC + +# Set to yes if building a shared library automatically hardcodes DIR into the library +# and all subsequent libraries and executables linked against it. +hardcode_automatic=$hardcode_automatic_RC + +# Variables whose values should be saved in libtool wrapper scripts and +# restored at relink time. +variables_saved_for_relink="$variables_saved_for_relink" + +# Whether libtool must link a program against all its dependency libraries. +link_all_deplibs=$link_all_deplibs_RC + +# Compile-time system search path for libraries +sys_lib_search_path_spec=$lt_sys_lib_search_path_spec + +# Run-time system search path for libraries +sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec + +# Fix the shell variable \$srcfile for the compiler. +fix_srcfile_path=$lt_fix_srcfile_path + +# Set to yes if exported symbols are required. +always_export_symbols=$always_export_symbols_RC + +# The commands to list exported symbols. +export_symbols_cmds=$lt_export_symbols_cmds_RC + +# The commands to extract the exported symbol list from a shared archive. +extract_expsyms_cmds=$lt_extract_expsyms_cmds + +# Symbols that should not be listed in the preloaded symbols. +exclude_expsyms=$lt_exclude_expsyms_RC + +# Symbols that must always be exported. +include_expsyms=$lt_include_expsyms_RC + +# ### END LIBTOOL TAG CONFIG: $tagname + +__EOF__ + + +else + # If there is no Makefile yet, we rely on a make rule to execute + # `config.status --recheck' to rerun these tests and create the + # libtool script then. + ltmain_in=`echo $ltmain | sed -e 's/\.sh$/.in/'` + if test -f "$ltmain_in"; then + test -f Makefile && make "$ltmain" + fi +fi + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +CC="$lt_save_CC" + + ;; + + *) + { { echo "$as_me:$LINENO: error: Unsupported tag name: $tagname" >&5 +echo "$as_me: error: Unsupported tag name: $tagname" >&2;} + { (exit 1); exit 1; }; } + ;; + esac + + # Append the new tag name to the list of available tags. + if test -n "$tagname" ; then + available_tags="$available_tags $tagname" + fi + fi + done + IFS="$lt_save_ifs" + + # Now substitute the updated list of available tags. + if eval "sed -e 's/^available_tags=.*\$/available_tags=\"$available_tags\"/' \"$ofile\" > \"${ofile}T\""; then + mv "${ofile}T" "$ofile" + chmod +x "$ofile" + else + rm -f "${ofile}T" + { { echo "$as_me:$LINENO: error: unable to update list of available tagged configurations." >&5 +echo "$as_me: error: unable to update list of available tagged configurations." >&2;} + { (exit 1); exit 1; }; } + fi +fi + + + +# This can be used to rebuild libtool when needed +LIBTOOL_DEPS="$ac_aux_dir/ltmain.sh" + +# Always use our own libtool. +LIBTOOL='$(SHELL) $(top_builddir)/libtool' + +# Prevent multiple expansion + + + + + + + + + + + + + + + + + + + + + +{ echo "$as_me:$LINENO: checking whether to enable maintainer-specific portions of Makefiles" >&5 +echo $ECHO_N "checking whether to enable maintainer-specific portions of Makefiles... $ECHO_C" >&6; } + # Check whether --enable-maintainer-mode was given. +if test "${enable_maintainer_mode+set}" = set; then + enableval=$enable_maintainer_mode; USE_MAINTAINER_MODE=$enableval +else + USE_MAINTAINER_MODE=no +fi + + { echo "$as_me:$LINENO: result: $USE_MAINTAINER_MODE" >&5 +echo "${ECHO_T}$USE_MAINTAINER_MODE" >&6; } + if test $USE_MAINTAINER_MODE = yes; then + MAINTAINER_MODE_TRUE= + MAINTAINER_MODE_FALSE='#' +else + MAINTAINER_MODE_TRUE='#' + MAINTAINER_MODE_FALSE= +fi + + MAINT=$MAINTAINER_MODE_TRUE + + + + +for ac_header in sys/mman.h +do +as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then + { echo "$as_me:$LINENO: checking for $ac_header" >&5 +echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +fi +ac_res=`eval echo '${'$as_ac_Header'}'` + { echo "$as_me:$LINENO: result: $ac_res" >&5 +echo "${ECHO_T}$ac_res" >&6; } +else + # Is the header compilable? +{ echo "$as_me:$LINENO: checking $ac_header usability" >&5 +echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; } +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +#include <$ac_header> +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_header_compiler=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_header_compiler=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +echo "${ECHO_T}$ac_header_compiler" >&6; } + +# Is the header present? +{ echo "$as_me:$LINENO: checking $ac_header presence" >&5 +echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; } +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include <$ac_header> +_ACEOF +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then + ac_header_preproc=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_header_preproc=no +fi + +rm -f conftest.err conftest.$ac_ext +{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +echo "${ECHO_T}$ac_header_preproc" >&6; } + +# So? What about this header? +case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in + yes:no: ) + { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 +echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 +echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} + ac_header_preproc=yes + ;; + no:yes:* ) + { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 +echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 +echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 +echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 +echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 +echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 +echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} + ( cat <<\_ASBOX +## ------------------------------------------- ## +## Report this to http://gcc.gnu.org/bugs.html ## +## ------------------------------------------- ## +_ASBOX + ) | sed "s/^/$as_me: WARNING: /" >&2 + ;; +esac +{ echo "$as_me:$LINENO: checking for $ac_header" >&5 +echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + eval "$as_ac_Header=\$ac_header_preproc" +fi +ac_res=`eval echo '${'$as_ac_Header'}'` + { echo "$as_me:$LINENO: result: $ac_res" >&5 +echo "${ECHO_T}$ac_res" >&6; } + +fi +if test `eval echo '${'$as_ac_Header'}'` = yes; then + cat >>confdefs.h <<_ACEOF +#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + +for ac_func in mmap +do +as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ echo "$as_me:$LINENO: checking for $ac_func" >&5 +echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +/* Define $ac_func to an innocuous variant, in case declares $ac_func. + For example, HP-UX 11i declares gettimeofday. */ +#define $ac_func innocuous_$ac_func + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char $ac_func (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef $ac_func + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char $ac_func (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_$ac_func || defined __stub___$ac_func +choke me +#endif + +int +main () +{ +return $ac_func (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + eval "$as_ac_var=yes" +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + eval "$as_ac_var=no" +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +fi +ac_res=`eval echo '${'$as_ac_var'}'` + { echo "$as_me:$LINENO: result: $ac_res" >&5 +echo "${ECHO_T}$ac_res" >&6; } +if test `eval echo '${'$as_ac_var'}'` = yes; then + cat >>confdefs.h <<_ACEOF +#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF + +fi +done + + +if test "${ac_cv_header_sys_mman_h+set}" = set; then + { echo "$as_me:$LINENO: checking for sys/mman.h" >&5 +echo $ECHO_N "checking for sys/mman.h... $ECHO_C" >&6; } +if test "${ac_cv_header_sys_mman_h+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +fi +{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_mman_h" >&5 +echo "${ECHO_T}$ac_cv_header_sys_mman_h" >&6; } +else + # Is the header compilable? +{ echo "$as_me:$LINENO: checking sys/mman.h usability" >&5 +echo $ECHO_N "checking sys/mman.h usability... $ECHO_C" >&6; } +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +#include +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_header_compiler=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_header_compiler=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +echo "${ECHO_T}$ac_header_compiler" >&6; } + +# Is the header present? +{ echo "$as_me:$LINENO: checking sys/mman.h presence" >&5 +echo $ECHO_N "checking sys/mman.h presence... $ECHO_C" >&6; } +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +_ACEOF +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then + ac_header_preproc=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_header_preproc=no +fi + +rm -f conftest.err conftest.$ac_ext +{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +echo "${ECHO_T}$ac_header_preproc" >&6; } + +# So? What about this header? +case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in + yes:no: ) + { echo "$as_me:$LINENO: WARNING: sys/mman.h: accepted by the compiler, rejected by the preprocessor!" >&5 +echo "$as_me: WARNING: sys/mman.h: accepted by the compiler, rejected by the preprocessor!" >&2;} + { echo "$as_me:$LINENO: WARNING: sys/mman.h: proceeding with the compiler's result" >&5 +echo "$as_me: WARNING: sys/mman.h: proceeding with the compiler's result" >&2;} + ac_header_preproc=yes + ;; + no:yes:* ) + { echo "$as_me:$LINENO: WARNING: sys/mman.h: present but cannot be compiled" >&5 +echo "$as_me: WARNING: sys/mman.h: present but cannot be compiled" >&2;} + { echo "$as_me:$LINENO: WARNING: sys/mman.h: check for missing prerequisite headers?" >&5 +echo "$as_me: WARNING: sys/mman.h: check for missing prerequisite headers?" >&2;} + { echo "$as_me:$LINENO: WARNING: sys/mman.h: see the Autoconf documentation" >&5 +echo "$as_me: WARNING: sys/mman.h: see the Autoconf documentation" >&2;} + { echo "$as_me:$LINENO: WARNING: sys/mman.h: section \"Present But Cannot Be Compiled\"" >&5 +echo "$as_me: WARNING: sys/mman.h: section \"Present But Cannot Be Compiled\"" >&2;} + { echo "$as_me:$LINENO: WARNING: sys/mman.h: proceeding with the preprocessor's result" >&5 +echo "$as_me: WARNING: sys/mman.h: proceeding with the preprocessor's result" >&2;} + { echo "$as_me:$LINENO: WARNING: sys/mman.h: in the future, the compiler will take precedence" >&5 +echo "$as_me: WARNING: sys/mman.h: in the future, the compiler will take precedence" >&2;} + ( cat <<\_ASBOX +## ------------------------------------------- ## +## Report this to http://gcc.gnu.org/bugs.html ## +## ------------------------------------------- ## +_ASBOX + ) | sed "s/^/$as_me: WARNING: /" >&2 + ;; +esac +{ echo "$as_me:$LINENO: checking for sys/mman.h" >&5 +echo $ECHO_N "checking for sys/mman.h... $ECHO_C" >&6; } +if test "${ac_cv_header_sys_mman_h+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_cv_header_sys_mman_h=$ac_header_preproc +fi +{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_mman_h" >&5 +echo "${ECHO_T}$ac_cv_header_sys_mman_h" >&6; } + +fi +if test $ac_cv_header_sys_mman_h = yes; then + libffi_header_sys_mman_h=yes +else + libffi_header_sys_mman_h=no +fi + + +{ echo "$as_me:$LINENO: checking for mmap" >&5 +echo $ECHO_N "checking for mmap... $ECHO_C" >&6; } +if test "${ac_cv_func_mmap+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +/* Define mmap to an innocuous variant, in case declares mmap. + For example, HP-UX 11i declares gettimeofday. */ +#define mmap innocuous_mmap + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char mmap (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef mmap + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char mmap (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_mmap || defined __stub___mmap +choke me +#endif + +int +main () +{ +return mmap (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + ac_cv_func_mmap=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_func_mmap=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $ac_cv_func_mmap" >&5 +echo "${ECHO_T}$ac_cv_func_mmap" >&6; } +if test $ac_cv_func_mmap = yes; then + libffi_func_mmap=yes +else + libffi_func_mmap=no +fi + +if test "$libffi_header_sys_mman_h" != yes \ + || test "$libffi_func_mmap" != yes; then + ac_cv_func_mmap_file=no + ac_cv_func_mmap_dev_zero=no + ac_cv_func_mmap_anon=no +else + { echo "$as_me:$LINENO: checking whether read-only mmap of a plain file works" >&5 +echo $ECHO_N "checking whether read-only mmap of a plain file works... $ECHO_C" >&6; } +if test "${ac_cv_func_mmap_file+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + # Add a system to this blacklist if + # mmap(0, stat_size, PROT_READ, MAP_PRIVATE, fd, 0) doesn't return a + # memory area containing the same data that you'd get if you applied + # read() to the same fd. The only system known to have a problem here + # is VMS, where text files have record structure. + case "$host_os" in + vms* | ultrix*) + ac_cv_func_mmap_file=no ;; + *) + ac_cv_func_mmap_file=yes;; + esac +fi +{ echo "$as_me:$LINENO: result: $ac_cv_func_mmap_file" >&5 +echo "${ECHO_T}$ac_cv_func_mmap_file" >&6; } + { echo "$as_me:$LINENO: checking whether mmap from /dev/zero works" >&5 +echo $ECHO_N "checking whether mmap from /dev/zero works... $ECHO_C" >&6; } +if test "${ac_cv_func_mmap_dev_zero+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + # Add a system to this blacklist if it has mmap() but /dev/zero + # does not exist, or if mmapping /dev/zero does not give anonymous + # zeroed pages with both the following properties: + # 1. If you map N consecutive pages in with one call, and then + # unmap any subset of those pages, the pages that were not + # explicitly unmapped remain accessible. + # 2. If you map two adjacent blocks of memory and then unmap them + # both at once, they must both go away. + # Systems known to be in this category are Windows (all variants), + # VMS, and Darwin. + case "$host_os" in + vms* | cygwin* | pe | mingw* | darwin* | ultrix* | hpux10* | hpux11.00) + ac_cv_func_mmap_dev_zero=no ;; + *) + ac_cv_func_mmap_dev_zero=yes;; + esac +fi +{ echo "$as_me:$LINENO: result: $ac_cv_func_mmap_dev_zero" >&5 +echo "${ECHO_T}$ac_cv_func_mmap_dev_zero" >&6; } + + # Unlike /dev/zero, the MAP_ANON(YMOUS) defines can be probed for. + { echo "$as_me:$LINENO: checking for MAP_ANON(YMOUS)" >&5 +echo $ECHO_N "checking for MAP_ANON(YMOUS)... $ECHO_C" >&6; } +if test "${ac_cv_decl_map_anon+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +#include +#include + +#ifndef MAP_ANONYMOUS +#define MAP_ANONYMOUS MAP_ANON +#endif + +int +main () +{ +int n = MAP_ANONYMOUS; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_decl_map_anon=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_decl_map_anon=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $ac_cv_decl_map_anon" >&5 +echo "${ECHO_T}$ac_cv_decl_map_anon" >&6; } + + if test $ac_cv_decl_map_anon = no; then + ac_cv_func_mmap_anon=no + else + { echo "$as_me:$LINENO: checking whether mmap with MAP_ANON(YMOUS) works" >&5 +echo $ECHO_N "checking whether mmap with MAP_ANON(YMOUS) works... $ECHO_C" >&6; } +if test "${ac_cv_func_mmap_anon+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + # Add a system to this blacklist if it has mmap() and MAP_ANON or + # MAP_ANONYMOUS, but using mmap(..., MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) + # doesn't give anonymous zeroed pages with the same properties listed + # above for use of /dev/zero. + # Systems known to be in this category are Windows, VMS, and SCO Unix. + case "$host_os" in + vms* | cygwin* | pe | mingw* | sco* | udk* ) + ac_cv_func_mmap_anon=no ;; + *) + ac_cv_func_mmap_anon=yes;; + esac +fi +{ echo "$as_me:$LINENO: result: $ac_cv_func_mmap_anon" >&5 +echo "${ECHO_T}$ac_cv_func_mmap_anon" >&6; } + fi +fi + +if test $ac_cv_func_mmap_file = yes; then + +cat >>confdefs.h <<\_ACEOF +#define HAVE_MMAP_FILE 1 +_ACEOF + +fi +if test $ac_cv_func_mmap_dev_zero = yes; then + +cat >>confdefs.h <<\_ACEOF +#define HAVE_MMAP_DEV_ZERO 1 +_ACEOF + +fi +if test $ac_cv_func_mmap_anon = yes; then + +cat >>confdefs.h <<\_ACEOF +#define HAVE_MMAP_ANON 1 +_ACEOF + +fi + + + if test -d $srcdir/testsuite; then + TESTSUBDIR_TRUE= + TESTSUBDIR_FALSE='#' +else + TESTSUBDIR_TRUE='#' + TESTSUBDIR_FALSE= +fi + + +TARGETDIR="unknown" +case "$host" in + alpha*-*-*) + TARGET=ALPHA; TARGETDIR=alpha; + # Support 128-bit long double, changable via command-line switch. + HAVE_LONG_DOUBLE='defined(__LONG_DOUBLE_128__)' + ;; + + arm*-*-*) + TARGET=ARM; TARGETDIR=arm + ;; + + amd64-*-freebsd*) + TARGET=X86_64; TARGETDIR=x86 + ;; + + cris-*-*) + TARGET=LIBFFI_CRIS; TARGETDIR=cris + ;; + + frv-*-*) + TARGET=FRV; TARGETDIR=frv + ;; + + hppa*-*-linux* | parisc*-*-linux*) + TARGET=PA_LINUX; TARGETDIR=pa + ;; + hppa*64-*-hpux*) + TARGET=PA64_HPUX; TARGETDIR=pa + ;; + hppa*-*-hpux*) + TARGET=PA_HPUX; TARGETDIR=pa + ;; + + i386-*-freebsd* | i386-*-openbsd*) + TARGET=X86_FREEBSD; TARGETDIR=x86 + ;; + i?86-win32* | i?86-*-cygwin* | i?86-*-mingw*) + TARGET=X86_WIN32; TARGETDIR=x86 + ;; + i?86-*-darwin*) + TARGET=X86_DARWIN; TARGETDIR=x86 + ;; + i?86-*-solaris2.1[0-9]*) + TARGET=X86_64; TARGETDIR=x86 + ;; + i?86-*-*) + TARGET=X86; TARGETDIR=x86 + ;; + + ia64*-*-*) + TARGET=IA64; TARGETDIR=ia64 + ;; + + m32r*-*-*) + TARGET=M32R; TARGETDIR=m32r + ;; + + m68k-*-*) + TARGET=M68K; TARGETDIR=m68k + ;; + + mips-sgi-irix5.* | mips-sgi-irix6.*) + TARGET=MIPS; TARGETDIR=mips + ;; + mips*-*-linux*) + TARGET=MIPS; TARGETDIR=mips + ;; + + powerpc*-*-linux* | powerpc-*-sysv*) + TARGET=POWERPC; TARGETDIR=powerpc + ;; + powerpc-*-beos*) + TARGET=POWERPC; TARGETDIR=powerpc + ;; + powerpc-*-darwin*) + TARGET=POWERPC_DARWIN; TARGETDIR=powerpc + ;; + powerpc-*-aix* | rs6000-*-aix*) + TARGET=POWERPC_AIX; TARGETDIR=powerpc + ;; + powerpc-*-freebsd*) + TARGET=POWERPC_FREEBSD; TARGETDIR=powerpc + ;; + powerpc*-*-rtems*) + TARGET=POWERPC; TARGETDIR=powerpc + ;; + + s390-*-* | s390x-*-*) + TARGET=S390; TARGETDIR=s390 + ;; + + sh-*-* | sh[34]*-*-*) + TARGET=SH; TARGETDIR=sh + ;; + sh64-*-* | sh5*-*-*) + TARGET=SH64; TARGETDIR=sh64 + ;; + + sparc*-*-*) + TARGET=SPARC; TARGETDIR=sparc + ;; + + x86_64-*-darwin*) + TARGET=X86_DARWIN; TARGETDIR=x86 + ;; + x86_64-*-cygwin* | x86_64-*-mingw*) + ;; + x86_64-*-*) + TARGET=X86_64; TARGETDIR=x86 + ;; +esac + + + +if test $TARGETDIR = unknown; then + { { echo "$as_me:$LINENO: error: \"libffi has not been ported to $host.\"" >&5 +echo "$as_me: error: \"libffi has not been ported to $host.\"" >&2;} + { (exit 1); exit 1; }; } +fi + + if test x$TARGET = xMIPS; then + MIPS_TRUE= + MIPS_FALSE='#' +else + MIPS_TRUE='#' + MIPS_FALSE= +fi + + if test x$TARGET = xSPARC; then + SPARC_TRUE= + SPARC_FALSE='#' +else + SPARC_TRUE='#' + SPARC_FALSE= +fi + + if test x$TARGET = xX86; then + X86_TRUE= + X86_FALSE='#' +else + X86_TRUE='#' + X86_FALSE= +fi + + if test x$TARGET = xX86_FREEBSD; then + X86_FREEBSD_TRUE= + X86_FREEBSD_FALSE='#' +else + X86_FREEBSD_TRUE='#' + X86_FREEBSD_FALSE= +fi + + if test x$TARGET = xX86_WIN32; then + X86_WIN32_TRUE= + X86_WIN32_FALSE='#' +else + X86_WIN32_TRUE='#' + X86_WIN32_FALSE= +fi + + if test x$TARGET = xX86_DARWIN; then + X86_DARWIN_TRUE= + X86_DARWIN_FALSE='#' +else + X86_DARWIN_TRUE='#' + X86_DARWIN_FALSE= +fi + + if test x$TARGET = xALPHA; then + ALPHA_TRUE= + ALPHA_FALSE='#' +else + ALPHA_TRUE='#' + ALPHA_FALSE= +fi + + if test x$TARGET = xIA64; then + IA64_TRUE= + IA64_FALSE='#' +else + IA64_TRUE='#' + IA64_FALSE= +fi + + if test x$TARGET = xM32R; then + M32R_TRUE= + M32R_FALSE='#' +else + M32R_TRUE='#' + M32R_FALSE= +fi + + if test x$TARGET = xM68K; then + M68K_TRUE= + M68K_FALSE='#' +else + M68K_TRUE='#' + M68K_FALSE= +fi + + if test x$TARGET = xPOWERPC; then + POWERPC_TRUE= + POWERPC_FALSE='#' +else + POWERPC_TRUE='#' + POWERPC_FALSE= +fi + + if test x$TARGET = xPOWERPC_AIX; then + POWERPC_AIX_TRUE= + POWERPC_AIX_FALSE='#' +else + POWERPC_AIX_TRUE='#' + POWERPC_AIX_FALSE= +fi + + if test x$TARGET = xPOWERPC_DARWIN; then + POWERPC_DARWIN_TRUE= + POWERPC_DARWIN_FALSE='#' +else + POWERPC_DARWIN_TRUE='#' + POWERPC_DARWIN_FALSE= +fi + + if test x$TARGET = xPOWERPC_FREEBSD; then + POWERPC_FREEBSD_TRUE= + POWERPC_FREEBSD_FALSE='#' +else + POWERPC_FREEBSD_TRUE='#' + POWERPC_FREEBSD_FALSE= +fi + + if test x$TARGET = xARM; then + ARM_TRUE= + ARM_FALSE='#' +else + ARM_TRUE='#' + ARM_FALSE= +fi + + if test x$TARGET = xLIBFFI_CRIS; then + LIBFFI_CRIS_TRUE= + LIBFFI_CRIS_FALSE='#' +else + LIBFFI_CRIS_TRUE='#' + LIBFFI_CRIS_FALSE= +fi + + if test x$TARGET = xFRV; then + FRV_TRUE= + FRV_FALSE='#' +else + FRV_TRUE='#' + FRV_FALSE= +fi + + if test x$TARGET = xS390; then + S390_TRUE= + S390_FALSE='#' +else + S390_TRUE='#' + S390_FALSE= +fi + + if test x$TARGET = xX86_64; then + X86_64_TRUE= + X86_64_FALSE='#' +else + X86_64_TRUE='#' + X86_64_FALSE= +fi + + if test x$TARGET = xSH; then + SH_TRUE= + SH_FALSE='#' +else + SH_TRUE='#' + SH_FALSE= +fi + + if test x$TARGET = xSH64; then + SH64_TRUE= + SH64_FALSE='#' +else + SH64_TRUE='#' + SH64_FALSE= fi -rm -f conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext + + if test x$TARGET = xPA_LINUX; then + PA_LINUX_TRUE= + PA_LINUX_FALSE='#' +else + PA_LINUX_TRUE='#' + PA_LINUX_FALSE= fi -echo "$as_me:$LINENO: result: $ac_cv_working_alloca_h" >&5 -echo "${ECHO_T}$ac_cv_working_alloca_h" >&6 -if test $ac_cv_working_alloca_h = yes; then -cat >>confdefs.h <<\_ACEOF -#define HAVE_ALLOCA_H 1 -_ACEOF + if test x$TARGET = xPA_HPUX; then + PA_HPUX_TRUE= + PA_HPUX_FALSE='#' +else + PA_HPUX_TRUE='#' + PA_HPUX_FALSE= +fi + if test x$TARGET = xPA64_HPUX; then + PA64_HPUX_TRUE= + PA64_HPUX_FALSE='#' +else + PA64_HPUX_TRUE='#' + PA64_HPUX_FALSE= fi -echo "$as_me:$LINENO: checking for alloca" >&5 -echo $ECHO_N "checking for alloca... $ECHO_C" >&6 -if test "${ac_cv_func_alloca_works+set}" = set; then + +{ echo "$as_me:$LINENO: checking for ANSI C header files" >&5 +echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6; } +if test "${ac_cv_header_stdc+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF @@ -3876,228 +20685,92 @@ cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -#ifdef __GNUC__ -# define alloca __builtin_alloca -#else -# ifdef _MSC_VER -# include -# define alloca _alloca -# else -# if HAVE_ALLOCA_H -# include -# else -# ifdef _AIX - #pragma alloca -# else -# ifndef alloca /* predefined by HP cc +Olibcalls */ -char *alloca (); -# endif -# endif -# endif -# endif -#endif +#include +#include +#include +#include int main () { -char *p = (char *) alloca (1); + ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 - (eval $ac_link) 2>conftest.er1 +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest$ac_exeext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_func_alloca_works=yes + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_header_stdc=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -ac_cv_func_alloca_works=no -fi -rm -f conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext + ac_cv_header_stdc=no fi -echo "$as_me:$LINENO: result: $ac_cv_func_alloca_works" >&5 -echo "${ECHO_T}$ac_cv_func_alloca_works" >&6 - -if test $ac_cv_func_alloca_works = yes; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_ALLOCA 1 -_ACEOF - -else - # The SVR3 libPW and SVR4 libucb both contain incompatible functions -# that cause trouble. Some versions do not even contain alloca or -# contain a buggy version. If you still want to use their alloca, -# use ar to extract alloca.o from them instead of compiling alloca.c. - -ALLOCA=alloca.$ac_objext - -cat >>confdefs.h <<\_ACEOF -#define C_ALLOCA 1 -_ACEOF +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -echo "$as_me:$LINENO: checking whether \`alloca.c' needs Cray hooks" >&5 -echo $ECHO_N "checking whether \`alloca.c' needs Cray hooks... $ECHO_C" >&6 -if test "${ac_cv_os_cray+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else +if test $ac_cv_header_stdc = yes; then + # SunOS 4.x string.h does not declare mem*, contrary to ANSI. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -#if defined(CRAY) && ! defined(CRAY2) -webecray -#else -wenotbecray -#endif +#include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "webecray" >/dev/null 2>&1; then - ac_cv_os_cray=yes + $EGREP "memchr" >/dev/null 2>&1; then + : else - ac_cv_os_cray=no + ac_cv_header_stdc=no fi rm -f conftest* fi -echo "$as_me:$LINENO: result: $ac_cv_os_cray" >&5 -echo "${ECHO_T}$ac_cv_os_cray" >&6 -if test $ac_cv_os_cray = yes; then - for ac_func in _getb67 GETB67 getb67; do - as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6 -if eval "test \"\${$as_ac_var+set}\" = set"; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else + +if test $ac_cv_header_stdc = yes; then + # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func - -/* Override any gcc2 internal prototype to avoid an error. */ -#ifdef __cplusplus -extern "C" -{ -#endif -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined (__stub_$ac_func) || defined (__stub___$ac_func) -choke me -#else -char (*f) () = $ac_func; -#endif -#ifdef __cplusplus -} -#endif +#include -int -main () -{ -return f != $ac_func; - ; - return 0; -} _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 - (eval $ac_link) 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest$ac_exeext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - eval "$as_ac_var=yes" +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "free" >/dev/null 2>&1; then + : else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -eval "$as_ac_var=no" -fi -rm -f conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -fi -echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_var'}'`" >&5 -echo "${ECHO_T}`eval echo '${'$as_ac_var'}'`" >&6 -if test `eval echo '${'$as_ac_var'}'` = yes; then - -cat >>confdefs.h <<_ACEOF -#define CRAY_STACKSEG_END $ac_func -_ACEOF - - break + ac_cv_header_stdc=no fi +rm -f conftest* - done fi -echo "$as_me:$LINENO: checking stack direction for C alloca" >&5 -echo $ECHO_N "checking stack direction for C alloca... $ECHO_C" >&6 -if test "${ac_cv_c_stack_direction+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else +if test $ac_cv_header_stdc = yes; then + # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. if test "$cross_compiling" = yes; then - ac_cv_c_stack_direction=0 + : else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -4105,63 +20778,83 @@ cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -int -find_stack_direction () -{ - static char *addr = 0; - auto char dummy; - if (addr == 0) - { - addr = &dummy; - return find_stack_direction (); - } - else - return (&dummy > addr) ? 1 : -1; -} +#include +#include +#if ((' ' & 0x0FF) == 0x020) +# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') +# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) +#else +# define ISLOWER(c) \ + (('a' <= (c) && (c) <= 'i') \ + || ('j' <= (c) && (c) <= 'r') \ + || ('s' <= (c) && (c) <= 'z')) +# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) +#endif +#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) int main () { - exit (find_stack_direction () < 0); + int i; + for (i = 0; i < 256; i++) + if (XOR (islower (i), ISLOWER (i)) + || toupper (i) != TOUPPER (i)) + return 2; + return 0; } _ACEOF rm -f conftest$ac_exeext -if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 - (eval $ac_link) 2>&5 +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then - ac_cv_c_stack_direction=1 + : else echo "$as_me: program exited with status $ac_status" >&5 echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) -ac_cv_c_stack_direction=-1 +ac_cv_header_stdc=no fi -rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi + + fi -echo "$as_me:$LINENO: result: $ac_cv_c_stack_direction" >&5 -echo "${ECHO_T}$ac_cv_c_stack_direction" >&6 +fi +{ echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5 +echo "${ECHO_T}$ac_cv_header_stdc" >&6; } +if test $ac_cv_header_stdc = yes; then -cat >>confdefs.h <<_ACEOF -#define STACK_DIRECTION $ac_cv_c_stack_direction +cat >>confdefs.h <<\_ACEOF +#define STDC_HEADERS 1 _ACEOF - fi -echo "$as_me:$LINENO: checking for double" >&5 -echo $ECHO_N "checking for double... $ECHO_C" >&6 -if test "${ac_cv_type_double+set}" = set; then +for ac_func in memcpy +do +as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ echo "$as_me:$LINENO: checking for $ac_func" >&5 +echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF @@ -4170,323 +20863,372 @@ cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -$ac_includes_default +/* Define $ac_func to an innocuous variant, in case declares $ac_func. + For example, HP-UX 11i declares gettimeofday. */ +#define $ac_func innocuous_$ac_func + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char $ac_func (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef $ac_func + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char $ac_func (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_$ac_func || defined __stub___$ac_func +choke me +#endif + int main () { -if ((double *) 0) - return 0; -if (sizeof (double)) - return 0; +return $ac_func (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_type_double=yes + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + eval "$as_ac_var=yes" else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -ac_cv_type_double=no + eval "$as_ac_var=no" fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext fi -echo "$as_me:$LINENO: result: $ac_cv_type_double" >&5 -echo "${ECHO_T}$ac_cv_type_double" >&6 +ac_res=`eval echo '${'$as_ac_var'}'` + { echo "$as_me:$LINENO: result: $ac_res" >&5 +echo "${ECHO_T}$ac_res" >&6; } +if test `eval echo '${'$as_ac_var'}'` = yes; then + cat >>confdefs.h <<_ACEOF +#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF -echo "$as_me:$LINENO: checking size of double" >&5 -echo $ECHO_N "checking size of double... $ECHO_C" >&6 -if test "${ac_cv_sizeof_double+set}" = set; then +fi +done + +# The Ultrix 4.2 mips builtin alloca declared by alloca.h only works +# for constant arguments. Useless! +{ echo "$as_me:$LINENO: checking for working alloca.h" >&5 +echo $ECHO_N "checking for working alloca.h... $ECHO_C" >&6; } +if test "${ac_cv_working_alloca_h+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else - if test "$ac_cv_type_double" = yes; then - # The cast to unsigned long works around a bug in the HP C Compiler - # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects - # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. - # This bug is HP SR number 8606223364. - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF + cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -$ac_includes_default +#include int main () { -static int test_array [1 - 2 * !(((long) (sizeof (double))) >= 0)]; -test_array [0] = 0 - +char *p = (char *) alloca (2 * sizeof (int)); + if (p) return 0; ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + ac_cv_working_alloca_h=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_working_alloca_h=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $ac_cv_working_alloca_h" >&5 +echo "${ECHO_T}$ac_cv_working_alloca_h" >&6; } +if test $ac_cv_working_alloca_h = yes; then + +cat >>confdefs.h <<\_ACEOF +#define HAVE_ALLOCA_H 1 +_ACEOF + +fi + +{ echo "$as_me:$LINENO: checking for alloca" >&5 +echo $ECHO_N "checking for alloca... $ECHO_C" >&6; } +if test "${ac_cv_func_alloca_works+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -$ac_includes_default +#ifdef __GNUC__ +# define alloca __builtin_alloca +#else +# ifdef _MSC_VER +# include +# define alloca _alloca +# else +# ifdef HAVE_ALLOCA_H +# include +# else +# ifdef _AIX + #pragma alloca +# else +# ifndef alloca /* predefined by HP cc +Olibcalls */ +char *alloca (); +# endif +# endif +# endif +# endif +#endif + int main () { -static int test_array [1 - 2 * !(((long) (sizeof (double))) <= $ac_mid)]; -test_array [0] = 0 - +char *p = (char *) alloca (1); + if (p) return 0; ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_hi=$ac_mid; break + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + ac_cv_func_alloca_works=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` + ac_cv_func_alloca_works=no fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $ac_cv_func_alloca_works" >&5 +echo "${ECHO_T}$ac_cv_func_alloca_works" >&6; } + +if test $ac_cv_func_alloca_works = yes; then + +cat >>confdefs.h <<\_ACEOF +#define HAVE_ALLOCA 1 _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long) (sizeof (double))) < 0)]; -test_array [0] = 0 - ; - return 0; -} +else + # The SVR3 libPW and SVR4 libucb both contain incompatible functions +# that cause trouble. Some versions do not even contain alloca or +# contain a buggy version. If you still want to use their alloca, +# use ar to extract alloca.o from them instead of compiling alloca.c. + +ALLOCA=\${LIBOBJDIR}alloca.$ac_objext + +cat >>confdefs.h <<\_ACEOF +#define C_ALLOCA 1 _ACEOF -rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF + + +{ echo "$as_me:$LINENO: checking whether \`alloca.c' needs Cray hooks" >&5 +echo $ECHO_N "checking whether \`alloca.c' needs Cray hooks... $ECHO_C" >&6; } +if test "${ac_cv_os_cray+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long) (sizeof (double))) >= $ac_mid)]; -test_array [0] = 0 +#if defined CRAY && ! defined CRAY2 +webecray +#else +wenotbecray +#endif - ; - return 0; -} _ACEOF -rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_lo=$ac_mid; break +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "webecray" >/dev/null 2>&1; then + ac_cv_os_cray=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` + ac_cv_os_cray=no fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +rm -f conftest* -ac_lo= ac_hi= -fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` +{ echo "$as_me:$LINENO: result: $ac_cv_os_cray" >&5 +echo "${ECHO_T}$ac_cv_os_cray" >&6; } +if test $ac_cv_os_cray = yes; then + for ac_func in _getb67 GETB67 getb67; do + as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ echo "$as_me:$LINENO: checking for $ac_func" >&5 +echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -$ac_includes_default +/* Define $ac_func to an innocuous variant, in case declares $ac_func. + For example, HP-UX 11i declares gettimeofday. */ +#define $ac_func innocuous_$ac_func + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char $ac_func (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef $ac_func + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char $ac_func (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_$ac_func || defined __stub___$ac_func +choke me +#endif + int main () { -static int test_array [1 - 2 * !(((long) (sizeof (double))) <= $ac_mid)]; -test_array [0] = 0 - +return $ac_func (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_hi=$ac_mid + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + eval "$as_ac_var=yes" else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -ac_lo=`expr '(' $ac_mid ')' + 1` + eval "$as_ac_var=no" fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_double=$ac_lo;; -'') { { echo "$as_me:$LINENO: error: cannot compute sizeof (double), 77 -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (double), 77 -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } ;; -esac + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +fi +ac_res=`eval echo '${'$as_ac_var'}'` + { echo "$as_me:$LINENO: result: $ac_res" >&5 +echo "${ECHO_T}$ac_res" >&6; } +if test `eval echo '${'$as_ac_var'}'` = yes; then + +cat >>confdefs.h <<_ACEOF +#define CRAY_STACKSEG_END $ac_func +_ACEOF + + break +fi + + done +fi + +{ echo "$as_me:$LINENO: checking stack direction for C alloca" >&5 +echo $ECHO_N "checking stack direction for C alloca... $ECHO_C" >&6; } +if test "${ac_cv_c_stack_direction+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 else if test "$cross_compiling" = yes; then - { { echo "$as_me:$LINENO: error: internal error: not reached in cross-compile" >&5 -echo "$as_me: error: internal error: not reached in cross-compile" >&2;} - { (exit 1); exit 1; }; } + ac_cv_c_stack_direction=0 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -4495,79 +21237,74 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default -long longval () { return (long) (sizeof (double)); } -unsigned long ulongval () { return (long) (sizeof (double)); } -#include -#include int -main () +find_stack_direction () { - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - exit (1); - if (((long) (sizeof (double))) < 0) + static char *addr = 0; + auto char dummy; + if (addr == 0) { - long i = longval (); - if (i != ((long) (sizeof (double)))) - exit (1); - fprintf (f, "%ld\n", i); + addr = &dummy; + return find_stack_direction (); } else - { - unsigned long i = ulongval (); - if (i != ((long) (sizeof (double)))) - exit (1); - fprintf (f, "%lu\n", i); - } - exit (ferror (f) || fclose (f) != 0); + return (&dummy > addr) ? 1 : -1; +} - ; - return 0; +int +main () +{ + return find_stack_direction () < 0; } _ACEOF rm -f conftest$ac_exeext -if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 - (eval $ac_link) 2>&5 +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then - ac_cv_sizeof_double=`cat conftest.val` + ac_cv_c_stack_direction=1 else echo "$as_me: program exited with status $ac_status" >&5 echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) -{ { echo "$as_me:$LINENO: error: cannot compute sizeof (double), 77 -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (double), 77 -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } -fi -rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi +ac_cv_c_stack_direction=-1 fi -rm -f conftest.val -else - ac_cv_sizeof_double=0 +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi + + fi -echo "$as_me:$LINENO: result: $ac_cv_sizeof_double" >&5 -echo "${ECHO_T}$ac_cv_sizeof_double" >&6 +{ echo "$as_me:$LINENO: result: $ac_cv_c_stack_direction" >&5 +echo "${ECHO_T}$ac_cv_c_stack_direction" >&6; } + cat >>confdefs.h <<_ACEOF -#define SIZEOF_DOUBLE $ac_cv_sizeof_double +#define STACK_DIRECTION $ac_cv_c_stack_direction _ACEOF -echo "$as_me:$LINENO: checking for long double" >&5 -echo $ECHO_N "checking for long double... $ECHO_C" >&6 -if test "${ac_cv_type_long_double+set}" = set; then +fi + + +{ echo "$as_me:$LINENO: checking for double" >&5 +echo $ECHO_N "checking for double... $ECHO_C" >&6; } +if test "${ac_cv_type_double+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF @@ -4577,60 +21314,57 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default +typedef double ac__type_new_; int main () { -if ((long double *) 0) +if ((ac__type_new_ *) 0) return 0; -if (sizeof (long double)) +if (sizeof (ac__type_new_)) return 0; ; return 0; } _ACEOF rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_type_long_double=yes + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_type_double=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -ac_cv_type_long_double=no + ac_cv_type_double=no fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -echo "$as_me:$LINENO: result: $ac_cv_type_long_double" >&5 -echo "${ECHO_T}$ac_cv_type_long_double" >&6 +{ echo "$as_me:$LINENO: result: $ac_cv_type_double" >&5 +echo "${ECHO_T}$ac_cv_type_double" >&6; } -echo "$as_me:$LINENO: checking size of long double" >&5 -echo $ECHO_N "checking size of long double... $ECHO_C" >&6 -if test "${ac_cv_sizeof_long_double+set}" = set; then +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ echo "$as_me:$LINENO: checking size of double" >&5 +echo $ECHO_N "checking size of double... $ECHO_C" >&6; } +if test "${ac_cv_sizeof_double+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else - if test "$ac_cv_type_long_double" = yes; then - # The cast to unsigned long works around a bug in the HP C Compiler - # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects - # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. - # This bug is HP SR number 8606223364. if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. cat >conftest.$ac_ext <<_ACEOF @@ -4640,10 +21374,11 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default + typedef double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long) (sizeof (long double))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; test_array [0] = 0 ; @@ -4651,26 +21386,22 @@ } _ACEOF rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then ac_lo=0 ac_mid=0 while :; do cat >conftest.$ac_ext <<_ACEOF @@ -4680,10 +21411,11 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default + typedef double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long) (sizeof (long double))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; test_array [0] = 0 ; @@ -4691,55 +21423,53 @@ } _ACEOF rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` + ac_lo=`expr $ac_mid + 1` + if test $ac_lo -le $ac_mid; then + ac_lo= ac_hi= + break + fi + ac_mid=`expr 2 '*' $ac_mid + 1` fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -cat >conftest.$ac_ext <<_ACEOF + cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default + typedef double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long) (sizeof (long double))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; test_array [0] = 0 ; @@ -4747,26 +21477,22 @@ } _ACEOF rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then ac_hi=-1 ac_mid=-1 while :; do cat >conftest.$ac_ext <<_ACEOF @@ -4776,10 +21502,11 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default + typedef double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long) (sizeof (long double))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; test_array [0] = 0 ; @@ -4787,49 +21514,48 @@ } _ACEOF rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` + ac_hi=`expr '(' $ac_mid ')' - 1` + if test $ac_mid -le $ac_hi; then + ac_lo= ac_hi= + break + fi + ac_mid=`expr 2 '*' $ac_mid` fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -ac_lo= ac_hi= + ac_lo= ac_hi= fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext # Binary search between lo and hi bounds. while test "x$ac_lo" != "x$ac_hi"; do ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` @@ -4840,10 +21566,11 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default + typedef double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long) (sizeof (long double))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; test_array [0] = 0 ; @@ -4851,49 +21578,45 @@ } _ACEOF rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -ac_lo=`expr '(' $ac_mid ')' + 1` + ac_lo=`expr '(' $ac_mid ')' + 1` fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done case $ac_lo in -?*) ac_cv_sizeof_long_double=$ac_lo;; -'') { { echo "$as_me:$LINENO: error: cannot compute sizeof (long double), 77 +?*) ac_cv_sizeof_double=$ac_lo;; +'') if test "$ac_cv_type_double" = yes; then + { { echo "$as_me:$LINENO: error: cannot compute sizeof (double) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long double), 77 +echo "$as_me: error: cannot compute sizeof (double) See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } ;; + { (exit 77); exit 77; }; } + else + ac_cv_sizeof_double=0 + fi ;; esac else - if test "$cross_compiling" = yes; then - { { echo "$as_me:$LINENO: error: internal error: not reached in cross-compile" >&5 -echo "$as_me: error: internal error: not reached in cross-compile" >&2;} - { (exit 1); exit 1; }; } -else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -4901,8 +21624,9 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default -long longval () { return (long) (sizeof (long double)); } -unsigned long ulongval () { return (long) (sizeof (long double)); } + typedef double ac__type_sizeof_; +static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } +static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } #include #include int @@ -4911,140 +21635,81 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) - exit (1); - if (((long) (sizeof (long double))) < 0) + return 1; + if (((long int) (sizeof (ac__type_sizeof_))) < 0) { - long i = longval (); - if (i != ((long) (sizeof (long double)))) - exit (1); + long int i = longval (); + if (i != ((long int) (sizeof (ac__type_sizeof_)))) + return 1; fprintf (f, "%ld\n", i); } else { - unsigned long i = ulongval (); - if (i != ((long) (sizeof (long double)))) - exit (1); + unsigned long int i = ulongval (); + if (i != ((long int) (sizeof (ac__type_sizeof_)))) + return 1; fprintf (f, "%lu\n", i); } - exit (ferror (f) || fclose (f) != 0); + return ferror (f) || fclose (f) != 0; ; return 0; } _ACEOF rm -f conftest$ac_exeext -if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 - (eval $ac_link) 2>&5 +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then - ac_cv_sizeof_long_double=`cat conftest.val` + ac_cv_sizeof_double=`cat conftest.val` else echo "$as_me: program exited with status $ac_status" >&5 echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) -{ { echo "$as_me:$LINENO: error: cannot compute sizeof (long double), 77 +if test "$ac_cv_type_double" = yes; then + { { echo "$as_me:$LINENO: error: cannot compute sizeof (double) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long double), 77 +echo "$as_me: error: cannot compute sizeof (double) See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } -fi -rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -fi -rm -f conftest.val -else - ac_cv_sizeof_long_double=0 -fi -fi -echo "$as_me:$LINENO: result: $ac_cv_sizeof_long_double" >&5 -echo "${ECHO_T}$ac_cv_sizeof_long_double" >&6 -cat >>confdefs.h <<_ACEOF -#define SIZEOF_LONG_DOUBLE $ac_cv_sizeof_long_double -_ACEOF - - - -# Also AC_SUBST this variable for ffi.h. -HAVE_LONG_DOUBLE=0 -if test $ac_cv_sizeof_double != $ac_cv_sizeof_long_double; then - if test $ac_cv_sizeof_long_double != 0; then - HAVE_LONG_DOUBLE=1 - -cat >>confdefs.h <<\_ACEOF -#define HAVE_LONG_DOUBLE 1 -_ACEOF - - fi -fi - - -echo "$as_me:$LINENO: checking for _Bool support" >&5 -echo $ECHO_N "checking for _Bool support... $ECHO_C" >&6 -have_c99_bool=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ -_Bool x; x = (_Bool)0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then + { (exit 77); exit 77; }; } + else + ac_cv_sizeof_double=0 + fi +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi +rm -f conftest.val +fi +{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_double" >&5 +echo "${ECHO_T}$ac_cv_sizeof_double" >&6; } -cat >>confdefs.h <<\_ACEOF -#define HAVE_C99_BOOL 1 -_ACEOF - have_c99_bool=yes +cat >>confdefs.h <<_ACEOF +#define SIZEOF_DOUBLE $ac_cv_sizeof_double +_ACEOF -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 -fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext -echo "$as_me:$LINENO: result: $have_c99_bool" >&5 -echo "${ECHO_T}$have_c99_bool" >&6 -if test "$have_c99_bool" = yes ; then -echo "$as_me:$LINENO: checking for _Bool" >&5 -echo $ECHO_N "checking for _Bool... $ECHO_C" >&6 -if test "${ac_cv_type__Bool+set}" = set; then +{ echo "$as_me:$LINENO: checking for long double" >&5 +echo $ECHO_N "checking for long double... $ECHO_C" >&6; } +if test "${ac_cv_type_long_double+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF @@ -5054,60 +21719,57 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default +typedef long double ac__type_new_; int main () { -if ((_Bool *) 0) +if ((ac__type_new_ *) 0) return 0; -if (sizeof (_Bool)) +if (sizeof (ac__type_new_)) return 0; ; return 0; } _ACEOF rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_type__Bool=yes + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_type_long_double=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -ac_cv_type__Bool=no + ac_cv_type_long_double=no fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -echo "$as_me:$LINENO: result: $ac_cv_type__Bool" >&5 -echo "${ECHO_T}$ac_cv_type__Bool" >&6 +{ echo "$as_me:$LINENO: result: $ac_cv_type_long_double" >&5 +echo "${ECHO_T}$ac_cv_type_long_double" >&6; } -echo "$as_me:$LINENO: checking size of _Bool" >&5 -echo $ECHO_N "checking size of _Bool... $ECHO_C" >&6 -if test "${ac_cv_sizeof__Bool+set}" = set; then +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ echo "$as_me:$LINENO: checking size of long double" >&5 +echo $ECHO_N "checking size of long double... $ECHO_C" >&6; } +if test "${ac_cv_sizeof_long_double+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else - if test "$ac_cv_type__Bool" = yes; then - # The cast to unsigned long works around a bug in the HP C Compiler - # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects - # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. - # This bug is HP SR number 8606223364. if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. cat >conftest.$ac_ext <<_ACEOF @@ -5117,10 +21779,11 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default + typedef long double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long) (sizeof (_Bool))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; test_array [0] = 0 ; @@ -5128,26 +21791,22 @@ } _ACEOF rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then ac_lo=0 ac_mid=0 while :; do cat >conftest.$ac_ext <<_ACEOF @@ -5157,10 +21816,11 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default + typedef long double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long) (sizeof (_Bool))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; test_array [0] = 0 ; @@ -5168,55 +21828,53 @@ } _ACEOF rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` + ac_lo=`expr $ac_mid + 1` + if test $ac_lo -le $ac_mid; then + ac_lo= ac_hi= + break + fi + ac_mid=`expr 2 '*' $ac_mid + 1` fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -cat >conftest.$ac_ext <<_ACEOF + cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default + typedef long double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long) (sizeof (_Bool))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; test_array [0] = 0 ; @@ -5224,26 +21882,22 @@ } _ACEOF rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then ac_hi=-1 ac_mid=-1 while :; do cat >conftest.$ac_ext <<_ACEOF @@ -5253,10 +21907,11 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default + typedef long double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long) (sizeof (_Bool))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; test_array [0] = 0 ; @@ -5264,49 +21919,48 @@ } _ACEOF rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` + ac_hi=`expr '(' $ac_mid ')' - 1` + if test $ac_mid -le $ac_hi; then + ac_lo= ac_hi= + break + fi + ac_mid=`expr 2 '*' $ac_mid` fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -ac_lo= ac_hi= + ac_lo= ac_hi= fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext # Binary search between lo and hi bounds. while test "x$ac_lo" != "x$ac_hi"; do ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` @@ -5317,10 +21971,11 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default + typedef long double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long) (sizeof (_Bool))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; test_array [0] = 0 ; @@ -5328,49 +21983,45 @@ } _ACEOF rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -ac_lo=`expr '(' $ac_mid ')' + 1` + ac_lo=`expr '(' $ac_mid ')' + 1` fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done case $ac_lo in -?*) ac_cv_sizeof__Bool=$ac_lo;; -'') { { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool), 77 +?*) ac_cv_sizeof_long_double=$ac_lo;; +'') if test "$ac_cv_type_long_double" = yes; then + { { echo "$as_me:$LINENO: error: cannot compute sizeof (long double) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (_Bool), 77 +echo "$as_me: error: cannot compute sizeof (long double) See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } ;; + { (exit 77); exit 77; }; } + else + ac_cv_sizeof_long_double=0 + fi ;; esac else - if test "$cross_compiling" = yes; then - { { echo "$as_me:$LINENO: error: internal error: not reached in cross-compile" >&5 -echo "$as_me: error: internal error: not reached in cross-compile" >&2;} - { (exit 1); exit 1; }; } -else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -5378,8 +22029,9 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default -long longval () { return (long) (sizeof (_Bool)); } -unsigned long ulongval () { return (long) (sizeof (_Bool)); } + typedef long double ac__type_sizeof_; +static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } +static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } #include #include int @@ -5388,70 +22040,97 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) - exit (1); - if (((long) (sizeof (_Bool))) < 0) + return 1; + if (((long int) (sizeof (ac__type_sizeof_))) < 0) { - long i = longval (); - if (i != ((long) (sizeof (_Bool)))) - exit (1); + long int i = longval (); + if (i != ((long int) (sizeof (ac__type_sizeof_)))) + return 1; fprintf (f, "%ld\n", i); } else { - unsigned long i = ulongval (); - if (i != ((long) (sizeof (_Bool)))) - exit (1); + unsigned long int i = ulongval (); + if (i != ((long int) (sizeof (ac__type_sizeof_)))) + return 1; fprintf (f, "%lu\n", i); } - exit (ferror (f) || fclose (f) != 0); + return ferror (f) || fclose (f) != 0; ; return 0; } _ACEOF rm -f conftest$ac_exeext -if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 - (eval $ac_link) 2>&5 +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then - ac_cv_sizeof__Bool=`cat conftest.val` + ac_cv_sizeof_long_double=`cat conftest.val` else echo "$as_me: program exited with status $ac_status" >&5 echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) -{ { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool), 77 +if test "$ac_cv_type_long_double" = yes; then + { { echo "$as_me:$LINENO: error: cannot compute sizeof (long double) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (_Bool), 77 +echo "$as_me: error: cannot compute sizeof (long double) See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } -fi -rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext + { (exit 77); exit 77; }; } + else + ac_cv_sizeof_long_double=0 + fi fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val -else - ac_cv_sizeof__Bool=0 -fi fi -echo "$as_me:$LINENO: result: $ac_cv_sizeof__Bool" >&5 -echo "${ECHO_T}$ac_cv_sizeof__Bool" >&6 +{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_long_double" >&5 +echo "${ECHO_T}$ac_cv_sizeof_long_double" >&6; } + + + cat >>confdefs.h <<_ACEOF -#define SIZEOF__BOOL $ac_cv_sizeof__Bool +#define SIZEOF_LONG_DOUBLE $ac_cv_sizeof_long_double _ACEOF + +# Also AC_SUBST this variable for ffi.h. +if test -z "$HAVE_LONG_DOUBLE"; then + HAVE_LONG_DOUBLE=0 + if test $ac_cv_sizeof_double != $ac_cv_sizeof_long_double; then + if test $ac_cv_sizeof_long_double != 0; then + HAVE_LONG_DOUBLE=1 + +cat >>confdefs.h <<\_ACEOF +#define HAVE_LONG_DOUBLE 1 +_ACEOF + + fi + fi fi -echo "$as_me:$LINENO: checking whether byte ordering is bigendian" >&5 -echo $ECHO_N "checking whether byte ordering is bigendian... $ECHO_C" >&6 + +{ echo "$as_me:$LINENO: checking whether byte ordering is bigendian" >&5 +echo $ECHO_N "checking whether byte ordering is bigendian... $ECHO_C" >&6; } if test "${ac_cv_c_bigendian+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else @@ -5468,7 +22147,8 @@ int main () { -#if !BYTE_ORDER || !BIG_ENDIAN || !LITTLE_ENDIAN +#if ! (defined BYTE_ORDER && defined BIG_ENDIAN && defined LITTLE_ENDIAN \ + && BYTE_ORDER && BIG_ENDIAN && LITTLE_ENDIAN) bogus endian macros #endif @@ -5477,26 +22157,22 @@ } _ACEOF rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then # It does; now see whether it defined to BIG_ENDIAN or not. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -5519,39 +22195,36 @@ } _ACEOF rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then ac_cv_c_bigendian=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -ac_cv_c_bigendian=no + ac_cv_c_bigendian=no fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -# It does not; compile a test program. + # It does not; compile a test program. if test "$cross_compiling" = yes; then # try to guess the endianness by grepping values into an object file ac_cv_c_bigendian=unknown @@ -5561,11 +22234,11 @@ cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -short ascii_mm[] = { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 }; -short ascii_ii[] = { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 }; +short int ascii_mm[] = { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 }; +short int ascii_ii[] = { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 }; void _ascii () { char *s = (char *) ascii_mm; s = (char *) ascii_ii; } -short ebcdic_ii[] = { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 }; -short ebcdic_mm[] = { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 }; +short int ebcdic_ii[] = { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 }; +short int ebcdic_mm[] = { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 }; void _ebcdic () { char *s = (char *) ebcdic_mm; s = (char *) ebcdic_ii; } int main () @@ -5576,26 +22249,22 @@ } _ACEOF rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then if grep BIGenDianSyS conftest.$ac_objext >/dev/null ; then ac_cv_c_bigendian=yes fi @@ -5611,8 +22280,10 @@ echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 + fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -5620,27 +22291,41 @@ cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ +$ac_includes_default int main () { + /* Are we little or big endian? From Harbison&Steele. */ union { - long l; - char c[sizeof (long)]; + long int l; + char c[sizeof (long int)]; } u; u.l = 1; - exit (u.c[sizeof (long) - 1] == 1); + return u.c[sizeof (long int) - 1] == 1; + + ; + return 0; } _ACEOF rm -f conftest$ac_exeext -if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 - (eval $ac_link) 2>&5 +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then @@ -5653,13 +22338,16 @@ ( exit $ac_status ) ac_cv_c_bigendian=yes fi -rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi + + fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -echo "$as_me:$LINENO: result: $ac_cv_c_bigendian" >&5 -echo "${ECHO_T}$ac_cv_c_bigendian" >&6 +{ echo "$as_me:$LINENO: result: $ac_cv_c_bigendian" >&5 +echo "${ECHO_T}$ac_cv_c_bigendian" >&6; } case $ac_cv_c_bigendian in yes) @@ -5678,12 +22366,69 @@ esac +{ echo "$as_me:$LINENO: checking assembler .cfi pseudo-op support" >&5 +echo $ECHO_N "checking assembler .cfi pseudo-op support... $ECHO_C" >&6; } +if test "${libffi_cv_as_cfi_pseudo_op+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + + libffi_cv_as_cfi_pseudo_op=unknown + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +asm (".cfi_startproc\n\t.cfi_endproc"); +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + libffi_cv_as_cfi_pseudo_op=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + libffi_cv_as_cfi_pseudo_op=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +fi +{ echo "$as_me:$LINENO: result: $libffi_cv_as_cfi_pseudo_op" >&5 +echo "${ECHO_T}$libffi_cv_as_cfi_pseudo_op" >&6; } +if test "x$libffi_cv_as_cfi_pseudo_op" = xyes; then +cat >>confdefs.h <<\_ACEOF +#define HAVE_AS_CFI_PSEUDO_OP 1 +_ACEOF +fi if test x$TARGET = xSPARC; then - echo "$as_me:$LINENO: checking assembler and linker support unaligned pc related relocs" >&5 -echo $ECHO_N "checking assembler and linker support unaligned pc related relocs... $ECHO_C" >&6 + { echo "$as_me:$LINENO: checking assembler and linker support unaligned pc related relocs" >&5 +echo $ECHO_N "checking assembler and linker support unaligned pc related relocs... $ECHO_C" >&6; } if test "${libffi_cv_as_sparc_ua_pcrel+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else @@ -5708,40 +22453,38 @@ } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext -if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 - (eval $ac_link) 2>conftest.er1 +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest$ac_exeext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then libffi_cv_as_sparc_ua_pcrel=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -libffi_cv_as_sparc_ua_pcrel=no + libffi_cv_as_sparc_ua_pcrel=no fi -rm -f conftest.err conftest.$ac_objext \ + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext CFLAGS="$save_CFLAGS" LDFLAGS="$save_LDFLAGS" fi -echo "$as_me:$LINENO: result: $libffi_cv_as_sparc_ua_pcrel" >&5 -echo "${ECHO_T}$libffi_cv_as_sparc_ua_pcrel" >&6 +{ echo "$as_me:$LINENO: result: $libffi_cv_as_sparc_ua_pcrel" >&5 +echo "${ECHO_T}$libffi_cv_as_sparc_ua_pcrel" >&6; } if test "x$libffi_cv_as_sparc_ua_pcrel" = xyes; then cat >>confdefs.h <<\_ACEOF @@ -5750,8 +22493,8 @@ fi - echo "$as_me:$LINENO: checking assembler .register pseudo-op support" >&5 -echo $ECHO_N "checking assembler .register pseudo-op support... $ECHO_C" >&6 + { echo "$as_me:$LINENO: checking assembler .register pseudo-op support" >&5 +echo $ECHO_N "checking assembler .register pseudo-op support... $ECHO_C" >&6; } if test "${libffi_cv_as_register_pseudo_op+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else @@ -5774,38 +22517,35 @@ } _ACEOF rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then libffi_cv_as_register_pseudo_op=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -libffi_cv_as_register_pseudo_op=no + libffi_cv_as_register_pseudo_op=no fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -echo "$as_me:$LINENO: result: $libffi_cv_as_register_pseudo_op" >&5 -echo "${ECHO_T}$libffi_cv_as_register_pseudo_op" >&6 +{ echo "$as_me:$LINENO: result: $libffi_cv_as_register_pseudo_op" >&5 +echo "${ECHO_T}$libffi_cv_as_register_pseudo_op" >&6; } if test "x$libffi_cv_as_register_pseudo_op" = xyes; then cat >>confdefs.h <<\_ACEOF @@ -5815,8 +22555,8 @@ fi fi -echo "$as_me:$LINENO: checking whether .eh_frame section should be read-only" >&5 -echo $ECHO_N "checking whether .eh_frame section should be read-only... $ECHO_C" >&6 +{ echo "$as_me:$LINENO: checking whether .eh_frame section should be read-only" >&5 +echo $ECHO_N "checking whether .eh_frame section should be read-only... $ECHO_C" >&6; } if test "${libffi_cv_ro_eh_frame+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else @@ -5834,8 +22574,8 @@ rm -f conftest.* fi -echo "$as_me:$LINENO: result: $libffi_cv_ro_eh_frame" >&5 -echo "${ECHO_T}$libffi_cv_ro_eh_frame" >&6 +{ echo "$as_me:$LINENO: result: $libffi_cv_ro_eh_frame" >&5 +echo "${ECHO_T}$libffi_cv_ro_eh_frame" >&6; } if test "x$libffi_cv_ro_eh_frame" = xyes; then cat >>confdefs.h <<\_ACEOF @@ -5855,8 +22595,8 @@ fi -echo "$as_me:$LINENO: checking for __attribute__((visibility(\"hidden\")))" >&5 -echo $ECHO_N "checking for __attribute__((visibility(\"hidden\")))... $ECHO_C" >&6 +{ echo "$as_me:$LINENO: checking for __attribute__((visibility(\"hidden\")))" >&5 +echo $ECHO_N "checking for __attribute__((visibility(\"hidden\")))... $ECHO_C" >&6; } if test "${libffi_cv_hidden_visibility_attribute+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else @@ -5876,50 +22616,109 @@ rm -f conftest.* fi -echo "$as_me:$LINENO: result: $libffi_cv_hidden_visibility_attribute" >&5 -echo "${ECHO_T}$libffi_cv_hidden_visibility_attribute" >&6 +{ echo "$as_me:$LINENO: result: $libffi_cv_hidden_visibility_attribute" >&5 +echo "${ECHO_T}$libffi_cv_hidden_visibility_attribute" >&6; } if test $libffi_cv_hidden_visibility_attribute = yes; then cat >>confdefs.h <<\_ACEOF -#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1 +#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1 +_ACEOF + +fi + + + + + + + + + +# Check whether --enable-debug was given. +if test "${enable_debug+set}" = set; then + enableval=$enable_debug; if test "$enable_debug" = "yes"; then + +cat >>confdefs.h <<\_ACEOF +#define FFI_DEBUG 1 _ACEOF + fi fi +# Check whether --enable-structs was given. +if test "${enable_structs+set}" = set; then + enableval=$enable_structs; if test "$enable_structs" = "no"; then +cat >>confdefs.h <<\_ACEOF +#define FFI_NO_STRUCTS 1 +_ACEOF + fi +fi +# Check whether --enable-raw-api was given. +if test "${enable_raw_api+set}" = set; then + enableval=$enable_raw_api; if test "$enable_raw_api" = "no"; then +cat >>confdefs.h <<\_ACEOF +#define FFI_NO_RAW_API 1 +_ACEOF + fi +fi +# Check whether --enable-purify-safety was given. +if test "${enable_purify_safety+set}" = set; then + enableval=$enable_purify_safety; if test "$enable_purify_safety" = "yes"; then cat >>confdefs.h <<\_ACEOF -#define FFI_NO_RAW_API 1 +#define USING_PURIFY 1 _ACEOF + fi +fi + - ac_config_commands="$ac_config_commands include" +if test -n "$with_cross_host" && + test x"$with_cross_host" != x"no"; then + toolexecdir='$(exec_prefix)/$(target_alias)' + toolexeclibdir='$(toolexecdir)/lib' +else + toolexecdir='$(libdir)/gcc-lib/$(target_alias)' + toolexeclibdir='$(libdir)' +fi +multi_os_directory=`$CC -print-multi-os-directory` +case $multi_os_directory in + .) ;; # Avoid trailing /. + *) toolexeclibdir=$toolexeclibdir/$multi_os_directory ;; +esac - ac_config_commands="$ac_config_commands src" -TARGETINCDIR=$TARGETDIR -case $host in -*-*-darwin*) - TARGETINCDIR="darwin" - ;; -esac +if test "${multilib}" = "yes"; then + multilib_arg="--enable-multilib" +else + multilib_arg= +fi + +ac_config_commands="$ac_config_commands include" + +ac_config_commands="$ac_config_commands src" - ac_config_links="$ac_config_links include/ffitarget.h:src/$TARGETINCDIR/ffitarget.h" +ac_config_links="$ac_config_links include/ffitarget.h:src/$TARGETDIR/ffitarget.h" - ac_config_links="$ac_config_links include/ffi_common.h:include/ffi_common.h" +ac_config_files="$ac_config_files include/ffi.h" - ac_config_files="$ac_config_files include/ffi.h fficonfig.py" + +ac_config_links="$ac_config_links include/ffi_common.h:include/ffi_common.h" + + +ac_config_files="$ac_config_files fficonfig.py" cat >confcache <<\_ACEOF @@ -5940,39 +22739,58 @@ # The following way of writing the cache mishandles newlines in values, # but we know of no workaround that is simple, portable, and efficient. -# So, don't put newlines in cache variables' values. +# So, we kill variables containing newlines. # Ultrix sh set writes to stderr and can't be redirected directly, # and sets the high bit in the cache file unless we assign to the vars. -{ +( + for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5 +echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + *) $as_unset $ac_var ;; + esac ;; + esac + done + (set) 2>&1 | - case `(ac_space=' '; set | grep ac_space) 2>&1` in - *ac_space=\ *) + case $as_nl`(ac_space=' '; set) 2>&1` in #( + *${as_nl}ac_space=\ *) # `set' does not quote correctly, so add quotes (double-quote # substitution turns \\\\ into \\, and sed turns \\ into \). sed -n \ "s/'/'\\\\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" - ;; + ;; #( *) # `set' quotes correctly as required by POSIX, so do not add quotes. - sed -n \ - "s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1=\\2/p" + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; - esac; -} | + esac | + sort +) | sed ' + /^ac_cv_env_/b end t clear - : clear + :clear s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ t end - /^ac_cv_env/!s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ - : end' >>confcache -if diff $cache_file confcache >/dev/null 2>&1; then :; else - if test -w $cache_file; then - test "x$cache_file" != "x/dev/null" && echo "updating cache $cache_file" + s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ + :end' >>confcache +if diff "$cache_file" confcache >/dev/null 2>&1; then :; else + if test -w "$cache_file"; then + test "x$cache_file" != "x/dev/null" && + { echo "$as_me:$LINENO: updating cache $cache_file" >&5 +echo "$as_me: updating cache $cache_file" >&6;} cat confcache >$cache_file else - echo "not updating unwritable cache $cache_file" + { echo "$as_me:$LINENO: not updating unwritable cache $cache_file" >&5 +echo "$as_me: not updating unwritable cache $cache_file" >&6;} fi fi rm -f confcache @@ -5981,38 +22799,234 @@ # Let make expand exec_prefix. test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' -# VPATH may cause trouble with some makes, so we remove $(srcdir), -# ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and -# trailing colons and then remove the whole line if VPATH becomes empty -# (actually we leave an empty line to preserve line numbers). -if test "x$srcdir" = x.; then - ac_vpsub='/^[ ]*VPATH[ ]*=/{ -s/:*\$(srcdir):*/:/; -s/:*\${srcdir}:*/:/; -s/:*@srcdir@:*/:/; -s/^\([^=]*=[ ]*\):*/\1/; -s/:*$//; -s/^[^=]*=[ ]*$//; -}' -fi - DEFS=-DHAVE_CONFIG_H ac_libobjs= ac_ltlibobjs= for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue # 1. Remove the extension, and $U if already installed. - ac_i=`echo "$ac_i" | - sed 's/\$U\././;s/\.o$//;s/\.obj$//'` - # 2. Add them. - ac_libobjs="$ac_libobjs $ac_i\$U.$ac_objext" - ac_ltlibobjs="$ac_ltlibobjs $ac_i"'$U.lo' + ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' + ac_i=`echo "$ac_i" | sed "$ac_script"` + # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR + # will be set to the directory where LIBOBJS objects are built. + ac_libobjs="$ac_libobjs \${LIBOBJDIR}$ac_i\$U.$ac_objext" + ac_ltlibobjs="$ac_ltlibobjs \${LIBOBJDIR}$ac_i"'$U.lo' done LIBOBJS=$ac_libobjs LTLIBOBJS=$ac_ltlibobjs +if test -z "${AMDEP_TRUE}" && test -z "${AMDEP_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"AMDEP\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"AMDEP\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${am__fastdepCC_TRUE}" && test -z "${am__fastdepCC_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"am__fastdepCC\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"am__fastdepCC\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${am__fastdepCCAS_TRUE}" && test -z "${am__fastdepCCAS_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"am__fastdepCCAS\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"am__fastdepCCAS\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${am__fastdepCXX_TRUE}" && test -z "${am__fastdepCXX_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"am__fastdepCXX\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"am__fastdepCXX\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${MAINTAINER_MODE_TRUE}" && test -z "${MAINTAINER_MODE_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"MAINTAINER_MODE\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"MAINTAINER_MODE\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${TESTSUBDIR_TRUE}" && test -z "${TESTSUBDIR_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"TESTSUBDIR\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"TESTSUBDIR\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${MIPS_TRUE}" && test -z "${MIPS_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"MIPS\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"MIPS\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${SPARC_TRUE}" && test -z "${SPARC_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"SPARC\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"SPARC\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${X86_TRUE}" && test -z "${X86_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"X86\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"X86\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${X86_FREEBSD_TRUE}" && test -z "${X86_FREEBSD_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"X86_FREEBSD\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"X86_FREEBSD\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${X86_WIN32_TRUE}" && test -z "${X86_WIN32_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"X86_WIN32\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"X86_WIN32\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${X86_DARWIN_TRUE}" && test -z "${X86_DARWIN_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"X86_DARWIN\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"X86_DARWIN\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${ALPHA_TRUE}" && test -z "${ALPHA_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"ALPHA\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"ALPHA\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${IA64_TRUE}" && test -z "${IA64_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"IA64\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"IA64\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${M32R_TRUE}" && test -z "${M32R_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"M32R\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"M32R\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${M68K_TRUE}" && test -z "${M68K_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"M68K\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"M68K\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${POWERPC_TRUE}" && test -z "${POWERPC_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"POWERPC\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"POWERPC\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${POWERPC_AIX_TRUE}" && test -z "${POWERPC_AIX_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"POWERPC_AIX\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"POWERPC_AIX\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${POWERPC_DARWIN_TRUE}" && test -z "${POWERPC_DARWIN_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"POWERPC_DARWIN\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"POWERPC_DARWIN\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${POWERPC_FREEBSD_TRUE}" && test -z "${POWERPC_FREEBSD_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"POWERPC_FREEBSD\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"POWERPC_FREEBSD\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${ARM_TRUE}" && test -z "${ARM_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"ARM\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"ARM\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${LIBFFI_CRIS_TRUE}" && test -z "${LIBFFI_CRIS_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"LIBFFI_CRIS\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"LIBFFI_CRIS\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${FRV_TRUE}" && test -z "${FRV_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"FRV\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"FRV\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${S390_TRUE}" && test -z "${S390_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"S390\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"S390\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${X86_64_TRUE}" && test -z "${X86_64_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"X86_64\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"X86_64\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${SH_TRUE}" && test -z "${SH_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"SH\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"SH\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${SH64_TRUE}" && test -z "${SH64_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"SH64\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"SH64\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${PA_LINUX_TRUE}" && test -z "${PA_LINUX_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"PA_LINUX\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"PA_LINUX\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${PA_HPUX_TRUE}" && test -z "${PA_HPUX_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"PA_HPUX\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"PA_HPUX\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${PA64_HPUX_TRUE}" && test -z "${PA64_HPUX_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"PA64_HPUX\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"PA64_HPUX\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi : ${CONFIG_STATUS=./config.status} ac_clean_files_save=$ac_clean_files @@ -6037,17 +23051,45 @@ ## M4sh Initialization. ## ## --------------------- ## -# Be Bourne compatible +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' -elif test -n "${BASH_VERSION+set}" && (set -o posix) >/dev/null 2>&1; then - set -o posix + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in + *posix*) set -o posix ;; +esac + +fi + + + + +# PATH needs CR +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + echo "#! /bin/sh" >conf$$.sh + echo "exit 0" >>conf$$.sh + chmod +x conf$$.sh + if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then + PATH_SEPARATOR=';' + else + PATH_SEPARATOR=: + fi + rm -f conf$$.sh fi -DUALCASE=1; export DUALCASE # for MKS sh # Support unset when possible. if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then @@ -6057,8 +23099,43 @@ fi +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +as_nl=' +' +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +case $0 in + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break +done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + { (exit 1); exit 1; } +fi + # Work around bugs in pre-3.0 UWIN ksh. -$as_unset ENV MAIL MAILPATH +for as_var in ENV MAIL MAILPATH +do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var +done PS1='$ ' PS2='> ' PS4='+ ' @@ -6072,18 +23149,19 @@ if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then eval $as_var=C; export $as_var else - $as_unset $as_var + ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var fi done # Required to use basename. -if expr a : '\(a\)' >/dev/null 2>&1; then +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi -if (basename /) >/dev/null 2>&1 && test "X`basename / 2>&1`" = "X/"; then +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false @@ -6091,159 +23169,120 @@ # Name of the executable. -as_me=`$as_basename "$0" || +as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ - X"$0" : 'X\(/\)$' \| \ - . : '\(.\)' 2>/dev/null || + X"$0" : 'X\(/\)' \| . 2>/dev/null || echo X/"$0" | - sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/; q; } - /^X\/\(\/\/\)$/{ s//\1/; q; } - /^X\/\(\/\).*/{ s//\1/; q; } - s/.*/./; q'` - - -# PATH needs CR, and LINENO needs CR and PATH. -# Avoid depending upon Character Ranges. -as_cr_letters='abcdefghijklmnopqrstuvwxyz' -as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' -as_cr_Letters=$as_cr_letters$as_cr_LETTERS -as_cr_digits='0123456789' -as_cr_alnum=$as_cr_Letters$as_cr_digits + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` -# The user is always right. -if test "${PATH_SEPARATOR+set}" != set; then - echo "#! /bin/sh" >conf$$.sh - echo "exit 0" >>conf$$.sh - chmod +x conf$$.sh - if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then - PATH_SEPARATOR=';' - else - PATH_SEPARATOR=: - fi - rm -f conf$$.sh -fi +# CDPATH. +$as_unset CDPATH - as_lineno_1=$LINENO - as_lineno_2=$LINENO - as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null` - test "x$as_lineno_1" != "x$as_lineno_2" && - test "x$as_lineno_3" = "x$as_lineno_2" || { - # Find who we are. Look in the path if we contain no path at all - # relative or not. - case $0 in - *[\\/]* ) as_myself=$0 ;; - *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break -done - ;; - esac - # We did not find ourselves, most probably we were run as `sh COMMAND' - # in which case we are not to be found in the path. - if test "x$as_myself" = x; then - as_myself=$0 - fi - if test ! -f "$as_myself"; then - { { echo "$as_me:$LINENO: error: cannot find myself; rerun with an absolute path" >&5 -echo "$as_me: error: cannot find myself; rerun with an absolute path" >&2;} - { (exit 1); exit 1; }; } - fi - case $CONFIG_SHELL in - '') - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for as_base in sh bash ksh sh5; do - case $as_dir in - /*) - if ("$as_dir/$as_base" -c ' as_lineno_1=$LINENO as_lineno_2=$LINENO - as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null` test "x$as_lineno_1" != "x$as_lineno_2" && - test "x$as_lineno_3" = "x$as_lineno_2" ') 2>/dev/null; then - $as_unset BASH_ENV || test "${BASH_ENV+set}" != set || { BASH_ENV=; export BASH_ENV; } - $as_unset ENV || test "${ENV+set}" != set || { ENV=; export ENV; } - CONFIG_SHELL=$as_dir/$as_base - export CONFIG_SHELL - exec "$CONFIG_SHELL" "$0" ${1+"$@"} - fi;; - esac - done -done -;; - esac + test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || { # Create $as_me.lineno as a copy of $as_myself, but with $LINENO # uniformly replaced by the line number. The first 'sed' inserts a - # line-number line before each line; the second 'sed' does the real - # work. The second script uses 'N' to pair each line-number line - # with the numbered line, and appends trailing '-' during - # substitution so that $LINENO is not a special case at line end. + # line-number line after each line using $LINENO; the second 'sed' + # does the real work. The second script uses 'N' to pair each + # line-number line with the line containing $LINENO, and appends + # trailing '-' during substitution so that $LINENO is not a special + # case at line end. # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the - # second 'sed' script. Blame Lee E. McMahon for sed's syntax. :-) - sed '=' <$as_myself | + # scripts with optimization help from Paolo Bonzini. Blame Lee + # E. McMahon (1931-1989) for sed's syntax. :-) + sed -n ' + p + /[$]LINENO/= + ' <$as_myself | sed ' + s/[$]LINENO.*/&-/ + t lineno + b + :lineno N - s,$,-, - : loop - s,^\(['$as_cr_digits']*\)\(.*\)[$]LINENO\([^'$as_cr_alnum'_]\),\1\2\1\3, + :loop + s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ t loop - s,-$,, - s,^['$as_cr_digits']*\n,, + s/-\n.*// ' >$as_me.lineno && - chmod +x $as_me.lineno || - { { echo "$as_me:$LINENO: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&5 -echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2;} + chmod +x "$as_me.lineno" || + { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 { (exit 1); exit 1; }; } # Don't try to exec as it changes $[0], causing all sort of problems # (the dirname of $[0] is not the place where we might find the - # original and so on. Autoconf is especially sensible to this). - . ./$as_me.lineno + # original and so on. Autoconf is especially sensitive to this). + . "./$as_me.lineno" # Exit status is that of the last command. exit } -case `echo "testing\c"; echo 1,2,3`,`echo -n testing; echo 1,2,3` in - *c*,-n*) ECHO_N= ECHO_C=' -' ECHO_T=' ' ;; - *c*,* ) ECHO_N=-n ECHO_C= ECHO_T= ;; - *) ECHO_N= ECHO_C='\c' ECHO_T= ;; +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in +-n*) + case `echo 'x\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + *) ECHO_C='\c';; + esac;; +*) + ECHO_N='-n';; esac -if expr a : '\(a\)' >/dev/null 2>&1; then +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir +fi echo >conf$$.file if ln -s conf$$.file conf$$ 2>/dev/null; then - # We could just check for DJGPP; but this test a) works b) is more generic - # and c) will remain valid once DJGPP supports symlinks (DJGPP 2.04). - if test -f conf$$.exe; then - # Don't use ln at all; we don't have any links + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -p'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -p' - else - as_ln_s='ln -s' - fi elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -p' fi -rm -f conf$$ conf$$.exe conf$$.file +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null if mkdir -p . 2>/dev/null; then as_mkdir_p=: @@ -6252,7 +23291,28 @@ as_mkdir_p=false fi -as_executable_p="test -f" +if test -x / >/dev/null 2>&1; then + as_test_x='test -x' +else + if ls -dL / >/dev/null 2>&1; then + as_ls_L_option=L + else + as_ls_L_option= + fi + as_test_x=' + eval sh -c '\'' + if test -d "$1"; then + test -d "$1/."; + else + case $1 in + -*)set "./$1";; + esac; + case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in + ???[sx]*):;;*)false;;esac;fi + '\'' sh + ' +fi +as_executable_p=$as_test_x # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" @@ -6261,31 +23321,14 @@ as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" -# IFS -# We need space, tab and new line, in precisely that order. -as_nl=' -' -IFS=" $as_nl" - -# CDPATH. -$as_unset CDPATH - exec 6>&1 -# Open the log real soon, to keep \$[0] and so on meaningful, and to +# Save the log message, to keep $[0] and so on meaningful, and to # report actual input values of CONFIG_FILES etc. instead of their -# values after options handling. Logging --version etc. is OK. -exec 5>>config.log -{ - echo - sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX -## Running $as_me. ## -_ASBOX -} >&5 -cat >&5 <<_CSEOF - -This file was extended by libffi $as_me 2.1, which was -generated by GNU Autoconf 2.59. Invocation command line was +# values after options handling. +ac_log=" +This file was extended by libffi $as_me 3.0.5, which was +generated by GNU Autoconf 2.61. Invocation command line was CONFIG_FILES = $CONFIG_FILES CONFIG_HEADERS = $CONFIG_HEADERS @@ -6293,30 +23336,21 @@ CONFIG_COMMANDS = $CONFIG_COMMANDS $ $0 $@ -_CSEOF -echo "on `(hostname || uname -n) 2>/dev/null | sed 1q`" >&5 -echo >&5 +on `(hostname || uname -n) 2>/dev/null | sed 1q` +" + _ACEOF +cat >>$CONFIG_STATUS <<_ACEOF # Files that config.status was made for. -if test -n "$ac_config_files"; then - echo "config_files=\"$ac_config_files\"" >>$CONFIG_STATUS -fi - -if test -n "$ac_config_headers"; then - echo "config_headers=\"$ac_config_headers\"" >>$CONFIG_STATUS -fi +config_files="$ac_config_files" +config_headers="$ac_config_headers" +config_links="$ac_config_links" +config_commands="$ac_config_commands" -if test -n "$ac_config_links"; then - echo "config_links=\"$ac_config_links\"" >>$CONFIG_STATUS -fi - -if test -n "$ac_config_commands"; then - echo "config_commands=\"$ac_config_commands\"" >>$CONFIG_STATUS -fi +_ACEOF cat >>$CONFIG_STATUS <<\_ACEOF - ac_cs_usage="\ \`$as_me' instantiates files from templates according to the current configuration. @@ -6324,7 +23358,7 @@ Usage: $0 [OPTIONS] [FILE]... -h, --help print this help, then exit - -V, --version print version number, then exit + -V, --version print version number and configuration settings, then exit -q, --quiet do not print progress messages -d, --debug don't remove temporary files --recheck update $as_me by reconfiguring in the same conditions @@ -6346,18 +23380,22 @@ $config_commands Report bugs to ." -_ACEOF +_ACEOF cat >>$CONFIG_STATUS <<_ACEOF ac_cs_version="\\ -libffi config.status 2.1 -configured by $0, generated by GNU Autoconf 2.59, - with options \\"`echo "$ac_configure_args" | sed 's/[\\""\`\$]/\\\\&/g'`\\" +libffi config.status 3.0.5 +configured by $0, generated by GNU Autoconf 2.61, + with options \\"`echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\" -Copyright (C) 2003 Free Software Foundation, Inc. +Copyright (C) 2006 Free Software Foundation, Inc. This config.status script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it." -srcdir=$srcdir + +ac_pwd='$ac_pwd' +srcdir='$srcdir' +INSTALL='$INSTALL' +MKDIR_P='$MKDIR_P' _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF @@ -6368,39 +23406,24 @@ do case $1 in --*=*) - ac_option=`expr "x$1" : 'x\([^=]*\)='` - ac_optarg=`expr "x$1" : 'x[^=]*=\(.*\)'` + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` ac_shift=: ;; - -*) + *) ac_option=$1 ac_optarg=$2 ac_shift=shift ;; - *) # This is not an option, so the user has probably given explicit - # arguments. - ac_option=$1 - ac_need_defaults=false;; esac case $ac_option in # Handling of the options. -_ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) ac_cs_recheck=: ;; - --version | --vers* | -V ) - echo "$ac_cs_version"; exit 0 ;; - --he | --h) - # Conflict between --help and --header - { { echo "$as_me:$LINENO: error: ambiguous option: $1 -Try \`$0 --help' for more information." >&5 -echo "$as_me: error: ambiguous option: $1 -Try \`$0 --help' for more information." >&2;} - { (exit 1); exit 1; }; };; - --help | --hel | -h ) - echo "$ac_cs_usage"; exit 0 ;; - --debug | --d* | -d ) + --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) + echo "$ac_cs_version"; exit ;; + --debug | --debu | --deb | --de | --d | -d ) debug=: ;; --file | --fil | --fi | --f ) $ac_shift @@ -6410,18 +23433,24 @@ $ac_shift CONFIG_HEADERS="$CONFIG_HEADERS $ac_optarg" ac_need_defaults=false;; + --he | --h) + # Conflict between --help and --header + { echo "$as_me: error: ambiguous option: $1 +Try \`$0 --help' for more information." >&2 + { (exit 1); exit 1; }; };; + --help | --hel | -h ) + echo "$ac_cs_usage"; exit ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil | --si | --s) ac_cs_silent=: ;; # This is an error. - -*) { { echo "$as_me:$LINENO: error: unrecognized option: $1 -Try \`$0 --help' for more information." >&5 -echo "$as_me: error: unrecognized option: $1 -Try \`$0 --help' for more information." >&2;} + -*) { echo "$as_me: error: unrecognized option: $1 +Try \`$0 --help' for more information." >&2 { (exit 1); exit 1; }; } ;; - *) ac_config_targets="$ac_config_targets $1" ;; + *) ac_config_targets="$ac_config_targets $1" + ac_need_defaults=false ;; esac shift @@ -6437,41 +23466,55 @@ _ACEOF cat >>$CONFIG_STATUS <<_ACEOF if \$ac_cs_recheck; then - echo "running $SHELL $0 " $ac_configure_args \$ac_configure_extra_args " --no-create --no-recursion" >&6 - exec $SHELL $0 $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion + echo "running CONFIG_SHELL=$SHELL $SHELL $0 "$ac_configure_args \$ac_configure_extra_args " --no-create --no-recursion" >&6 + CONFIG_SHELL=$SHELL + export CONFIG_SHELL + exec $SHELL "$0"$ac_configure_args \$ac_configure_extra_args --no-create --no-recursion fi _ACEOF - +cat >>$CONFIG_STATUS <<\_ACEOF +exec 5>>config.log +{ + echo + sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX +## Running $as_me. ## +_ASBOX + echo "$ac_log" +} >&5 + +_ACEOF cat >>$CONFIG_STATUS <<_ACEOF # -# INIT-COMMANDS section. +# INIT-COMMANDS # - +AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir" TARGETDIR="$TARGETDIR" _ACEOF - - cat >>$CONFIG_STATUS <<\_ACEOF + +# Handling of arguments. for ac_config_target in $ac_config_targets do - case "$ac_config_target" in - # Handling of arguments. - "include/ffi.h" ) CONFIG_FILES="$CONFIG_FILES include/ffi.h" ;; - "fficonfig.py" ) CONFIG_FILES="$CONFIG_FILES fficonfig.py" ;; - "include/ffitarget.h" ) CONFIG_LINKS="$CONFIG_LINKS include/ffitarget.h:src/$TARGETINCDIR/ffitarget.h" ;; - "include/ffi_common.h" ) CONFIG_LINKS="$CONFIG_LINKS include/ffi_common.h:include/ffi_common.h" ;; - "include" ) CONFIG_COMMANDS="$CONFIG_COMMANDS include" ;; - "src" ) CONFIG_COMMANDS="$CONFIG_COMMANDS src" ;; - "fficonfig.h" ) CONFIG_HEADERS="$CONFIG_HEADERS fficonfig.h" ;; + case $ac_config_target in + "fficonfig.h") CONFIG_HEADERS="$CONFIG_HEADERS fficonfig.h" ;; + "depfiles") CONFIG_COMMANDS="$CONFIG_COMMANDS depfiles" ;; + "include") CONFIG_COMMANDS="$CONFIG_COMMANDS include" ;; + "src") CONFIG_COMMANDS="$CONFIG_COMMANDS src" ;; + "include/ffitarget.h") CONFIG_LINKS="$CONFIG_LINKS include/ffitarget.h:src/$TARGETDIR/ffitarget.h" ;; + "include/ffi.h") CONFIG_FILES="$CONFIG_FILES include/ffi.h" ;; + "include/ffi_common.h") CONFIG_LINKS="$CONFIG_LINKS include/ffi_common.h:include/ffi_common.h" ;; + "fficonfig.py") CONFIG_FILES="$CONFIG_FILES fficonfig.py" ;; + *) { { echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5 echo "$as_me: error: invalid argument: $ac_config_target" >&2;} { (exit 1); exit 1; }; };; esac done + # If the user did not use the arguments to specify the items to instantiate, # then the envvar interface is used. Set only those that are not. # We use the long form for the default assignment because of an extremely @@ -6484,820 +23527,866 @@ fi # Have a temporary directory for convenience. Make it in the build tree -# simply because there is no reason to put it here, and in addition, +# simply because there is no reason against having it here, and in addition, # creating and moving files from /tmp can sometimes cause problems. -# Create a temporary directory, and hook for its removal unless debugging. +# Hook for its removal unless debugging. +# Note that there is a small window in which the directory will not be cleaned: +# after its creation but before its name has been assigned to `$tmp'. $debug || { - trap 'exit_status=$?; rm -rf $tmp && exit $exit_status' 0 + tmp= + trap 'exit_status=$? + { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status +' 0 trap '{ (exit 1); exit 1; }' 1 2 13 15 } - # Create a (secure) tmp directory for tmp files. { - tmp=`(umask 077 && mktemp -d -q "./confstatXXXXXX") 2>/dev/null` && + tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" } || { - tmp=./confstat$$-$RANDOM - (umask 077 && mkdir $tmp) + tmp=./conf$$-$RANDOM + (umask 077 && mkdir "$tmp") } || { echo "$me: cannot create a temporary directory in ." >&2 { (exit 1); exit 1; } } -_ACEOF - -cat >>$CONFIG_STATUS <<_ACEOF - # -# CONFIG_FILES section. +# Set up the sed scripts for CONFIG_FILES section. # # No need to generate the scripts if there are no CONFIG_FILES. # This happens for instance when ./config.status config.h -if test -n "\$CONFIG_FILES"; then - # Protect against being on the right side of a sed subst in config.status. - sed 's/,@/@@/; s/@,/@@/; s/,;t t\$/@;t t/; /@;t t\$/s/[\\\\&,]/\\\\&/g; - s/@@/,@/; s/@@/@,/; s/@;t t\$/,;t t/' >\$tmp/subs.sed <<\\CEOF -s, at SHELL@,$SHELL,;t t -s, at PATH_SEPARATOR@,$PATH_SEPARATOR,;t t -s, at PACKAGE_NAME@,$PACKAGE_NAME,;t t -s, at PACKAGE_TARNAME@,$PACKAGE_TARNAME,;t t -s, at PACKAGE_VERSION@,$PACKAGE_VERSION,;t t -s, at PACKAGE_STRING@,$PACKAGE_STRING,;t t -s, at PACKAGE_BUGREPORT@,$PACKAGE_BUGREPORT,;t t -s, at exec_prefix@,$exec_prefix,;t t -s, at prefix@,$prefix,;t t -s, at program_transform_name@,$program_transform_name,;t t -s, at bindir@,$bindir,;t t -s, at sbindir@,$sbindir,;t t -s, at libexecdir@,$libexecdir,;t t -s, at datadir@,$datadir,;t t -s, at sysconfdir@,$sysconfdir,;t t -s, at sharedstatedir@,$sharedstatedir,;t t -s, at localstatedir@,$localstatedir,;t t -s, at libdir@,$libdir,;t t -s, at includedir@,$includedir,;t t -s, at oldincludedir@,$oldincludedir,;t t -s, at infodir@,$infodir,;t t -s, at mandir@,$mandir,;t t -s, at build_alias@,$build_alias,;t t -s, at host_alias@,$host_alias,;t t -s, at target_alias@,$target_alias,;t t -s, at DEFS@,$DEFS,;t t -s, at ECHO_C@,$ECHO_C,;t t -s, at ECHO_N@,$ECHO_N,;t t -s, at ECHO_T@,$ECHO_T,;t t -s, at LIBS@,$LIBS,;t t -s, at build@,$build,;t t -s, at build_cpu@,$build_cpu,;t t -s, at build_vendor@,$build_vendor,;t t -s, at build_os@,$build_os,;t t -s, at host@,$host,;t t -s, at host_cpu@,$host_cpu,;t t -s, at host_vendor@,$host_vendor,;t t -s, at host_os@,$host_os,;t t -s, at target@,$target,;t t -s, at target_cpu@,$target_cpu,;t t -s, at target_vendor@,$target_vendor,;t t -s, at target_os@,$target_os,;t t -s, at CC@,$CC,;t t -s, at ac_ct_CC@,$ac_ct_CC,;t t -s, at EXEEXT@,$EXEEXT,;t t -s, at OBJEXT@,$OBJEXT,;t t -s, at CFLAGS@,$CFLAGS,;t t -s, at CPP@,$CPP,;t t -s, at CPPFLAGS@,$CPPFLAGS,;t t -s, at EGREP@,$EGREP,;t t -s, at ALLOCA@,$ALLOCA,;t t -s, at HAVE_LONG_DOUBLE@,$HAVE_LONG_DOUBLE,;t t -s, at TARGET@,$TARGET,;t t -s, at TARGETDIR@,$TARGETDIR,;t t -s, at MKTARGET@,$MKTARGET,;t t -s, at LIBOBJS@,$LIBOBJS,;t t -s, at LTLIBOBJS@,$LTLIBOBJS,;t t -CEOF - -_ACEOF - - cat >>$CONFIG_STATUS <<\_ACEOF - # Split the substitutions into bite-sized pieces for seds with - # small command number limits, like on Digital OSF/1 and HP-UX. - ac_max_sed_lines=48 - ac_sed_frag=1 # Number of current file. - ac_beg=1 # First line for current file. - ac_end=$ac_max_sed_lines # Line after last line for current file. - ac_more_lines=: - ac_sed_cmds= - while $ac_more_lines; do - if test $ac_beg -gt 1; then - sed "1,${ac_beg}d; ${ac_end}q" $tmp/subs.sed >$tmp/subs.frag - else - sed "${ac_end}q" $tmp/subs.sed >$tmp/subs.frag - fi - if test ! -s $tmp/subs.frag; then - ac_more_lines=false - else - # The purpose of the label and of the branching condition is to - # speed up the sed processing (if there are no `@' at all, there - # is no need to browse any of the substitutions). - # These are the two extra sed commands mentioned above. - (echo ':t - /@[a-zA-Z_][a-zA-Z_0-9]*@/!b' && cat $tmp/subs.frag) >$tmp/subs-$ac_sed_frag.sed - if test -z "$ac_sed_cmds"; then - ac_sed_cmds="sed -f $tmp/subs-$ac_sed_frag.sed" - else - ac_sed_cmds="$ac_sed_cmds | sed -f $tmp/subs-$ac_sed_frag.sed" - fi - ac_sed_frag=`expr $ac_sed_frag + 1` - ac_beg=$ac_end - ac_end=`expr $ac_end + $ac_max_sed_lines` - fi - done - if test -z "$ac_sed_cmds"; then - ac_sed_cmds=cat +if test -n "$CONFIG_FILES"; then + +_ACEOF + + + +ac_delim='%!_!# ' +for ac_last_try in false false false false false :; do + cat >conf$$subs.sed <<_ACEOF +SHELL!$SHELL$ac_delim +PATH_SEPARATOR!$PATH_SEPARATOR$ac_delim +PACKAGE_NAME!$PACKAGE_NAME$ac_delim +PACKAGE_TARNAME!$PACKAGE_TARNAME$ac_delim +PACKAGE_VERSION!$PACKAGE_VERSION$ac_delim +PACKAGE_STRING!$PACKAGE_STRING$ac_delim +PACKAGE_BUGREPORT!$PACKAGE_BUGREPORT$ac_delim +exec_prefix!$exec_prefix$ac_delim +prefix!$prefix$ac_delim +program_transform_name!$program_transform_name$ac_delim +bindir!$bindir$ac_delim +sbindir!$sbindir$ac_delim +libexecdir!$libexecdir$ac_delim +datarootdir!$datarootdir$ac_delim +datadir!$datadir$ac_delim +sysconfdir!$sysconfdir$ac_delim +sharedstatedir!$sharedstatedir$ac_delim +localstatedir!$localstatedir$ac_delim +includedir!$includedir$ac_delim +oldincludedir!$oldincludedir$ac_delim +docdir!$docdir$ac_delim +infodir!$infodir$ac_delim +htmldir!$htmldir$ac_delim +dvidir!$dvidir$ac_delim +pdfdir!$pdfdir$ac_delim +psdir!$psdir$ac_delim +libdir!$libdir$ac_delim +localedir!$localedir$ac_delim +mandir!$mandir$ac_delim +DEFS!$DEFS$ac_delim +ECHO_C!$ECHO_C$ac_delim +ECHO_N!$ECHO_N$ac_delim +ECHO_T!$ECHO_T$ac_delim +LIBS!$LIBS$ac_delim +build_alias!$build_alias$ac_delim +host_alias!$host_alias$ac_delim +target_alias!$target_alias$ac_delim +build!$build$ac_delim +build_cpu!$build_cpu$ac_delim +build_vendor!$build_vendor$ac_delim +build_os!$build_os$ac_delim +host!$host$ac_delim +host_cpu!$host_cpu$ac_delim +host_vendor!$host_vendor$ac_delim +host_os!$host_os$ac_delim +target!$target$ac_delim +target_cpu!$target_cpu$ac_delim +target_vendor!$target_vendor$ac_delim +target_os!$target_os$ac_delim +INSTALL_PROGRAM!$INSTALL_PROGRAM$ac_delim +INSTALL_SCRIPT!$INSTALL_SCRIPT$ac_delim +INSTALL_DATA!$INSTALL_DATA$ac_delim +am__isrc!$am__isrc$ac_delim +CYGPATH_W!$CYGPATH_W$ac_delim +PACKAGE!$PACKAGE$ac_delim +VERSION!$VERSION$ac_delim +ACLOCAL!$ACLOCAL$ac_delim +AUTOCONF!$AUTOCONF$ac_delim +AUTOMAKE!$AUTOMAKE$ac_delim +AUTOHEADER!$AUTOHEADER$ac_delim +MAKEINFO!$MAKEINFO$ac_delim +install_sh!$install_sh$ac_delim +STRIP!$STRIP$ac_delim +INSTALL_STRIP_PROGRAM!$INSTALL_STRIP_PROGRAM$ac_delim +mkdir_p!$mkdir_p$ac_delim +AWK!$AWK$ac_delim +SET_MAKE!$SET_MAKE$ac_delim +am__leading_dot!$am__leading_dot$ac_delim +AMTAR!$AMTAR$ac_delim +am__tar!$am__tar$ac_delim +am__untar!$am__untar$ac_delim +CC!$CC$ac_delim +CFLAGS!$CFLAGS$ac_delim +LDFLAGS!$LDFLAGS$ac_delim +CPPFLAGS!$CPPFLAGS$ac_delim +ac_ct_CC!$ac_ct_CC$ac_delim +EXEEXT!$EXEEXT$ac_delim +OBJEXT!$OBJEXT$ac_delim +DEPDIR!$DEPDIR$ac_delim +am__include!$am__include$ac_delim +am__quote!$am__quote$ac_delim +AMDEP_TRUE!$AMDEP_TRUE$ac_delim +AMDEP_FALSE!$AMDEP_FALSE$ac_delim +AMDEPBACKSLASH!$AMDEPBACKSLASH$ac_delim +CCDEPMODE!$CCDEPMODE$ac_delim +am__fastdepCC_TRUE!$am__fastdepCC_TRUE$ac_delim +am__fastdepCC_FALSE!$am__fastdepCC_FALSE$ac_delim +CCAS!$CCAS$ac_delim +CCASFLAGS!$CCASFLAGS$ac_delim +CCASDEPMODE!$CCASDEPMODE$ac_delim +am__fastdepCCAS_TRUE!$am__fastdepCCAS_TRUE$ac_delim +am__fastdepCCAS_FALSE!$am__fastdepCCAS_FALSE$ac_delim +SED!$SED$ac_delim +GREP!$GREP$ac_delim +EGREP!$EGREP$ac_delim +LN_S!$LN_S$ac_delim +ECHO!$ECHO$ac_delim +_ACEOF + + if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 97; then + break + elif $ac_last_try; then + { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 +echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} + { (exit 1); exit 1; }; } + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi -fi # test -n "$CONFIG_FILES" +done +ac_eof=`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed` +if test -n "$ac_eof"; then + ac_eof=`echo "$ac_eof" | sort -nru | sed 1q` + ac_eof=`expr $ac_eof + 1` +fi + +cat >>$CONFIG_STATUS <<_ACEOF +cat >"\$tmp/subs-1.sed" <<\CEOF$ac_eof +/@[a-zA-Z_][a-zA-Z_0-9]*@/!b +_ACEOF +sed ' +s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g +s/^/s,@/; s/!/@,|#_!!_#|/ +:n +t n +s/'"$ac_delim"'$/,g/; t +s/$/\\/; p +N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n +' >>$CONFIG_STATUS >$CONFIG_STATUS <<_ACEOF +CEOF$ac_eof +_ACEOF + + +ac_delim='%!_!# ' +for ac_last_try in false false false false false :; do + cat >conf$$subs.sed <<_ACEOF +AR!$AR$ac_delim +RANLIB!$RANLIB$ac_delim +CPP!$CPP$ac_delim +CXX!$CXX$ac_delim +CXXFLAGS!$CXXFLAGS$ac_delim +ac_ct_CXX!$ac_ct_CXX$ac_delim +CXXDEPMODE!$CXXDEPMODE$ac_delim +am__fastdepCXX_TRUE!$am__fastdepCXX_TRUE$ac_delim +am__fastdepCXX_FALSE!$am__fastdepCXX_FALSE$ac_delim +CXXCPP!$CXXCPP$ac_delim +F77!$F77$ac_delim +FFLAGS!$FFLAGS$ac_delim +ac_ct_F77!$ac_ct_F77$ac_delim +LIBTOOL!$LIBTOOL$ac_delim +MAINTAINER_MODE_TRUE!$MAINTAINER_MODE_TRUE$ac_delim +MAINTAINER_MODE_FALSE!$MAINTAINER_MODE_FALSE$ac_delim +MAINT!$MAINT$ac_delim +TESTSUBDIR_TRUE!$TESTSUBDIR_TRUE$ac_delim +TESTSUBDIR_FALSE!$TESTSUBDIR_FALSE$ac_delim +AM_RUNTESTFLAGS!$AM_RUNTESTFLAGS$ac_delim +MIPS_TRUE!$MIPS_TRUE$ac_delim +MIPS_FALSE!$MIPS_FALSE$ac_delim +SPARC_TRUE!$SPARC_TRUE$ac_delim +SPARC_FALSE!$SPARC_FALSE$ac_delim +X86_TRUE!$X86_TRUE$ac_delim +X86_FALSE!$X86_FALSE$ac_delim +X86_FREEBSD_TRUE!$X86_FREEBSD_TRUE$ac_delim +X86_FREEBSD_FALSE!$X86_FREEBSD_FALSE$ac_delim +X86_WIN32_TRUE!$X86_WIN32_TRUE$ac_delim +X86_WIN32_FALSE!$X86_WIN32_FALSE$ac_delim +X86_DARWIN_TRUE!$X86_DARWIN_TRUE$ac_delim +X86_DARWIN_FALSE!$X86_DARWIN_FALSE$ac_delim +ALPHA_TRUE!$ALPHA_TRUE$ac_delim +ALPHA_FALSE!$ALPHA_FALSE$ac_delim +IA64_TRUE!$IA64_TRUE$ac_delim +IA64_FALSE!$IA64_FALSE$ac_delim +M32R_TRUE!$M32R_TRUE$ac_delim +M32R_FALSE!$M32R_FALSE$ac_delim +M68K_TRUE!$M68K_TRUE$ac_delim +M68K_FALSE!$M68K_FALSE$ac_delim +POWERPC_TRUE!$POWERPC_TRUE$ac_delim +POWERPC_FALSE!$POWERPC_FALSE$ac_delim +POWERPC_AIX_TRUE!$POWERPC_AIX_TRUE$ac_delim +POWERPC_AIX_FALSE!$POWERPC_AIX_FALSE$ac_delim +POWERPC_DARWIN_TRUE!$POWERPC_DARWIN_TRUE$ac_delim +POWERPC_DARWIN_FALSE!$POWERPC_DARWIN_FALSE$ac_delim +POWERPC_FREEBSD_TRUE!$POWERPC_FREEBSD_TRUE$ac_delim +POWERPC_FREEBSD_FALSE!$POWERPC_FREEBSD_FALSE$ac_delim +ARM_TRUE!$ARM_TRUE$ac_delim +ARM_FALSE!$ARM_FALSE$ac_delim +LIBFFI_CRIS_TRUE!$LIBFFI_CRIS_TRUE$ac_delim +LIBFFI_CRIS_FALSE!$LIBFFI_CRIS_FALSE$ac_delim +FRV_TRUE!$FRV_TRUE$ac_delim +FRV_FALSE!$FRV_FALSE$ac_delim +S390_TRUE!$S390_TRUE$ac_delim +S390_FALSE!$S390_FALSE$ac_delim +X86_64_TRUE!$X86_64_TRUE$ac_delim +X86_64_FALSE!$X86_64_FALSE$ac_delim +SH_TRUE!$SH_TRUE$ac_delim +SH_FALSE!$SH_FALSE$ac_delim +SH64_TRUE!$SH64_TRUE$ac_delim +SH64_FALSE!$SH64_FALSE$ac_delim +PA_LINUX_TRUE!$PA_LINUX_TRUE$ac_delim +PA_LINUX_FALSE!$PA_LINUX_FALSE$ac_delim +PA_HPUX_TRUE!$PA_HPUX_TRUE$ac_delim +PA_HPUX_FALSE!$PA_HPUX_FALSE$ac_delim +PA64_HPUX_TRUE!$PA64_HPUX_TRUE$ac_delim +PA64_HPUX_FALSE!$PA64_HPUX_FALSE$ac_delim +ALLOCA!$ALLOCA$ac_delim +HAVE_LONG_DOUBLE!$HAVE_LONG_DOUBLE$ac_delim +TARGET!$TARGET$ac_delim +TARGETDIR!$TARGETDIR$ac_delim +toolexecdir!$toolexecdir$ac_delim +toolexeclibdir!$toolexeclibdir$ac_delim +LIBOBJS!$LIBOBJS$ac_delim +LTLIBOBJS!$LTLIBOBJS$ac_delim +_ACEOF + + if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 76; then + break + elif $ac_last_try; then + { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 +echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} + { (exit 1); exit 1; }; } + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done + +ac_eof=`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed` +if test -n "$ac_eof"; then + ac_eof=`echo "$ac_eof" | sort -nru | sed 1q` + ac_eof=`expr $ac_eof + 1` +fi + +cat >>$CONFIG_STATUS <<_ACEOF +cat >"\$tmp/subs-2.sed" <<\CEOF$ac_eof +/@[a-zA-Z_][a-zA-Z_0-9]*@/!b end _ACEOF +sed ' +s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g +s/^/s,@/; s/!/@,|#_!!_#|/ +:n +t n +s/'"$ac_delim"'$/,g/; t +s/$/\\/; p +N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n +' >>$CONFIG_STATUS >$CONFIG_STATUS <<_ACEOF +:end +s/|#_!!_#|//g +CEOF$ac_eof +_ACEOF + + +# VPATH may cause trouble with some makes, so we remove $(srcdir), +# ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and +# trailing colons and then remove the whole line if VPATH becomes empty +# (actually we leave an empty line to preserve line numbers). +if test "x$srcdir" = x.; then + ac_vpsub='/^[ ]*VPATH[ ]*=/{ +s/:*\$(srcdir):*/:/ +s/:*\${srcdir}:*/:/ +s/:*@srcdir@:*/:/ +s/^\([^=]*=[ ]*\):*/\1/ +s/:*$// +s/^[^=]*=[ ]*$// +}' +fi + cat >>$CONFIG_STATUS <<\_ACEOF -for ac_file in : $CONFIG_FILES; do test "x$ac_file" = x: && continue - # Support "outfile[:infile[:infile...]]", defaulting infile="outfile.in". - case $ac_file in - - | *:- | *:-:* ) # input from stdin - cat >$tmp/stdin - ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'` - ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;; - *:* ) ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'` - ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;; - * ) ac_file_in=$ac_file.in ;; +fi # test -n "$CONFIG_FILES" + + +for ac_tag in :F $CONFIG_FILES :H $CONFIG_HEADERS :L $CONFIG_LINKS :C $CONFIG_COMMANDS +do + case $ac_tag in + :[FHLC]) ac_mode=$ac_tag; continue;; + esac + case $ac_mode$ac_tag in + :[FHL]*:*);; + :L* | :C*:*) { { echo "$as_me:$LINENO: error: Invalid tag $ac_tag." >&5 +echo "$as_me: error: Invalid tag $ac_tag." >&2;} + { (exit 1); exit 1; }; };; + :[FH]-) ac_tag=-:-;; + :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; + esac + ac_save_IFS=$IFS + IFS=: + set x $ac_tag + IFS=$ac_save_IFS + shift + ac_file=$1 + shift + + case $ac_mode in + :L) ac_source=$1;; + :[FH]) + ac_file_inputs= + for ac_f + do + case $ac_f in + -) ac_f="$tmp/stdin";; + *) # Look for the file first in the build tree, then in the source tree + # (if the path is not absolute). The absolute path cannot be DOS-style, + # because $ac_f cannot contain `:'. + test -f "$ac_f" || + case $ac_f in + [\\/$]*) false;; + *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; + esac || + { { echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5 +echo "$as_me: error: cannot find input file: $ac_f" >&2;} + { (exit 1); exit 1; }; };; + esac + ac_file_inputs="$ac_file_inputs $ac_f" + done + + # Let's still pretend it is `configure' which instantiates (i.e., don't + # use $as_me), people would be surprised to read: + # /* config.h. Generated by config.status. */ + configure_input="Generated from "`IFS=: + echo $* | sed 's|^[^:]*/||;s|:[^:]*/|, |g'`" by configure." + if test x"$ac_file" != x-; then + configure_input="$ac_file. $configure_input" + { echo "$as_me:$LINENO: creating $ac_file" >&5 +echo "$as_me: creating $ac_file" >&6;} + fi + + case $ac_tag in + *:-:* | *:-) cat >"$tmp/stdin";; + esac + ;; esac - # Compute @srcdir@, @top_srcdir@, and @INSTALL@ for subdirectories. - ac_dir=`(dirname "$ac_file") 2>/dev/null || + ac_dir=`$as_dirname -- "$ac_file" || $as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$ac_file" : 'X\(//\)[^/]' \| \ X"$ac_file" : 'X\(//\)$' \| \ - X"$ac_file" : 'X\(/\)' \| \ - . : '\(.\)' 2>/dev/null || + X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || echo X"$ac_file" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; } - /^X\(\/\/\)[^/].*/{ s//\1/; q; } - /^X\(\/\/\)$/{ s//\1/; q; } - /^X\(\/\).*/{ s//\1/; q; } - s/.*/./; q'` - { if $as_mkdir_p; then - mkdir -p "$ac_dir" - else - as_dir="$ac_dir" + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + { as_dir="$ac_dir" + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || { as_dirs= - while test ! -d "$as_dir"; do - as_dirs="$as_dir $as_dirs" - as_dir=`(dirname "$as_dir") 2>/dev/null || + while :; do + case $as_dir in #( + *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ - X"$as_dir" : 'X\(/\)' \| \ - . : '\(.\)' 2>/dev/null || + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || echo X"$as_dir" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; } - /^X\(\/\/\)[^/].*/{ s//\1/; q; } - /^X\(\/\/\)$/{ s//\1/; q; } - /^X\(\/\).*/{ s//\1/; q; } - s/.*/./; q'` + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break done - test ! -n "$as_dirs" || mkdir $as_dirs - fi || { { echo "$as_me:$LINENO: error: cannot create directory \"$ac_dir\"" >&5 -echo "$as_me: error: cannot create directory \"$ac_dir\"" >&2;} + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5 +echo "$as_me: error: cannot create directory $as_dir" >&2;} { (exit 1); exit 1; }; }; } - ac_builddir=. -if test "$ac_dir" != .; then +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'` - # A "../" for each directory in $ac_dir_suffix. - ac_top_builddir=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,../,g'` -else - ac_dir_suffix= ac_top_builddir= -fi + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix case $srcdir in - .) # No --srcdir option. We are building in place. + .) # We are building in place. ac_srcdir=. - if test -z "$ac_top_builddir"; then - ac_top_srcdir=. - else - ac_top_srcdir=`echo $ac_top_builddir | sed 's,/$,,'` - fi ;; - [\\/]* | ?:[\\/]* ) # Absolute path. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; - ac_top_srcdir=$srcdir ;; - *) # Relative path. - ac_srcdir=$ac_top_builddir$srcdir$ac_dir_suffix - ac_top_srcdir=$ac_top_builddir$srcdir ;; -esac - -# Do not use `cd foo && pwd` to compute absolute paths, because -# the directories may not exist. -case `pwd` in -.) ac_abs_builddir="$ac_dir";; -*) - case "$ac_dir" in - .) ac_abs_builddir=`pwd`;; - [\\/]* | ?:[\\/]* ) ac_abs_builddir="$ac_dir";; - *) ac_abs_builddir=`pwd`/"$ac_dir";; - esac;; -esac -case $ac_abs_builddir in -.) ac_abs_top_builddir=${ac_top_builddir}.;; -*) - case ${ac_top_builddir}. in - .) ac_abs_top_builddir=$ac_abs_builddir;; - [\\/]* | ?:[\\/]* ) ac_abs_top_builddir=${ac_top_builddir}.;; - *) ac_abs_top_builddir=$ac_abs_builddir/${ac_top_builddir}.;; - esac;; -esac -case $ac_abs_builddir in -.) ac_abs_srcdir=$ac_srcdir;; -*) - case $ac_srcdir in - .) ac_abs_srcdir=$ac_abs_builddir;; - [\\/]* | ?:[\\/]* ) ac_abs_srcdir=$ac_srcdir;; - *) ac_abs_srcdir=$ac_abs_builddir/$ac_srcdir;; - esac;; -esac -case $ac_abs_builddir in -.) ac_abs_top_srcdir=$ac_top_srcdir;; -*) - case $ac_top_srcdir in - .) ac_abs_top_srcdir=$ac_abs_builddir;; - [\\/]* | ?:[\\/]* ) ac_abs_top_srcdir=$ac_top_srcdir;; - *) ac_abs_top_srcdir=$ac_abs_builddir/$ac_top_srcdir;; - esac;; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + case $ac_mode in + :F) + # + # CONFIG_FILE + # + + case $INSTALL in + [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;; + *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;; + esac + ac_MKDIR_P=$MKDIR_P + case $MKDIR_P in + [\\/$]* | ?:[\\/]* ) ;; + */*) ac_MKDIR_P=$ac_top_build_prefix$MKDIR_P ;; + esac +_ACEOF - # Let's still pretend it is `configure' which instantiates (i.e., don't - # use $as_me), people would be surprised to read: - # /* config.h. Generated by config.status. */ - if test x"$ac_file" = x-; then - configure_input= - else - configure_input="$ac_file. " - fi - configure_input=$configure_input"Generated from `echo $ac_file_in | - sed 's,.*/,,'` by configure." - - # First look for the input files in the build tree, otherwise in the - # src tree. - ac_file_inputs=`IFS=: - for f in $ac_file_in; do - case $f in - -) echo $tmp/stdin ;; - [\\/$]*) - # Absolute (can't be DOS-style, as IFS=:) - test -f "$f" || { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5 -echo "$as_me: error: cannot find input file: $f" >&2;} - { (exit 1); exit 1; }; } - echo "$f";; - *) # Relative - if test -f "$f"; then - # Build tree - echo "$f" - elif test -f "$srcdir/$f"; then - # Source tree - echo "$srcdir/$f" - else - # /dev/null tree - { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5 -echo "$as_me: error: cannot find input file: $f" >&2;} - { (exit 1); exit 1; }; } - fi;; - esac - done` || { (exit 1); exit 1; } - - if test x"$ac_file" != x-; then - { echo "$as_me:$LINENO: creating $ac_file" >&5 -echo "$as_me: creating $ac_file" >&6;} - rm -f "$ac_file" - fi +cat >>$CONFIG_STATUS <<\_ACEOF +# If the template does not know about datarootdir, expand it. +# FIXME: This hack should be removed a few years after 2.60. +ac_datarootdir_hack=; ac_datarootdir_seen= + +case `sed -n '/datarootdir/ { + p + q +} +/@datadir@/p +/@docdir@/p +/@infodir@/p +/@localedir@/p +/@mandir@/p +' $ac_file_inputs` in +*datarootdir*) ac_datarootdir_seen=yes;; +*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) + { echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 +echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} _ACEOF cat >>$CONFIG_STATUS <<_ACEOF + ac_datarootdir_hack=' + s&@datadir@&$datadir&g + s&@docdir@&$docdir&g + s&@infodir@&$infodir&g + s&@localedir@&$localedir&g + s&@mandir@&$mandir&g + s&\\\${datarootdir}&$datarootdir&g' ;; +esac +_ACEOF + +# Neutralize VPATH when `$srcdir' = `.'. +# Shell code in configure.ac might set extrasub. +# FIXME: do we really want to maintain this feature? +cat >>$CONFIG_STATUS <<_ACEOF sed "$ac_vpsub $extrasub _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF :t /@[a-zA-Z_][a-zA-Z_0-9]*@/!b -s, at configure_input@,$configure_input,;t t -s, at srcdir@,$ac_srcdir,;t t -s, at abs_srcdir@,$ac_abs_srcdir,;t t -s, at top_srcdir@,$ac_top_srcdir,;t t -s, at abs_top_srcdir@,$ac_abs_top_srcdir,;t t -s, at builddir@,$ac_builddir,;t t -s, at abs_builddir@,$ac_abs_builddir,;t t -s, at top_builddir@,$ac_top_builddir,;t t -s, at abs_top_builddir@,$ac_abs_top_builddir,;t t -" $ac_file_inputs | (eval "$ac_sed_cmds") >$tmp/out - rm -f $tmp/stdin - if test x"$ac_file" != x-; then - mv $tmp/out $ac_file - else - cat $tmp/out - rm -f $tmp/out - fi - -done -_ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF - -# -# CONFIG_HEADER section. -# - -# These sed commands are passed to sed as "A NAME B NAME C VALUE D", where -# NAME is the cpp macro being defined and VALUE is the value it is being given. -# -# ac_d sets the value in "#define NAME VALUE" lines. -ac_dA='s,^\([ ]*\)#\([ ]*define[ ][ ]*\)' -ac_dB='[ ].*$,\1#\2' -ac_dC=' ' -ac_dD=',;t' -# ac_u turns "#undef NAME" without trailing blanks into "#define NAME VALUE". -ac_uA='s,^\([ ]*\)#\([ ]*\)undef\([ ][ ]*\)' -ac_uB='$,\1#\2define\3' -ac_uC=' ' -ac_uD=',;t' +s&@configure_input@&$configure_input&;t t +s&@top_builddir@&$ac_top_builddir_sub&;t t +s&@srcdir@&$ac_srcdir&;t t +s&@abs_srcdir@&$ac_abs_srcdir&;t t +s&@top_srcdir@&$ac_top_srcdir&;t t +s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t +s&@builddir@&$ac_builddir&;t t +s&@abs_builddir@&$ac_abs_builddir&;t t +s&@abs_top_builddir@&$ac_abs_top_builddir&;t t +s&@INSTALL@&$ac_INSTALL&;t t +s&@MKDIR_P@&$ac_MKDIR_P&;t t +$ac_datarootdir_hack +" $ac_file_inputs | sed -f "$tmp/subs-1.sed" | sed -f "$tmp/subs-2.sed" >$tmp/out + +test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && + { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } && + { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } && + { echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined." >&5 +echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined." >&2;} -for ac_file in : $CONFIG_HEADERS; do test "x$ac_file" = x: && continue - # Support "outfile[:infile[:infile...]]", defaulting infile="outfile.in". + rm -f "$tmp/stdin" case $ac_file in - - | *:- | *:-:* ) # input from stdin - cat >$tmp/stdin - ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'` - ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;; - *:* ) ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'` - ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;; - * ) ac_file_in=$ac_file.in ;; + -) cat "$tmp/out"; rm -f "$tmp/out";; + *) rm -f "$ac_file"; mv "$tmp/out" $ac_file;; esac + ;; + :H) + # + # CONFIG_HEADER + # +_ACEOF + +# Transform confdefs.h into a sed script `conftest.defines', that +# substitutes the proper values into config.h.in to produce config.h. +rm -f conftest.defines conftest.tail +# First, append a space to every undef/define line, to ease matching. +echo 's/$/ /' >conftest.defines +# Then, protect against being on the right side of a sed subst, or in +# an unquoted here document, in config.status. If some macros were +# called several times there might be several #defines for the same +# symbol, which is useless. But do not sort them, since the last +# AC_DEFINE must be honored. +ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* +# These sed commands are passed to sed as "A NAME B PARAMS C VALUE D", where +# NAME is the cpp macro being defined, VALUE is the value it is being given. +# PARAMS is the parameter list in the macro definition--in most cases, it's +# just an empty string. +ac_dA='s,^\\([ #]*\\)[^ ]*\\([ ]*' +ac_dB='\\)[ (].*,\\1define\\2' +ac_dC=' ' +ac_dD=' ,' - test x"$ac_file" != x- && { echo "$as_me:$LINENO: creating $ac_file" >&5 -echo "$as_me: creating $ac_file" >&6;} - - # First look for the input files in the build tree, otherwise in the - # src tree. - ac_file_inputs=`IFS=: - for f in $ac_file_in; do - case $f in - -) echo $tmp/stdin ;; - [\\/$]*) - # Absolute (can't be DOS-style, as IFS=:) - test -f "$f" || { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5 -echo "$as_me: error: cannot find input file: $f" >&2;} - { (exit 1); exit 1; }; } - # Do quote $f, to prevent DOS paths from being IFS'd. - echo "$f";; - *) # Relative - if test -f "$f"; then - # Build tree - echo "$f" - elif test -f "$srcdir/$f"; then - # Source tree - echo "$srcdir/$f" - else - # /dev/null tree - { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5 -echo "$as_me: error: cannot find input file: $f" >&2;} - { (exit 1); exit 1; }; } - fi;; - esac - done` || { (exit 1); exit 1; } - # Remove the trailing spaces. - sed 's/[ ]*$//' $ac_file_inputs >$tmp/in - -_ACEOF - -# Transform confdefs.h into two sed scripts, `conftest.defines' and -# `conftest.undefs', that substitutes the proper values into -# config.h.in to produce config.h. The first handles `#define' -# templates, and the second `#undef' templates. -# And first: Protect against being on the right side of a sed subst in -# config.status. Protect against being in an unquoted here document -# in config.status. -rm -f conftest.defines conftest.undefs -# Using a here document instead of a string reduces the quoting nightmare. -# Putting comments in sed scripts is not portable. -# -# `end' is used to avoid that the second main sed command (meant for -# 0-ary CPP macros) applies to n-ary macro definitions. -# See the Autoconf documentation for `clear'. -cat >confdef2sed.sed <<\_ACEOF -s/[\\&,]/\\&/g -s,[\\$`],\\&,g -t clear -: clear -s,^[ ]*#[ ]*define[ ][ ]*\([^ (][^ (]*\)\(([^)]*)\)[ ]*\(.*\)$,${ac_dA}\1${ac_dB}\1\2${ac_dC}\3${ac_dD},gp -t end -s,^[ ]*#[ ]*define[ ][ ]*\([^ ][^ ]*\)[ ]*\(.*\)$,${ac_dA}\1${ac_dB}\1${ac_dC}\2${ac_dD},gp -: end -_ACEOF -# If some macros were called several times there might be several times -# the same #defines, which is useless. Nevertheless, we may not want to -# sort them, since we want the *last* AC-DEFINE to be honored. -uniq confdefs.h | sed -n -f confdef2sed.sed >conftest.defines -sed 's/ac_d/ac_u/g' conftest.defines >conftest.undefs -rm -f confdef2sed.sed +uniq confdefs.h | + sed -n ' + t rset + :rset + s/^[ ]*#[ ]*define[ ][ ]*// + t ok + d + :ok + s/[\\&,]/\\&/g + s/^\('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/ '"$ac_dA"'\1'"$ac_dB"'\2'"${ac_dC}"'\3'"$ac_dD"'/p + s/^\('"$ac_word_re"'\)[ ]*\(.*\)/'"$ac_dA"'\1'"$ac_dB$ac_dC"'\2'"$ac_dD"'/p + ' >>conftest.defines -# This sed command replaces #undef with comments. This is necessary, for +# Remove the space that was appended to ease matching. +# Then replace #undef with comments. This is necessary, for # example, in the case of _POSIX_SOURCE, which is predefined and required # on some systems where configure will not decide to define it. -cat >>conftest.undefs <<\_ACEOF -s,^[ ]*#[ ]*undef[ ][ ]*[a-zA-Z_][a-zA-Z_0-9]*,/* & */, -_ACEOF +# (The regexp can be short, since the line contains either #define or #undef.) +echo 's/ $// +s,^[ #]*u.*,/* & */,' >>conftest.defines + +# Break up conftest.defines: +ac_max_sed_lines=50 + +# First sed command is: sed -f defines.sed $ac_file_inputs >"$tmp/out1" +# Second one is: sed -f defines.sed "$tmp/out1" >"$tmp/out2" +# Third one will be: sed -f defines.sed "$tmp/out2" >"$tmp/out1" +# et cetera. +ac_in='$ac_file_inputs' +ac_out='"$tmp/out1"' +ac_nxt='"$tmp/out2"' -# Break up conftest.defines because some shells have a limit on the size -# of here documents, and old seds have small limits too (100 cmds). -echo ' # Handle all the #define templates only if necessary.' >>$CONFIG_STATUS -echo ' if grep "^[ ]*#[ ]*define" $tmp/in >/dev/null; then' >>$CONFIG_STATUS -echo ' # If there are no defines, we may have an empty if/fi' >>$CONFIG_STATUS -echo ' :' >>$CONFIG_STATUS -rm -f conftest.tail -while grep . conftest.defines >/dev/null -do - # Write a limited-size here document to $tmp/defines.sed. - echo ' cat >$tmp/defines.sed <>$CONFIG_STATUS - # Speed up: don't consider the non `#define' lines. - echo '/^[ ]*#[ ]*define/!b' >>$CONFIG_STATUS - # Work around the forget-to-reset-the-flag bug. - echo 't clr' >>$CONFIG_STATUS - echo ': clr' >>$CONFIG_STATUS - sed ${ac_max_here_lines}q conftest.defines >>$CONFIG_STATUS +while : +do + # Write a here document: + cat >>$CONFIG_STATUS <<_ACEOF + # First, check the format of the line: + cat >"\$tmp/defines.sed" <<\\CEOF +/^[ ]*#[ ]*undef[ ][ ]*$ac_word_re[ ]*\$/b def +/^[ ]*#[ ]*define[ ][ ]*$ac_word_re[( ]/b def +b +:def +_ACEOF + sed ${ac_max_sed_lines}q conftest.defines >>$CONFIG_STATUS echo 'CEOF - sed -f $tmp/defines.sed $tmp/in >$tmp/out - rm -f $tmp/in - mv $tmp/out $tmp/in -' >>$CONFIG_STATUS - sed 1,${ac_max_here_lines}d conftest.defines >conftest.tail + sed -f "$tmp/defines.sed"' "$ac_in >$ac_out" >>$CONFIG_STATUS + ac_in=$ac_out; ac_out=$ac_nxt; ac_nxt=$ac_in + sed 1,${ac_max_sed_lines}d conftest.defines >conftest.tail + grep . conftest.tail >/dev/null || break rm -f conftest.defines mv conftest.tail conftest.defines done -rm -f conftest.defines -echo ' fi # grep' >>$CONFIG_STATUS -echo >>$CONFIG_STATUS - -# Break up conftest.undefs because some shells have a limit on the size -# of here documents, and old seds have small limits too (100 cmds). -echo ' # Handle all the #undef templates' >>$CONFIG_STATUS -rm -f conftest.tail -while grep . conftest.undefs >/dev/null -do - # Write a limited-size here document to $tmp/undefs.sed. - echo ' cat >$tmp/undefs.sed <>$CONFIG_STATUS - # Speed up: don't consider the non `#undef' - echo '/^[ ]*#[ ]*undef/!b' >>$CONFIG_STATUS - # Work around the forget-to-reset-the-flag bug. - echo 't clr' >>$CONFIG_STATUS - echo ': clr' >>$CONFIG_STATUS - sed ${ac_max_here_lines}q conftest.undefs >>$CONFIG_STATUS - echo 'CEOF - sed -f $tmp/undefs.sed $tmp/in >$tmp/out - rm -f $tmp/in - mv $tmp/out $tmp/in -' >>$CONFIG_STATUS - sed 1,${ac_max_here_lines}d conftest.undefs >conftest.tail - rm -f conftest.undefs - mv conftest.tail conftest.undefs -done -rm -f conftest.undefs +rm -f conftest.defines conftest.tail +echo "ac_result=$ac_in" >>$CONFIG_STATUS cat >>$CONFIG_STATUS <<\_ACEOF - # Let's still pretend it is `configure' which instantiates (i.e., don't - # use $as_me), people would be surprised to read: - # /* config.h. Generated by config.status. */ - if test x"$ac_file" = x-; then - echo "/* Generated by configure. */" >$tmp/config.h - else - echo "/* $ac_file. Generated by configure. */" >$tmp/config.h - fi - cat $tmp/in >>$tmp/config.h - rm -f $tmp/in if test x"$ac_file" != x-; then - if diff $ac_file $tmp/config.h >/dev/null 2>&1; then + echo "/* $configure_input */" >"$tmp/config.h" + cat "$ac_result" >>"$tmp/config.h" + if diff $ac_file "$tmp/config.h" >/dev/null 2>&1; then { echo "$as_me:$LINENO: $ac_file is unchanged" >&5 echo "$as_me: $ac_file is unchanged" >&6;} else - ac_dir=`(dirname "$ac_file") 2>/dev/null || -$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$ac_file" : 'X\(//\)[^/]' \| \ - X"$ac_file" : 'X\(//\)$' \| \ - X"$ac_file" : 'X\(/\)' \| \ - . : '\(.\)' 2>/dev/null || -echo X"$ac_file" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; } - /^X\(\/\/\)[^/].*/{ s//\1/; q; } - /^X\(\/\/\)$/{ s//\1/; q; } - /^X\(\/\).*/{ s//\1/; q; } - s/.*/./; q'` - { if $as_mkdir_p; then - mkdir -p "$ac_dir" - else - as_dir="$ac_dir" - as_dirs= - while test ! -d "$as_dir"; do - as_dirs="$as_dir $as_dirs" - as_dir=`(dirname "$as_dir") 2>/dev/null || -$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$as_dir" : 'X\(//\)[^/]' \| \ - X"$as_dir" : 'X\(//\)$' \| \ - X"$as_dir" : 'X\(/\)' \| \ - . : '\(.\)' 2>/dev/null || -echo X"$as_dir" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; } - /^X\(\/\/\)[^/].*/{ s//\1/; q; } - /^X\(\/\/\)$/{ s//\1/; q; } - /^X\(\/\).*/{ s//\1/; q; } - s/.*/./; q'` - done - test ! -n "$as_dirs" || mkdir $as_dirs - fi || { { echo "$as_me:$LINENO: error: cannot create directory \"$ac_dir\"" >&5 -echo "$as_me: error: cannot create directory \"$ac_dir\"" >&2;} - { (exit 1); exit 1; }; }; } - rm -f $ac_file - mv $tmp/config.h $ac_file + mv "$tmp/config.h" $ac_file fi else - cat $tmp/config.h - rm -f $tmp/config.h + echo "/* $configure_input */" + cat "$ac_result" fi + rm -f "$tmp/out12" +# Compute $ac_file's index in $config_headers. +_am_stamp_count=1 +for _am_header in $config_headers :; do + case $_am_header in + $ac_file | $ac_file:* ) + break ;; + * ) + _am_stamp_count=`expr $_am_stamp_count + 1` ;; + esac done -_ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF - -# -# CONFIG_LINKS section. -# - -for ac_file in : $CONFIG_LINKS; do test "x$ac_file" = x: && continue - ac_dest=`echo "$ac_file" | sed 's,:.*,,'` - ac_source=`echo "$ac_file" | sed 's,[^:]*:,,'` +echo "timestamp for $ac_file" >`$as_dirname -- $ac_file || +$as_expr X$ac_file : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X$ac_file : 'X\(//\)[^/]' \| \ + X$ac_file : 'X\(//\)$' \| \ + X$ac_file : 'X\(/\)' \| . 2>/dev/null || +echo X$ac_file | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'`/stamp-h$_am_stamp_count + ;; + :L) + # + # CONFIG_LINK + # - { echo "$as_me:$LINENO: linking $srcdir/$ac_source to $ac_dest" >&5 -echo "$as_me: linking $srcdir/$ac_source to $ac_dest" >&6;} + { echo "$as_me:$LINENO: linking $srcdir/$ac_source to $ac_file" >&5 +echo "$as_me: linking $srcdir/$ac_source to $ac_file" >&6;} - if test ! -r $srcdir/$ac_source; then + if test ! -r "$srcdir/$ac_source"; then { { echo "$as_me:$LINENO: error: $srcdir/$ac_source: file not found" >&5 echo "$as_me: error: $srcdir/$ac_source: file not found" >&2;} { (exit 1); exit 1; }; } fi - rm -f $ac_dest - - # Make relative symlinks. - ac_dest_dir=`(dirname "$ac_dest") 2>/dev/null || -$as_expr X"$ac_dest" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$ac_dest" : 'X\(//\)[^/]' \| \ - X"$ac_dest" : 'X\(//\)$' \| \ - X"$ac_dest" : 'X\(/\)' \| \ - . : '\(.\)' 2>/dev/null || -echo X"$ac_dest" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; } - /^X\(\/\/\)[^/].*/{ s//\1/; q; } - /^X\(\/\/\)$/{ s//\1/; q; } - /^X\(\/\).*/{ s//\1/; q; } - s/.*/./; q'` - { if $as_mkdir_p; then - mkdir -p "$ac_dest_dir" - else - as_dir="$ac_dest_dir" - as_dirs= - while test ! -d "$as_dir"; do - as_dirs="$as_dir $as_dirs" - as_dir=`(dirname "$as_dir") 2>/dev/null || -$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$as_dir" : 'X\(//\)[^/]' \| \ - X"$as_dir" : 'X\(//\)$' \| \ - X"$as_dir" : 'X\(/\)' \| \ - . : '\(.\)' 2>/dev/null || -echo X"$as_dir" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; } - /^X\(\/\/\)[^/].*/{ s//\1/; q; } - /^X\(\/\/\)$/{ s//\1/; q; } - /^X\(\/\).*/{ s//\1/; q; } - s/.*/./; q'` - done - test ! -n "$as_dirs" || mkdir $as_dirs - fi || { { echo "$as_me:$LINENO: error: cannot create directory \"$ac_dest_dir\"" >&5 -echo "$as_me: error: cannot create directory \"$ac_dest_dir\"" >&2;} - { (exit 1); exit 1; }; }; } - - ac_builddir=. - -if test "$ac_dest_dir" != .; then - ac_dir_suffix=/`echo "$ac_dest_dir" | sed 's,^\.[\\/],,'` - # A "../" for each directory in $ac_dir_suffix. - ac_top_builddir=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,../,g'` -else - ac_dir_suffix= ac_top_builddir= -fi - -case $srcdir in - .) # No --srcdir option. We are building in place. - ac_srcdir=. - if test -z "$ac_top_builddir"; then - ac_top_srcdir=. - else - ac_top_srcdir=`echo $ac_top_builddir | sed 's,/$,,'` - fi ;; - [\\/]* | ?:[\\/]* ) # Absolute path. - ac_srcdir=$srcdir$ac_dir_suffix; - ac_top_srcdir=$srcdir ;; - *) # Relative path. - ac_srcdir=$ac_top_builddir$srcdir$ac_dir_suffix - ac_top_srcdir=$ac_top_builddir$srcdir ;; -esac - -# Do not use `cd foo && pwd` to compute absolute paths, because -# the directories may not exist. -case `pwd` in -.) ac_abs_builddir="$ac_dest_dir";; -*) - case "$ac_dest_dir" in - .) ac_abs_builddir=`pwd`;; - [\\/]* | ?:[\\/]* ) ac_abs_builddir="$ac_dest_dir";; - *) ac_abs_builddir=`pwd`/"$ac_dest_dir";; - esac;; -esac -case $ac_abs_builddir in -.) ac_abs_top_builddir=${ac_top_builddir}.;; -*) - case ${ac_top_builddir}. in - .) ac_abs_top_builddir=$ac_abs_builddir;; - [\\/]* | ?:[\\/]* ) ac_abs_top_builddir=${ac_top_builddir}.;; - *) ac_abs_top_builddir=$ac_abs_builddir/${ac_top_builddir}.;; - esac;; -esac -case $ac_abs_builddir in -.) ac_abs_srcdir=$ac_srcdir;; -*) - case $ac_srcdir in - .) ac_abs_srcdir=$ac_abs_builddir;; - [\\/]* | ?:[\\/]* ) ac_abs_srcdir=$ac_srcdir;; - *) ac_abs_srcdir=$ac_abs_builddir/$ac_srcdir;; - esac;; -esac -case $ac_abs_builddir in -.) ac_abs_top_srcdir=$ac_top_srcdir;; -*) - case $ac_top_srcdir in - .) ac_abs_top_srcdir=$ac_abs_builddir;; - [\\/]* | ?:[\\/]* ) ac_abs_top_srcdir=$ac_top_srcdir;; - *) ac_abs_top_srcdir=$ac_abs_builddir/$ac_top_srcdir;; - esac;; -esac - + rm -f "$ac_file" + # Try a relative symlink, then a hard link, then a copy. case $srcdir in [\\/$]* | ?:[\\/]* ) ac_rel_source=$srcdir/$ac_source ;; - *) ac_rel_source=$ac_top_builddir$srcdir/$ac_source ;; + *) ac_rel_source=$ac_top_build_prefix$srcdir/$ac_source ;; esac - - # Try a symlink, then a hard link, then a copy. - ln -s $ac_rel_source $ac_dest 2>/dev/null || - ln $srcdir/$ac_source $ac_dest 2>/dev/null || - cp -p $srcdir/$ac_source $ac_dest || - { { echo "$as_me:$LINENO: error: cannot link or copy $srcdir/$ac_source to $ac_dest" >&5 -echo "$as_me: error: cannot link or copy $srcdir/$ac_source to $ac_dest" >&2;} + ln -s "$ac_rel_source" "$ac_file" 2>/dev/null || + ln "$srcdir/$ac_source" "$ac_file" 2>/dev/null || + cp -p "$srcdir/$ac_source" "$ac_file" || + { { echo "$as_me:$LINENO: error: cannot link or copy $srcdir/$ac_source to $ac_file" >&5 +echo "$as_me: error: cannot link or copy $srcdir/$ac_source to $ac_file" >&2;} { (exit 1); exit 1; }; } -done -_ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF + ;; + :C) { echo "$as_me:$LINENO: executing $ac_file commands" >&5 +echo "$as_me: executing $ac_file commands" >&6;} + ;; + esac -# -# CONFIG_COMMANDS section. -# -for ac_file in : $CONFIG_COMMANDS; do test "x$ac_file" = x: && continue - ac_dest=`echo "$ac_file" | sed 's,:.*,,'` - ac_source=`echo "$ac_file" | sed 's,[^:]*:,,'` - ac_dir=`(dirname "$ac_dest") 2>/dev/null || -$as_expr X"$ac_dest" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$ac_dest" : 'X\(//\)[^/]' \| \ - X"$ac_dest" : 'X\(//\)$' \| \ - X"$ac_dest" : 'X\(/\)' \| \ - . : '\(.\)' 2>/dev/null || -echo X"$ac_dest" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; } - /^X\(\/\/\)[^/].*/{ s//\1/; q; } - /^X\(\/\/\)$/{ s//\1/; q; } - /^X\(\/\).*/{ s//\1/; q; } - s/.*/./; q'` - { if $as_mkdir_p; then - mkdir -p "$ac_dir" + + case $ac_file$ac_mode in + "depfiles":C) test x"$AMDEP_TRUE" != x"" || for mf in $CONFIG_FILES; do + # Strip MF so we end up with the name of the file. + mf=`echo "$mf" | sed -e 's/:.*$//'` + # Check whether this is an Automake generated Makefile or not. + # We used to match only the files named `Makefile.in', but + # some people rename them; so instead we look at the file content. + # Grep'ing the first line is not enough: some people post-process + # each Makefile.in and add a new line on top of each file to say so. + # Grep'ing the whole file is not good either: AIX grep has a line + # limit of 2048, but all sed's we know have understand at least 4000. + if sed 10q "$mf" | grep '^#.*generated by automake' > /dev/null 2>&1; then + dirpart=`$as_dirname -- "$mf" || +$as_expr X"$mf" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$mf" : 'X\(//\)[^/]' \| \ + X"$mf" : 'X\(//\)$' \| \ + X"$mf" : 'X\(/\)' \| . 2>/dev/null || +echo X"$mf" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` else - as_dir="$ac_dir" + continue + fi + # Extract the definition of DEPDIR, am__include, and am__quote + # from the Makefile without running `make'. + DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` + test -z "$DEPDIR" && continue + am__include=`sed -n 's/^am__include = //p' < "$mf"` + test -z "am__include" && continue + am__quote=`sed -n 's/^am__quote = //p' < "$mf"` + # When using ansi2knr, U may be empty or an underscore; expand it + U=`sed -n 's/^U = //p' < "$mf"` + # Find all dependency output files, they are included files with + # $(DEPDIR) in their names. We invoke sed twice because it is the + # simplest approach to changing $(DEPDIR) to its actual value in the + # expansion. + for file in `sed -n " + s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \ + sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do + # Make sure the directory exists. + test -f "$dirpart/$file" && continue + fdir=`$as_dirname -- "$file" || +$as_expr X"$file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$file" : 'X\(//\)[^/]' \| \ + X"$file" : 'X\(//\)$' \| \ + X"$file" : 'X\(/\)' \| . 2>/dev/null || +echo X"$file" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + { as_dir=$dirpart/$fdir + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || { as_dirs= - while test ! -d "$as_dir"; do - as_dirs="$as_dir $as_dirs" - as_dir=`(dirname "$as_dir") 2>/dev/null || + while :; do + case $as_dir in #( + *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ - X"$as_dir" : 'X\(/\)' \| \ - . : '\(.\)' 2>/dev/null || + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || echo X"$as_dir" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; } - /^X\(\/\/\)[^/].*/{ s//\1/; q; } - /^X\(\/\/\)$/{ s//\1/; q; } - /^X\(\/\).*/{ s//\1/; q; } - s/.*/./; q'` + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break done - test ! -n "$as_dirs" || mkdir $as_dirs - fi || { { echo "$as_me:$LINENO: error: cannot create directory \"$ac_dir\"" >&5 -echo "$as_me: error: cannot create directory \"$ac_dir\"" >&2;} + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5 +echo "$as_me: error: cannot create directory $as_dir" >&2;} { (exit 1); exit 1; }; }; } - - ac_builddir=. - -if test "$ac_dir" != .; then - ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'` - # A "../" for each directory in $ac_dir_suffix. - ac_top_builddir=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,../,g'` -else - ac_dir_suffix= ac_top_builddir= -fi - -case $srcdir in - .) # No --srcdir option. We are building in place. - ac_srcdir=. - if test -z "$ac_top_builddir"; then - ac_top_srcdir=. - else - ac_top_srcdir=`echo $ac_top_builddir | sed 's,/$,,'` - fi ;; - [\\/]* | ?:[\\/]* ) # Absolute path. - ac_srcdir=$srcdir$ac_dir_suffix; - ac_top_srcdir=$srcdir ;; - *) # Relative path. - ac_srcdir=$ac_top_builddir$srcdir$ac_dir_suffix - ac_top_srcdir=$ac_top_builddir$srcdir ;; -esac - -# Do not use `cd foo && pwd` to compute absolute paths, because -# the directories may not exist. -case `pwd` in -.) ac_abs_builddir="$ac_dir";; -*) - case "$ac_dir" in - .) ac_abs_builddir=`pwd`;; - [\\/]* | ?:[\\/]* ) ac_abs_builddir="$ac_dir";; - *) ac_abs_builddir=`pwd`/"$ac_dir";; - esac;; -esac -case $ac_abs_builddir in -.) ac_abs_top_builddir=${ac_top_builddir}.;; -*) - case ${ac_top_builddir}. in - .) ac_abs_top_builddir=$ac_abs_builddir;; - [\\/]* | ?:[\\/]* ) ac_abs_top_builddir=${ac_top_builddir}.;; - *) ac_abs_top_builddir=$ac_abs_builddir/${ac_top_builddir}.;; - esac;; -esac -case $ac_abs_builddir in -.) ac_abs_srcdir=$ac_srcdir;; -*) - case $ac_srcdir in - .) ac_abs_srcdir=$ac_abs_builddir;; - [\\/]* | ?:[\\/]* ) ac_abs_srcdir=$ac_srcdir;; - *) ac_abs_srcdir=$ac_abs_builddir/$ac_srcdir;; - esac;; -esac -case $ac_abs_builddir in -.) ac_abs_top_srcdir=$ac_top_srcdir;; -*) - case $ac_top_srcdir in - .) ac_abs_top_srcdir=$ac_abs_builddir;; - [\\/]* | ?:[\\/]* ) ac_abs_top_srcdir=$ac_top_srcdir;; - *) ac_abs_top_srcdir=$ac_abs_builddir/$ac_top_srcdir;; - esac;; -esac - - - { echo "$as_me:$LINENO: executing $ac_dest commands" >&5 -echo "$as_me: executing $ac_dest commands" >&6;} - case $ac_dest in - include ) test -d include || mkdir include ;; - src ) + # echo "creating $dirpart/$file" + echo '# dummy' > "$dirpart/$file" + done +done + ;; + "include":C) test -d include || mkdir include ;; + "src":C) test -d src || mkdir src test -d src/$TARGETDIR || mkdir src/$TARGETDIR ;; + esac -done -_ACEOF +done # for ac_tag -cat >>$CONFIG_STATUS <<\_ACEOF { (exit 0); exit 0; } _ACEOF Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/configure.ac ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/configure.ac (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/configure.ac Wed Apr 30 15:57:13 2008 @@ -1,13 +1,25 @@ dnl Process this with autoconf to create configure +# +# file from libffi - slightly patched for ctypes +# AC_PREREQ(2.59) -AC_INIT([libffi], [2.1], [http://gcc.gnu.org/bugs.html]) +AC_INIT([libffi], [3.0.5], [http://gcc.gnu.org/bugs.html]) AC_CONFIG_HEADERS([fficonfig.h]) AC_CANONICAL_SYSTEM target_alias=${target_alias-$host_alias} +. ${srcdir}/configure.host + +AM_INIT_AUTOMAKE + +# The same as in boehm-gc and libstdc++. Have to borrow it from there. +# We must force CC to /not/ be precious variables; otherwise +# the wrong, non-multilib-adjusted value will be used in multilibs. +# As a side effect, we have to subst CFLAGS ourselves. + m4_rename([_AC_ARG_VAR_PRECIOUS],[real_PRECIOUS]) m4_define([_AC_ARG_VAR_PRECIOUS],[]) AC_PROG_CC @@ -15,79 +27,162 @@ AC_SUBST(CFLAGS) +AM_PROG_AS +AM_PROG_CC_C_O +AC_PROG_LIBTOOL + +AM_MAINTAINER_MODE + AC_CHECK_HEADERS(sys/mman.h) AC_CHECK_FUNCS(mmap) AC_FUNC_MMAP_BLACKLIST +dnl The -no-testsuite modules omit the test subdir. +AM_CONDITIONAL(TESTSUBDIR, test -d $srcdir/testsuite) + TARGETDIR="unknown" case "$host" in -x86_64-*-openbsd*) TARGET=X86_64; TARGETDIR=x86;; -mips*-*-openbsd*) TARGET=MIPS; TARGETDIR=mips;; -sparc-*-openbsd*) TARGET=SPARC; TARGETDIR=sparc;; -sparc64-*-openbsd*) TARGET=SPARC; TARGETDIR=sparc;; -alpha*-*-openbsd*) TARGET=ALPHA; TARGETDIR=alpha;; -m68k-*-openbsd*) TARGET=M68K; TARGETDIR=m68k;; -powerpc-*-openbsd*) TARGET=POWERPC; TARGETDIR=powerpc;; -i*86-*-darwin*) TARGET=X86_DARWIN; TARGETDIR=x86;; -i*86-*-linux*) TARGET=X86; TARGETDIR=x86;; -i*86-*-gnu*) TARGET=X86; TARGETDIR=x86;; -i*86-*-solaris2.1[[0-9]]*) TARGET=X86_64; TARGETDIR=x86;; -i*86-*-solaris*) TARGET=X86; TARGETDIR=x86;; -i*86-*-beos*) TARGET=X86; TARGETDIR=x86;; -i*86-*-freebsd* | i*86-*-kfreebsd*-gnu) TARGET=X86; TARGETDIR=x86;; -i*86-*-netbsdelf* | i*86-*-knetbsd*-gnu) TARGET=X86; TARGETDIR=x86;; -i*86-*-openbsd*) TARGET=X86; TARGETDIR=x86;; -i*86-*-rtems*) TARGET=X86; TARGETDIR=x86;; -i*86-*-win32*) TARGET=X86_WIN32; TARGETDIR=x86;; -i*86-*-cygwin*) TARGET=X86_WIN32; TARGETDIR=x86;; -i*86-*-mingw*) TARGET=X86_WIN32; TARGETDIR=x86;; -frv-*-*) TARGET=FRV; TARGETDIR=frv;; -sparc-sun-4*) TARGET=SPARC; TARGETDIR=sparc;; -sparc*-sun-*) TARGET=SPARC; TARGETDIR=sparc;; -sparc-*-linux* | sparc-*-netbsdelf* | sparc-*-knetbsd*-gnu) TARGET=SPARC; TARGETDIR=sparc;; -sparc*-*-rtems*) TARGET=SPARC; TARGETDIR=sparc;; -sparc64-*-linux* | sparc64-*-freebsd* | sparc64-*-netbsd* | sparc64-*-knetbsd*-gnu) TARGET=SPARC; TARGETDIR=sparc;; -alpha*-*-linux* | alpha*-*-osf* | alpha*-*-freebsd* | alpha*-*-kfreebsd*-gnu | alpha*-*-netbsd* | alpha*-*-knetbsd*-gnu) TARGET=ALPHA; TARGETDIR=alpha;; -ia64*-*-*) TARGET=IA64; TARGETDIR=ia64;; -m32r*-*-linux* ) TARGET=M32R; TARGETDIR=m32r;; -m68k-*-linux*) TARGET=M68K; TARGETDIR=m68k;; -mips64*-*);; -mips-sgi-irix5.* | mips-sgi-irix6.*) TARGET=MIPS_IRIX; TARGETDIR=mips;; -mips*-*-linux*) TARGET=MIPS_LINUX; TARGETDIR=mips;; -powerpc*-*-linux* | powerpc-*-sysv*) TARGET=POWERPC; TARGETDIR=powerpc;; -powerpc-*-beos*) TARGET=POWERPC; TARGETDIR=powerpc;; -powerpc-*-darwin*) TARGET=POWERPC_DARWIN; TARGETDIR=powerpc;; -powerpc-*-aix*) TARGET=POWERPC_AIX; TARGETDIR=powerpc;; -powerpc-*-freebsd*) TARGET=POWERPC_FREEBSD; TARGETDIR=powerpc;; -powerpc*-*-rtems*) TARGET=POWERPC; TARGETDIR=powerpc;; -rs6000-*-aix*) TARGET=POWERPC_AIX; TARGETDIR=powerpc;; -arm*-*-linux-*) TARGET=ARM; TARGETDIR=arm;; -arm*-*-netbsdelf* | arm*-*-knetbsd*-gnu) TARGET=ARM; TARGETDIR=arm;; -arm*-*-rtems*) TARGET=ARM; TARGETDIR=arm;; -cris-*-*) TARGET=LIBFFI_CRIS; TARGETDIR=cris;; -s390-*-linux-*) TARGET=S390; TARGETDIR=s390;; -s390x-*-linux-*) TARGET=S390; TARGETDIR=s390;; -amd64-*-freebsd* | x86_64-*-linux* | x86_64-*-freebsd* | x86_64-*-kfreebsd*-gnu) TARGET=X86_64; TARGETDIR=x86;; -sh-*-linux* | sh[[34]]*-*-linux*) TARGET=SH; TARGETDIR=sh;; -sh-*-rtems*) TARGET=SH; TARGETDIR=sh;; -sh64-*-linux* | sh5*-*-linux*) TARGET=SH64; TARGETDIR=sh64;; -hppa*-*-linux* | parisc*-*-linux*) TARGET=PA; TARGETDIR=pa;; + alpha*-*-*) + TARGET=ALPHA; TARGETDIR=alpha; + # Support 128-bit long double, changable via command-line switch. + HAVE_LONG_DOUBLE='defined(__LONG_DOUBLE_128__)' + ;; + + arm*-*-*) + TARGET=ARM; TARGETDIR=arm + ;; + + amd64-*-freebsd*) + TARGET=X86_64; TARGETDIR=x86 + ;; + + cris-*-*) + TARGET=LIBFFI_CRIS; TARGETDIR=cris + ;; + + frv-*-*) + TARGET=FRV; TARGETDIR=frv + ;; + + hppa*-*-linux* | parisc*-*-linux*) + TARGET=PA_LINUX; TARGETDIR=pa + ;; + hppa*64-*-hpux*) + TARGET=PA64_HPUX; TARGETDIR=pa + ;; + hppa*-*-hpux*) + TARGET=PA_HPUX; TARGETDIR=pa + ;; + + i386-*-freebsd* | i386-*-openbsd*) + TARGET=X86_FREEBSD; TARGETDIR=x86 + ;; + i?86-win32* | i?86-*-cygwin* | i?86-*-mingw*) + TARGET=X86_WIN32; TARGETDIR=x86 + ;; + i?86-*-darwin*) + TARGET=X86_DARWIN; TARGETDIR=x86 + ;; + i?86-*-solaris2.1[[0-9]]*) + TARGET=X86_64; TARGETDIR=x86 + ;; + i?86-*-*) + TARGET=X86; TARGETDIR=x86 + ;; + + ia64*-*-*) + TARGET=IA64; TARGETDIR=ia64 + ;; + + m32r*-*-*) + TARGET=M32R; TARGETDIR=m32r + ;; + + m68k-*-*) + TARGET=M68K; TARGETDIR=m68k + ;; + + mips-sgi-irix5.* | mips-sgi-irix6.*) + TARGET=MIPS; TARGETDIR=mips + ;; + mips*-*-linux*) + TARGET=MIPS; TARGETDIR=mips + ;; + + powerpc*-*-linux* | powerpc-*-sysv*) + TARGET=POWERPC; TARGETDIR=powerpc + ;; + powerpc-*-beos*) + TARGET=POWERPC; TARGETDIR=powerpc + ;; + powerpc-*-darwin*) + TARGET=POWERPC_DARWIN; TARGETDIR=powerpc + ;; + powerpc-*-aix* | rs6000-*-aix*) + TARGET=POWERPC_AIX; TARGETDIR=powerpc + ;; + powerpc-*-freebsd*) + TARGET=POWERPC_FREEBSD; TARGETDIR=powerpc + ;; + powerpc*-*-rtems*) + TARGET=POWERPC; TARGETDIR=powerpc + ;; + + s390-*-* | s390x-*-*) + TARGET=S390; TARGETDIR=s390 + ;; + + sh-*-* | sh[[34]]*-*-*) + TARGET=SH; TARGETDIR=sh + ;; + sh64-*-* | sh5*-*-*) + TARGET=SH64; TARGETDIR=sh64 + ;; + + sparc*-*-*) + TARGET=SPARC; TARGETDIR=sparc + ;; + + x86_64-*-darwin*) + TARGET=X86_DARWIN; TARGETDIR=x86 + ;; + x86_64-*-cygwin* | x86_64-*-mingw*) + ;; + x86_64-*-*) + TARGET=X86_64; TARGETDIR=x86 + ;; esac +AC_SUBST(AM_RUNTESTFLAGS) + if test $TARGETDIR = unknown; then AC_MSG_ERROR(["libffi has not been ported to $host."]) fi -dnl libffi changes TARGET for MIPS to define a such macro in the header -dnl while MIPS_IRIX or MIPS_LINUX is separatedly used to decide which -dnl files will be compiled. So, we need to keep the original decision -dnl of TARGET to use in fficonfig.py.in. -MKTARGET=$TARGET - -case x$TARGET in - xMIPS*) TARGET=MIPS ;; - *) ;; -esac +AM_CONDITIONAL(MIPS, test x$TARGET = xMIPS) +AM_CONDITIONAL(SPARC, test x$TARGET = xSPARC) +AM_CONDITIONAL(X86, test x$TARGET = xX86) +AM_CONDITIONAL(X86_FREEBSD, test x$TARGET = xX86_FREEBSD) +AM_CONDITIONAL(X86_WIN32, test x$TARGET = xX86_WIN32) +AM_CONDITIONAL(X86_DARWIN, test x$TARGET = xX86_DARWIN) +AM_CONDITIONAL(ALPHA, test x$TARGET = xALPHA) +AM_CONDITIONAL(IA64, test x$TARGET = xIA64) +AM_CONDITIONAL(M32R, test x$TARGET = xM32R) +AM_CONDITIONAL(M68K, test x$TARGET = xM68K) +AM_CONDITIONAL(POWERPC, test x$TARGET = xPOWERPC) +AM_CONDITIONAL(POWERPC_AIX, test x$TARGET = xPOWERPC_AIX) +AM_CONDITIONAL(POWERPC_DARWIN, test x$TARGET = xPOWERPC_DARWIN) +AM_CONDITIONAL(POWERPC_FREEBSD, test x$TARGET = xPOWERPC_FREEBSD) +AM_CONDITIONAL(ARM, test x$TARGET = xARM) +AM_CONDITIONAL(LIBFFI_CRIS, test x$TARGET = xLIBFFI_CRIS) +AM_CONDITIONAL(FRV, test x$TARGET = xFRV) +AM_CONDITIONAL(S390, test x$TARGET = xS390) +AM_CONDITIONAL(X86_64, test x$TARGET = xX86_64) +AM_CONDITIONAL(SH, test x$TARGET = xSH) +AM_CONDITIONAL(SH64, test x$TARGET = xSH64) +AM_CONDITIONAL(PA_LINUX, test x$TARGET = xPA_LINUX) +AM_CONDITIONAL(PA_HPUX, test x$TARGET = xPA_HPUX) +AM_CONDITIONAL(PA64_HPUX, test x$TARGET = xPA64_HPUX) AC_HEADER_STDC AC_CHECK_FUNCS(memcpy) @@ -97,45 +192,30 @@ AC_CHECK_SIZEOF(long double) # Also AC_SUBST this variable for ffi.h. -HAVE_LONG_DOUBLE=0 -if test $ac_cv_sizeof_double != $ac_cv_sizeof_long_double; then - if test $ac_cv_sizeof_long_double != 0; then - HAVE_LONG_DOUBLE=1 - AC_DEFINE(HAVE_LONG_DOUBLE, 1, [Define if you have the long double type and it is bigger than a double]) +if test -z "$HAVE_LONG_DOUBLE"; then + HAVE_LONG_DOUBLE=0 + if test $ac_cv_sizeof_double != $ac_cv_sizeof_long_double; then + if test $ac_cv_sizeof_long_double != 0; then + HAVE_LONG_DOUBLE=1 + AC_DEFINE(HAVE_LONG_DOUBLE, 1, [Define if you have the long double type and it is bigger than a double]) + fi fi fi AC_SUBST(HAVE_LONG_DOUBLE) -AC_MSG_CHECKING(for _Bool support) -have_c99_bool=no -AC_TRY_COMPILE([], [_Bool x; x = (_Bool)0;], [ - AC_DEFINE(HAVE_C99_BOOL, 1, [Define this if you have the type _Bool.]) - have_c99_bool=yes -]) -AC_MSG_RESULT($have_c99_bool) -if test "$have_c99_bool" = yes ; then -AC_CHECK_SIZEOF(_Bool, 1) -fi - AC_C_BIGENDIAN -AH_VERBATIM([WORDS_BIGENDIAN], -[ -/* Define to 1 if your processor stores words with the most significant byte - first (like Motorola and SPARC, unlike Intel and VAX). - - The block below does compile-time checking for endianness on platforms - that use GCC and therefore allows compiling fat binaries on OSX by using - '-arch ppc -arch i386' as the compile flags. The phrasing was choosen - such that the configure-result is used on systems that don't use GCC. -*/ -#ifdef __BIG_ENDIAN__ -#define WORDS_BIGENDIAN 1 -#else -#ifndef __LITTLE_ENDIAN__ -#undef WORDS_BIGENDIAN -#endif -#endif]) +AC_CACHE_CHECK([assembler .cfi pseudo-op support], + libffi_cv_as_cfi_pseudo_op, [ + libffi_cv_as_cfi_pseudo_op=unknown + AC_TRY_COMPILE([asm (".cfi_startproc\n\t.cfi_endproc");],, + [libffi_cv_as_cfi_pseudo_op=yes], + [libffi_cv_as_cfi_pseudo_op=no]) +]) +if test "x$libffi_cv_as_cfi_pseudo_op" = xyes; then + AC_DEFINE(HAVE_AS_CFI_PSEUDO_OP, 1, + [Define if your assembler supports .cfi_* directives.]) +fi if test x$TARGET = xSPARC; then AC_CACHE_CHECK([assembler and linker support unaligned pc related relocs], @@ -226,11 +306,54 @@ AC_SUBST(TARGET) AC_SUBST(TARGETDIR) -AC_SUBST(MKTARGET) AC_SUBST(SHELL) -AC_DEFINE(FFI_NO_RAW_API, 1, [Define this is you do not want support for the raw API.]) +AC_ARG_ENABLE(debug, +[ --enable-debug debugging mode], + if test "$enable_debug" = "yes"; then + AC_DEFINE(FFI_DEBUG, 1, [Define this if you want extra debugging.]) + fi) + +AC_ARG_ENABLE(structs, +[ --disable-structs omit code for struct support], + if test "$enable_structs" = "no"; then + AC_DEFINE(FFI_NO_STRUCTS, 1, [Define this is you do not want support for aggregate types.]) + fi) + +AC_ARG_ENABLE(raw-api, +[ --disable-raw-api make the raw api unavailable], + if test "$enable_raw_api" = "no"; then + AC_DEFINE(FFI_NO_RAW_API, 1, [Define this is you do not want support for the raw API.]) + fi) + +AC_ARG_ENABLE(purify-safety, +[ --enable-purify-safety purify-safe mode], + if test "$enable_purify_safety" = "yes"; then + AC_DEFINE(USING_PURIFY, 1, [Define this if you are using Purify and want to suppress spurious messages.]) + fi) + +if test -n "$with_cross_host" && + test x"$with_cross_host" != x"no"; then + toolexecdir='$(exec_prefix)/$(target_alias)' + toolexeclibdir='$(toolexecdir)/lib' +else + toolexecdir='$(libdir)/gcc-lib/$(target_alias)' + toolexeclibdir='$(libdir)' +fi +multi_os_directory=`$CC -print-multi-os-directory` +case $multi_os_directory in + .) ;; # Avoid trailing /. + *) toolexeclibdir=$toolexeclibdir/$multi_os_directory ;; +esac +AC_SUBST(toolexecdir) +AC_SUBST(toolexeclibdir) + +if test "${multilib}" = "yes"; then + multilib_arg="--enable-multilib" +else + multilib_arg= +fi AC_CONFIG_COMMANDS(include, [test -d include || mkdir include]) AC_CONFIG_COMMANDS(src, [ @@ -238,17 +361,12 @@ test -d src/$TARGETDIR || mkdir src/$TARGETDIR ], [TARGETDIR="$TARGETDIR"]) -TARGETINCDIR=$TARGETDIR -case $host in -*-*-darwin*) - TARGETINCDIR="darwin" - ;; -esac +AC_CONFIG_LINKS(include/ffitarget.h:src/$TARGETDIR/ffitarget.h) +AC_CONFIG_FILES(include/ffi.h) -AC_CONFIG_LINKS(include/ffitarget.h:src/$TARGETINCDIR/ffitarget.h) AC_CONFIG_LINKS(include/ffi_common.h:include/ffi_common.h) -AC_CONFIG_FILES(include/ffi.h fficonfig.py) +AC_CONFIG_FILES(fficonfig.py) AC_OUTPUT Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/fficonfig.h.in ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/fficonfig.h.in (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/fficonfig.h.in Wed Apr 30 15:57:13 2008 @@ -11,9 +11,15 @@ /* Define to the flags needed for the .section .eh_frame directive. */ #undef EH_FRAME_FLAGS +/* Define this if you want extra debugging. */ +#undef FFI_DEBUG + /* Define this is you do not want support for the raw API. */ #undef FFI_NO_RAW_API +/* Define this is you do not want support for aggregate types. */ +#undef FFI_NO_STRUCTS + /* Define to 1 if you have `alloca', as a function or macro. */ #undef HAVE_ALLOCA @@ -21,6 +27,9 @@ */ #undef HAVE_ALLOCA_H +/* Define if your assembler supports .cfi_* directives. */ +#undef HAVE_AS_CFI_PSEUDO_OP + /* Define if your assembler supports .register. */ #undef HAVE_AS_REGISTER_PSEUDO_OP @@ -28,8 +37,8 @@ */ #undef HAVE_AS_SPARC_UA_PCREL -/* Define this if you have the type _Bool. */ -#undef HAVE_C99_BOOL +/* Define to 1 if you have the header file. */ +#undef HAVE_DLFCN_H /* Define if __attribute__((visibility("hidden"))) is supported. */ #undef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE @@ -85,6 +94,12 @@ /* Define to 1 if you have the header file. */ #undef HAVE_UNISTD_H +/* Define to 1 if your C compiler doesn't accept -c and -o together. */ +#undef NO_MINUS_C_MINUS_O + +/* Name of package */ +#undef PACKAGE + /* Define to the address where bug reports for this package should be sent. */ #undef PACKAGE_BUGREPORT @@ -100,18 +115,15 @@ /* Define to the version of this package. */ #undef PACKAGE_VERSION -/* The size of a `double', as computed by sizeof. */ +/* The size of `double', as computed by sizeof. */ #undef SIZEOF_DOUBLE -/* The size of a `long double', as computed by sizeof. */ +/* The size of `long double', as computed by sizeof. */ #undef SIZEOF_LONG_DOUBLE -/* The size of a `_Bool', as computed by sizeof. */ -#undef SIZEOF__BOOL - /* If using the C implementation of alloca, define if you know the direction of stack growth for your system; otherwise it will be - automatically deduced at run-time. + automatically deduced at runtime. STACK_DIRECTION > 0 => grows toward higher addresses STACK_DIRECTION < 0 => grows toward lower addresses STACK_DIRECTION = 0 => direction of growth unknown */ @@ -120,22 +132,16 @@ /* Define to 1 if you have the ANSI C header files. */ #undef STDC_HEADERS +/* Define this if you are using Purify and want to suppress spurious messages. + */ +#undef USING_PURIFY -/* Define to 1 if your processor stores words with the most significant byte - first (like Motorola and SPARC, unlike Intel and VAX). +/* Version number of package */ +#undef VERSION - The block below does compile-time checking for endianness on platforms - that use GCC and therefore allows compiling fat binaries on OSX by using - '-arch ppc -arch i386' as the compile flags. The phrasing was choosen - such that the configure-result is used on systems that don't use GCC. -*/ -#ifdef __BIG_ENDIAN__ -#define WORDS_BIGENDIAN 1 -#else -#ifndef __LITTLE_ENDIAN__ +/* Define to 1 if your processor stores words with the most significant byte + first (like Motorola and SPARC, unlike Intel and VAX). */ #undef WORDS_BIGENDIAN -#endif -#endif #ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/fficonfig.py.in ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/fficonfig.py.in (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/fficonfig.py.in Wed Apr 30 15:57:13 2008 @@ -6,7 +6,7 @@ 'MIPS_IRIX': ['src/mips/ffi.c', 'src/mips/o32.S', 'src/mips/n32.S'], 'MIPS_LINUX': ['src/mips/ffi.c', 'src/mips/o32.S'], 'X86': ['src/x86/ffi.c', 'src/x86/sysv.S'], - 'X86_DARWIN': ['src/x86/ffi_darwin.c', 'src/x86/darwin.S'], + 'X86_FREEBSD': ['src/x86/ffi.c', 'src/x86/sysv.S'], 'X86_WIN32': ['src/x86/ffi.c', 'src/x86/win32.S'], 'SPARC': ['src/sparc/ffi.c', 'src/sparc/v8.S', 'src/sparc/v9.S'], 'ALPHA': ['src/alpha/ffi.c', 'src/alpha/osf.S'], @@ -14,8 +14,7 @@ 'M32R': ['src/m32r/sysv.S', 'src/m32r/ffi.c'], 'M68K': ['src/m68k/ffi.c', 'src/m68k/sysv.S'], 'POWERPC': ['src/powerpc/ffi.c', 'src/powerpc/sysv.S', 'src/powerpc/ppc_closure.S', 'src/powerpc/linux64.S', 'src/powerpc/linux64_closure.S'], - 'POWERPC_AIX': ['src/powerpc/ffi_darwin.c', 'src/powerpc/aix.S', 'src/powerpc/aix_closure.S'], - 'POWERPC_DARWIN': ['src/powerpc/ffi_darwin.c', 'src/powerpc/darwin.S', 'src/powerpc/darwin_closure.S'], + 'POWERPC_AIX': ['src/powerpc/ffi.c', 'src/powerpc/aix.S', 'src/powerpc/aix_closure.S'], 'POWERPC_FREEBSD': ['src/powerpc/ffi.c', 'src/powerpc/sysv.S', 'src/powerpc/ppc_closure.S'], 'ARM': ['src/arm/sysv.S', 'src/arm/ffi.c'], 'LIBFFI_CRIS': ['src/cris/sysv.S', 'src/cris/ffi.c'], @@ -25,21 +24,11 @@ 'SH': ['src/sh/sysv.S', 'src/sh/ffi.c'], 'SH64': ['src/sh64/sysv.S', 'src/sh64/ffi.c'], 'PA': ['src/pa/linux.S', 'src/pa/ffi.c'], + 'PA_LINUX': ['src/pa/linux.S', 'src/pa/ffi.c'], } -# Build all darwin related files on all supported darwin architectures, this -# makes it easier to build universal binaries. -if 1: - all_darwin = ('X86_DARWIN', 'POWERPC_DARWIN') - all_darwin_files = [] - for pn in all_darwin: - all_darwin_files.extend(ffi_platforms[pn]) - for pn in all_darwin: - ffi_platforms[pn] = all_darwin_files - del all_darwin, all_darwin_files, pn - ffi_srcdir = '@srcdir@' -ffi_sources += ffi_platforms['@MKTARGET@'] +ffi_sources += ffi_platforms['@TARGET@'] ffi_sources = [os.path.join('@srcdir@', f) for f in ffi_sources] ffi_cflags = '@CFLAGS@' Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/include/ffi.h.in ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/include/ffi.h.in (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/include/ffi.h.in Wed Apr 30 15:57:13 2008 @@ -1,5 +1,5 @@ /* -----------------------------------------------------------------*-C-*- - libffi @VERSION@ - Copyright (c) 1996-2003 Red Hat, Inc. + libffi @VERSION@ - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the @@ -12,13 +12,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ @@ -56,7 +57,9 @@ #endif /* Specify which architecture libffi is configured for. */ +#ifndef @TARGET@ #define @TARGET@ +#endif /* ---- System configuration information --------------------------------- */ @@ -82,6 +85,18 @@ # endif #endif +/* The closure code assumes that this works on pointers, i.e. a size_t */ +/* can hold a pointer. */ + +typedef struct _ffi_type +{ + size_t size; + unsigned short alignment; + unsigned short type; + struct _ffi_type **elements; +} ffi_type; + +#ifndef LIBFFI_HIDE_BASIC_TYPES #if SCHAR_MAX == 127 # define ffi_type_uchar ffi_type_uint8 # define ffi_type_schar ffi_type_sint8 @@ -112,26 +127,23 @@ #error "int size not supported" #endif -#define ffi_type_ulong ffi_type_uint64 -#define ffi_type_slong ffi_type_sint64 #if LONG_MAX == 2147483647 # if FFI_LONG_LONG_MAX != 9223372036854775807 - #error "no 64-bit data type supported" + #error "no 64-bit data type supported" # endif #elif LONG_MAX != 9223372036854775807 #error "long size not supported" #endif -/* The closure code assumes that this works on pointers, i.e. a size_t */ -/* can hold a pointer. */ - -typedef struct _ffi_type -{ - size_t size; - unsigned short alignment; - unsigned short type; - /*@null@*/ struct _ffi_type **elements; -} ffi_type; +#if LONG_MAX == 2147483647 +# define ffi_type_ulong ffi_type_uint32 +# define ffi_type_slong ffi_type_sint32 +#elif LONG_MAX == 9223372036854775807 +# define ffi_type_ulong ffi_type_uint64 +# define ffi_type_slong ffi_type_sint64 +#else + #error "long size not supported" +#endif /* These are defined in types.c */ extern ffi_type ffi_type_void; @@ -145,14 +157,19 @@ extern ffi_type ffi_type_sint64; extern ffi_type ffi_type_float; extern ffi_type ffi_type_double; -extern ffi_type ffi_type_longdouble; extern ffi_type ffi_type_pointer; +#if @HAVE_LONG_DOUBLE@ +extern ffi_type ffi_type_longdouble; +#else +#define ffi_type_longdouble ffi_type_double +#endif +#endif /* LIBFFI_HIDE_BASIC_TYPES */ typedef enum { FFI_OK = 0, FFI_BAD_TYPEDEF, - FFI_BAD_ABI + FFI_BAD_ABI } ffi_status; typedef unsigned FFI_TYPE; @@ -160,8 +177,8 @@ typedef struct { ffi_abi abi; unsigned nargs; - /*@dependent@*/ ffi_type **arg_types; - /*@dependent@*/ ffi_type *rtype; + ffi_type **arg_types; + ffi_type *rtype; unsigned bytes; unsigned flags; #ifdef FFI_EXTRA_CIF_FIELDS @@ -179,6 +196,10 @@ # endif #endif +#ifndef FFI_SIZEOF_JAVA_RAW +# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG +#endif + typedef union { ffi_sarg sint; ffi_arg uint; @@ -187,10 +208,25 @@ void* ptr; } ffi_raw; -void ffi_raw_call (/*@dependent@*/ ffi_cif *cif, - void (*fn)(void), - /*@out@*/ void *rvalue, - /*@dependent@*/ ffi_raw *avalue); +#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8 +/* This is a special case for mips64/n32 ABI (and perhaps others) where + sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */ +typedef union { + signed int sint; + unsigned int uint; + float flt; + char data[FFI_SIZEOF_JAVA_RAW]; + void* ptr; +} ffi_java_raw; +#else +typedef ffi_raw ffi_java_raw; +#endif + + +void ffi_raw_call (ffi_cif *cif, + void (*fn)(void), + void *rvalue, + ffi_raw *avalue); void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw); void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args); @@ -200,13 +236,13 @@ /* packing, even on 64-bit machines. I.e. on 64-bit machines */ /* longs and doubles are followed by an empty 64-bit word. */ -void ffi_java_raw_call (/*@dependent@*/ ffi_cif *cif, - void (*fn)(void), - /*@out@*/ void *rvalue, - /*@dependent@*/ ffi_raw *avalue); +void ffi_java_raw_call (ffi_cif *cif, + void (*fn)(void), + void *rvalue, + ffi_java_raw *avalue); -void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw); -void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args); +void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw); +void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args); size_t ffi_java_raw_size (ffi_cif *cif); /* ---- Definitions for closures ----------------------------------------- */ @@ -220,12 +256,22 @@ void *user_data; } ffi_closure __attribute__((aligned (8))); +void *ffi_closure_alloc (size_t size, void **code); +void ffi_closure_free (void *); + ffi_status ffi_prep_closure (ffi_closure*, ffi_cif *, void (*fun)(ffi_cif*,void*,void**,void*), void *user_data); +ffi_status +ffi_prep_closure_loc (ffi_closure*, + ffi_cif *, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + void*codeloc); + typedef struct { char tramp[FFI_TRAMPOLINE_SIZE]; @@ -247,6 +293,27 @@ } ffi_raw_closure; +typedef struct { + char tramp[FFI_TRAMPOLINE_SIZE]; + + ffi_cif *cif; + +#if !FFI_NATIVE_RAW_API + + /* if this is enabled, then a raw closure has the same layout + as a regular closure. We use this to install an intermediate + handler to do the transaltion, void** -> ffi_raw*. */ + + void (*translate_args)(ffi_cif*,void*,void**,void*); + void *this_closure; + +#endif + + void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*); + void *user_data; + +} ffi_java_raw_closure; + ffi_status ffi_prep_raw_closure (ffi_raw_closure*, ffi_cif *cif, @@ -254,28 +321,42 @@ void *user_data); ffi_status -ffi_prep_java_raw_closure (ffi_raw_closure*, +ffi_prep_raw_closure_loc (ffi_raw_closure*, + ffi_cif *cif, + void (*fun)(ffi_cif*,void*,ffi_raw*,void*), + void *user_data, + void *codeloc); + +ffi_status +ffi_prep_java_raw_closure (ffi_java_raw_closure*, ffi_cif *cif, - void (*fun)(ffi_cif*,void*,ffi_raw*,void*), + void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*), void *user_data); +ffi_status +ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*, + ffi_cif *cif, + void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*), + void *user_data, + void *codeloc); + #endif /* FFI_CLOSURES */ /* ---- Public interface definition -------------------------------------- */ -ffi_status ffi_prep_cif(/*@out@*/ /*@partial@*/ ffi_cif *cif, +ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi, - unsigned int nargs, - /*@dependent@*/ /*@out@*/ /*@partial@*/ ffi_type *rtype, - /*@dependent@*/ ffi_type **atypes); - -void ffi_call(/*@dependent@*/ ffi_cif *cif, - void (*fn)(void), - /*@out@*/ void *rvalue, - /*@dependent@*/ void **avalue); + unsigned int nargs, + ffi_type *rtype, + ffi_type **atypes); + +void ffi_call(ffi_cif *cif, + void (*fn)(void), + void *rvalue, + void **avalue); /* Useful for eliminating compiler warnings */ -#define FFI_FN(f) ((void (*)())f) +#define FFI_FN(f) ((void (*)(void))f) /* ---- Definitions shared with assembly code ---------------------------- */ @@ -310,4 +391,3 @@ #endif #endif - Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/include/ffi_common.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/include/ffi_common.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/include/ffi_common.h Wed Apr 30 15:57:13 2008 @@ -1,5 +1,6 @@ /* ----------------------------------------------------------------------- ffi_common.h - Copyright (c) 1996 Red Hat, Inc. + Copyright (C) 2007 Free Software Foundation, Inc Common internal definitions and macros. Only necessary for building libffi. @@ -18,7 +19,9 @@ this is positioned. */ #ifdef __GNUC__ # define alloca __builtin_alloca +# define MAYBE_UNUSED __attribute__((__unused__)) #else +# define MAYBE_UNUSED # if HAVE_ALLOCA_H # include # else @@ -41,20 +44,20 @@ # endif #endif -#if defined(FFI_DEBUG) +#if defined(FFI_DEBUG) #include #endif #ifdef FFI_DEBUG -/*@exits@*/ void ffi_assert(/*@temp@*/ char *expr, /*@temp@*/ char *file, int line); +void ffi_assert(char *expr, char *file, int line); void ffi_stop_here(void); -void ffi_type_test(/*@temp@*/ /*@out@*/ ffi_type *a, /*@temp@*/ char *file, int line); +void ffi_type_test(ffi_type *a, char *file, int line); #define FFI_ASSERT(x) ((x) ? (void)0 : ffi_assert(#x, __FILE__,__LINE__)) #define FFI_ASSERT_AT(x, f, l) ((x) ? 0 : ffi_assert(#x, (f), (l))) #define FFI_ASSERT_VALID_TYPE(x) ffi_type_test (x, __FILE__, __LINE__) #else -#define FFI_ASSERT(x) +#define FFI_ASSERT(x) #define FFI_ASSERT_AT(x, f, l) #define FFI_ASSERT_VALID_TYPE(x) #endif @@ -68,9 +71,9 @@ /* Extended cif, used in callback from assembly routine */ typedef struct { - /*@dependent@*/ ffi_cif *cif; - /*@dependent@*/ void *rvalue; - /*@dependent@*/ void **avalue; + ffi_cif *cif; + void *rvalue; + void **avalue; } extended_cif; /* Terse sized type definitions. */ Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/install-sh ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/install-sh (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/install-sh Wed Apr 30 15:57:13 2008 @@ -1,7 +1,8 @@ #!/bin/sh -# # install - install a program, script, or datafile -# + +scriptversion=2004-12-17.09 + # This originates from X11R5 (mit/util/scripts/install.sh), which was # later released in X11R6 (xc/config/util/install.sh) with the # following copyright and license. @@ -41,13 +42,11 @@ # from scratch. It can only install one file at a time, a restriction # shared with many OS's install programs. - # set DOITPROG to echo to test this script # Don't use :- since 4.3BSD and earlier shells don't like it. doit="${DOITPROG-}" - # put in absolute paths if you don't have them in your path; or use env. vars. mvprog="${MVPROG-mv}" @@ -59,236 +58,266 @@ rmprog="${RMPROG-rm}" mkdirprog="${MKDIRPROG-mkdir}" -transformbasename="" -transform_arg="" -instcmd="$mvprog" chmodcmd="$chmodprog 0755" -chowncmd="" -chgrpcmd="" -stripcmd="" +chowncmd= +chgrpcmd= +stripcmd= rmcmd="$rmprog -f" mvcmd="$mvprog" -src="" -dst="" -dir_arg="" - -while [ x"$1" != x ]; do - case $1 in - -c) instcmd=$cpprog - shift - continue;; - - -d) dir_arg=true - shift - continue;; - - -m) chmodcmd="$chmodprog $2" - shift - shift - continue;; - - -o) chowncmd="$chownprog $2" - shift - shift - continue;; - - -g) chgrpcmd="$chgrpprog $2" - shift - shift - continue;; - - -s) stripcmd=$stripprog - shift - continue;; - - -t=*) transformarg=`echo $1 | sed 's/-t=//'` - shift - continue;; - - -b=*) transformbasename=`echo $1 | sed 's/-b=//'` - shift - continue;; - - *) if [ x"$src" = x ] - then - src=$1 - else - # this colon is to work around a 386BSD /bin/sh bug - : - dst=$1 - fi - shift - continue;; - esac -done - -if [ x"$src" = x ] -then - echo "$0: no input file specified" >&2 - exit 1 -else - : -fi +src= +dst= +dir_arg= +dstarg= +no_target_directory= + +usage="Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE + or: $0 [OPTION]... SRCFILES... DIRECTORY + or: $0 [OPTION]... -t DIRECTORY SRCFILES... + or: $0 [OPTION]... -d DIRECTORIES... + +In the 1st form, copy SRCFILE to DSTFILE. +In the 2nd and 3rd, copy all SRCFILES to DIRECTORY. +In the 4th, create DIRECTORIES. + +Options: +-c (ignored) +-d create directories instead of installing files. +-g GROUP $chgrpprog installed files to GROUP. +-m MODE $chmodprog installed files to MODE. +-o USER $chownprog installed files to USER. +-s $stripprog installed files. +-t DIRECTORY install into DIRECTORY. +-T report an error if DSTFILE is a directory. +--help display this help and exit. +--version display version info and exit. + +Environment variables override the default commands: + CHGRPPROG CHMODPROG CHOWNPROG CPPROG MKDIRPROG MVPROG RMPROG STRIPPROG +" + +while test -n "$1"; do + case $1 in + -c) shift + continue;; + + -d) dir_arg=true + shift + continue;; + + -g) chgrpcmd="$chgrpprog $2" + shift + shift + continue;; + + --help) echo "$usage"; exit 0;; + + -m) chmodcmd="$chmodprog $2" + shift + shift + continue;; + + -o) chowncmd="$chownprog $2" + shift + shift + continue;; + + -s) stripcmd=$stripprog + shift + continue;; -if [ x"$dir_arg" != x ]; then - dst=$src - src="" - - if [ -d "$dst" ]; then - instcmd=: - chmodcmd="" - else - instcmd=$mkdirprog - fi -else - -# Waiting for this to be detected by the "$instcmd $src $dsttmp" command -# might cause directories to be created, which would be especially bad -# if $src (and thus $dsttmp) contains '*'. - - if [ -f "$src" ] || [ -d "$src" ] - then - : - else - echo "$0: $src does not exist" >&2 - exit 1 - fi - - if [ x"$dst" = x ] - then - echo "$0: no destination specified" >&2 - exit 1 - else - : - fi - -# If destination is a directory, append the input filename; if your system -# does not like double slashes in filenames, you may need to add some logic - - if [ -d "$dst" ] - then - dst=$dst/`basename "$src"` - else - : - fi -fi - -## this sed command emulates the dirname command -dstdir=`echo "$dst" | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'` - -# Make sure that the destination directory exists. -# this part is taken from Noah Friedman's mkinstalldirs script - -# Skip lots of stat calls in the usual case. -if [ ! -d "$dstdir" ]; then -defaultIFS=' - ' -IFS="${IFS-$defaultIFS}" - -oIFS=$IFS -# Some sh's can't handle IFS=/ for some reason. -IFS='%' -set - `echo "$dstdir" | sed -e 's@/@%@g' -e 's@^%@/@'` -IFS=$oIFS - -pathcomp='' + -t) dstarg=$2 + shift + shift + continue;; -while [ $# -ne 0 ] ; do - pathcomp=$pathcomp$1 + -T) no_target_directory=true shift + continue;; - if [ ! -d "$pathcomp" ] ; - then - $mkdirprog "$pathcomp" - else - : - fi + --version) echo "$0 $scriptversion"; exit 0;; - pathcomp=$pathcomp/ + *) # When -d is used, all remaining arguments are directories to create. + # When -t is used, the destination is already specified. + test -n "$dir_arg$dstarg" && break + # Otherwise, the last argument is the destination. Remove it from $@. + for arg + do + if test -n "$dstarg"; then + # $@ is not empty: it contains at least $arg. + set fnord "$@" "$dstarg" + shift # fnord + fi + shift # arg + dstarg=$arg + done + break;; + esac done -fi - -if [ x"$dir_arg" != x ] -then - $doit $instcmd "$dst" && - - if [ x"$chowncmd" != x ]; then $doit $chowncmd "$dst"; else : ; fi && - if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd "$dst"; else : ; fi && - if [ x"$stripcmd" != x ]; then $doit $stripcmd "$dst"; else : ; fi && - if [ x"$chmodcmd" != x ]; then $doit $chmodcmd "$dst"; else : ; fi -else - -# If we're going to rename the final executable, determine the name now. - if [ x"$transformarg" = x ] - then - dstfile=`basename "$dst"` - else - dstfile=`basename "$dst" $transformbasename | - sed $transformarg`$transformbasename - fi - -# don't allow the sed command to completely eliminate the filename - - if [ x"$dstfile" = x ] - then - dstfile=`basename "$dst"` - else - : - fi - -# Make a couple of temp file names in the proper directory. - - dsttmp=$dstdir/#inst.$$# - rmtmp=$dstdir/#rm.$$# - -# Trap to clean up temp files at exit. - - trap 'status=$?; rm -f "$dsttmp" "$rmtmp" && exit $status' 0 - trap '(exit $?); exit' 1 2 13 15 - -# Move or copy the file name to the temp name - - $doit $instcmd "$src" "$dsttmp" && - -# and set any options; do chmod last to preserve setuid bits - -# If any of these fail, we abort the whole thing. If we want to -# ignore errors from any of these, just make sure not to ignore -# errors from the above "$doit $instcmd $src $dsttmp" command. - - if [ x"$chowncmd" != x ]; then $doit $chowncmd "$dsttmp"; else :;fi && - if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd "$dsttmp"; else :;fi && - if [ x"$stripcmd" != x ]; then $doit $stripcmd "$dsttmp"; else :;fi && - if [ x"$chmodcmd" != x ]; then $doit $chmodcmd "$dsttmp"; else :;fi && - -# Now remove or move aside any old file at destination location. We try this -# two ways since rm can't unlink itself on some systems and the destination -# file might be busy for other reasons. In this case, the final cleanup -# might fail but the new file should still install successfully. - -{ - if [ -f "$dstdir/$dstfile" ] - then - $doit $rmcmd -f "$dstdir/$dstfile" 2>/dev/null || - $doit $mvcmd -f "$dstdir/$dstfile" "$rmtmp" 2>/dev/null || - { - echo "$0: cannot unlink or rename $dstdir/$dstfile" >&2 - (exit 1); exit - } - else - : - fi -} && - -# Now rename the file to the real destination. +if test -z "$1"; then + if test -z "$dir_arg"; then + echo "$0: no input file specified." >&2 + exit 1 + fi + # It's OK to call `install-sh -d' without argument. + # This can happen when creating conditional directories. + exit 0 +fi - $doit $mvcmd "$dsttmp" "$dstdir/$dstfile" +for src +do + # Protect names starting with `-'. + case $src in + -*) src=./$src ;; + esac + + if test -n "$dir_arg"; then + dst=$src + src= + + if test -d "$dst"; then + mkdircmd=: + chmodcmd= + else + mkdircmd=$mkdirprog + fi + else + # Waiting for this to be detected by the "$cpprog $src $dsttmp" command + # might cause directories to be created, which would be especially bad + # if $src (and thus $dsttmp) contains '*'. + if test ! -f "$src" && test ! -d "$src"; then + echo "$0: $src does not exist." >&2 + exit 1 + fi + + if test -z "$dstarg"; then + echo "$0: no destination specified." >&2 + exit 1 + fi + + dst=$dstarg + # Protect names starting with `-'. + case $dst in + -*) dst=./$dst ;; + esac -fi && + # If destination is a directory, append the input filename; won't work + # if double slashes aren't ignored. + if test -d "$dst"; then + if test -n "$no_target_directory"; then + echo "$0: $dstarg: Is a directory" >&2 + exit 1 + fi + dst=$dst/`basename "$src"` + fi + fi + + # This sed command emulates the dirname command. + dstdir=`echo "$dst" | sed -e 's,/*$,,;s,[^/]*$,,;s,/*$,,;s,^$,.,'` + + # Make sure that the destination directory exists. + + # Skip lots of stat calls in the usual case. + if test ! -d "$dstdir"; then + defaultIFS=' + ' + IFS="${IFS-$defaultIFS}" + + oIFS=$IFS + # Some sh's can't handle IFS=/ for some reason. + IFS='%' + set x `echo "$dstdir" | sed -e 's@/@%@g' -e 's@^%@/@'` + shift + IFS=$oIFS + + pathcomp= + + while test $# -ne 0 ; do + pathcomp=$pathcomp$1 + shift + if test ! -d "$pathcomp"; then + $mkdirprog "$pathcomp" + # mkdir can fail with a `File exist' error in case several + # install-sh are creating the directory concurrently. This + # is OK. + test -d "$pathcomp" || exit + fi + pathcomp=$pathcomp/ + done + fi + + if test -n "$dir_arg"; then + $doit $mkdircmd "$dst" \ + && { test -z "$chowncmd" || $doit $chowncmd "$dst"; } \ + && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } \ + && { test -z "$stripcmd" || $doit $stripcmd "$dst"; } \ + && { test -z "$chmodcmd" || $doit $chmodcmd "$dst"; } + + else + dstfile=`basename "$dst"` + + # Make a couple of temp file names in the proper directory. + dsttmp=$dstdir/_inst.$$_ + rmtmp=$dstdir/_rm.$$_ + + # Trap to clean up those temp files at exit. + trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0 + trap '(exit $?); exit' 1 2 13 15 + + # Copy the file name to the temp name. + $doit $cpprog "$src" "$dsttmp" && + + # and set any options; do chmod last to preserve setuid bits. + # + # If any of these fail, we abort the whole thing. If we want to + # ignore errors from any of these, just make sure not to ignore + # errors from the above "$doit $cpprog $src $dsttmp" command. + # + { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } \ + && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } \ + && { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } \ + && { test -z "$chmodcmd" || $doit $chmodcmd "$dsttmp"; } && + + # Now rename the file to the real destination. + { $doit $mvcmd -f "$dsttmp" "$dstdir/$dstfile" 2>/dev/null \ + || { + # The rename failed, perhaps because mv can't rename something else + # to itself, or perhaps because mv is so ancient that it does not + # support -f. + + # Now remove or move aside any old file at destination location. + # We try this two ways since rm can't unlink itself on some + # systems and the destination file might be busy for other + # reasons. In this case, the final cleanup might fail but the new + # file should still install successfully. + { + if test -f "$dstdir/$dstfile"; then + $doit $rmcmd -f "$dstdir/$dstfile" 2>/dev/null \ + || $doit $mvcmd -f "$dstdir/$dstfile" "$rmtmp" 2>/dev/null \ + || { + echo "$0: cannot unlink or rename $dstdir/$dstfile" >&2 + (exit 1); exit 1 + } + else + : + fi + } && + + # Now rename the file to the real destination. + $doit $mvcmd "$dsttmp" "$dstdir/$dstfile" + } + } + fi || { (exit 1); exit 1; } +done # The final little trick to "correctly" pass the exit status to the exit trap. - { - (exit 0); exit + (exit 0); exit 0 } + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-end: "$" +# End: Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/alpha/ffi.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/alpha/ffi.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/alpha/ffi.c Wed Apr 30 15:57:13 2008 @@ -1,5 +1,5 @@ /* ----------------------------------------------------------------------- - ffi.c - Copyright (c) 1998, 2001 Red Hat, Inc. + ffi.c - Copyright (c) 1998, 2001, 2007, 2008 Red Hat, Inc. Alpha Foreign Function Interface @@ -14,22 +14,34 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #include #include - #include -extern void ffi_call_osf(void *, unsigned long, unsigned, void *, void (*)(void)); -extern void ffi_closure_osf(void); +/* Force FFI_TYPE_LONGDOUBLE to be different than FFI_TYPE_DOUBLE; + all further uses in this file will refer to the 128-bit type. */ +#if defined(__LONG_DOUBLE_128__) +# if FFI_TYPE_LONGDOUBLE != 4 +# error FFI_TYPE_LONGDOUBLE out of date +# endif +#else +# undef FFI_TYPE_LONGDOUBLE +# define FFI_TYPE_LONGDOUBLE 4 +#endif + +extern void ffi_call_osf(void *, unsigned long, unsigned, void *, void (*)(void)) + FFI_HIDDEN; +extern void ffi_closure_osf(void) FFI_HIDDEN; ffi_status @@ -49,6 +61,11 @@ cif->flags = cif->rtype->type; break; + case FFI_TYPE_LONGDOUBLE: + /* 128-bit long double is returned in memory, like a struct. */ + cif->flags = FFI_TYPE_STRUCT; + break; + default: cif->flags = FFI_TYPE_INT; break; @@ -57,6 +74,7 @@ return FFI_OK; } + void ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) { @@ -64,8 +82,6 @@ long i, avn; ffi_type **arg_types; - FFI_ASSERT (cif->abi == FFI_OSF); - /* If the return value is a struct and we don't have a return value address then we need to make one. */ if (rvalue == NULL && cif->flags == FFI_TYPE_STRUCT) @@ -84,6 +100,8 @@ while (i < avn) { + size_t size = (*arg_types)->size; + switch ((*arg_types)->type) { case FFI_TYPE_SINT8: @@ -129,6 +147,12 @@ *(double *) argp = *(double *)(* avalue); break; + case FFI_TYPE_LONGDOUBLE: + /* 128-bit long double is passed by reference. */ + *(long double **) argp = (long double *)(* avalue); + size = sizeof (long double *); + break; + case FFI_TYPE_STRUCT: memcpy(argp, *avalue, (*arg_types)->size); break; @@ -137,7 +161,7 @@ FFI_ASSERT(0); } - argp += ALIGN((*arg_types)->size, FFI_SIZEOF_ARG) / FFI_SIZEOF_ARG; + argp += ALIGN(size, FFI_SIZEOF_ARG) / FFI_SIZEOF_ARG; i++, arg_types++, avalue++; } @@ -146,15 +170,14 @@ ffi_status -ffi_prep_closure (ffi_closure* closure, - ffi_cif* cif, - void (*fun)(ffi_cif*, void*, void**, void*), - void *user_data) +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + void *codeloc) { unsigned int *tramp; - FFI_ASSERT (cif->abi == FFI_OSF); - tramp = (unsigned int *) &closure->tramp[0]; tramp[0] = 0x47fb0401; /* mov $27,$1 */ tramp[1] = 0xa77b0010; /* ldq $27,16($27) */ @@ -177,7 +200,8 @@ return FFI_OK; } -int + +long FFI_HIDDEN ffi_closure_osf_inner(ffi_closure *closure, void *rvalue, unsigned long *argp) { ffi_cif *cif; @@ -205,6 +229,8 @@ /* Grab the addresses of the arguments from the stack frame. */ while (i < avn) { + size_t size = arg_types[i]->size; + switch (arg_types[i]->type) { case FFI_TYPE_SINT8: @@ -236,16 +262,22 @@ avalue[i] = &argp[argn - (argn < 6 ? 6 : 0)]; break; + case FFI_TYPE_LONGDOUBLE: + /* 128-bit long double is passed by reference. */ + avalue[i] = (long double *) argp[argn]; + size = sizeof (long double *); + break; + default: - FFI_ASSERT(0); + abort (); } - argn += ALIGN(arg_types[i]->size, FFI_SIZEOF_ARG) / FFI_SIZEOF_ARG; + argn += ALIGN(size, FFI_SIZEOF_ARG) / FFI_SIZEOF_ARG; i++; } /* Invoke the closure. */ - (closure->fun) (cif, rvalue, avalue, closure->user_data); + closure->fun (cif, rvalue, avalue, closure->user_data); /* Tell ffi_closure_osf how to perform return type promotions. */ return cif->rtype->type; Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/alpha/ffitarget.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/alpha/ffitarget.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/alpha/ffitarget.h Wed Apr 30 15:57:13 2008 @@ -13,13 +13,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ @@ -33,8 +34,8 @@ typedef enum ffi_abi { FFI_FIRST_ABI = 0, FFI_OSF, - FFI_DEFAULT_ABI = FFI_OSF, - FFI_LAST_ABI = FFI_DEFAULT_ABI + 1 + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_OSF } ffi_abi; #endif @@ -45,4 +46,3 @@ #define FFI_NATIVE_RAW_API 0 #endif - Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/alpha/osf.S ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/alpha/osf.S (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/alpha/osf.S Wed Apr 30 15:57:13 2008 @@ -1,10 +1,8 @@ /* ----------------------------------------------------------------------- - osf.S - Copyright (c) 1998, 2001 Red Hat + osf.S - Copyright (c) 1998, 2001, 2007, 2008 Red Hat Alpha/OSF Foreign Function Interface - $Id: osf.S,v 1.2 2006/03/03 20:24:26 theller Exp $ - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ``Software''), to deal in the Software without restriction, including @@ -16,13 +14,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #define LIBFFI_ASM @@ -33,7 +32,7 @@ .text /* ffi_call_osf (void *args, unsigned long bytes, unsigned flags, - void *raddr, void (*fnaddr)()); + void *raddr, void (*fnaddr)(void)); Bit o trickiness here -- ARGS+BYTES is the base of the stack frame for this function. This has been allocated by ffi_call. We also @@ -42,6 +41,8 @@ .align 3 .globl ffi_call_osf .ent ffi_call_osf + FFI_HIDDEN(ffi_call_osf) + ffi_call_osf: .frame $15, 32, $26, 0 .mask 0x4008000, -32 @@ -129,6 +130,8 @@ .align 3 .globl ffi_closure_osf .ent ffi_closure_osf + FFI_HIDDEN(ffi_closure_osf) + ffi_closure_osf: .frame $30, 16*8, $26, 0 .mask 0x4000000, -16*8 @@ -265,7 +268,7 @@ .gprel32 $load_32 # FFI_TYPE_INT .gprel32 $load_float # FFI_TYPE_FLOAT .gprel32 $load_double # FFI_TYPE_DOUBLE - .gprel32 $load_double # FFI_TYPE_LONGDOUBLE + .gprel32 $load_none # FFI_TYPE_LONGDOUBLE .gprel32 $load_u8 # FFI_TYPE_UINT8 .gprel32 $load_s8 # FFI_TYPE_SINT8 .gprel32 $load_u16 # FFI_TYPE_UINT16 @@ -356,4 +359,8 @@ .byte 16 # uleb128 offset 16*-8 .align 3 $LEFDE3: + +#ifdef __linux__ + .section .note.GNU-stack,"", at progbits +#endif #endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/arm/ffi.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/arm/ffi.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/arm/ffi.c Wed Apr 30 15:57:13 2008 @@ -1,5 +1,5 @@ /* ----------------------------------------------------------------------- - ffi.c - Copyright (c) 1998 Red Hat, Inc. + ffi.c - Copyright (c) 1998, 2008 Red Hat, Inc. ARM Foreign Function Interface @@ -14,13 +14,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #include @@ -31,9 +32,7 @@ /* ffi_prep_args is called by the assembly routine once stack space has been allocated for the function's arguments */ -/*@-exportheader@*/ void ffi_prep_args(char *stack, extended_cif *ecif) -/*@=exportheader@*/ { register unsigned int i; register void **p_argv; @@ -42,7 +41,7 @@ argp = stack; - if ( ecif->cif->rtype->type == FFI_TYPE_STRUCT ) { + if ( ecif->cif->flags == FFI_TYPE_STRUCT ) { *(void **) argp = ecif->rvalue; argp += 4; } @@ -60,6 +59,9 @@ argp = (char *) ALIGN(argp, (*p_arg)->alignment); } + if ((*p_arg)->type == FFI_TYPE_STRUCT) + argp = (char *) ALIGN(argp, 4); + z = (*p_arg)->size; if (z < sizeof(int)) { @@ -83,7 +85,7 @@ break; case FFI_TYPE_STRUCT: - *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); + memcpy(argp, *p_argv, (*p_arg)->size); break; default: @@ -117,7 +119,6 @@ switch (cif->rtype->type) { case FFI_TYPE_VOID: - case FFI_TYPE_STRUCT: case FFI_TYPE_FLOAT: case FFI_TYPE_DOUBLE: cif->flags = (unsigned) cif->rtype->type; @@ -128,6 +129,17 @@ cif->flags = (unsigned) FFI_TYPE_SINT64; break; + case FFI_TYPE_STRUCT: + if (cif->rtype->size <= 4) + /* A Composite Type not larger than 4 bytes is returned in r0. */ + cif->flags = (unsigned)FFI_TYPE_INT; + else + /* A Composite Type larger than 4 bytes, or whose size cannot + be determined statically ... is stored in memory at an + address passed [in r0]. */ + cif->flags = (unsigned)FFI_TYPE_STRUCT; + break; + default: cif->flags = FFI_TYPE_INT; break; @@ -136,50 +148,162 @@ return FFI_OK; } -/*@-declundef@*/ -/*@-exportheader@*/ -extern void ffi_call_SYSV(void (*)(char *, extended_cif *), - /*@out@*/ extended_cif *, - unsigned, unsigned, - /*@out@*/ unsigned *, - void (*fn)()); -/*@=declundef@*/ -/*@=exportheader@*/ +extern void ffi_call_SYSV(void (*)(char *, extended_cif *), extended_cif *, + unsigned, unsigned, unsigned *, void (*fn)(void)); -void ffi_call(/*@dependent@*/ ffi_cif *cif, - void (*fn)(), - /*@out@*/ void *rvalue, - /*@dependent@*/ void **avalue) +void ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) { extended_cif ecif; + int small_struct = (cif->flags == FFI_TYPE_INT + && cif->rtype->type == FFI_TYPE_STRUCT); + ecif.cif = cif; ecif.avalue = avalue; + + unsigned int temp; /* If the return value is a struct and we don't have a return */ /* value address then we need to make one */ if ((rvalue == NULL) && - (cif->rtype->type == FFI_TYPE_STRUCT)) + (cif->flags == FFI_TYPE_STRUCT)) { - /*@-sysunrecog@*/ ecif.rvalue = alloca(cif->rtype->size); - /*@=sysunrecog@*/ } + else if (small_struct) + ecif.rvalue = &temp; else ecif.rvalue = rvalue; - - + switch (cif->abi) { case FFI_SYSV: - /*@-usedef@*/ - ffi_call_SYSV(ffi_prep_args, &ecif, cif->bytes, - cif->flags, ecif.rvalue, fn); - /*@=usedef@*/ + ffi_call_SYSV(ffi_prep_args, &ecif, cif->bytes, cif->flags, ecif.rvalue, + fn); + break; default: FFI_ASSERT(0); break; } + if (small_struct) + memcpy (rvalue, &temp, cif->rtype->size); +} + +/** private members **/ + +static void ffi_prep_incoming_args_SYSV (char *stack, void **ret, + void** args, ffi_cif* cif); + +void ffi_closure_SYSV (ffi_closure *); + +/* This function is jumped to by the trampoline */ + +unsigned int +ffi_closure_SYSV_inner (closure, respp, args) + ffi_closure *closure; + void **respp; + void *args; +{ + // our various things... + ffi_cif *cif; + void **arg_area; + + cif = closure->cif; + arg_area = (void**) alloca (cif->nargs * sizeof (void*)); + + /* this call will initialize ARG_AREA, such that each + * element in that array points to the corresponding + * value on the stack; and if the function returns + * a structure, it will re-set RESP to point to the + * structure return address. */ + + ffi_prep_incoming_args_SYSV(args, respp, arg_area, cif); + + (closure->fun) (cif, *respp, arg_area, closure->user_data); + + return cif->flags; +} + +/*@-exportheader@*/ +static void +ffi_prep_incoming_args_SYSV(char *stack, void **rvalue, + void **avalue, ffi_cif *cif) +/*@=exportheader@*/ +{ + register unsigned int i; + register void **p_argv; + register char *argp; + register ffi_type **p_arg; + + argp = stack; + + if ( cif->flags == FFI_TYPE_STRUCT ) { + *rvalue = *(void **) argp; + argp += 4; + } + + p_argv = avalue; + + for (i = cif->nargs, p_arg = cif->arg_types; (i != 0); i--, p_arg++) + { + size_t z; + + size_t alignment = (*p_arg)->alignment; + if (alignment < 4) + alignment = 4; + /* Align if necessary */ + if ((alignment - 1) & (unsigned) argp) { + argp = (char *) ALIGN(argp, alignment); + } + + z = (*p_arg)->size; + + /* because we're little endian, this is what it turns into. */ + + *p_argv = (void*) argp; + + p_argv++; + argp += z; + } + + return; +} + +/* How to make a trampoline. */ + +#define FFI_INIT_TRAMPOLINE(TRAMP,FUN,CTX) \ +({ unsigned char *__tramp = (unsigned char*)(TRAMP); \ + unsigned int __fun = (unsigned int)(FUN); \ + unsigned int __ctx = (unsigned int)(CTX); \ + *(unsigned int*) &__tramp[0] = 0xe92d000f; /* stmfd sp!, {r0-r3} */ \ + *(unsigned int*) &__tramp[4] = 0xe59f0000; /* ldr r0, [pc] */ \ + *(unsigned int*) &__tramp[8] = 0xe59ff000; /* ldr pc, [pc] */ \ + *(unsigned int*) &__tramp[12] = __ctx; \ + *(unsigned int*) &__tramp[16] = __fun; \ + __clear_cache((&__tramp[0]), (&__tramp[19])); \ + }) + + +/* the cif must already be prep'ed */ + +ffi_status +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + void *codeloc) +{ + FFI_ASSERT (cif->abi == FFI_SYSV); + + FFI_INIT_TRAMPOLINE (&closure->tramp[0], \ + &ffi_closure_SYSV, \ + codeloc); + + closure->cif = cif; + closure->user_data = user_data; + closure->fun = fun; + + return FFI_OK; } Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/arm/ffitarget.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/arm/ffitarget.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/arm/ffitarget.h Wed Apr 30 15:57:13 2008 @@ -13,13 +13,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ @@ -40,7 +41,8 @@ /* ---- Definitions for closures ----------------------------------------- */ -#define FFI_CLOSURES 0 +#define FFI_CLOSURES 1 +#define FFI_TRAMPOLINE_SIZE 20 #define FFI_NATIVE_RAW_API 0 #endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/arm/sysv.S ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/arm/sysv.S (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/arm/sysv.S Wed Apr 30 15:57:13 2008 @@ -1,5 +1,5 @@ /* ----------------------------------------------------------------------- - sysv.S - Copyright (c) 1998 Red Hat, Inc. + sysv.S - Copyright (c) 1998, 2008 Red Hat, Inc. ARM Foreign Function Interface @@ -14,13 +14,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #define LIBFFI_ASM @@ -82,6 +83,14 @@ # define call_reg(x) mov lr, pc ; mov pc, x #endif +/* Conditionally compile unwinder directives. */ +#ifdef __ARM_EABI__ +#define UNWIND +#else +#define UNWIND @ +#endif + + #if defined(__thumb__) && !defined(__THUMB_INTERWORK__) .macro ARM_FUNC_START name .text @@ -92,6 +101,7 @@ bx pc nop .arm + UNWIND .fnstart /* A hook to tell gdb that we've switched to ARM mode. Also used to call directly from other local arm routines. */ _L__\name: @@ -102,6 +112,7 @@ .align 0 .arm ENTRY(\name) + UNWIND .fnstart .endm #endif @@ -134,8 +145,11 @@ ARM_FUNC_START ffi_call_SYSV @ Save registers stmfd sp!, {r0-r3, fp, lr} + UNWIND .save {r0-r3, fp, lr} mov fp, sp + UNWIND .setfp fp, sp + @ Make room for all of the new args. sub sp, fp, r2 @@ -205,5 +219,81 @@ RETLDM "r0-r3,fp" .ffi_call_SYSV_end: + UNWIND .fnend .size CNAME(ffi_call_SYSV),.ffi_call_SYSV_end-CNAME(ffi_call_SYSV) +/* + unsigned int FFI_HIDDEN + ffi_closure_SYSV_inner (closure, respp, args) + ffi_closure *closure; + void **respp; + void *args; +*/ + +ARM_FUNC_START ffi_closure_SYSV + UNWIND .pad #16 + add ip, sp, #16 + stmfd sp!, {ip, lr} + UNWIND .save {r0, lr} + add r2, sp, #8 + .pad #16 + sub sp, sp, #16 + str sp, [sp, #8] + add r1, sp, #8 + bl ffi_closure_SYSV_inner + cmp r0, #FFI_TYPE_INT + beq .Lretint + + cmp r0, #FFI_TYPE_FLOAT +#ifdef __SOFTFP__ + beq .Lretint +#else + beq .Lretfloat +#endif + + cmp r0, #FFI_TYPE_DOUBLE +#ifdef __SOFTFP__ + beq .Lretlonglong +#else + beq .Lretdouble +#endif + + cmp r0, #FFI_TYPE_LONGDOUBLE +#ifdef __SOFTFP__ + beq .Lretlonglong +#else + beq .Lretlongdouble +#endif + + cmp r0, #FFI_TYPE_SINT64 + beq .Lretlonglong +.Lclosure_epilogue: + add sp, sp, #16 + ldmfd sp, {sp, pc} +.Lretint: + ldr r0, [sp] + b .Lclosure_epilogue +.Lretlonglong: + ldr r0, [sp] + ldr r1, [sp, #4] + b .Lclosure_epilogue + +#ifndef __SOFTFP__ +.Lretfloat: + ldfs f0, [sp] + b .Lclosure_epilogue +.Lretdouble: + ldfd f0, [sp] + b .Lclosure_epilogue +.Lretlongdouble: + ldfd f0, [sp] + b .Lclosure_epilogue +#endif + +.ffi_closure_SYSV_end: + UNWIND .fnend + .size CNAME(ffi_closure_SYSV),.ffi_closure_SYSV_end-CNAME(ffi_closure_SYSV) + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"",%progbits +#endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/cris/ffi.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/cris/ffi.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/cris/ffi.c Wed Apr 30 15:57:13 2008 @@ -2,6 +2,7 @@ ffi.c - Copyright (c) 1998 Cygnus Solutions Copyright (c) 2004 Simon Posnjak Copyright (c) 2005 Axis Communications AB + Copyright (C) 2007 Free Software Foundation, Inc. CRIS Foreign Function Interface @@ -360,10 +361,11 @@ /* API function: Prepare the trampoline. */ ffi_status -ffi_prep_closure (ffi_closure* closure, - ffi_cif* cif, - void (*fun)(ffi_cif *, void *, void **, void*), - void *user_data) +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif *, void *, void **, void*), + void *user_data, + void *codeloc) { void *innerfn = ffi_prep_closure_inner; FFI_ASSERT (cif->abi == FFI_SYSV); @@ -375,7 +377,7 @@ memcpy (closure->tramp + ffi_cris_trampoline_fn_offset, &innerfn, sizeof (void *)); memcpy (closure->tramp + ffi_cris_trampoline_closure_offset, - &closure, sizeof (void *)); + &codeloc, sizeof (void *)); return FFI_OK; } Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/cris/ffitarget.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/cris/ffitarget.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/cris/ffitarget.h Wed Apr 30 15:57:13 2008 @@ -13,13 +13,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/frv/eabi.S ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/frv/eabi.S (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/frv/eabi.S Wed Apr 30 15:57:13 2008 @@ -3,8 +3,6 @@ FR-V Assembly glue. - $Id: eabi.S,v 1.2 2006/03/03 20:24:46 theller Exp $ - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ``Software''), to deal in the Software without restriction, including Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/frv/ffi.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/frv/ffi.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/frv/ffi.c Wed Apr 30 15:57:13 2008 @@ -1,5 +1,7 @@ /* ----------------------------------------------------------------------- - ffi.c - Copyright (c) 2004 Anthony Green + ffi.c - Copyright (C) 2004 Anthony Green + Copyright (C) 2007 Free Software Foundation, Inc. + Copyright (C) 2008 Red Hat, Inc. FR-V Foreign Function Interface @@ -14,13 +16,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #include @@ -124,10 +127,10 @@ extended_cif *, unsigned, unsigned, unsigned *, - void (*fn)()); + void (*fn)(void)); void ffi_call(ffi_cif *cif, - void (*fn)(), + void (*fn)(void), void *rvalue, void **avalue) { @@ -243,14 +246,15 @@ } ffi_status -ffi_prep_closure (ffi_closure* closure, - ffi_cif* cif, - void (*fun)(ffi_cif*, void*, void**, void*), - void *user_data) +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + void *codeloc) { unsigned int *tramp = (unsigned int *) &closure->tramp[0]; unsigned long fn = (long) ffi_closure_eabi; - unsigned long cls = (long) closure; + unsigned long cls = (long) codeloc; #ifdef __FRV_FDPIC__ register void *got __asm__("gr15"); #endif @@ -259,7 +263,7 @@ fn = (unsigned long) ffi_closure_eabi; #ifdef __FRV_FDPIC__ - tramp[0] = &tramp[2]; + tramp[0] = &((unsigned int *)codeloc)[2]; tramp[1] = got; tramp[2] = 0x8cfc0000 + (fn & 0xffff); /* setlos lo(fn), gr6 */ tramp[3] = 0x8efc0000 + (cls & 0xffff); /* setlos lo(cls), gr7 */ @@ -281,7 +285,8 @@ /* Cache flushing. */ for (i = 0; i < FFI_TRAMPOLINE_SIZE; i++) - __asm__ volatile ("dcf @(%0,%1)\n\tici @(%0,%1)" :: "r" (tramp), "r" (i)); + __asm__ volatile ("dcf @(%0,%1)\n\tici @(%2,%1)" :: "r" (tramp), "r" (i), + "r" (codeloc)); return FFI_OK; } Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/frv/ffitarget.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/frv/ffitarget.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/frv/ffitarget.h Wed Apr 30 15:57:13 2008 @@ -13,13 +13,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/ia64/ffi.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/ia64/ffi.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/ia64/ffi.c Wed Apr 30 15:57:13 2008 @@ -1,5 +1,5 @@ /* ----------------------------------------------------------------------- - ffi.c - Copyright (c) 1998 Red Hat, Inc. + ffi.c - Copyright (c) 1998, 2007, 2008 Red Hat, Inc. Copyright (c) 2000 Hewlett Packard Company IA64 Foreign Function Interface @@ -15,13 +15,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #include @@ -69,24 +70,19 @@ #endif } -/* Store VALUE to ADDR in the current cpu implementation's fp spill format. */ +/* Store VALUE to ADDR in the current cpu implementation's fp spill format. + This is a macro instead of a function, so that it works for all 3 floating + point types without type conversions. Type conversion to long double breaks + the denorm support. */ -static inline void -stf_spill(fpreg *addr, __float80 value) -{ +#define stf_spill(addr, value) \ asm ("stf.spill %0 = %1%P0" : "=m" (*addr) : "f"(value)); -} /* Load a value from ADDR, which is in the current cpu implementation's - fp spill format. */ + fp spill format. As above, this must also be a macro. */ -static inline __float80 -ldf_fill(fpreg *addr) -{ - __float80 ret; - asm ("ldf.fill %0 = %1%P1" : "=f"(ret) : "m"(*addr)); - return ret; -} +#define ldf_fill(result, addr) \ + asm ("ldf.fill %0 = %1%P1" : "=f"(result) : "m"(*addr)); /* Return the size of the C type associated with with TYPE. Which will be one of the FFI_IA64_TYPE_HFA_* values. */ @@ -110,17 +106,20 @@ /* Load from ADDR a value indicated by TYPE. Which will be one of the FFI_IA64_TYPE_HFA_* values. */ -static __float80 -hfa_type_load (int type, void *addr) +static void +hfa_type_load (fpreg *fpaddr, int type, void *addr) { switch (type) { case FFI_IA64_TYPE_HFA_FLOAT: - return *(float *) addr; + stf_spill (fpaddr, *(float *) addr); + return; case FFI_IA64_TYPE_HFA_DOUBLE: - return *(double *) addr; + stf_spill (fpaddr, *(double *) addr); + return; case FFI_IA64_TYPE_HFA_LDOUBLE: - return *(__float80 *) addr; + stf_spill (fpaddr, *(__float80 *) addr); + return; default: abort (); } @@ -130,19 +129,31 @@ the FFI_IA64_TYPE_HFA_* values. */ static void -hfa_type_store (int type, void *addr, __float80 value) +hfa_type_store (int type, void *addr, fpreg *fpaddr) { switch (type) { case FFI_IA64_TYPE_HFA_FLOAT: - *(float *) addr = value; - break; + { + float result; + ldf_fill (result, fpaddr); + *(float *) addr = result; + break; + } case FFI_IA64_TYPE_HFA_DOUBLE: - *(double *) addr = value; - break; + { + double result; + ldf_fill (result, fpaddr); + *(double *) addr = result; + break; + } case FFI_IA64_TYPE_HFA_LDOUBLE: - *(__float80 *) addr = value; - break; + { + __float80 result; + ldf_fill (result, fpaddr); + *(__float80 *) addr = result; + break; + } default: abort (); } @@ -351,8 +362,8 @@ && offset < size && gp_offset < 8 * 8) { - stf_spill (&stack->fp_regs[fpcount], - hfa_type_load (hfa_type, avalue[i] + offset)); + hfa_type_load (&stack->fp_regs[fpcount], hfa_type, + avalue[i] + offset); offset += hfa_size; gp_offset += hfa_size; fpcount += 1; @@ -387,13 +398,14 @@ gp pointer to the closure. This allows the function entry code to both retrieve the user data, and to restire the correct gp pointer. */ -extern void ffi_closure_unix (void); +extern void ffi_closure_unix (); ffi_status -ffi_prep_closure (ffi_closure* closure, - ffi_cif* cif, - void (*fun)(ffi_cif*,void*,void**,void*), - void *user_data) +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + void *codeloc) { /* The layout of a function descriptor. A C function pointer really points to one of these. */ @@ -420,7 +432,7 @@ tramp->code_pointer = fd->code_pointer; tramp->real_gp = fd->gp; - tramp->fake_gp = (UINT64)(PTR64)closure; + tramp->fake_gp = (UINT64)(PTR64)codeloc; closure->cif = cif; closure->user_data = user_data; closure->fun = fun; @@ -475,9 +487,11 @@ case FFI_TYPE_FLOAT: if (gpcount < 8 && fpcount < 8) { - void *addr = &stack->fp_regs[fpcount++]; + fpreg *addr = &stack->fp_regs[fpcount++]; + float result; avalue[i] = addr; - *(float *)addr = ldf_fill (addr); + ldf_fill (result, addr); + *(float *)addr = result; } else avalue[i] = endian_adjust(&stack->gp_regs[gpcount], 4); @@ -487,9 +501,11 @@ case FFI_TYPE_DOUBLE: if (gpcount < 8 && fpcount < 8) { - void *addr = &stack->fp_regs[fpcount++]; + fpreg *addr = &stack->fp_regs[fpcount++]; + double result; avalue[i] = addr; - *(double *)addr = ldf_fill (addr); + ldf_fill (result, addr); + *(double *)addr = result; } else avalue[i] = &stack->gp_regs[gpcount]; @@ -501,9 +517,11 @@ gpcount++; if (LDBL_MANT_DIG == 64 && gpcount < 8 && fpcount < 8) { - void *addr = &stack->fp_regs[fpcount++]; + fpreg *addr = &stack->fp_regs[fpcount++]; + __float80 result; avalue[i] = addr; - *(__float80 *)addr = ldf_fill (addr); + ldf_fill (result, addr); + *(__float80 *)addr = result; } else avalue[i] = &stack->gp_regs[gpcount]; @@ -533,8 +551,8 @@ && offset < size && gp_offset < 8 * 8) { - hfa_type_store (hfa_type, addr + offset, - ldf_fill (&stack->fp_regs[fpcount])); + hfa_type_store (hfa_type, addr + offset, + &stack->fp_regs[fpcount]); offset += hfa_size; gp_offset += hfa_size; fpcount += 1; Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/ia64/ffitarget.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/ia64/ffitarget.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/ia64/ffitarget.h Wed Apr 30 15:57:13 2008 @@ -13,13 +13,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/ia64/ia64_flags.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/ia64/ia64_flags.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/ia64/ia64_flags.h Wed Apr 30 15:57:13 2008 @@ -16,13 +16,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ /* "Type" codes used between assembly and C. When used as a part of Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/ia64/unix.S ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/ia64/unix.S (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/ia64/unix.S Wed Apr 30 15:57:13 2008 @@ -1,5 +1,5 @@ /* ----------------------------------------------------------------------- - unix.S - Copyright (c) 1998 Red Hat, Inc. + unix.S - Copyright (c) 1998, 2008 Red Hat, Inc. Copyright (c) 2000 Hewlett Packard Company IA64/unix Foreign Function Interface @@ -19,13 +19,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #define LIBFFI_ASM @@ -37,7 +38,7 @@ .text /* int ffi_call_unix (struct ia64_args *stack, PTR64 rvalue, - void (*fn)(), int flags); + void (*fn)(void), int flags); */ .align 16 @@ -553,3 +554,7 @@ data8 @pcrel(.Lld_hfa_float) // FFI_IA64_TYPE_HFA_FLOAT data8 @pcrel(.Lld_hfa_double) // FFI_IA64_TYPE_HFA_DOUBLE data8 @pcrel(.Lld_hfa_ldouble) // FFI_IA64_TYPE_HFA_LDOUBLE + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"", at progbits +#endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/m32r/ffi.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/m32r/ffi.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/m32r/ffi.c Wed Apr 30 15:57:13 2008 @@ -1,5 +1,6 @@ /* ----------------------------------------------------------------------- ffi.c - Copyright (c) 2004 Renesas Technology + Copyright (c) 2008 Red Hat, Inc. M32R Foreign Function Interface @@ -31,9 +32,7 @@ /* ffi_prep_args is called by the assembly routine once stack space has been allocated for the function's arguments. */ -/*@-exportheader@*/ void ffi_prep_args(char *stack, extended_cif *ecif) -/*@=exportheader@*/ { unsigned int i; int tmp; @@ -173,20 +172,10 @@ return FFI_OK; } -/*@-declundef@*/ -/*@-exportheader@*/ -extern void ffi_call_SYSV(void (*)(char *, extended_cif *), - /*@out@*/ extended_cif *, - unsigned, unsigned, - /*@out@*/ unsigned *, - void (*fn)()); -/*@=declundef@*/ -/*@=exportheader@*/ - -void ffi_call(/*@dependent@*/ ffi_cif *cif, - void (*fn)(), - /*@out@*/ void *rvalue, - /*@dependent@*/ void **avalue) +extern void ffi_call_SYSV(void (*)(char *, extended_cif *), extended_cif *, + unsigned, unsigned, unsigned *, void (*fn)(void)); + +void ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) { extended_cif ecif; @@ -198,9 +187,7 @@ if ((rvalue == NULL) && (cif->rtype->type == FFI_TYPE_STRUCT)) { - /*@-sysunrecog@*/ ecif.rvalue = alloca (cif->rtype->size); - /*@=sysunrecog@*/ } else ecif.rvalue = rvalue; @@ -208,7 +195,6 @@ switch (cif->abi) { case FFI_SYSV: - /*@-usedef@*/ ffi_call_SYSV(ffi_prep_args, &ecif, cif->bytes, cif->flags, ecif.rvalue, fn); if (cif->rtype->type == FFI_TYPE_STRUCT) @@ -237,7 +223,6 @@ } } } - /*@=usedef@*/ break; default: Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/m68k/ffi.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/m68k/ffi.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/m68k/ffi.c Wed Apr 30 15:57:13 2008 @@ -8,11 +8,23 @@ #include #include +#include +#include +#include + +void ffi_call_SYSV (extended_cif *, + unsigned, unsigned, + void *, void (*fn) ()); +void *ffi_prep_args (void *stack, extended_cif *ecif); +void ffi_closure_SYSV (ffi_closure *); +void ffi_closure_struct_SYSV (ffi_closure *); +unsigned int ffi_closure_SYSV_inner (ffi_closure *closure, + void *resp, void *args); /* ffi_prep_args is called by the assembly routine once stack space has been allocated for the function's arguments. */ -static void * +void * ffi_prep_args (void *stack, extended_cif *ecif) { unsigned int i; @@ -24,7 +36,7 @@ argp = stack; if (ecif->cif->rtype->type == FFI_TYPE_STRUCT - && ecif->cif->rtype->size > 8) + && !ecif->cif->flags) struct_value_ptr = ecif->rvalue; else struct_value_ptr = NULL; @@ -37,44 +49,47 @@ { size_t z; - /* Align if necessary. */ - if (((*p_arg)->alignment - 1) & (unsigned) argp) - argp = (char *) ALIGN (argp, (*p_arg)->alignment); - - z = (*p_arg)->size; - if (z < sizeof (int)) + z = (*p_arg)->size; + if (z < sizeof (int)) + { + switch ((*p_arg)->type) { - switch ((*p_arg)->type) - { - case FFI_TYPE_SINT8: - *(signed int *) argp = (signed int) *(SINT8 *) *p_argv; - break; - - case FFI_TYPE_UINT8: - *(unsigned int *) argp = (unsigned int) *(UINT8 *) *p_argv; - break; - - case FFI_TYPE_SINT16: - *(signed int *) argp = (signed int) *(SINT16 *) *p_argv; - break; - - case FFI_TYPE_UINT16: - *(unsigned int *) argp = (unsigned int) *(UINT16 *) *p_argv; - break; - - case FFI_TYPE_STRUCT: - memcpy (argp + sizeof (int) - z, *p_argv, z); - break; - - default: - FFI_ASSERT (0); - } - z = sizeof (int); + case FFI_TYPE_SINT8: + *(signed int *) argp = (signed int) *(SINT8 *) *p_argv; + break; + + case FFI_TYPE_UINT8: + *(unsigned int *) argp = (unsigned int) *(UINT8 *) *p_argv; + break; + + case FFI_TYPE_SINT16: + *(signed int *) argp = (signed int) *(SINT16 *) *p_argv; + break; + + case FFI_TYPE_UINT16: + *(unsigned int *) argp = (unsigned int) *(UINT16 *) *p_argv; + break; + + case FFI_TYPE_STRUCT: + memcpy (argp + sizeof (int) - z, *p_argv, z); + break; + + default: + FFI_ASSERT (0); } - else - memcpy (argp, *p_argv, z); - p_argv++; - argp += z; + z = sizeof (int); + } + else + { + memcpy (argp, *p_argv, z); + + /* Align if necessary. */ + if ((sizeof(int) - 1) & z) + z = ALIGN(z, sizeof(int)); + } + + p_argv++; + argp += z; } return struct_value_ptr; @@ -86,7 +101,8 @@ #define CIF_FLAGS_DOUBLE 8 #define CIF_FLAGS_LDOUBLE 16 #define CIF_FLAGS_POINTER 32 -#define CIF_FLAGS_STRUCT 64 +#define CIF_FLAGS_STRUCT1 64 +#define CIF_FLAGS_STRUCT2 128 /* Perform machine dependent cif processing */ ffi_status @@ -100,12 +116,24 @@ break; case FFI_TYPE_STRUCT: - if (cif->rtype->size > 4 && cif->rtype->size <= 8) - cif->flags = CIF_FLAGS_DINT; - else if (cif->rtype->size <= 4) - cif->flags = CIF_FLAGS_STRUCT; - else - cif->flags = 0; + switch (cif->rtype->size) + { + case 1: + cif->flags = CIF_FLAGS_STRUCT1; + break; + case 2: + cif->flags = CIF_FLAGS_STRUCT2; + break; + case 4: + cif->flags = CIF_FLAGS_INT; + break; + case 8: + cif->flags = CIF_FLAGS_DINT; + break; + default: + cif->flags = 0; + break; + } break; case FFI_TYPE_FLOAT: @@ -137,11 +165,6 @@ return FFI_OK; } -extern void ffi_call_SYSV (void *(*) (void *, extended_cif *), - extended_cif *, - unsigned, unsigned, unsigned, - void *, void (*fn) ()); - void ffi_call (ffi_cif *cif, void (*fn) (), void *rvalue, void **avalue) { @@ -149,7 +172,7 @@ ecif.cif = cif; ecif.avalue = avalue; - + /* If the return value is a struct and we don't have a return value address then we need to make one. */ @@ -159,13 +182,11 @@ ecif.rvalue = alloca (cif->rtype->size); else ecif.rvalue = rvalue; - - - switch (cif->abi) + + switch (cif->abi) { case FFI_SYSV: - ffi_call_SYSV (ffi_prep_args, &ecif, cif->bytes, - cif->flags, cif->rtype->size * 8, + ffi_call_SYSV (&ecif, cif->bytes, cif->flags, ecif.rvalue, fn); break; @@ -174,3 +195,84 @@ break; } } + +static void +ffi_prep_incoming_args_SYSV (char *stack, void **avalue, ffi_cif *cif) +{ + unsigned int i; + void **p_argv; + char *argp; + ffi_type **p_arg; + + argp = stack; + p_argv = avalue; + + for (i = cif->nargs, p_arg = cif->arg_types; (i != 0); i--, p_arg++) + { + size_t z; + + z = (*p_arg)->size; + if (z <= 4) + { + *p_argv = (void *) (argp + 4 - z); + + z = 4; + } + else + { + *p_argv = (void *) argp; + + /* Align if necessary */ + if ((sizeof(int) - 1) & z) + z = ALIGN(z, sizeof(int)); + } + + p_argv++; + argp += z; + } +} + +unsigned int +ffi_closure_SYSV_inner (ffi_closure *closure, void *resp, void *args) +{ + ffi_cif *cif; + void **arg_area; + + cif = closure->cif; + arg_area = (void**) alloca (cif->nargs * sizeof (void *)); + + ffi_prep_incoming_args_SYSV(args, arg_area, cif); + + (closure->fun) (cif, resp, arg_area, closure->user_data); + + return cif->flags; +} + +ffi_status +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + void *codeloc) +{ + FFI_ASSERT (cif->abi == FFI_SYSV); + + *(unsigned short *)closure->tramp = 0x207c; + *(void **)(closure->tramp + 2) = codeloc; + *(unsigned short *)(closure->tramp + 6) = 0x4ef9; + if (cif->rtype->type == FFI_TYPE_STRUCT + && !cif->flags) + *(void **)(closure->tramp + 8) = ffi_closure_struct_SYSV; + else + *(void **)(closure->tramp + 8) = ffi_closure_SYSV; + + syscall(SYS_cacheflush, codeloc, FLUSH_SCOPE_LINE, + FLUSH_CACHE_BOTH, FFI_TRAMPOLINE_SIZE); + + closure->cif = cif; + closure->user_data = user_data; + closure->fun = fun; + + return FFI_OK; +} + Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/m68k/ffitarget.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/m68k/ffitarget.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/m68k/ffitarget.h Wed Apr 30 15:57:13 2008 @@ -13,13 +13,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ @@ -40,7 +41,8 @@ /* ---- Definitions for closures ----------------------------------------- */ -#define FFI_CLOSURES 0 +#define FFI_CLOSURES 1 +#define FFI_TRAMPOLINE_SIZE 16 #define FFI_NATIVE_RAW_API 0 #endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/m68k/sysv.S ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/m68k/sysv.S (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/m68k/sysv.S Wed Apr 30 15:57:13 2008 @@ -1,47 +1,88 @@ /* ----------------------------------------------------------------------- - sysv.S + sysv.S - Copyright (c) 1998 Andreas Schwab + Copyright (c) 2008 Red Hat, Inc. m68k Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #define LIBFFI_ASM #include #include +#ifdef HAVE_AS_CFI_PSEUDO_OP +#define CFI_STARTPROC() .cfi_startproc +#define CFI_OFFSET(reg,off) .cfi_offset reg,off +#define CFI_DEF_CFA(reg,off) .cfi_def_cfa reg,off +#define CFI_ENDPROC() .cfi_endproc +#else +#define CFI_STARTPROC() +#define CFI_OFFSET(reg,off) +#define CFI_DEF_CFA(reg,off) +#define CFI_ENDPROC() +#endif + .text .globl ffi_call_SYSV .type ffi_call_SYSV, at function + .align 4 ffi_call_SYSV: + CFI_STARTPROC() link %fp,#0 + CFI_OFFSET(14,-8) + CFI_DEF_CFA(14,8) move.l %d2,-(%sp) + CFI_OFFSET(2,-12) | Make room for all of the new args. - sub.l 16(%fp),%sp + sub.l 12(%fp),%sp | Call ffi_prep_args - move.l 12(%fp),-(%sp) + move.l 8(%fp),-(%sp) pea 4(%sp) - move.l 8(%fp),%a0 - jsr (%a0) +#if !defined __PIC__ + jsr ffi_prep_args +#else + bsr.l ffi_prep_args at PLTPC +#endif addq.l #8,%sp | Pass pointer to struct value, if any move.l %a0,%a1 | Call the function - move.l 32(%fp),%a0 + move.l 24(%fp),%a0 jsr (%a0) | Remove the space we pushed for the args - add.l 16(%fp),%sp + add.l 12(%fp),%sp | Load the pointer to storage for the return value - move.l 28(%fp),%a1 + move.l 20(%fp),%a1 | Load the return type code - move.l 20(%fp),%d2 + move.l 16(%fp),%d2 | If the return value pointer is NULL, assume no return value. tst.l %a1 @@ -79,19 +120,115 @@ retpointer: btst #5,%d2 - jbeq retstruct + jbeq retstruct1 move.l %a0,(%a1) jbra epilogue -retstruct: +retstruct1: btst #6,%d2 + jbeq retstruct2 + move.b %d0,(%a1) + jbra epilogue + +retstruct2: + btst #7,%d2 jbeq noretval - move.l 24(%fp),%d2 - bfins %d0,(%a1){#0,%d2} + move.w %d0,(%a1) noretval: epilogue: move.l (%sp)+,%d2 - unlk %a6 + unlk %fp rts + CFI_ENDPROC() .size ffi_call_SYSV,.-ffi_call_SYSV + + .globl ffi_closure_SYSV + .type ffi_closure_SYSV, @function + .align 4 + +ffi_closure_SYSV: + CFI_STARTPROC() + link %fp,#-12 + CFI_OFFSET(14,-8) + CFI_DEF_CFA(14,8) + move.l %sp,-12(%fp) + pea 8(%fp) + pea -12(%fp) + move.l %a0,-(%sp) +#if !defined __PIC__ + jsr ffi_closure_SYSV_inner +#else + bsr.l ffi_closure_SYSV_inner at PLTPC +#endif + + lsr.l #1,%d0 + jne 1f + jcc .Lcls_epilogue + move.l -12(%fp),%d0 +.Lcls_epilogue: + unlk %fp + rts +1: + lea -12(%fp),%a0 + lsr.l #2,%d0 + jne 1f + jcs .Lcls_ret_float + move.l (%a0)+,%d0 + move.l (%a0),%d1 + jra .Lcls_epilogue +.Lcls_ret_float: + fmove.s (%a0),%fp0 + jra .Lcls_epilogue +1: + lsr.l #2,%d0 + jne 1f + jcs .Lcls_ret_ldouble + fmove.d (%a0),%fp0 + jra .Lcls_epilogue +.Lcls_ret_ldouble: + fmove.x (%a0),%fp0 + jra .Lcls_epilogue +1: + lsr.l #2,%d0 + jne .Lcls_ret_struct2 + jcs .Lcls_ret_struct1 + move.l (%a0),%a0 + move.l %a0,%d0 + jra .Lcls_epilogue +.Lcls_ret_struct1: + move.b (%a0),%d0 + jra .Lcls_epilogue +.Lcls_ret_struct2: + move.w (%a0),%d0 + jra .Lcls_epilogue + CFI_ENDPROC() + + .size ffi_closure_SYSV,.-ffi_closure_SYSV + + .globl ffi_closure_struct_SYSV + .type ffi_closure_struct_SYSV, @function + .align 4 + +ffi_closure_struct_SYSV: + CFI_STARTPROC() + link %fp,#0 + CFI_OFFSET(14,-8) + CFI_DEF_CFA(14,8) + move.l %sp,-12(%fp) + pea 8(%fp) + move.l %a1,-(%sp) + move.l %a0,-(%sp) +#if !defined __PIC__ + jsr ffi_closure_SYSV_inner +#else + bsr.l ffi_closure_SYSV_inner at PLTPC +#endif + unlk %fp + rts + CFI_ENDPROC() + .size ffi_closure_struct_SYSV,.-ffi_closure_struct_SYSV + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"", at progbits +#endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/mips/ffi.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/mips/ffi.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/mips/ffi.c Wed Apr 30 15:57:13 2008 @@ -1,5 +1,6 @@ /* ----------------------------------------------------------------------- - ffi.c - Copyright (c) 1996 Red Hat, Inc. + ffi.c - Copyright (c) 1996, 2007, 2008 Red Hat, Inc. + Copyright (c) 2008 David Daney MIPS Foreign Function Interface @@ -14,28 +15,44 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #include #include #include + +#ifdef __GNUC__ +# if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)) +# define USE__BUILTIN___CLEAR_CACHE 1 +# endif +#endif + +#ifndef USE__BUILTIN___CLEAR_CACHE #include +#endif -#if _MIPS_SIM == _ABIN32 +#ifdef FFI_DEBUG +# define FFI_MIPS_STOP_HERE() ffi_stop_here() +#else +# define FFI_MIPS_STOP_HERE() do {} while(0) +#endif + +#ifdef FFI_MIPS_N32 #define FIX_ARGP \ FFI_ASSERT(argp <= &stack[bytes]); \ if (argp == &stack[bytes]) \ { \ argp = stack; \ - ffi_stop_here(); \ + FFI_MIPS_STOP_HERE(); \ } #else #define FIX_ARGP @@ -55,7 +72,7 @@ char *argp; ffi_type **p_arg; -#if _MIPS_SIM == _ABIN32 +#ifdef FFI_MIPS_N32 /* If more than 8 double words are used, the remainder go on the stack. We reorder stuff on the stack here to support this easily. */ @@ -69,7 +86,7 @@ memset(stack, 0, bytes); -#if _MIPS_SIM == _ABIN32 +#ifdef FFI_MIPS_N32 if ( ecif->cif->rstruct_flag != 0 ) #else if ( ecif->cif->rtype->type == FFI_TYPE_STRUCT ) @@ -92,7 +109,7 @@ if (a < sizeof(ffi_arg)) a = sizeof(ffi_arg); - if ((a - 1) & (unsigned int) argp) + if ((a - 1) & (unsigned long) argp) { argp = (char *) ALIGN(argp, a); FIX_ARGP; @@ -101,9 +118,15 @@ z = (*p_arg)->size; if (z <= sizeof(ffi_arg)) { + int type = (*p_arg)->type; z = sizeof(ffi_arg); - switch ((*p_arg)->type) + /* The size of a pointer depends on the ABI */ + if (type == FFI_TYPE_POINTER) + type = + (ecif->cif->abi == FFI_N64) ? FFI_TYPE_SINT64 : FFI_TYPE_SINT32; + + switch (type) { case FFI_TYPE_SINT8: *(ffi_arg *)argp = *(SINT8 *)(* p_argv); @@ -126,7 +149,6 @@ break; case FFI_TYPE_UINT32: - case FFI_TYPE_POINTER: *(ffi_arg *)argp = *(UINT32 *)(* p_argv); break; @@ -135,8 +157,7 @@ *(float *) argp = *(float *)(* p_argv); break; - /* Handle small structures. */ - case FFI_TYPE_STRUCT: + /* Handle structures. */ default: memcpy(argp, *p_argv, (*p_arg)->size); break; @@ -144,12 +165,12 @@ } else { -#if _MIPS_SIM == _ABIO32 +#ifdef FFI_MIPS_O32 memcpy(argp, *p_argv, z); #else { - unsigned end = (unsigned) argp+z; - unsigned cap = (unsigned) stack+bytes; + unsigned long end = (unsigned long) argp + z; + unsigned long cap = (unsigned long) stack + bytes; /* Check if the data will fit within the register space. Handle it if it doesn't. */ @@ -158,12 +179,13 @@ memcpy(argp, *p_argv, z); else { - unsigned portion = end - cap; + unsigned long portion = cap - (unsigned long)argp; memcpy(argp, *p_argv, portion); argp = stack; - memcpy(argp, - (void*)((unsigned)(*p_argv)+portion), z - portion); + z -= portion; + memcpy(argp, (void*)((unsigned long)(*p_argv) + portion), + z); } } #endif @@ -174,7 +196,7 @@ } } -#if _MIPS_SIM == _ABIN32 +#ifdef FFI_MIPS_N32 /* The n32 spec says that if "a chunk consists solely of a double float field (but not a double, which is part of a union), it @@ -182,35 +204,41 @@ passed in an integer register". This code traverses structure definitions and generates the appropriate flags. */ -unsigned calc_n32_struct_flags(ffi_type *arg, unsigned *shift) +static unsigned +calc_n32_struct_flags(ffi_type *arg, unsigned *loc, unsigned *arg_reg) { unsigned flags = 0; unsigned index = 0; ffi_type *e; - while (e = arg->elements[index]) + while ((e = arg->elements[index])) { + /* Align this object. */ + *loc = ALIGN(*loc, e->alignment); if (e->type == FFI_TYPE_DOUBLE) { - flags += (FFI_TYPE_DOUBLE << *shift); - *shift += FFI_FLAG_BITS; + /* Already aligned to FFI_SIZEOF_ARG. */ + *arg_reg = *loc / FFI_SIZEOF_ARG; + if (*arg_reg > 7) + break; + flags += (FFI_TYPE_DOUBLE << (*arg_reg * FFI_FLAG_BITS)); + *loc += e->size; } - else if (e->type == FFI_TYPE_STRUCT) - flags += calc_n32_struct_flags(e, shift); else - *shift += FFI_FLAG_BITS; - + *loc += e->size; index++; } + /* Next Argument register at alignment of FFI_SIZEOF_ARG. */ + *arg_reg = ALIGN(*loc, FFI_SIZEOF_ARG) / FFI_SIZEOF_ARG; return flags; } -unsigned calc_n32_return_struct_flags(ffi_type *arg) +static unsigned +calc_n32_return_struct_flags(ffi_type *arg) { unsigned flags = 0; - unsigned index = 0; unsigned small = FFI_TYPE_SMALLSTRUCT; ffi_type *e; @@ -229,16 +257,16 @@ e = arg->elements[0]; if (e->type == FFI_TYPE_DOUBLE) - flags = FFI_TYPE_DOUBLE << FFI_FLAG_BITS; + flags = FFI_TYPE_DOUBLE; else if (e->type == FFI_TYPE_FLOAT) - flags = FFI_TYPE_FLOAT << FFI_FLAG_BITS; + flags = FFI_TYPE_FLOAT; if (flags && (e = arg->elements[1])) { if (e->type == FFI_TYPE_DOUBLE) - flags += FFI_TYPE_DOUBLE; + flags += FFI_TYPE_DOUBLE << FFI_FLAG_BITS; else if (e->type == FFI_TYPE_FLOAT) - flags += FFI_TYPE_FLOAT; + flags += FFI_TYPE_FLOAT << FFI_FLAG_BITS; else return small; @@ -263,7 +291,7 @@ { cif->flags = 0; -#if _MIPS_SIM == _ABIO32 +#ifdef FFI_MIPS_O32 /* Set the flags necessary for O32 processing. FFI_O32_SOFT_FLOAT * does not have special handling for floating point args. */ @@ -351,10 +379,11 @@ } #endif -#if _MIPS_SIM == _ABIN32 +#ifdef FFI_MIPS_N32 /* Set the flags necessary for N32 processing */ { - unsigned shift = 0; + unsigned arg_reg = 0; + unsigned loc = 0; unsigned count = (cif->nargs < 8) ? cif->nargs : 8; unsigned index = 0; @@ -369,7 +398,7 @@ /* This means that the structure is being passed as a hidden argument */ - shift = FFI_FLAG_BITS; + arg_reg = 1; count = (cif->nargs < 7) ? cif->nargs : 7; cif->rstruct_flag = !0; @@ -380,23 +409,37 @@ else cif->rstruct_flag = 0; - while (count-- > 0) + while (count-- > 0 && arg_reg < 8) { switch ((cif->arg_types)[index]->type) { case FFI_TYPE_FLOAT: case FFI_TYPE_DOUBLE: - cif->flags += ((cif->arg_types)[index]->type << shift); - shift += FFI_FLAG_BITS; + cif->flags += + ((cif->arg_types)[index]->type << (arg_reg * FFI_FLAG_BITS)); + arg_reg++; break; + case FFI_TYPE_LONGDOUBLE: + /* Align it. */ + arg_reg = ALIGN(arg_reg, 2); + /* Treat it as two adjacent doubles. */ + cif->flags += + (FFI_TYPE_DOUBLE << (arg_reg * FFI_FLAG_BITS)); + arg_reg++; + cif->flags += + (FFI_TYPE_DOUBLE << (arg_reg * FFI_FLAG_BITS)); + arg_reg++; + break; case FFI_TYPE_STRUCT: + loc = arg_reg * FFI_SIZEOF_ARG; cif->flags += calc_n32_struct_flags((cif->arg_types)[index], - &shift); + &loc, &arg_reg); break; default: - shift += FFI_FLAG_BITS; + arg_reg++; + break; } index++; @@ -431,7 +474,13 @@ case FFI_TYPE_DOUBLE: cif->flags += cif->rtype->type << (FFI_FLAG_BITS * 8); break; - + case FFI_TYPE_LONGDOUBLE: + /* Long double is returned as if it were a struct containing + two doubles. */ + cif->flags += FFI_TYPE_STRUCT << (FFI_FLAG_BITS * 8); + cif->flags += (FFI_TYPE_DOUBLE + (FFI_TYPE_DOUBLE << FFI_FLAG_BITS)) + << (4 + (FFI_FLAG_BITS * 8)); + break; default: cif->flags += FFI_TYPE_INT << (FFI_FLAG_BITS * 8); break; @@ -470,7 +519,7 @@ switch (cif->abi) { -#if _MIPS_SIM == _ABIO32 +#ifdef FFI_MIPS_O32 case FFI_O32: case FFI_O32_SOFT_FLOAT: ffi_call_O32(ffi_prep_args, &ecif, cif->bytes, @@ -478,10 +527,25 @@ break; #endif -#if _MIPS_SIM == _ABIN32 +#ifdef FFI_MIPS_N32 case FFI_N32: - ffi_call_N32(ffi_prep_args, &ecif, cif->bytes, - cif->flags, ecif.rvalue, fn); + case FFI_N64: + { + int copy_rvalue = 0; + void *rvalue_copy = ecif.rvalue; + if (cif->rtype->type == FFI_TYPE_STRUCT && cif->rtype->size < 16) + { + /* For structures smaller than 16 bytes we clobber memory + in 8 byte increments. Make a copy so we don't clobber + the callers memory outside of the struct bounds. */ + rvalue_copy = alloca(16); + copy_rvalue = 1; + } + ffi_call_N32(ffi_prep_args, &ecif, cif->bytes, + cif->flags, rvalue_copy, fn); + if (copy_rvalue) + memcpy(ecif.rvalue, rvalue_copy, cif->rtype->size); + } break; #endif @@ -491,42 +555,83 @@ } } -#if FFI_CLOSURES /* N32 not implemented yet, FFI_CLOSURES not defined */ +#if FFI_CLOSURES #if defined(FFI_MIPS_O32) extern void ffi_closure_O32(void); +#else +extern void ffi_closure_N32(void); #endif /* FFI_MIPS_O32 */ ffi_status -ffi_prep_closure (ffi_closure *closure, - ffi_cif *cif, - void (*fun)(ffi_cif*,void*,void**,void*), - void *user_data) +ffi_prep_closure_loc (ffi_closure *closure, + ffi_cif *cif, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + void *codeloc) { unsigned int *tramp = (unsigned int *) &closure->tramp[0]; - unsigned int fn; - unsigned int ctx = (unsigned int) closure; + void * fn; + char *clear_location = (char *) codeloc; #if defined(FFI_MIPS_O32) FFI_ASSERT(cif->abi == FFI_O32 || cif->abi == FFI_O32_SOFT_FLOAT); - fn = (unsigned int) ffi_closure_O32; + fn = ffi_closure_O32; #else /* FFI_MIPS_N32 */ - FFI_ASSERT(cif->abi == FFI_N32); - FFI_ASSERT(!"not implemented"); + FFI_ASSERT(cif->abi == FFI_N32 || cif->abi == FFI_N64); + fn = ffi_closure_N32; #endif /* FFI_MIPS_O32 */ - tramp[0] = 0x3c190000 | (fn >> 16); /* lui $25,high(fn) */ - tramp[1] = 0x37390000 | (fn & 0xffff); /* ori $25,low(fn) */ - tramp[2] = 0x3c080000 | (ctx >> 16); /* lui $8,high(ctx) */ - tramp[3] = 0x03200008; /* jr $25 */ - tramp[4] = 0x35080000 | (ctx & 0xffff); /* ori $8,low(ctx) */ +#if defined(FFI_MIPS_O32) || (_MIPS_SIM ==_ABIN32) + /* lui $25,high(fn) */ + tramp[0] = 0x3c190000 | ((unsigned)fn >> 16); + /* ori $25,low(fn) */ + tramp[1] = 0x37390000 | ((unsigned)fn & 0xffff); + /* lui $12,high(codeloc) */ + tramp[2] = 0x3c0c0000 | ((unsigned)codeloc >> 16); + /* jr $25 */ + tramp[3] = 0x03200008; + /* ori $12,low(codeloc) */ + tramp[4] = 0x358c0000 | ((unsigned)codeloc & 0xffff); +#else + /* N64 has a somewhat larger trampoline. */ + /* lui $25,high(fn) */ + tramp[0] = 0x3c190000 | ((unsigned long)fn >> 48); + /* lui $12,high(codeloc) */ + tramp[1] = 0x3c0c0000 | ((unsigned long)codeloc >> 48); + /* ori $25,mid-high(fn) */ + tramp[2] = 0x37390000 | (((unsigned long)fn >> 32 ) & 0xffff); + /* ori $12,mid-high(codeloc) */ + tramp[3] = 0x358c0000 | (((unsigned long)codeloc >> 32) & 0xffff); + /* dsll $25,$25,16 */ + tramp[4] = 0x0019cc38; + /* dsll $12,$12,16 */ + tramp[5] = 0x000c6438; + /* ori $25,mid-low(fn) */ + tramp[6] = 0x37390000 | (((unsigned long)fn >> 16 ) & 0xffff); + /* ori $12,mid-low(codeloc) */ + tramp[7] = 0x358c0000 | (((unsigned long)codeloc >> 16) & 0xffff); + /* dsll $25,$25,16 */ + tramp[8] = 0x0019cc38; + /* dsll $12,$12,16 */ + tramp[9] = 0x000c6438; + /* ori $25,low(fn) */ + tramp[10] = 0x37390000 | ((unsigned long)fn & 0xffff); + /* jr $25 */ + tramp[11] = 0x03200008; + /* ori $12,low(codeloc) */ + tramp[12] = 0x358c0000 | ((unsigned long)codeloc & 0xffff); + +#endif closure->cif = cif; closure->fun = fun; closure->user_data = user_data; - /* XXX this is available on Linux, but anything else? */ - cacheflush (tramp, FFI_TRAMPOLINE_SIZE, ICACHE); - +#ifdef USE__BUILTIN___CLEAR_CACHE + __builtin___clear_cache(clear_location, clear_location + FFI_TRAMPOLINE_SIZE); +#else + cacheflush (clear_location, FFI_TRAMPOLINE_SIZE, ICACHE); +#endif return FFI_OK; } @@ -567,7 +672,7 @@ if ((cif->flags >> (FFI_FLAG_BITS * 2)) == FFI_TYPE_STRUCT) { - rvalue = (void *) ar[0]; + rvalue = (void *)(UINT32)ar[0]; argn = 1; } @@ -645,4 +750,177 @@ } } +#if defined(FFI_MIPS_N32) + +static void +copy_struct_N32(char *target, unsigned offset, ffi_abi abi, ffi_type *type, + int argn, unsigned arg_offset, ffi_arg *ar, + ffi_arg *fpr) +{ + ffi_type **elt_typep = type->elements; + while(*elt_typep) + { + ffi_type *elt_type = *elt_typep; + unsigned o; + char *tp; + char *argp; + char *fpp; + + o = ALIGN(offset, elt_type->alignment); + arg_offset += o - offset; + offset = o; + argn += arg_offset / sizeof(ffi_arg); + arg_offset = arg_offset % sizeof(ffi_arg); + + argp = (char *)(ar + argn); + fpp = (char *)(argn >= 8 ? ar + argn : fpr + argn); + + tp = target + offset; + + if (elt_type->type == FFI_TYPE_DOUBLE) + *(double *)tp = *(double *)fpp; + else + memcpy(tp, argp + arg_offset, elt_type->size); + + offset += elt_type->size; + arg_offset += elt_type->size; + elt_typep++; + argn += arg_offset / sizeof(ffi_arg); + arg_offset = arg_offset % sizeof(ffi_arg); + } +} + +/* + * Decodes the arguments to a function, which will be stored on the + * stack. AR is the pointer to the beginning of the integer + * arguments. FPR is a pointer to the area where floating point + * registers have been saved. + * + * RVALUE is the location where the function return value will be + * stored. CLOSURE is the prepared closure to invoke. + * + * This function should only be called from assembly, which is in + * turn called from a trampoline. + * + * Returns the function return flags. + * + */ +int +ffi_closure_mips_inner_N32 (ffi_closure *closure, + void *rvalue, ffi_arg *ar, + ffi_arg *fpr) +{ + ffi_cif *cif; + void **avaluep; + ffi_arg *avalue; + ffi_type **arg_types; + int i, avn, argn; + + cif = closure->cif; + avalue = alloca (cif->nargs * sizeof (ffi_arg)); + avaluep = alloca (cif->nargs * sizeof (ffi_arg)); + + argn = 0; + + if (cif->rstruct_flag) + { +#if _MIPS_SIM==_ABIN32 + rvalue = (void *)(UINT32)ar[0]; +#else /* N64 */ + rvalue = (void *)ar[0]; +#endif + argn = 1; + } + + i = 0; + avn = cif->nargs; + arg_types = cif->arg_types; + + while (i < avn) + { + if (arg_types[i]->type == FFI_TYPE_FLOAT + || arg_types[i]->type == FFI_TYPE_DOUBLE) + { + ffi_arg *argp = argn >= 8 ? ar + argn : fpr + argn; +#ifdef __MIPSEB__ + if (arg_types[i]->type == FFI_TYPE_FLOAT && argn < 8) + avaluep[i] = ((char *) argp) + sizeof (float); + else +#endif + avaluep[i] = (char *) argp; + } + else + { + unsigned type = arg_types[i]->type; + + if (arg_types[i]->alignment > sizeof(ffi_arg)) + argn = ALIGN(argn, arg_types[i]->alignment / sizeof(ffi_arg)); + + ffi_arg *argp = ar + argn; + + /* The size of a pointer depends on the ABI */ + if (type == FFI_TYPE_POINTER) + type = (cif->abi == FFI_N64) ? FFI_TYPE_SINT64 : FFI_TYPE_SINT32; + + switch (type) + { + case FFI_TYPE_SINT8: + avaluep[i] = &avalue[i]; + *(SINT8 *) &avalue[i] = (SINT8) *argp; + break; + + case FFI_TYPE_UINT8: + avaluep[i] = &avalue[i]; + *(UINT8 *) &avalue[i] = (UINT8) *argp; + break; + + case FFI_TYPE_SINT16: + avaluep[i] = &avalue[i]; + *(SINT16 *) &avalue[i] = (SINT16) *argp; + break; + + case FFI_TYPE_UINT16: + avaluep[i] = &avalue[i]; + *(UINT16 *) &avalue[i] = (UINT16) *argp; + break; + + case FFI_TYPE_SINT32: + avaluep[i] = &avalue[i]; + *(SINT32 *) &avalue[i] = (SINT32) *argp; + break; + + case FFI_TYPE_UINT32: + avaluep[i] = &avalue[i]; + *(UINT32 *) &avalue[i] = (UINT32) *argp; + break; + + case FFI_TYPE_STRUCT: + if (argn < 8) + { + /* Allocate space for the struct as at least part of + it was passed in registers. */ + avaluep[i] = alloca(arg_types[i]->size); + copy_struct_N32(avaluep[i], 0, cif->abi, arg_types[i], + argn, 0, ar, fpr); + + break; + } + /* Else fall through. */ + default: + avaluep[i] = (char *) argp; + break; + } + } + argn += ALIGN(arg_types[i]->size, sizeof(ffi_arg)) / sizeof(ffi_arg); + i++; + } + + /* Invoke the closure. */ + (closure->fun) (cif, rvalue, avaluep, closure->user_data); + + return cif->flags >> (FFI_FLAG_BITS * 8); +} + +#endif /* FFI_MIPS_N32 */ + #endif /* FFI_CLOSURES */ Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/mips/ffitarget.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/mips/ffitarget.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/mips/ffitarget.h Wed Apr 30 15:57:13 2008 @@ -13,19 +13,33 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #ifndef LIBFFI_TARGET_H #define LIBFFI_TARGET_H +#ifdef linux +#include +# ifndef _ABIN32 +# define _ABIN32 _MIPS_SIM_NABI32 +# endif +# ifndef _ABI64 +# define _ABI64 _MIPS_SIM_ABI64 +# endif +# ifndef _ABIO32 +# define _ABIO32 _MIPS_SIM_ABI32 +# endif +#endif + #if !defined(_MIPS_SIM) -- something is very wrong -- #else @@ -42,10 +56,13 @@ #ifdef FFI_MIPS_O32 /* O32 stack frames have 32bit integer args */ -#define FFI_SIZEOF_ARG 4 +# define FFI_SIZEOF_ARG 4 #else /* N32 and N64 frames have 64bit integer args */ -#define FFI_SIZEOF_ARG 8 +# define FFI_SIZEOF_ARG 8 +# if _MIPS_SIM == _ABIN32 +# define FFI_SIZEOF_JAVA_RAW 4 +# endif #endif #define FFI_FLAG_BITS 2 @@ -104,19 +121,28 @@ #define ra $31 #ifdef FFI_MIPS_O32 -#define REG_L lw -#define REG_S sw -#define SUBU subu -#define ADDU addu -#define SRL srl -#define LI li +# define REG_L lw +# define REG_S sw +# define SUBU subu +# define ADDU addu +# define SRL srl +# define LI li #else /* !FFI_MIPS_O32 */ -#define REG_L ld -#define REG_S sd -#define SUBU dsubu -#define ADDU daddu -#define SRL dsrl -#define LI dli +# define REG_L ld +# define REG_S sd +# define SUBU dsubu +# define ADDU daddu +# define SRL dsrl +# define LI dli +# if (_MIPS_SIM==_ABI64) +# define LA dla +# define EH_FRAME_ALIGN 3 +# define FDE_ADDR_BYTES .8byte +# else +# define LA la +# define EH_FRAME_ALIGN 2 +# define FDE_ADDR_BYTES .4byte +# endif /* _MIPS_SIM==_ABI64 */ #endif /* !FFI_MIPS_O32 */ #else /* !LIBFFI_ASM */ #ifdef FFI_MIPS_O32 @@ -143,7 +169,11 @@ FFI_DEFAULT_ABI = FFI_O32, #endif #else +# if _MIPS_SIM==_ABI64 + FFI_DEFAULT_ABI = FFI_N64, +# else FFI_DEFAULT_ABI = FFI_N32, +# endif #endif FFI_LAST_ABI = FFI_DEFAULT_ABI + 1 @@ -158,8 +188,13 @@ #define FFI_CLOSURES 1 #define FFI_TRAMPOLINE_SIZE 20 #else -/* N32/N64 not implemented yet. */ -#define FFI_CLOSURES 0 +/* N32/N64. */ +# define FFI_CLOSURES 1 +#if _MIPS_SIM==_ABI64 +#define FFI_TRAMPOLINE_SIZE 52 +#else +#define FFI_TRAMPOLINE_SIZE 20 +#endif #endif /* FFI_MIPS_O32 */ #define FFI_NATIVE_RAW_API 0 Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/mips/n32.S ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/mips/n32.S (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/mips/n32.S Wed Apr 30 15:57:13 2008 @@ -17,7 +17,8 @@ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. @@ -45,13 +46,19 @@ .globl ffi_call_N32 .ent ffi_call_N32 ffi_call_N32: +.LFB3: + .frame $fp, SIZEOF_FRAME, ra + .mask 0xc0000000,-FFI_SIZEOF_ARG + .fmask 0x00000000,0 # Prologue SUBU $sp, SIZEOF_FRAME # Frame size +.LCFI0: REG_S $fp, SIZEOF_FRAME - 2*FFI_SIZEOF_ARG($sp) # Save frame pointer REG_S ra, SIZEOF_FRAME - 1*FFI_SIZEOF_ARG($sp) # Save return address +.LCFI1: move $fp, $sp - +.LCFI3: move t9, callback # callback function pointer REG_S bytes, 2*FFI_SIZEOF_ARG($fp) # bytes REG_S flags, 3*FFI_SIZEOF_ARG($fp) # flags @@ -72,14 +79,12 @@ SUBU $sp, $sp, v0 # move the stack pointer to reflect the # arg space - ADDU a0, $sp, 0 # 4 * FFI_SIZEOF_ARG + move a0, $sp # 4 * FFI_SIZEOF_ARG ADDU a3, $fp, 3 * FFI_SIZEOF_ARG # Call ffi_prep_args jal t9 - # ADDU $sp, $sp, 4 * FFI_SIZEOF_ARG # adjust $sp to new args - # Copy the stack pointer to t9 move t9, $sp @@ -90,18 +95,16 @@ REG_L t6, 2*FFI_SIZEOF_ARG($fp) # Is it bigger than 8 * FFI_SIZEOF_ARG? - dadd t7, $0, 8 * FFI_SIZEOF_ARG - dsub t8, t6, t7 + daddiu t8, t6, -(8 * FFI_SIZEOF_ARG) bltz t8, loadregs - add t9, t9, t8 + ADDU t9, t9, t8 loadregs: - REG_L t4, 3*FFI_SIZEOF_ARG($fp) # load the flags word - add t6, t4, 0 # and copy it into t6 + REG_L t6, 3*FFI_SIZEOF_ARG($fp) # load the flags word into t6. - and t4, ((1< + (c) 2008 Red Hat, Inc. HPPA Foreign Function Interface + HP-UX PA ABI support (c) 2006 Free Software Foundation, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the @@ -14,13 +16,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #include @@ -30,15 +33,19 @@ #include #define ROUND_UP(v, a) (((size_t)(v) + (a) - 1) & ~((a) - 1)) -#define ROUND_DOWN(v, a) (((size_t)(v) - (a) + 1) & ~((a) - 1)) + #define MIN_STACK_SIZE 64 #define FIRST_ARG_SLOT 9 #define DEBUG_LEVEL 0 -#define fldw(addr, fpreg) asm volatile ("fldw 0(%0), %%" #fpreg "L" : : "r"(addr) : #fpreg) -#define fstw(fpreg, addr) asm volatile ("fstw %%" #fpreg "L, 0(%0)" : : "r"(addr)) -#define fldd(addr, fpreg) asm volatile ("fldd 0(%0), %%" #fpreg : : "r"(addr) : #fpreg) -#define fstd(fpreg, addr) asm volatile ("fstd %%" #fpreg "L, 0(%0)" : : "r"(addr)) +#define fldw(addr, fpreg) \ + __asm__ volatile ("fldw 0(%0), %%" #fpreg "L" : : "r"(addr) : #fpreg) +#define fstw(fpreg, addr) \ + __asm__ volatile ("fstw %%" #fpreg "L, 0(%0)" : : "r"(addr)) +#define fldd(addr, fpreg) \ + __asm__ volatile ("fldd 0(%0), %%" #fpreg : : "r"(addr) : #fpreg) +#define fstd(fpreg, addr) \ + __asm__ volatile ("fstd %%" #fpreg "L, 0(%0)" : : "r"(addr)) #define debug(lvl, x...) do { if (lvl <= DEBUG_LEVEL) { printf(x); } } while (0) @@ -47,16 +54,19 @@ size_t sz = t->size; /* Small structure results are passed in registers, - larger ones are passed by pointer. */ + larger ones are passed by pointer. Note that + small structures of size 2, 4 and 8 differ from + the corresponding integer types in that they have + different alignment requirements. */ if (sz <= 1) return FFI_TYPE_UINT8; else if (sz == 2) - return FFI_TYPE_UINT16; + return FFI_TYPE_SMALL_STRUCT2; else if (sz == 3) return FFI_TYPE_SMALL_STRUCT3; else if (sz == 4) - return FFI_TYPE_UINT32; + return FFI_TYPE_SMALL_STRUCT4; else if (sz == 5) return FFI_TYPE_SMALL_STRUCT5; else if (sz == 6) @@ -64,61 +74,80 @@ else if (sz == 7) return FFI_TYPE_SMALL_STRUCT7; else if (sz <= 8) - return FFI_TYPE_UINT64; + return FFI_TYPE_SMALL_STRUCT8; else return FFI_TYPE_STRUCT; /* else, we pass it by pointer. */ } /* PA has a downward growing stack, which looks like this: - + Offset - [ Variable args ] + [ Variable args ] SP = (4*(n+9)) arg word N ... SP-52 arg word 4 - [ Fixed args ] + [ Fixed args ] SP-48 arg word 3 SP-44 arg word 2 SP-40 arg word 1 SP-36 arg word 0 - [ Frame marker ] + [ Frame marker ] ... SP-20 RP SP-4 previous SP - - First 4 non-FP 32-bit args are passed in gr26, gr25, gr24 and gr23 - First 2 non-FP 64-bit args are passed in register pairs, starting - on an even numbered register (i.e. r26/r25 and r24+r23) - First 4 FP 32-bit arguments are passed in fr4L, fr5L, fr6L and fr7L - First 2 FP 64-bit arguments are passed in fr5 and fr7 - The rest are passed on the stack starting at SP-52, but 64-bit - arguments need to be aligned to an 8-byte boundary - + + The first four argument words on the stack are reserved for use by + the callee. Instead, the general and floating registers replace + the first four argument slots. Non FP arguments are passed solely + in the general registers. FP arguments are passed in both general + and floating registers when using libffi. + + Non-FP 32-bit args are passed in gr26, gr25, gr24 and gr23. + Non-FP 64-bit args are passed in register pairs, starting + on an odd numbered register (i.e. r25+r26 and r23+r24). + FP 32-bit arguments are passed in fr4L, fr5L, fr6L and fr7L. + FP 64-bit arguments are passed in fr5 and fr7. + + The registers are allocated in the same manner as stack slots. + This allows the callee to save its arguments on the stack if + necessary: + + arg word 3 -> gr23 or fr7L + arg word 2 -> gr24 or fr6L or fr7R + arg word 1 -> gr25 or fr5L + arg word 0 -> gr26 or fr4L or fr5R + + Note that fr4R and fr6R are never used for arguments (i.e., + doubles are not passed in fr4 or fr6). + + The rest of the arguments are passed on the stack starting at SP-52, + but 64-bit arguments need to be aligned to an 8-byte boundary + This means we can have holes either in the register allocation, or in the stack. */ /* ffi_prep_args is called by the assembly routine once stack space has been allocated for the function's arguments - + The following code will put everything into the stack frame (which was allocated by the asm routine), and on return the asm routine will load the arguments that should be passed by register into the appropriate registers - + NOTE: We load floating point args in this function... that means we assume gcc will not mess with fp regs in here. */ -/*@-exportheader@*/ -void ffi_prep_args_LINUX(UINT32 *stack, extended_cif *ecif, unsigned bytes) -/*@=exportheader@*/ +void ffi_prep_args_pa32(UINT32 *stack, extended_cif *ecif, unsigned bytes) { register unsigned int i; register ffi_type **p_arg; register void **p_argv; - unsigned int slot = FIRST_ARG_SLOT - 1; + unsigned int slot = FIRST_ARG_SLOT; char *dest_cpy; + size_t len; - debug(1, "%s: stack = %p, ecif = %p, bytes = %u\n", __FUNCTION__, stack, ecif, bytes); + debug(1, "%s: stack = %p, ecif = %p, bytes = %u\n", __FUNCTION__, stack, + ecif, bytes); p_arg = ecif->cif->arg_types; p_argv = ecif->avalue; @@ -130,116 +159,105 @@ switch (type) { case FFI_TYPE_SINT8: - slot++; *(SINT32 *)(stack - slot) = *(SINT8 *)(*p_argv); break; case FFI_TYPE_UINT8: - slot++; *(UINT32 *)(stack - slot) = *(UINT8 *)(*p_argv); break; case FFI_TYPE_SINT16: - slot++; *(SINT32 *)(stack - slot) = *(SINT16 *)(*p_argv); break; case FFI_TYPE_UINT16: - slot++; *(UINT32 *)(stack - slot) = *(UINT16 *)(*p_argv); break; case FFI_TYPE_UINT32: case FFI_TYPE_SINT32: case FFI_TYPE_POINTER: - slot++; - debug(3, "Storing UINT32 %u in slot %u\n", *(UINT32 *)(*p_argv), slot); + debug(3, "Storing UINT32 %u in slot %u\n", *(UINT32 *)(*p_argv), + slot); *(UINT32 *)(stack - slot) = *(UINT32 *)(*p_argv); break; case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: - slot += 2; - if (slot & 1) - slot++; - - *(UINT32 *)(stack - slot) = (*(UINT64 *)(*p_argv)) >> 32; - *(UINT32 *)(stack - slot + 1) = (*(UINT64 *)(*p_argv)) & 0xffffffffUL; + /* Align slot for 64-bit type. */ + slot += (slot & 1) ? 1 : 2; + *(UINT64 *)(stack - slot) = *(UINT64 *)(*p_argv); break; case FFI_TYPE_FLOAT: - /* First 4 args go in fr4L - fr7L */ - slot++; + /* First 4 args go in fr4L - fr7L. */ + debug(3, "Storing UINT32(float) in slot %u\n", slot); + *(UINT32 *)(stack - slot) = *(UINT32 *)(*p_argv); switch (slot - FIRST_ARG_SLOT) { - case 0: fldw(*p_argv, fr4); break; - case 1: fldw(*p_argv, fr5); break; - case 2: fldw(*p_argv, fr6); break; - case 3: fldw(*p_argv, fr7); break; - default: - /* Other ones are just passed on the stack. */ - debug(3, "Storing UINT32(float) in slot %u\n", slot); - *(UINT32 *)(stack - slot) = *(UINT32 *)(*p_argv); - break; + /* First 4 args go in fr4L - fr7L. */ + case 0: fldw(stack - slot, fr4); break; + case 1: fldw(stack - slot, fr5); break; + case 2: fldw(stack - slot, fr6); break; + case 3: fldw(stack - slot, fr7); break; } - break; + break; case FFI_TYPE_DOUBLE: - slot += 2; - if (slot & 1) - slot++; - switch (slot - FIRST_ARG_SLOT + 1) + /* Align slot for 64-bit type. */ + slot += (slot & 1) ? 1 : 2; + debug(3, "Storing UINT64(double) at slot %u\n", slot); + *(UINT64 *)(stack - slot) = *(UINT64 *)(*p_argv); + switch (slot - FIRST_ARG_SLOT) { - /* First 2 args go in fr5, fr7 */ - case 2: fldd(*p_argv, fr5); break; - case 4: fldd(*p_argv, fr7); break; - default: - debug(3, "Storing UINT64(double) at slot %u\n", slot); - *(UINT64 *)(stack - slot) = *(UINT64 *)(*p_argv); - break; + /* First 2 args go in fr5, fr7. */ + case 1: fldd(stack - slot, fr5); break; + case 3: fldd(stack - slot, fr7); break; } break; +#ifdef PA_HPUX + case FFI_TYPE_LONGDOUBLE: + /* Long doubles are passed in the same manner as structures + larger than 8 bytes. */ + *(UINT32 *)(stack - slot) = (UINT32)(*p_argv); + break; +#endif + case FFI_TYPE_STRUCT: /* Structs smaller or equal than 4 bytes are passed in one register. Structs smaller or equal 8 bytes are passed in two registers. Larger structures are passed by pointer. */ - if((*p_arg)->size <= 4) + len = (*p_arg)->size; + if (len <= 4) { - slot++; - dest_cpy = (char *)(stack - slot); - dest_cpy += 4 - (*p_arg)->size; - memcpy((char *)dest_cpy, (char *)*p_argv, (*p_arg)->size); + dest_cpy = (char *)(stack - slot) + 4 - len; + memcpy(dest_cpy, (char *)*p_argv, len); } - else if ((*p_arg)->size <= 8) + else if (len <= 8) { - slot += 2; - if (slot & 1) - slot++; - dest_cpy = (char *)(stack - slot); - dest_cpy += 8 - (*p_arg)->size; - memcpy((char *)dest_cpy, (char *)*p_argv, (*p_arg)->size); - } - else - { - slot++; - *(UINT32 *)(stack - slot) = (UINT32)(*p_argv); + slot += (slot & 1) ? 1 : 2; + dest_cpy = (char *)(stack - slot) + 8 - len; + memcpy(dest_cpy, (char *)*p_argv, len); } + else + *(UINT32 *)(stack - slot) = (UINT32)(*p_argv); break; default: FFI_ASSERT(0); } + slot++; p_arg++; p_argv++; } /* Make sure we didn't mess up and scribble on the stack. */ { - int n; + unsigned int n; debug(5, "Stack setup:\n"); for (n = 0; n < (bytes + 3) / 4; n++) @@ -255,7 +273,7 @@ return; } -static void ffi_size_stack_LINUX(ffi_cif *cif) +static void ffi_size_stack_pa32(ffi_cif *cif) { ffi_type **ptr; int i; @@ -273,6 +291,9 @@ z += 2 + (z & 1); /* must start on even regs, so we may waste one */ break; +#ifdef PA_HPUX + case FFI_TYPE_LONGDOUBLE: +#endif case FFI_TYPE_STRUCT: z += 1; /* pass by ptr, callee will copy */ break; @@ -304,6 +325,13 @@ cif->flags = (unsigned) cif->rtype->type; break; +#ifdef PA_HPUX + case FFI_TYPE_LONGDOUBLE: + /* Long doubles are treated like a structure. */ + cif->flags = FFI_TYPE_STRUCT; + break; +#endif + case FFI_TYPE_STRUCT: /* For the return type we have to check the size of the structures. If the size is smaller or equal 4 bytes, the result is given back @@ -327,8 +355,8 @@ own stack sizing. */ switch (cif->abi) { - case FFI_LINUX: - ffi_size_stack_LINUX(cif); + case FFI_PA32: + ffi_size_stack_pa32(cif); break; default: @@ -339,20 +367,11 @@ return FFI_OK; } -/*@-declundef@*/ -/*@-exportheader@*/ -extern void ffi_call_LINUX(void (*)(UINT32 *, extended_cif *, unsigned), - /*@out@*/ extended_cif *, - unsigned, unsigned, - /*@out@*/ unsigned *, - void (*fn)(void)); -/*@=declundef@*/ -/*@=exportheader@*/ - -void ffi_call(/*@dependent@*/ ffi_cif *cif, - void (*fn)(void), - /*@out@*/ void *rvalue, - /*@dependent@*/ void **avalue) +extern void ffi_call_pa32(void (*)(UINT32 *, extended_cif *, unsigned), + extended_cif *, unsigned, unsigned, unsigned *, + void (*fn)(void)); + +void ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) { extended_cif ecif; @@ -362,12 +381,15 @@ /* If the return value is a struct and we don't have a return value address then we need to make one. */ - if ((rvalue == NULL) && - (cif->rtype->type == FFI_TYPE_STRUCT)) + if (rvalue == NULL +#ifdef PA_HPUX + && (cif->rtype->type == FFI_TYPE_STRUCT + || cif->rtype->type == FFI_TYPE_LONGDOUBLE)) +#else + && cif->rtype->type == FFI_TYPE_STRUCT) +#endif { - /*@-sysunrecog@*/ ecif.rvalue = alloca(cif->rtype->size); - /*@=sysunrecog@*/ } else ecif.rvalue = rvalue; @@ -375,12 +397,10 @@ switch (cif->abi) { - case FFI_LINUX: - /*@-usedef@*/ - debug(2, "Calling ffi_call_LINUX: ecif=%p, bytes=%u, flags=%u, rvalue=%p, fn=%p\n", &ecif, cif->bytes, cif->flags, ecif.rvalue, (void *)fn); - ffi_call_LINUX(ffi_prep_args_LINUX, &ecif, cif->bytes, + case FFI_PA32: + debug(3, "Calling ffi_call_pa32: ecif=%p, bytes=%u, flags=%u, rvalue=%p, fn=%p\n", &ecif, cif->bytes, cif->flags, ecif.rvalue, (void *)fn); + ffi_call_pa32(ffi_prep_args_pa32, &ecif, cif->bytes, cif->flags, ecif.rvalue, fn); - /*@=usedef@*/ break; default: @@ -394,7 +414,7 @@ the stack, and we need to fill them into a cif structure and invoke the user function. This really ought to be in asm to make sure the compiler doesn't do things we don't expect. */ -UINT32 ffi_closure_inner_LINUX(ffi_closure *closure, UINT32 *stack) +ffi_status ffi_closure_inner_pa32(ffi_closure *closure, UINT32 *stack) { ffi_cif *cif; void **avalue; @@ -402,7 +422,8 @@ UINT32 ret[2]; /* function can return up to 64-bits in registers */ ffi_type **p_arg; char *tmp; - int i, avn, slot = FIRST_ARG_SLOT - 1; + int i, avn; + unsigned int slot = FIRST_ARG_SLOT; register UINT32 r28 asm("r28"); cif = closure->cif; @@ -430,20 +451,23 @@ case FFI_TYPE_SINT32: case FFI_TYPE_UINT32: case FFI_TYPE_POINTER: - slot++; avalue[i] = (char *)(stack - slot) + sizeof(UINT32) - (*p_arg)->size; break; case FFI_TYPE_SINT64: case FFI_TYPE_UINT64: - slot += 2; - if (slot & 1) - slot++; + slot += (slot & 1) ? 1 : 2; avalue[i] = (void *)(stack - slot); break; case FFI_TYPE_FLOAT: - slot++; +#ifdef PA_LINUX + /* The closure call is indirect. In Linux, floating point + arguments in indirect calls with a prototype are passed + in the floating point registers instead of the general + registers. So, we need to replace what was previously + stored in the current slot with the value in the + corresponding floating point register. */ switch (slot - FIRST_ARG_SLOT) { case 0: fstw(fr4, (void *)(stack - slot)); break; @@ -451,18 +475,20 @@ case 2: fstw(fr6, (void *)(stack - slot)); break; case 3: fstw(fr7, (void *)(stack - slot)); break; } +#endif avalue[i] = (void *)(stack - slot); break; case FFI_TYPE_DOUBLE: - slot += 2; - if (slot & 1) - slot++; - switch (slot - FIRST_ARG_SLOT + 1) + slot += (slot & 1) ? 1 : 2; +#ifdef PA_LINUX + /* See previous comment for FFI_TYPE_FLOAT. */ + switch (slot - FIRST_ARG_SLOT) { - case 2: fstd(fr5, (void *)(stack - slot)); break; - case 4: fstd(fr7, (void *)(stack - slot)); break; + case 1: fstd(fr5, (void *)(stack - slot)); break; + case 3: fstd(fr7, (void *)(stack - slot)); break; } +#endif avalue[i] = (void *)(stack - slot); break; @@ -470,35 +496,36 @@ /* Structs smaller or equal than 4 bytes are passed in one register. Structs smaller or equal 8 bytes are passed in two registers. Larger structures are passed by pointer. */ - if((*p_arg)->size <= 4) { - slot++; - avalue[i] = (void *)(stack - slot) + sizeof(UINT32) - - (*p_arg)->size; - } else if ((*p_arg)->size <= 8) { - slot += 2; - if (slot & 1) - slot++; - avalue[i] = (void *)(stack - slot) + sizeof(UINT64) - - (*p_arg)->size; - } else { - slot++; + if((*p_arg)->size <= 4) + { + avalue[i] = (void *)(stack - slot) + sizeof(UINT32) - + (*p_arg)->size; + } + else if ((*p_arg)->size <= 8) + { + slot += (slot & 1) ? 1 : 2; + avalue[i] = (void *)(stack - slot) + sizeof(UINT64) - + (*p_arg)->size; + } + else avalue[i] = (void *) *(stack - slot); - } break; default: FFI_ASSERT(0); } + slot++; p_arg++; } /* Invoke the closure. */ (closure->fun) (cif, rvalue, avalue, closure->user_data); - debug(3, "after calling function, ret[0] = %08x, ret[1] = %08x\n", ret[0], ret[1]); + debug(3, "after calling function, ret[0] = %08x, ret[1] = %08x\n", ret[0], + ret[1]); - /* Store the result */ + /* Store the result using the lower 2 bytes of the flags. */ switch (cif->flags) { case FFI_TYPE_UINT8: @@ -536,7 +563,9 @@ /* Don't need a return value, done by caller. */ break; + case FFI_TYPE_SMALL_STRUCT2: case FFI_TYPE_SMALL_STRUCT3: + case FFI_TYPE_SMALL_STRUCT4: tmp = (void*)(stack - FIRST_ARG_SLOT); tmp += 4 - cif->rtype->size; memcpy((void*)tmp, &ret[0], cif->rtype->size); @@ -545,6 +574,7 @@ case FFI_TYPE_SMALL_STRUCT5: case FFI_TYPE_SMALL_STRUCT6: case FFI_TYPE_SMALL_STRUCT7: + case FFI_TYPE_SMALL_STRUCT8: { unsigned int ret2[2]; int off; @@ -582,39 +612,93 @@ cif specifies the argument and result types for fun. The cif must already be prep'ed. */ -void ffi_closure_LINUX(void); +extern void ffi_closure_pa32(void); ffi_status -ffi_prep_closure (ffi_closure* closure, - ffi_cif* cif, - void (*fun)(ffi_cif*,void*,void**,void*), - void *user_data) +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + void *codeloc) { UINT32 *tramp = (UINT32 *)(closure->tramp); +#ifdef PA_HPUX + UINT32 *tmp; +#endif - FFI_ASSERT (cif->abi == FFI_LINUX); + FFI_ASSERT (cif->abi == FFI_PA32); /* Make a small trampoline that will branch to our handler function. Use PC-relative addressing. */ - tramp[0] = 0xeaa00000; /* b,l .+8, %r21 ; %r21 <- pc+8 */ - tramp[1] = 0xd6a01c1e; /* depi 0,31,2, %r21 ; mask priv bits */ - tramp[2] = 0x4aa10028; /* ldw 20(%r21), %r1 ; load plabel */ - tramp[3] = 0x36b53ff1; /* ldo -8(%r21), %r21 ; get closure addr */ - tramp[4] = 0x0c201096; /* ldw 0(%r1), %r22 ; address of handler */ - tramp[5] = 0xeac0c000; /* bv %r0(%r22) ; branch to handler */ - tramp[6] = 0x0c281093; /* ldw 4(%r1), %r19 ; GP of handler */ - tramp[7] = ((UINT32)(ffi_closure_LINUX) & ~2); +#ifdef PA_LINUX + tramp[0] = 0xeaa00000; /* b,l .+8,%r21 ; %r21 <- pc+8 */ + tramp[1] = 0xd6a01c1e; /* depi 0,31,2,%r21 ; mask priv bits */ + tramp[2] = 0x4aa10028; /* ldw 20(%r21),%r1 ; load plabel */ + tramp[3] = 0x36b53ff1; /* ldo -8(%r21),%r21 ; get closure addr */ + tramp[4] = 0x0c201096; /* ldw 0(%r1),%r22 ; address of handler */ + tramp[5] = 0xeac0c000; /* bv%r0(%r22) ; branch to handler */ + tramp[6] = 0x0c281093; /* ldw 4(%r1),%r19 ; GP of handler */ + tramp[7] = ((UINT32)(ffi_closure_pa32) & ~2); /* Flush d/icache -- have to flush up 2 two lines because of alignment. */ - asm volatile ( - "fdc 0(%0)\n" - "fdc %1(%0)\n" - "fic 0(%%sr4, %0)\n" - "fic %1(%%sr4, %0)\n" - "sync\n" - : : "r"((unsigned long)tramp & ~31), "r"(32 /* stride */)); + __asm__ volatile( + "fdc 0(%0)\n\t" + "fdc %1(%0)\n\t" + "fic 0(%%sr4, %0)\n\t" + "fic %1(%%sr4, %0)\n\t" + "sync\n\t" + "nop\n\t" + "nop\n\t" + "nop\n\t" + "nop\n\t" + "nop\n\t" + "nop\n\t" + "nop\n" + : + : "r"((unsigned long)tramp & ~31), + "r"(32 /* stride */) + : "memory"); +#endif + +#ifdef PA_HPUX + tramp[0] = 0xeaa00000; /* b,l .+8,%r21 ; %r21 <- pc+8 */ + tramp[1] = 0xd6a01c1e; /* depi 0,31,2,%r21 ; mask priv bits */ + tramp[2] = 0x4aa10038; /* ldw 28(%r21),%r1 ; load plabel */ + tramp[3] = 0x36b53ff1; /* ldo -8(%r21),%r21 ; get closure addr */ + tramp[4] = 0x0c201096; /* ldw 0(%r1),%r22 ; address of handler */ + tramp[5] = 0x02c010b4; /* ldsid (%r22),%r20 ; load space id */ + tramp[6] = 0x00141820; /* mtsp %r20,%sr0 ; into %sr0 */ + tramp[7] = 0xe2c00000; /* be 0(%sr0,%r22) ; branch to handler */ + tramp[8] = 0x0c281093; /* ldw 4(%r1),%r19 ; GP of handler */ + tramp[9] = ((UINT32)(ffi_closure_pa32) & ~2); + + /* Flush d/icache -- have to flush three lines because of alignment. */ + __asm__ volatile( + "copy %1,%0\n\t" + "fdc,m %2(%0)\n\t" + "fdc,m %2(%0)\n\t" + "fdc,m %2(%0)\n\t" + "ldsid (%1),%0\n\t" + "mtsp %0,%%sr0\n\t" + "copy %1,%0\n\t" + "fic,m %2(%%sr0,%0)\n\t" + "fic,m %2(%%sr0,%0)\n\t" + "fic,m %2(%%sr0,%0)\n\t" + "sync\n\t" + "nop\n\t" + "nop\n\t" + "nop\n\t" + "nop\n\t" + "nop\n\t" + "nop\n\t" + "nop\n" + : "=&r" ((unsigned long)tmp) + : "r" ((unsigned long)tramp & ~31), + "r" (32/* stride */) + : "memory"); +#endif closure->cif = cif; closure->user_data = user_data; Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/pa/ffitarget.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/pa/ffitarget.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/pa/ffitarget.h Wed Apr 30 15:57:13 2008 @@ -13,13 +13,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ @@ -35,9 +36,20 @@ typedef enum ffi_abi { FFI_FIRST_ABI = 0, -#ifdef PA - FFI_LINUX, - FFI_DEFAULT_ABI = FFI_LINUX, +#ifdef PA_LINUX + FFI_PA32, + FFI_DEFAULT_ABI = FFI_PA32, +#endif + +#ifdef PA_HPUX + FFI_PA32, + FFI_DEFAULT_ABI = FFI_PA32, +#endif + +#ifdef PA64_HPUX +#error "PA64_HPUX FFI is not yet implemented" + FFI_PA64, + FFI_DEFAULT_ABI = FFI_PA64, #endif FFI_LAST_ABI = FFI_DEFAULT_ABI + 1 @@ -49,11 +61,17 @@ #define FFI_CLOSURES 1 #define FFI_NATIVE_RAW_API 0 +#ifdef PA_LINUX #define FFI_TRAMPOLINE_SIZE 32 - -#define FFI_TYPE_SMALL_STRUCT3 -1 -#define FFI_TYPE_SMALL_STRUCT5 -2 -#define FFI_TYPE_SMALL_STRUCT6 -3 -#define FFI_TYPE_SMALL_STRUCT7 -4 +#else +#define FFI_TRAMPOLINE_SIZE 40 #endif +#define FFI_TYPE_SMALL_STRUCT2 -1 +#define FFI_TYPE_SMALL_STRUCT3 -2 +#define FFI_TYPE_SMALL_STRUCT4 -3 +#define FFI_TYPE_SMALL_STRUCT5 -4 +#define FFI_TYPE_SMALL_STRUCT6 -5 +#define FFI_TYPE_SMALL_STRUCT7 -6 +#define FFI_TYPE_SMALL_STRUCT8 -7 +#endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/pa/linux.S ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/pa/linux.S (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/pa/linux.S Wed Apr 30 15:57:13 2008 @@ -1,5 +1,6 @@ /* ----------------------------------------------------------------------- linux.S - (c) 2003-2004 Randolph Chung + (c) 2008 Red Hat, Inc. HPPA Foreign Function Interface @@ -17,7 +18,7 @@ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR + IN NO EVENT SHALL RENESAS TECHNOLOGY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. @@ -31,20 +32,20 @@ .level 1.1 .align 4 - /* void ffi_call_LINUX(void (*)(char *, extended_cif *), + /* void ffi_call_pa32(void (*)(char *, extended_cif *), extended_cif *ecif, unsigned bytes, unsigned flags, unsigned *rvalue, - void (*fn)()); + void (*fn)(void)); */ - .export ffi_call_LINUX,code - .import ffi_prep_args_LINUX,code + .export ffi_call_pa32,code + .import ffi_prep_args_pa32,code - .type ffi_call_LINUX, @function + .type ffi_call_pa32, @function .LFB1: -ffi_call_LINUX: +ffi_call_pa32: .proc .callinfo FRAME=64,CALLS,SAVE_RP,SAVE_SP,ENTRY_GR=4 .entry @@ -63,7 +64,7 @@ [ 64-bytes register save area ] <- %r4 [ Stack space for actual call, passed as ] <- %arg0 - [ arg0 to ffi_prep_args_LINUX ] + [ arg0 to ffi_prep_args_pa32 ] [ Stack for calling prep_args ] <- %sp */ @@ -73,14 +74,14 @@ .LCFI13: copy %sp, %r4 - addl %arg2, %r4, %arg0 /* arg stack */ - stw %arg3, -48(%r3) /* save flags; we need it later */ + addl %arg2, %r4, %arg0 /* arg stack */ + stw %arg3, -48(%r3) /* save flags; we need it later */ /* Call prep_args: %arg0(stack) -- set up above %arg1(ecif) -- same as incoming param %arg2(bytes) -- same as incoming param */ - bl ffi_prep_args_LINUX,%r2 + bl ffi_prep_args_pa32,%r2 ldo 64(%arg0), %sp ldo -64(%sp), %sp @@ -106,90 +107,139 @@ /* Store the result according to the return type. */ -checksmst3: - comib,<>,n FFI_TYPE_SMALL_STRUCT3, %r21, checksmst567 - /* 3-byte structs are returned in ret0 as ??xxyyzz. Shift - left 8 bits to write to the result structure. */ - zdep %ret0, 23, 24, %r22 - b done - stw %r22, 0(%r20) - -checksmst567: - /* 5-7 byte values are returned right justified: +.Lcheckint: + comib,<>,n FFI_TYPE_INT, %r21, .Lcheckint8 + b .Ldone + stw %ret0, 0(%r20) + +.Lcheckint8: + comib,<>,n FFI_TYPE_UINT8, %r21, .Lcheckint16 + b .Ldone + stb %ret0, 0(%r20) + +.Lcheckint16: + comib,<>,n FFI_TYPE_UINT16, %r21, .Lcheckdbl + b .Ldone + sth %ret0, 0(%r20) + +.Lcheckdbl: + comib,<>,n FFI_TYPE_DOUBLE, %r21, .Lcheckfloat + b .Ldone + fstd %fr4,0(%r20) + +.Lcheckfloat: + comib,<>,n FFI_TYPE_FLOAT, %r21, .Lcheckll + b .Ldone + fstw %fr4L,0(%r20) + +.Lcheckll: + comib,<>,n FFI_TYPE_UINT64, %r21, .Lchecksmst2 + stw %ret0, 0(%r20) + b .Ldone + stw %ret1, 4(%r20) + +.Lchecksmst2: + comib,<>,n FFI_TYPE_SMALL_STRUCT2, %r21, .Lchecksmst3 + /* 2-byte structs are returned in ret0 as ????xxyy. */ + extru %ret0, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + b .Ldone + stb %ret0, 0(%r20) + +.Lchecksmst3: + comib,<>,n FFI_TYPE_SMALL_STRUCT3, %r21, .Lchecksmst4 + /* 3-byte structs are returned in ret0 as ??xxyyzz. */ + extru %ret0, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret0, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + b .Ldone + stb %ret0, 0(%r20) + +.Lchecksmst4: + comib,<>,n FFI_TYPE_SMALL_STRUCT4, %r21, .Lchecksmst5 + /* 4-byte structs are returned in ret0 as wwxxyyzz. */ + extru %ret0, 7, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret0, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret0, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + b .Ldone + stb %ret0, 0(%r20) + +.Lchecksmst5: + comib,<>,n FFI_TYPE_SMALL_STRUCT5, %r21, .Lchecksmst6 + /* 5 byte values are returned right justified: + ret0 ret1 + 5: ??????aa bbccddee */ + stbs,ma %ret0, 1(%r20) + extru %ret1, 7, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + b .Ldone + stb %ret1, 0(%r20) + +.Lchecksmst6: + comib,<>,n FFI_TYPE_SMALL_STRUCT6, %r21, .Lchecksmst7 + /* 6 byte values are returned right justified: + ret0 ret1 + 6: ????aabb ccddeeff */ + extru %ret0, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + stbs,ma %ret0, 1(%r20) + extru %ret1, 7, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + b .Ldone + stb %ret1, 0(%r20) + +.Lchecksmst7: + comib,<>,n FFI_TYPE_SMALL_STRUCT7, %r21, .Lchecksmst8 + /* 7 byte values are returned right justified: ret0 ret1 - 5: ??????aa bbccddee - 6: ????aabb ccddeeff - 7: ??aabbcc ddeeffgg - - To store this in the result, write the first 4 bytes into a temp - register using shrpw (t1 = aabbccdd), followed by a rotation of - ret1: - - ret0 ret1 ret1 - 5: ??????aa bbccddee -> eebbccdd (rotate 8) - 6: ????aabb ccddeeff -> eeffccdd (rotate 16) - 7: ??aabbcc ddeeffgg -> eeffggdd (rotate 24) - - then we write (t1, ret1) into the result. */ - - addi,<> -FFI_TYPE_SMALL_STRUCT5,%r21,%r0 - ldi 8, %r22 - addi,<> -FFI_TYPE_SMALL_STRUCT6,%r21,%r0 - ldi 16, %r22 - addi,<> -FFI_TYPE_SMALL_STRUCT7,%r21,%r0 - ldi 24, %r22 - - /* This relies on all the FFI_TYPE_*_STRUCT* defines being <0 */ - cmpib,<=,n 0, %r21, checkint8 - mtsar %r22 - - shrpw %ret0, %ret1, %sar, %ret0 /* ret0 = aabbccdd */ - shrpw %ret1, %ret1, %sar, %ret1 /* rotate ret1 */ - - stw %ret0, 0(%r20) - b done - stw %ret1, 4(%r20) - -checkint8: - comib,<>,n FFI_TYPE_UINT8, %r21, checkint16 - b done - stb %ret0, 0(%r20) - -checkint16: - comib,<>,n FFI_TYPE_UINT16, %r21, checkint32 - b done - sth %ret0, 0(%r20) - -checkint32: - comib,<>,n FFI_TYPE_UINT32, %r21, checkint - b done - stw %ret0, 0(%r20) - -checkint: - comib,<>,n FFI_TYPE_INT, %r21, checkll - b done - stw %ret0, 0(%r20) - -checkll: - comib,<>,n FFI_TYPE_UINT64, %r21, checkdbl - stw %ret0, 0(%r20) - b done - stw %ret1, 4(%r20) - -checkdbl: - comib,<>,n FFI_TYPE_DOUBLE, %r21, checkfloat - b done - fstd %fr4,0(%r20) - -checkfloat: - comib,<>,n FFI_TYPE_FLOAT, %r21, done - fstw %fr4L,0(%r20) - - /* structure returns are either handled by one of the - INT/UINT64 cases above, or, if passed by pointer, - is handled by the callee. */ + 7: ??aabbcc ddeeffgg */ + extru %ret0, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret0, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + stbs,ma %ret0, 1(%r20) + extru %ret1, 7, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + b .Ldone + stb %ret1, 0(%r20) + +.Lchecksmst8: + comib,<>,n FFI_TYPE_SMALL_STRUCT8, %r21, .Ldone + /* 8 byte values are returned right justified: + ret0 ret1 + 8: aabbccdd eeffgghh */ + extru %ret0, 7, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret0, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret0, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + stbs,ma %ret0, 1(%r20) + extru %ret1, 7, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + stb %ret1, 0(%r20) -done: +.Ldone: /* all done, return */ copy %r4, %sp /* pop arg stack */ ldw 12(%r3), %r4 @@ -201,14 +251,14 @@ .procend .LFE1: - /* void ffi_closure_LINUX(void); + /* void ffi_closure_pa32(void); Called with closure argument in %r21 */ - .export ffi_closure_LINUX,code - .import ffi_closure_inner_LINUX,code + .export ffi_closure_pa32,code + .import ffi_closure_inner_pa32,code - .type ffi_closure_LINUX, @function + .type ffi_closure_pa32, @function .LFB2: -ffi_closure_LINUX: +ffi_closure_pa32: .proc .callinfo FRAME=64,CALLS,SAVE_RP,SAVE_SP,ENTRY_GR=3 .entry @@ -228,7 +278,7 @@ stw %arg3, -48(%r3) copy %r21, %arg0 - bl ffi_closure_inner_LINUX, %r2 + bl ffi_closure_inner_pa32, %r2 copy %r3, %arg1 ldwm -64(%sp), %r3 @@ -299,7 +349,7 @@ .sleb128 -5 .byte 0x4 ;# DW_CFA_advance_loc4 - .word .LCFI12-.LCFI11 + .word .LCFI22-.LCFI21 .byte 0xd ;# DW_CFA_def_cfa_register = r3 .uleb128 0x3 Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/darwin.S ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/darwin.S (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/darwin.S Wed Apr 30 15:57:13 2008 @@ -1,4 +1,3 @@ -#ifdef __ppc__ /* ----------------------------------------------------------------------- darwin.S - Copyright (c) 2000 John Hornkvist Copyright (c) 2004 Free Software Foundation, Inc. @@ -244,4 +243,3 @@ .align LOG2_GPR_BYTES LLFB0$non_lazy_ptr: .g_long LFB0 -#endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/darwin_closure.S ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/darwin_closure.S (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/darwin_closure.S Wed Apr 30 15:57:13 2008 @@ -1,4 +1,3 @@ -#ifdef __ppc__ /* ----------------------------------------------------------------------- darwin_closure.S - Copyright (c) 2002, 2003, 2004, Free Software Foundation, Inc. based on ppc_closure.S @@ -247,7 +246,7 @@ /* END(ffi_closure_ASM) */ .data -.section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms +.section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support EH_frame1: .set L$set$0,LECIE1-LSCIE1 .long L$set$0 ; Length of Common Information Entry @@ -316,4 +315,3 @@ .align LOG2_GPR_BYTES LLFB1$non_lazy_ptr: .g_long LFB1 -#endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/ffi.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/ffi.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/ffi.c Wed Apr 30 15:57:13 2008 @@ -1,5 +1,7 @@ /* ----------------------------------------------------------------------- ffi.c - Copyright (c) 1998 Geoffrey Keating + Copyright (C) 2007 Free Software Foundation, Inc + Copyright (C) 2008 Red Hat, Inc PowerPC Foreign Function Interface @@ -39,7 +41,8 @@ FLAG_RETURNS_NOTHING = 1 << (31-30), /* These go in cr7 */ FLAG_RETURNS_FP = 1 << (31-29), FLAG_RETURNS_64BITS = 1 << (31-28), - FLAG_RETURNS_128BITS = 1 << (31-27), + + FLAG_RETURNS_128BITS = 1 << (31-27), /* cr6 */ FLAG_ARG_NEEDS_COPY = 1 << (31- 7), FLAG_FP_ARGUMENTS = 1 << (31- 6), /* cr1.eq; specified by ABI */ @@ -48,10 +51,13 @@ }; /* About the SYSV ABI. */ -enum { - NUM_GPR_ARG_REGISTERS = 8, - NUM_FPR_ARG_REGISTERS = 8 -}; +unsigned int NUM_GPR_ARG_REGISTERS = 8; +#ifndef __NO_FPRS__ +unsigned int NUM_FPR_ARG_REGISTERS = 8; +#else +unsigned int NUM_FPR_ARG_REGISTERS = 0; +#endif + enum { ASM_NEEDS_REGISTERS = 4 }; /* ffi_prep_args_SYSV is called by the assembly routine once stack space @@ -80,10 +86,8 @@ */ -/*@-exportheader@*/ void ffi_prep_args_SYSV (extended_cif *ecif, unsigned *const stack) -/*@=exportheader@*/ { const unsigned bytes = ecif->cif->bytes; const unsigned flags = ecif->cif->flags; @@ -116,7 +120,7 @@ /* 'next_arg' grows up as we put parameters in it. */ valp next_arg; - int i; + int i, ii MAYBE_UNUSED; ffi_type **ptr; double double_tmp; union { @@ -134,6 +138,9 @@ size_t struct_copy_size; unsigned gprvalue; + if (ecif->cif->abi == FFI_LINUX_SOFT_FLOAT) + NUM_FPR_ARG_REGISTERS = 0; + stacktop.c = (char *) stack + bytes; gpr_base.u = stacktop.u - ASM_NEEDS_REGISTERS - NUM_GPR_ARG_REGISTERS; intarg_count = 0; @@ -165,6 +172,9 @@ switch ((*ptr)->type) { case FFI_TYPE_FLOAT: + /* With FFI_LINUX_SOFT_FLOAT floats are handled like UINT32. */ + if (ecif->cif->abi == FFI_LINUX_SOFT_FLOAT) + goto soft_float_prep; double_tmp = **p_argv.f; if (fparg_count >= NUM_FPR_ARG_REGISTERS) { @@ -178,6 +188,9 @@ break; case FFI_TYPE_DOUBLE: + /* With FFI_LINUX_SOFT_FLOAT doubles are handled like UINT64. */ + if (ecif->cif->abi == FFI_LINUX_SOFT_FLOAT) + goto soft_double_prep; double_tmp = **p_argv.d; if (fparg_count >= NUM_FPR_ARG_REGISTERS) @@ -197,8 +210,77 @@ FFI_ASSERT (flags & FLAG_FP_ARGUMENTS); break; +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: + if ((ecif->cif->abi != FFI_LINUX) + && (ecif->cif->abi != FFI_LINUX_SOFT_FLOAT)) + goto do_struct; + /* The soft float ABI for long doubles works like this, + a long double is passed in four consecutive gprs if available. + A maximum of 2 long doubles can be passed in gprs. + If we do not have 4 gprs left, the long double is passed on the + stack, 4-byte aligned. */ + if (ecif->cif->abi == FFI_LINUX_SOFT_FLOAT) + { + unsigned int int_tmp = (*p_argv.ui)[0]; + if (intarg_count >= NUM_GPR_ARG_REGISTERS - 3) + { + if (intarg_count < NUM_GPR_ARG_REGISTERS) + intarg_count += NUM_GPR_ARG_REGISTERS - intarg_count; + *next_arg.u = int_tmp; + next_arg.u++; + for (ii = 1; ii < 4; ii++) + { + int_tmp = (*p_argv.ui)[ii]; + *next_arg.u = int_tmp; + next_arg.u++; + } + } + else + { + *gpr_base.u++ = int_tmp; + for (ii = 1; ii < 4; ii++) + { + int_tmp = (*p_argv.ui)[ii]; + *gpr_base.u++ = int_tmp; + } + } + intarg_count +=4; + } + else + { + double_tmp = (*p_argv.d)[0]; + + if (fparg_count >= NUM_FPR_ARG_REGISTERS - 1) + { + if (intarg_count >= NUM_GPR_ARG_REGISTERS + && intarg_count % 2 != 0) + { + intarg_count++; + next_arg.u++; + } + *next_arg.d = double_tmp; + next_arg.u += 2; + double_tmp = (*p_argv.d)[1]; + *next_arg.d = double_tmp; + next_arg.u += 2; + } + else + { + *fpr_base.d++ = double_tmp; + double_tmp = (*p_argv.d)[1]; + *fpr_base.d++ = double_tmp; + } + + fparg_count += 2; + FFI_ASSERT (flags & FLAG_FP_ARGUMENTS); + } + break; +#endif + case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: + soft_double_prep: if (intarg_count == NUM_GPR_ARG_REGISTERS-1) intarg_count++; if (intarg_count >= NUM_GPR_ARG_REGISTERS) @@ -232,7 +314,7 @@ case FFI_TYPE_STRUCT: #if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE - case FFI_TYPE_LONGDOUBLE: + do_struct: #endif struct_copy_size = ((*ptr)->size + 15) & ~0xF; copy_space.c -= struct_copy_size; @@ -261,6 +343,8 @@ case FFI_TYPE_UINT32: case FFI_TYPE_SINT32: case FFI_TYPE_POINTER: + soft_float_prep: + gprvalue = **p_argv.ui; putgpr: @@ -322,10 +406,8 @@ */ -/*@-exportheader@*/ void FFI_HIDDEN ffi_prep_args64 (extended_cif *ecif, unsigned long *const stack) -/*@=exportheader@*/ { const unsigned long bytes = ecif->cif->bytes; const unsigned long flags = ecif->cif->flags; @@ -433,6 +515,7 @@ if (fparg_count < NUM_FPR_ARG_REGISTERS64) *fpr_base.d++ = double_tmp; fparg_count++; + FFI_ASSERT (__LDBL_MANT_DIG__ == 106); FFI_ASSERT (flags & FLAG_FP_ARGUMENTS); break; #endif @@ -515,6 +598,9 @@ unsigned type = cif->rtype->type; unsigned size = cif->rtype->size; + if (cif->abi == FFI_LINUX_SOFT_FLOAT) + NUM_FPR_ARG_REGISTERS = 0; + if (cif->abi != FFI_LINUX64) { /* All the machine-independent calculation of cif->bytes will be wrong. @@ -536,11 +622,6 @@ /* Space for the mandatory parm save area and general registers. */ bytes += 2 * NUM_GPR_ARG_REGISTERS64 * sizeof (long); - -#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE - if (type == FFI_TYPE_LONGDOUBLE) - type = FFI_TYPE_DOUBLE; -#endif } /* Return value handling. The rules for SYSV are as follows: @@ -549,19 +630,33 @@ - 64-bit integer values and structures between 5 and 8 bytes are returned in gpr3 and gpr4; - Single/double FP values are returned in fpr1; - - Larger structures and long double (if not equivalent to double) values - are allocated space and a pointer is passed as the first argument. + - Larger structures are allocated space and a pointer is passed as + the first argument. + - long doubles (if not equivalent to double) are returned in + fpr1,fpr2 for Linux and as for large structs for SysV. For LINUX64: - integer values in gpr3; - Structures/Unions by reference; - - Single/double FP values in fpr1, long double in fpr1,fpr2. */ + - Single/double FP values in fpr1, long double in fpr1,fpr2. + - soft-float float/doubles are treated as UINT32/UINT64 respectivley. + - soft-float long doubles are returned in gpr3-gpr6. */ switch (type) { +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: + if (cif->abi != FFI_LINUX && cif->abi != FFI_LINUX64 + && cif->abi != FFI_LINUX_SOFT_FLOAT) + goto byref; + flags |= FLAG_RETURNS_128BITS; + /* Fall through. */ +#endif case FFI_TYPE_DOUBLE: flags |= FLAG_RETURNS_64BITS; /* Fall through. */ case FFI_TYPE_FLOAT: - flags |= FLAG_RETURNS_FP; + /* With FFI_LINUX_SOFT_FLOAT no fp registers are used. */ + if (cif->abi != FFI_LINUX_SOFT_FLOAT) + flags |= FLAG_RETURNS_FP; break; case FFI_TYPE_UINT64: @@ -598,15 +693,8 @@ } } } - /* else fall through. */ #if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE - case FFI_TYPE_LONGDOUBLE: - if (type == FFI_TYPE_LONGDOUBLE && cif->abi == FFI_LINUX64) - { - flags |= FLAG_RETURNS_128BITS; - flags |= FLAG_RETURNS_FP; - break; - } + byref: #endif intarg_count++; flags |= FLAG_RETVAL_REFERENCE; @@ -631,11 +719,36 @@ switch ((*ptr)->type) { case FFI_TYPE_FLOAT: + /* With FFI_LINUX_SOFT_FLOAT floats are handled like UINT32. */ + if (cif->abi == FFI_LINUX_SOFT_FLOAT) + goto soft_float_cif; fparg_count++; /* floating singles are not 8-aligned on stack */ break; +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: + if (cif->abi != FFI_LINUX && cif->abi != FFI_LINUX_SOFT_FLOAT) + goto do_struct; + if (cif->abi == FFI_LINUX_SOFT_FLOAT) + { + if (intarg_count >= NUM_GPR_ARG_REGISTERS - 3 + || intarg_count < NUM_GPR_ARG_REGISTERS) + /* A long double in FFI_LINUX_SOFT_FLOAT can use only + a set of four consecutive gprs. If we have not enough, + we have to adjust the intarg_count value. */ + intarg_count += NUM_GPR_ARG_REGISTERS - intarg_count; + intarg_count += 4; + break; + } + else + fparg_count++; + /* Fall thru */ +#endif case FFI_TYPE_DOUBLE: + /* With FFI_LINUX_SOFT_FLOAT doubles are handled like UINT64. */ + if (cif->abi == FFI_LINUX_SOFT_FLOAT) + goto soft_double_cif; fparg_count++; /* If this FP arg is going on the stack, it must be 8-byte-aligned. */ @@ -647,6 +760,7 @@ case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: + soft_double_cif: /* 'long long' arguments are passed as two words, but either both words must fit in registers or both go on the stack. If they go on the stack, they must @@ -664,7 +778,7 @@ case FFI_TYPE_STRUCT: #if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE - case FFI_TYPE_LONGDOUBLE: + do_struct: #endif /* We must allocate space for a copy of these to enforce pass-by-value. Pad the space up to a multiple of 16 @@ -674,6 +788,7 @@ /* Fall through (allocate space for the pointer). */ default: + soft_float_cif: /* Everything else is passed as a 4-byte word in a GPR, either the object itself or a pointer to it. */ intarg_count++; @@ -687,8 +802,13 @@ { #if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE case FFI_TYPE_LONGDOUBLE: - fparg_count += 2; - intarg_count += 2; + if (cif->abi == FFI_LINUX_SOFT_FLOAT) + intarg_count += 4; + else + { + fparg_count += 2; + intarg_count += 2; + } break; #endif case FFI_TYPE_FLOAT: @@ -751,24 +871,14 @@ return FFI_OK; } -/*@-declundef@*/ -/*@-exportheader@*/ -extern void ffi_call_SYSV(/*@out@*/ extended_cif *, - unsigned, unsigned, - /*@out@*/ unsigned *, +extern void ffi_call_SYSV(extended_cif *, unsigned, unsigned, unsigned *, void (*fn)(void)); -extern void FFI_HIDDEN ffi_call_LINUX64(/*@out@*/ extended_cif *, - unsigned long, unsigned long, - /*@out@*/ unsigned long *, +extern void FFI_HIDDEN ffi_call_LINUX64(extended_cif *, unsigned long, + unsigned long, unsigned long *, void (*fn)(void)); -/*@=declundef@*/ -/*@=exportheader@*/ void -ffi_call(/*@dependent@*/ ffi_cif *cif, - void (*fn)(void), - /*@out@*/ void *rvalue, - /*@dependent@*/ void **avalue) +ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) { extended_cif ecif; @@ -780,9 +890,7 @@ if ((rvalue == NULL) && (cif->rtype->type == FFI_TYPE_STRUCT)) { - /*@-sysunrecog@*/ ecif.rvalue = alloca(cif->rtype->size); - /*@=sysunrecog@*/ } else ecif.rvalue = rvalue; @@ -793,15 +901,13 @@ #ifndef POWERPC64 case FFI_SYSV: case FFI_GCC_SYSV: - /*@-usedef@*/ + case FFI_LINUX: + case FFI_LINUX_SOFT_FLOAT: ffi_call_SYSV (&ecif, -cif->bytes, cif->flags, ecif.rvalue, fn); - /*@=usedef@*/ break; #else case FFI_LINUX64: - /*@-usedef@*/ ffi_call_LINUX64 (&ecif, -(long) cif->bytes, cif->flags, ecif.rvalue, fn); - /*@=usedef@*/ break; #endif default: @@ -815,27 +921,24 @@ #define MIN_CACHE_LINE_SIZE 8 static void -flush_icache (char *addr1, int size) +flush_icache (char *wraddr, char *xaddr, int size) { int i; - char * addr; for (i = 0; i < size; i += MIN_CACHE_LINE_SIZE) - { - addr = addr1 + i; - __asm__ volatile ("icbi 0,%0;" "dcbf 0,%0;" - : : "r" (addr) : "memory"); - } - addr = addr1 + size - 1; - __asm__ volatile ("icbi 0,%0;" "dcbf 0,%0;" "sync;" "isync;" - : : "r"(addr) : "memory"); + __asm__ volatile ("icbi 0,%0;" "dcbf 0,%1;" + : : "r" (xaddr + i), "r" (wraddr + i) : "memory"); + __asm__ volatile ("icbi 0,%0;" "dcbf 0,%1;" "sync;" "isync;" + : : "r"(xaddr + size - 1), "r"(wraddr + size - 1) + : "memory"); } #endif ffi_status -ffi_prep_closure (ffi_closure *closure, - ffi_cif *cif, - void (*fun) (ffi_cif *, void *, void **, void *), - void *user_data) +ffi_prep_closure_loc (ffi_closure *closure, + ffi_cif *cif, + void (*fun) (ffi_cif *, void *, void **, void *), + void *user_data, + void *codeloc) { #ifdef POWERPC64 void **tramp = (void **) &closure->tramp[0]; @@ -843,7 +946,7 @@ FFI_ASSERT (cif->abi == FFI_LINUX64); /* Copy function address and TOC from ffi_closure_LINUX64. */ memcpy (tramp, (char *) ffi_closure_LINUX64, 16); - tramp[2] = (void *) closure; + tramp[2] = codeloc; #else unsigned int *tramp; @@ -859,10 +962,10 @@ tramp[8] = 0x7c0903a6; /* mtctr r0 */ tramp[9] = 0x4e800420; /* bctr */ *(void **) &tramp[2] = (void *) ffi_closure_SYSV; /* function */ - *(void **) &tramp[3] = (void *) closure; /* context */ + *(void **) &tramp[3] = codeloc; /* context */ /* Flush the icache. */ - flush_icache (&closure->tramp[0],FFI_TRAMPOLINE_SIZE); + flush_icache ((char *)tramp, (char *)codeloc, FFI_TRAMPOLINE_SIZE); #endif closure->cif = cif; @@ -920,14 +1023,17 @@ For FFI_SYSV the result is passed in r3/r4 if the struct size is less or equal 8 bytes. */ - if (cif->rtype->type == FFI_TYPE_STRUCT) + if ((cif->rtype->type == FFI_TYPE_STRUCT + && !((cif->abi == FFI_SYSV) && (size <= 8))) +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + || (cif->rtype->type == FFI_TYPE_LONGDOUBLE + && cif->abi != FFI_LINUX && cif->abi != FFI_LINUX_SOFT_FLOAT) +#endif + ) { - if (!((cif->abi == FFI_SYSV) && (size <= 8))) - { - rvalue = (void *) *pgr; - ng++; - pgr++; - } + rvalue = (void *) *pgr; + ng++; + pgr++; } i = 0; @@ -974,6 +1080,7 @@ case FFI_TYPE_SINT32: case FFI_TYPE_UINT32: case FFI_TYPE_POINTER: + soft_float_closure: /* there are 8 gpr registers used to pass values */ if (ng < 8) { @@ -989,6 +1096,9 @@ break; case FFI_TYPE_STRUCT: +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + do_struct: +#endif /* Structs are passed by reference. The address will appear in a gpr if it is one of the first 8 arguments. */ if (ng < 8) @@ -1006,6 +1116,7 @@ case FFI_TYPE_SINT64: case FFI_TYPE_UINT64: + soft_double_closure: /* passing long long ints are complex, they must * be passed in suitable register pairs such as * (r3,r4) or (r5,r6) or (r6,r7), or (r7,r8) or (r9,r10) @@ -1037,6 +1148,9 @@ break; case FFI_TYPE_FLOAT: + /* With FFI_LINUX_SOFT_FLOAT floats are handled like UINT32. */ + if (cif->abi == FFI_LINUX_SOFT_FLOAT) + goto soft_float_closure; /* unfortunately float values are stored as doubles * in the ffi_closure_SYSV code (since we don't check * the type in that routine). @@ -1060,12 +1174,14 @@ * naughty thing to do but... */ avalue[i] = pst; - nf++; pst += 1; } break; case FFI_TYPE_DOUBLE: + /* With FFI_LINUX_SOFT_FLOAT doubles are handled like UINT64. */ + if (cif->abi == FFI_LINUX_SOFT_FLOAT) + goto soft_double_closure; /* On the outgoing stack all values are aligned to 8 */ /* there are 8 64bit floating point registers */ @@ -1080,11 +1196,47 @@ if (((long) pst) & 4) pst++; avalue[i] = pst; - nf++; pst += 2; } break; +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: + if (cif->abi != FFI_LINUX && cif->abi != FFI_LINUX_SOFT_FLOAT) + goto do_struct; + if (cif->abi == FFI_LINUX_SOFT_FLOAT) + { /* Test if for the whole long double, 4 gprs are available. + otherwise the stuff ends up on the stack. */ + if (ng < 5) + { + avalue[i] = pgr; + pgr += 4; + ng += 4; + } + else + { + avalue[i] = pst; + pst += 4; + } + break; + } + if (nf < 7) + { + avalue[i] = pfr; + pfr += 2; + nf += 2; + } + else + { + if (((long) pst) & 4) + pst++; + avalue[i] = pst; + pst += 4; + nf = 8; + } + break; +#endif + default: FFI_ASSERT (0); } @@ -1101,8 +1253,36 @@ if (cif->abi == FFI_SYSV && cif->rtype->type == FFI_TYPE_STRUCT && size <= 8) return FFI_SYSV_TYPE_SMALL_STRUCT + size; - return cif->rtype->type; - +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + else if (cif->rtype->type == FFI_TYPE_LONGDOUBLE + && cif->abi != FFI_LINUX && cif->abi != FFI_LINUX_SOFT_FLOAT) + return FFI_TYPE_STRUCT; +#endif + /* With FFI_LINUX_SOFT_FLOAT floats and doubles are handled like UINT32 + respectivley UINT64. */ + if (cif->abi == FFI_LINUX_SOFT_FLOAT) + { + switch (cif->rtype->type) + { + case FFI_TYPE_FLOAT: + return FFI_TYPE_UINT32; + break; + case FFI_TYPE_DOUBLE: + return FFI_TYPE_UINT64; + break; +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: + return FFI_TYPE_UINT128; + break; +#endif + default: + return cif->rtype->type; + } + } + else + { + return cif->rtype->type; + } } int FFI_HIDDEN ffi_closure_helper_LINUX64 (ffi_closure *, void *, Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/ffi_darwin.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/ffi_darwin.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/ffi_darwin.c Wed Apr 30 15:57:13 2008 @@ -1,12 +1,12 @@ -#if !(defined(__APPLE__) && !defined(__ppc__)) /* ----------------------------------------------------------------------- - ffi.c - Copyright (c) 1998 Geoffrey Keating + ffi_darwin.c - PowerPC Foreign Function Interface - - Darwin ABI support (c) 2001 John Hornkvist - AIX ABI support (c) 2002 Free Software Foundation, Inc. + Copyright (C) 1998 Geoffrey Keating + Copyright (C) 2001 John Hornkvist + Copyright (C) 2002, 2006, 2007 Free Software Foundation, Inc. + FFI support for Darwin and AIX. + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ``Software''), to deal in the Software without restriction, including @@ -80,9 +80,7 @@ */ -/*@-exportheader@*/ void ffi_prep_args(extended_cif *ecif, unsigned *const stack) -/*@=exportheader@*/ { const unsigned bytes = ecif->cif->bytes; const unsigned flags = ecif->cif->flags; @@ -228,6 +226,48 @@ //FFI_ASSERT(flags & FLAG_4_GPR_ARGUMENTS || intarg_count <= 4); } +/* Adjust the size of S to be correct for Darwin. + On Darwin, the first field of a structure has natural alignment. */ + +static void +darwin_adjust_aggregate_sizes (ffi_type *s) +{ + int i; + + if (s->type != FFI_TYPE_STRUCT) + return; + + s->size = 0; + for (i = 0; s->elements[i] != NULL; i++) + { + ffi_type *p; + int align; + + p = s->elements[i]; + darwin_adjust_aggregate_sizes (p); + if (i == 0 + && (p->type == FFI_TYPE_UINT64 + || p->type == FFI_TYPE_SINT64 + || p->type == FFI_TYPE_DOUBLE + || p->alignment == 8)) + align = 8; + else if (p->alignment == 16 || p->alignment < 4) + align = p->alignment; + else + align = 4; + s->size = ALIGN(s->size, align) + p->size; + } + + s->size = ALIGN(s->size, s->alignment); + + if (s->elements[0]->type == FFI_TYPE_UINT64 + || s->elements[0]->type == FFI_TYPE_SINT64 + || s->elements[0]->type == FFI_TYPE_DOUBLE + || s->elements[0]->alignment == 8) + s->alignment = s->alignment > 8 ? s->alignment : 8; + /* Do not add additional tail padding. */ +} + /* Perform machine dependent cif processing. */ ffi_status ffi_prep_cif_machdep(ffi_cif *cif) { @@ -240,8 +280,16 @@ unsigned size_al = 0; /* All the machine-independent calculation of cif->bytes will be wrong. + All the calculation of structure sizes will also be wrong. Redo the calculation for DARWIN. */ + if (cif->abi == FFI_DARWIN) + { + darwin_adjust_aggregate_sizes (cif->rtype); + for (i = 0; i < cif->nargs; i++) + darwin_adjust_aggregate_sizes (cif->arg_types[i]); + } + /* Space for the frame pointer, callee's LR, CR, etc, and for the asm's temp regs. */ @@ -376,25 +424,12 @@ return FFI_OK; } -/*@-declundef@*/ -/*@-exportheader@*/ -extern void ffi_call_AIX(/*@out@*/ extended_cif *, - unsigned, unsigned, - /*@out@*/ unsigned *, - void (*fn)(void), - void (*fn2)(extended_cif *, unsigned *const)); -extern void ffi_call_DARWIN(/*@out@*/ extended_cif *, - unsigned, unsigned, - /*@out@*/ unsigned *, - void (*fn)(void), - void (*fn2)(extended_cif *, unsigned *const)); -/*@=declundef@*/ -/*@=exportheader@*/ - -void ffi_call(/*@dependent@*/ ffi_cif *cif, - void (*fn)(void), - /*@out@*/ void *rvalue, - /*@dependent@*/ void **avalue) +extern void ffi_call_AIX(extended_cif *, unsigned, unsigned, unsigned *, + void (*fn)(void), void (*fn2)(void)); +extern void ffi_call_DARWIN(extended_cif *, unsigned, unsigned, unsigned *, + void (*fn)(void), void (*fn2)(void)); + +void ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) { extended_cif ecif; @@ -407,9 +442,7 @@ if ((rvalue == NULL) && (cif->rtype->type == FFI_TYPE_STRUCT)) { - /*@-sysunrecog@*/ ecif.rvalue = alloca(cif->rtype->size); - /*@=sysunrecog@*/ } else ecif.rvalue = rvalue; @@ -417,16 +450,12 @@ switch (cif->abi) { case FFI_AIX: - /*@-usedef@*/ - ffi_call_AIX(&ecif, -cif->bytes, - cif->flags, ecif.rvalue, fn, ffi_prep_args); - /*@=usedef@*/ + ffi_call_AIX(&ecif, -cif->bytes, cif->flags, ecif.rvalue, fn, + ffi_prep_args); break; case FFI_DARWIN: - /*@-usedef@*/ - ffi_call_DARWIN(&ecif, -cif->bytes, - cif->flags, ecif.rvalue, fn, ffi_prep_args); - /*@=usedef@*/ + ffi_call_DARWIN(&ecif, -cif->bytes, cif->flags, ecif.rvalue, fn, + ffi_prep_args); break; default: FFI_ASSERT(0); @@ -499,10 +528,11 @@ */ ffi_status -ffi_prep_closure (ffi_closure* closure, - ffi_cif* cif, - void (*fun)(ffi_cif*, void*, void**, void*), - void *user_data) +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + void *codeloc) { unsigned int *tramp; struct ffi_aix_trampoline_struct *tramp_aix; @@ -524,14 +554,14 @@ tramp[8] = 0x816b0004; /* lwz r11,4(r11) static chain */ tramp[9] = 0x4e800420; /* bctr */ tramp[2] = (unsigned long) ffi_closure_ASM; /* function */ - tramp[3] = (unsigned long) closure; /* context */ + tramp[3] = (unsigned long) codeloc; /* context */ closure->cif = cif; closure->fun = fun; closure->user_data = user_data; /* Flush the icache. Only necessary on Darwin. */ - flush_range(&closure->tramp[0],FFI_TRAMPOLINE_SIZE); + flush_range(codeloc, FFI_TRAMPOLINE_SIZE); break; @@ -544,7 +574,7 @@ tramp_aix->code_pointer = fd->code_pointer; tramp_aix->toc = fd->toc; - tramp_aix->static_chain = closure; + tramp_aix->static_chain = codeloc; closure->cif = cif; closure->fun = fun; closure->user_data = user_data; @@ -768,4 +798,3 @@ /* Tell ffi_closure_ASM to perform return type promotions. */ return cif->rtype->type; } -#endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/ffitarget.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/ffitarget.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/ffitarget.h Wed Apr 30 15:57:13 2008 @@ -1,5 +1,6 @@ /* -----------------------------------------------------------------*-C-*- ffitarget.h - Copyright (c) 1996-2003 Red Hat, Inc. + Copyright (C) 2007 Free Software Foundation, Inc Target configuration macros for PowerPC. Permission is hereby granted, free of charge, to any person obtaining @@ -13,13 +14,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ @@ -43,10 +45,20 @@ FFI_SYSV, FFI_GCC_SYSV, FFI_LINUX64, + FFI_LINUX, + FFI_LINUX_SOFT_FLOAT, # ifdef POWERPC64 FFI_DEFAULT_ABI = FFI_LINUX64, # else +# if (!defined(__NO_FPRS__) && (__LDBL_MANT_DIG__ == 106)) + FFI_DEFAULT_ABI = FFI_LINUX, +# else +# ifdef __NO_FPRS__ + FFI_DEFAULT_ABI = FFI_LINUX_SOFT_FLOAT, +# else FFI_DEFAULT_ABI = FFI_GCC_SYSV, +# endif +# endif # endif #endif @@ -69,7 +81,7 @@ FFI_DEFAULT_ABI = FFI_SYSV, #endif - FFI_LAST_ABI = FFI_DEFAULT_ABI + 1 + FFI_LAST_ABI } ffi_abi; #endif @@ -78,8 +90,14 @@ #define FFI_CLOSURES 1 #define FFI_NATIVE_RAW_API 0 +/* For additional types like the below, take care about the order in + ppc_closures.S. They must follow after the FFI_TYPE_LAST. */ + +/* Needed for soft-float long-double-128 support. */ +#define FFI_TYPE_UINT128 (FFI_TYPE_LAST + 1) + /* Needed for FFI_SYSV small structure returns. */ -#define FFI_SYSV_TYPE_SMALL_STRUCT (FFI_TYPE_LAST) +#define FFI_SYSV_TYPE_SMALL_STRUCT (FFI_TYPE_LAST + 2) #if defined(POWERPC64) || defined(POWERPC_AIX) #define FFI_TRAMPOLINE_SIZE 24 Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/linux64.S ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/linux64.S (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/linux64.S Wed Apr 30 15:57:13 2008 @@ -1,5 +1,6 @@ /* ----------------------------------------------------------------------- sysv.h - Copyright (c) 2003 Jakub Jelinek + Copyright (c) 2008 Red Hat, Inc. PowerPC64 Assembly glue. @@ -14,13 +15,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #define LIBFFI_ASM @@ -47,8 +49,8 @@ std %r0, 16(%r1) mr %r28, %r1 /* our AP. */ - stdux %r1, %r1, %r4 .LCFI0: + stdux %r1, %r1, %r4 mr %r31, %r5 /* flags, */ mr %r30, %r6 /* rvalue, */ mr %r29, %r7 /* function address. */ @@ -100,6 +102,10 @@ /* Make the call. */ bctrl + /* This must follow the call immediately, the unwinder + uses this to find out if r2 has been saved or not. */ + ld %r2, 40(%r1) + /* Now, deal with the return value. */ mtcrf 0x01, %r31 bt- 30, .Ldone_return_value @@ -109,7 +115,6 @@ .Ldone_return_value: /* Restore the registers we used and return. */ - ld %r2, 40(%r1) mr %r1, %r28 ld %r0, 16(%r28) ld %r28, -32(%r1) @@ -120,12 +125,10 @@ blr .Lfp_return_value: - bt 27, .Lfd_return_value bf 28, .Lfloat_return_value stfd %f1, 0(%r30) - b .Ldone_return_value -.Lfd_return_value: - stfd %f1, 0(%r30) + mtcrf 0x02, %r31 /* cr6 */ + bf 27, .Ldone_return_value stfd %f2, 8(%r30) b .Ldone_return_value .Lfloat_return_value: @@ -178,3 +181,7 @@ .align 3 .LEFDE1: #endif + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"", at progbits +#endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/linux64_closure.S ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/linux64_closure.S (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/linux64_closure.S Wed Apr 30 15:57:13 2008 @@ -1,3 +1,29 @@ +/* ----------------------------------------------------------------------- + sysv.h - Copyright (c) 2003 Jakub Jelinek + Copyright (c) 2008 Red Hat, Inc. + + PowerPC64 Assembly glue. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ #define LIBFFI_ASM #include #include @@ -204,3 +230,7 @@ .align 3 .LEFDE1: #endif + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"", at progbits +#endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/ppc_closure.S ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/ppc_closure.S (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/ppc_closure.S Wed Apr 30 15:57:13 2008 @@ -1,3 +1,29 @@ +/* ----------------------------------------------------------------------- + sysv.h - Copyright (c) 2003 Jakub Jelinek + Copyright (c) 2008 Red Hat, Inc. + + PowerPC Assembly glue. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ #define LIBFFI_ASM #include #include @@ -28,6 +54,7 @@ stw %r9, 40(%r1) stw %r10,44(%r1) +#ifndef __NO_FPRS__ # next save fpr 1 to fpr 8 (aligned to 8) stfd %f1, 48(%r1) stfd %f2, 56(%r1) @@ -37,6 +64,7 @@ stfd %f6, 88(%r1) stfd %f7, 96(%r1) stfd %f8, 104(%r1) +#endif # set up registers for the routine that actually does the work # get the context pointer from the trampoline @@ -58,218 +86,190 @@ # make the call bl ffi_closure_helper_SYSV at local - +.Lret: # now r3 contains the return type # so use it to look up in a table # so we know how to deal with each type # look up the proper starting point in table # by using return type as offset - addi %r6,%r1,112 # get pointer to results area - bl .Lget_ret_type0_addr # get pointer to .Lret_type0 into LR - mflr %r4 # move to r4 - slwi %r3,%r3,4 # now multiply return type by 16 - add %r3,%r3,%r4 # add contents of table to table address + + mflr %r4 # move address of .Lret to r4 + slwi %r3,%r3,4 # now multiply return type by 16 + addi %r4, %r4, .Lret_type0 - .Lret + lwz %r0,148(%r1) + add %r3,%r3,%r4 # add contents of table to table address mtctr %r3 - bctr # jump to it + bctr # jump to it .LFE1: # Each of the ret_typeX code fragments has to be exactly 16 bytes long # (4 instructions). For cache effectiveness we align to a 16 byte boundary # first. .align 4 - - nop - nop - nop -.Lget_ret_type0_addr: - blrl - # case FFI_TYPE_VOID .Lret_type0: - b .Lfinish - nop - nop + mtlr %r0 + addi %r1,%r1,144 + blr nop # case FFI_TYPE_INT -.Lret_type1: - lwz %r3,0(%r6) - b .Lfinish - nop - nop + lwz %r3,112+0(%r1) + mtlr %r0 +.Lfinish: + addi %r1,%r1,144 + blr # case FFI_TYPE_FLOAT -.Lret_type2: - lfs %f1,0(%r6) - b .Lfinish - nop - nop + lfs %f1,112+0(%r1) + mtlr %r0 + addi %r1,%r1,144 + blr # case FFI_TYPE_DOUBLE -.Lret_type3: - lfd %f1,0(%r6) - b .Lfinish - nop - nop + lfd %f1,112+0(%r1) + mtlr %r0 + addi %r1,%r1,144 + blr # case FFI_TYPE_LONGDOUBLE -.Lret_type4: - lfd %f1,0(%r6) + lfd %f1,112+0(%r1) + lfd %f2,112+8(%r1) + mtlr %r0 b .Lfinish - nop - nop # case FFI_TYPE_UINT8 -.Lret_type5: - lbz %r3,3(%r6) - b .Lfinish - nop - nop + lbz %r3,112+3(%r1) + mtlr %r0 + addi %r1,%r1,144 + blr # case FFI_TYPE_SINT8 -.Lret_type6: - lbz %r3,3(%r6) + lbz %r3,112+3(%r1) extsb %r3,%r3 + mtlr %r0 b .Lfinish - nop # case FFI_TYPE_UINT16 -.Lret_type7: - lhz %r3,2(%r6) - b .Lfinish - nop - nop + lhz %r3,112+2(%r1) + mtlr %r0 + addi %r1,%r1,144 + blr # case FFI_TYPE_SINT16 -.Lret_type8: - lha %r3,2(%r6) - b .Lfinish - nop - nop + lha %r3,112+2(%r1) + mtlr %r0 + addi %r1,%r1,144 + blr # case FFI_TYPE_UINT32 -.Lret_type9: - lwz %r3,0(%r6) - b .Lfinish - nop - nop + lwz %r3,112+0(%r1) + mtlr %r0 + addi %r1,%r1,144 + blr # case FFI_TYPE_SINT32 -.Lret_type10: - lwz %r3,0(%r6) - b .Lfinish - nop - nop + lwz %r3,112+0(%r1) + mtlr %r0 + addi %r1,%r1,144 + blr # case FFI_TYPE_UINT64 -.Lret_type11: - lwz %r3,0(%r6) - lwz %r4,4(%r6) + lwz %r3,112+0(%r1) + lwz %r4,112+4(%r1) + mtlr %r0 b .Lfinish - nop # case FFI_TYPE_SINT64 -.Lret_type12: - lwz %r3,0(%r6) - lwz %r4,4(%r6) + lwz %r3,112+0(%r1) + lwz %r4,112+4(%r1) + mtlr %r0 b .Lfinish - nop # case FFI_TYPE_STRUCT -.Lret_type13: - b .Lfinish - nop - nop + mtlr %r0 + addi %r1,%r1,144 + blr nop # case FFI_TYPE_POINTER -.Lret_type14: - lwz %r3,0(%r6) - b .Lfinish - nop - nop + lwz %r3,112+0(%r1) + mtlr %r0 + addi %r1,%r1,144 + blr + +# case FFI_TYPE_UINT128 + lwz %r3,112+0(%r1) + lwz %r4,112+4(%r1) + lwz %r5,112+8(%r1) + bl .Luint128 # The return types below are only used when the ABI type is FFI_SYSV. # case FFI_SYSV_TYPE_SMALL_STRUCT + 1. One byte struct. -.Lret_type15: -# fall through. - lbz %r3,0(%r6) - b .Lfinish - nop - nop + lbz %r3,112+0(%r1) + mtlr %r0 + addi %r1,%r1,144 + blr # case FFI_SYSV_TYPE_SMALL_STRUCT + 2. Two byte struct. -.Lret_type16: -# fall through. - lhz %r3,0(%r6) - b .Lfinish - nop - nop + lhz %r3,112+0(%r1) + mtlr %r0 + addi %r1,%r1,144 + blr # case FFI_SYSV_TYPE_SMALL_STRUCT + 3. Three byte struct. -.Lret_type17: -# fall through. - lwz %r3,0(%r6) + lwz %r3,112+0(%r1) srwi %r3,%r3,8 + mtlr %r0 b .Lfinish - nop # case FFI_SYSV_TYPE_SMALL_STRUCT + 4. Four byte struct. -.Lret_type18: -# this one handles the structs from above too. - lwz %r3,0(%r6) - b .Lfinish - nop - nop + lwz %r3,112+0(%r1) + mtlr %r0 + addi %r1,%r1,144 + blr # case FFI_SYSV_TYPE_SMALL_STRUCT + 5. Five byte struct. -.Lret_type19: -# fall through. - lwz %r3,0(%r6) - lwz %r4,4(%r6) + lwz %r3,112+0(%r1) + lwz %r4,112+4(%r1) li %r5,24 b .Lstruct567 # case FFI_SYSV_TYPE_SMALL_STRUCT + 6. Six byte struct. -.Lret_type20: -# fall through. - lwz %r3,0(%r6) - lwz %r4,4(%r6) + lwz %r3,112+0(%r1) + lwz %r4,112+4(%r1) li %r5,16 b .Lstruct567 # case FFI_SYSV_TYPE_SMALL_STRUCT + 7. Seven byte struct. -.Lret_type21: -# fall through. - lwz %r3,0(%r6) - lwz %r4,4(%r6) + lwz %r3,112+0(%r1) + lwz %r4,112+4(%r1) li %r5,8 b .Lstruct567 # case FFI_SYSV_TYPE_SMALL_STRUCT + 8. Eight byte struct. -.Lret_type22: -# this one handles the above unhandled structs. - lwz %r3,0(%r6) - lwz %r4,4(%r6) + lwz %r3,112+0(%r1) + lwz %r4,112+4(%r1) + mtlr %r0 b .Lfinish - nop -# case done -.Lfinish: +.Lstruct567: + subfic %r6,%r5,32 + srw %r4,%r4,%r5 + slw %r6,%r3,%r6 + srw %r3,%r3,%r5 + or %r4,%r6,%r4 + mtlr %r0 + addi %r1,%r1,144 + blr - lwz %r0,148(%r1) +.Luint128: + lwz %r6,112+12(%r1) mtlr %r0 addi %r1,%r1,144 blr -.Lstruct567: - subfic %r0,%r5,32 - srw %r4,%r4,%r5 - slw %r0,%r3,%r0 - srw %r3,%r3,%r5 - or %r4,%r0,%r4 - b .Lfinish END(ffi_closure_SYSV) .section ".eh_frame",EH_FRAME_FLAGS, at progbits @@ -321,3 +321,7 @@ .LEFDE1: #endif + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"", at progbits +#endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/sysv.S ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/sysv.S (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/powerpc/sysv.S Wed Apr 30 15:57:13 2008 @@ -1,5 +1,6 @@ /* ----------------------------------------------------------------------- - sysv.h - Copyright (c) 1998 Geoffrey Keating + sysv.S - Copyright (c) 1998 Geoffrey Keating + Copyright (C) 2007 Free Software Foundation, Inc PowerPC Assembly glue. @@ -14,13 +15,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #define LIBFFI_ASM @@ -98,13 +100,17 @@ bctrl /* Now, deal with the return value. */ - mtcrf 0x01,%r31 + mtcrf 0x01,%r31 /* cr7 */ bt- 31,L(small_struct_return_value) bt- 30,L(done_return_value) bt- 29,L(fp_return_value) stw %r3,0(%r30) bf+ 28,L(done_return_value) stw %r4,4(%r30) + mtcrf 0x02,%r31 /* cr6 */ + bf 27,L(done_return_value) + stw %r5,8(%r30) + stw %r6,12(%r30) /* Fall through... */ L(done_return_value): @@ -121,6 +127,9 @@ L(fp_return_value): bf 28,L(float_return_value) stfd %f1,0(%r30) + mtcrf 0x02,%r31 /* cr6 */ + bf 27,L(done_return_value) + stfd %f2,8(%r30) b L(done_return_value) L(float_return_value): stfs %f1,0(%r30) @@ -215,3 +224,7 @@ .align 2 .LEFDE1: #endif + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"", at progbits +#endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/prep_cif.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/prep_cif.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/prep_cif.c Wed Apr 30 15:57:13 2008 @@ -1,5 +1,5 @@ /* ----------------------------------------------------------------------- - prep_cif.c - Copyright (c) 1996, 1998 Red Hat, Inc. + prep_cif.c - Copyright (c) 1996, 1998, 2007 Red Hat, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the @@ -12,20 +12,20 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #include #include #include - /* Round up to FFI_SIZEOF_ARG. */ #define STACK_ARG_SIZE(x) ALIGN(x, FFI_SIZEOF_ARG) @@ -33,14 +33,12 @@ /* Perform machine independent initialization of aggregate type specifications. */ -static ffi_status initialize_aggregate(/*@out@*/ ffi_type *arg) +static ffi_status initialize_aggregate(ffi_type *arg) { - ffi_type **ptr; + ffi_type **ptr; FFI_ASSERT(arg != NULL); - /*@-usedef@*/ - FFI_ASSERT(arg->elements != NULL); FFI_ASSERT(arg->size == 0); FFI_ASSERT(arg->alignment == 0); @@ -51,33 +49,15 @@ { if (((*ptr)->size == 0) && (initialize_aggregate((*ptr)) != FFI_OK)) return FFI_BAD_TYPEDEF; - + /* Perform a sanity check on the argument type */ FFI_ASSERT_VALID_TYPE(*ptr); -#ifdef POWERPC_DARWIN - { - int curalign; - - curalign = (*ptr)->alignment; - if (ptr != &(arg->elements[0])) { - if (curalign > 4 && curalign != 16) { - curalign = 4; - } - } - arg->size = ALIGN(arg->size, curalign); - arg->size += (*ptr)->size; - - arg->alignment = (arg->alignment > curalign) ? - arg->alignment : curalign; - } -#else arg->size = ALIGN(arg->size, (*ptr)->alignment); arg->size += (*ptr)->size; - arg->alignment = (arg->alignment > (*ptr)->alignment) ? + arg->alignment = (arg->alignment > (*ptr)->alignment) ? arg->alignment : (*ptr)->alignment; -#endif ptr++; } @@ -95,8 +75,6 @@ return FFI_BAD_TYPEDEF; else return FFI_OK; - - /*@=usedef@*/ } #ifndef __CRIS__ @@ -107,23 +85,8 @@ /* Perform machine independent ffi_cif preparation, then call machine dependent routine. */ -#ifdef X86_DARWIN -static inline int struct_on_stack(int size) -{ - if (size > 8) return 1; - /* This is not what the ABI says, but is what is really implemented */ - switch (size) { - case 1: case 2: case 4: case 8: return 0; - } - return 1; -} -#endif - - -ffi_status ffi_prep_cif(/*@out@*/ /*@partial@*/ ffi_cif *cif, - ffi_abi abi, unsigned int nargs, - /*@dependent@*/ /*@out@*/ /*@partial@*/ ffi_type *rtype, - /*@dependent@*/ ffi_type **atypes) +ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi, unsigned int nargs, + ffi_type *rtype, ffi_type **atypes) { unsigned bytes = 0; unsigned int i; @@ -140,10 +103,8 @@ cif->flags = 0; /* Initialize the return type if necessary */ - /*@-usedef@*/ if ((cif->rtype->size == 0) && (initialize_aggregate(cif->rtype) != FFI_OK)) return FFI_BAD_TYPEDEF; - /*@=usedef@*/ /* Perform a sanity check on the return type */ FFI_ASSERT_VALID_TYPE(cif->rtype); @@ -156,10 +117,9 @@ && (cif->abi != FFI_V9 || cif->rtype->size > 32) #endif #ifdef X86_DARWIN - - && (struct_on_stack(cif->rtype->size)) + && (cif->rtype->size > 8) #endif - ) + ) bytes = STACK_ARG_SIZE(sizeof(void*)); #endif @@ -170,20 +130,11 @@ if (((*ptr)->size == 0) && (initialize_aggregate((*ptr)) != FFI_OK)) return FFI_BAD_TYPEDEF; - /* Perform a sanity check on the argument type, do this + /* Perform a sanity check on the argument type, do this check after the initialization. */ FFI_ASSERT_VALID_TYPE(*ptr); -#if defined(X86_DARWIN) - { - int align = (*ptr)->alignment; - if (align > 4) align = 4; - if ((align - 1) & bytes) - bytes = ALIGN(bytes, align); - bytes += STACK_ARG_SIZE((*ptr)->size); - } - -#elif !defined __x86_64__ && !defined S390 && !defined PA +#if !defined __x86_64__ && !defined S390 && !defined PA #ifdef SPARC if (((*ptr)->type == FFI_TYPE_STRUCT && ((*ptr)->size > 16 || cif->abi != FFI_V9)) @@ -196,7 +147,7 @@ /* Add any padding if necessary */ if (((*ptr)->alignment - 1) & bytes) bytes = ALIGN(bytes, (*ptr)->alignment); - + bytes += STACK_ARG_SIZE((*ptr)->size); } #endif @@ -208,3 +159,16 @@ return ffi_prep_cif_machdep(cif); } #endif /* not __CRIS__ */ + +#if FFI_CLOSURES + +ffi_status +ffi_prep_closure (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data) +{ + return ffi_prep_closure_loc (closure, cif, fun, user_data, closure); +} + +#endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/s390/ffi.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/s390/ffi.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/s390/ffi.c Wed Apr 30 15:57:13 2008 @@ -1,5 +1,6 @@ /* ----------------------------------------------------------------------- - ffi.c - Copyright (c) 2000 Software AG + ffi.c - Copyright (c) 2000, 2007 Software AG + Copyright (c) 2008 Red Hat, Inc S390 Foreign Function Interface @@ -207,6 +208,12 @@ void *arg = *p_argv; int type = (*ptr)->type; +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + /* 16-byte long double is passed like a struct. */ + if (type == FFI_TYPE_LONGDOUBLE) + type = FFI_TYPE_STRUCT; +#endif + /* Check how a structure type is passed. */ if (type == FFI_TYPE_STRUCT) { @@ -364,6 +371,12 @@ cif->flags = FFI390_RET_DOUBLE; break; +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: + cif->flags = FFI390_RET_STRUCT; + n_gpr++; + break; +#endif /* Integer values are returned in gpr 2 (and gpr 3 for 64-bit values on 31-bit machines). */ case FFI_TYPE_UINT64: @@ -400,6 +413,12 @@ { int type = (*ptr)->type; +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + /* 16-byte long double is passed like a struct. */ + if (type == FFI_TYPE_LONGDOUBLE) + type = FFI_TYPE_STRUCT; +#endif + /* Check how a structure type is passed. */ if (type == FFI_TYPE_STRUCT) { @@ -562,6 +581,12 @@ int deref_struct_pointer = 0; int type = (*ptr)->type; +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + /* 16-byte long double is passed like a struct. */ + if (type == FFI_TYPE_LONGDOUBLE) + type = FFI_TYPE_STRUCT; +#endif + /* Check how a structure type is passed. */ if (type == FFI_TYPE_STRUCT) { @@ -662,6 +687,9 @@ /* Void is easy, and so is struct. */ case FFI_TYPE_VOID: case FFI_TYPE_STRUCT: +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: +#endif break; /* Floating point values are returned in fpr 0. */ @@ -709,17 +737,18 @@ /*====================================================================*/ /* */ -/* Name - ffi_prep_closure. */ +/* Name - ffi_prep_closure_loc. */ /* */ /* Function - Prepare a FFI closure. */ /* */ /*====================================================================*/ ffi_status -ffi_prep_closure (ffi_closure *closure, - ffi_cif *cif, - void (*fun) (ffi_cif *, void *, void **, void *), - void *user_data) +ffi_prep_closure_loc (ffi_closure *closure, + ffi_cif *cif, + void (*fun) (ffi_cif *, void *, void **, void *), + void *user_data, + void *codeloc) { FFI_ASSERT (cif->abi == FFI_SYSV); @@ -728,7 +757,7 @@ *(short *)&closure->tramp [2] = 0x9801; /* lm %r0,%r1,6(%r1) */ *(short *)&closure->tramp [4] = 0x1006; *(short *)&closure->tramp [6] = 0x07f1; /* br %r1 */ - *(long *)&closure->tramp [8] = (long)closure; + *(long *)&closure->tramp [8] = (long)codeloc; *(long *)&closure->tramp[12] = (long)&ffi_closure_SYSV; #else *(short *)&closure->tramp [0] = 0x0d10; /* basr %r1,0 */ @@ -736,7 +765,7 @@ *(short *)&closure->tramp [4] = 0x100e; *(short *)&closure->tramp [6] = 0x0004; *(short *)&closure->tramp [8] = 0x07f1; /* br %r1 */ - *(long *)&closure->tramp[16] = (long)closure; + *(long *)&closure->tramp[16] = (long)codeloc; *(long *)&closure->tramp[24] = (long)&ffi_closure_SYSV; #endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/s390/ffitarget.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/s390/ffitarget.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/s390/ffitarget.h Wed Apr 30 15:57:13 2008 @@ -13,13 +13,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/s390/sysv.S ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/s390/sysv.S (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/s390/sysv.S Wed Apr 30 15:57:13 2008 @@ -1,6 +1,7 @@ /* ----------------------------------------------------------------------- sysv.S - Copyright (c) 2000 Software AG - + Copyright (c) 2008 Red Hat, Inc. + S390 Foreign Function Interface Permission is hereby granted, free of charge, to any person obtaining @@ -14,13 +15,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #define LIBFFI_ASM @@ -427,3 +429,6 @@ #endif +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"", at progbits +#endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh/ffi.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh/ffi.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh/ffi.c Wed Apr 30 15:57:13 2008 @@ -1,5 +1,6 @@ /* ----------------------------------------------------------------------- - ffi.c - Copyright (c) 2002, 2003, 2004, 2005 Kaz Kojima + ffi.c - Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007 Kaz Kojima + Copyright (c) 2008 Red Hat, Inc. SuperH Foreign Function Interface @@ -14,13 +15,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #include @@ -106,9 +108,7 @@ /* ffi_prep_args is called by the assembly routine once stack space has been allocated for the function's arguments */ -/*@-exportheader@*/ void ffi_prep_args(char *stack, extended_cif *ecif) -/*@=exportheader@*/ { register unsigned int i; register int tmp; @@ -406,20 +406,10 @@ return FFI_OK; } -/*@-declundef@*/ -/*@-exportheader@*/ -extern void ffi_call_SYSV(void (*)(char *, extended_cif *), - /*@out@*/ extended_cif *, - unsigned, unsigned, - /*@out@*/ unsigned *, - void (*fn)()); -/*@=declundef@*/ -/*@=exportheader@*/ - -void ffi_call(/*@dependent@*/ ffi_cif *cif, - void (*fn)(), - /*@out@*/ void *rvalue, - /*@dependent@*/ void **avalue) +extern void ffi_call_SYSV(void (*)(char *, extended_cif *), extended_cif *, + unsigned, unsigned, unsigned *, void (*fn)(void)); + +void ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) { extended_cif ecif; UINT64 trvalue; @@ -436,9 +426,7 @@ else if ((rvalue == NULL) && (cif->rtype->type == FFI_TYPE_STRUCT)) { - /*@-sysunrecog@*/ ecif.rvalue = alloca(cif->rtype->size); - /*@=sysunrecog@*/ } else ecif.rvalue = rvalue; @@ -446,10 +434,8 @@ switch (cif->abi) { case FFI_SYSV: - /*@-usedef@*/ - ffi_call_SYSV(ffi_prep_args, &ecif, cif->bytes, - cif->flags, ecif.rvalue, fn); - /*@=usedef@*/ + ffi_call_SYSV(ffi_prep_args, &ecif, cif->bytes, cif->flags, ecif.rvalue, + fn); break; default: FFI_ASSERT(0); @@ -468,10 +454,11 @@ #endif ffi_status -ffi_prep_closure (ffi_closure* closure, - ffi_cif* cif, - void (*fun)(ffi_cif*, void*, void**, void*), - void *user_data) +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + void *codeloc) { unsigned int *tramp; unsigned short insn; @@ -491,7 +478,7 @@ tramp[0] = 0xd102d301; tramp[1] = 0x412b0000 | insn; #endif - *(void **) &tramp[2] = (void *)closure; /* ctx */ + *(void **) &tramp[2] = (void *)codeloc; /* ctx */ *(void **) &tramp[3] = (void *)ffi_closure_SYSV; /* funaddr */ closure->cif = cif; @@ -500,7 +487,7 @@ #if defined(__SH4__) /* Flush the icache. */ - __ic_invalidate(&closure->tramp[0]); + __ic_invalidate(codeloc); #endif return FFI_OK; @@ -535,7 +522,6 @@ int freg = 0; #endif ffi_cif *cif; - double temp; cif = closure->cif; avalue = alloca(cif->nargs * sizeof(void *)); @@ -544,7 +530,7 @@ returns the data directly to the caller. */ if (cif->rtype->type == FFI_TYPE_STRUCT && STRUCT_VALUE_ADDRESS_WITH_ARG) { - rvalue = *pgr++; + rvalue = (void *) *pgr++; ireg = 1; } else @@ -611,6 +597,8 @@ { if (freg + 1 >= NFREGARG) continue; + if (freg & 1) + pfr++; freg = (freg + 1) & ~1; freg += 2; avalue[i] = pfr; Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh/ffitarget.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh/ffitarget.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh/ffitarget.h Wed Apr 30 15:57:13 2008 @@ -13,13 +13,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh/sysv.S ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh/sysv.S (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh/sysv.S Wed Apr 30 15:57:13 2008 @@ -1,5 +1,5 @@ /* ----------------------------------------------------------------------- - sysv.S - Copyright (c) 2002, 2003, 2004 Kaz Kojima + sysv.S - Copyright (c) 2002, 2003, 2004, 2006 Kaz Kojima SuperH Foreign Function Interface @@ -17,7 +17,8 @@ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. @@ -829,13 +830,13 @@ .byte 0x6 /* uleb128 0x6 */ .byte 0x8e /* DW_CFA_offset, column 0xe */ .byte 0x5 /* uleb128 0x5 */ - .byte 0x8b /* DW_CFA_offset, column 0xb */ + .byte 0x84 /* DW_CFA_offset, column 0x4 */ .byte 0x4 /* uleb128 0x4 */ - .byte 0x8a /* DW_CFA_offset, column 0xa */ + .byte 0x85 /* DW_CFA_offset, column 0x5 */ .byte 0x3 /* uleb128 0x3 */ - .byte 0x89 /* DW_CFA_offset, column 0x9 */ + .byte 0x86 /* DW_CFA_offset, column 0x6 */ .byte 0x2 /* uleb128 0x2 */ - .byte 0x88 /* DW_CFA_offset, column 0x8 */ + .byte 0x87 /* DW_CFA_offset, column 0x7 */ .byte 0x1 /* uleb128 0x1 */ .byte 0x4 /* DW_CFA_advance_loc4 */ .4byte .LCFIE-.LCFID Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh64/ffi.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh64/ffi.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh64/ffi.c Wed Apr 30 15:57:13 2008 @@ -1,5 +1,6 @@ /* ----------------------------------------------------------------------- ffi.c - Copyright (c) 2003, 2004 Kaz Kojima + Copyright (c) 2008 Anthony Green SuperH SHmedia Foreign Function Interface @@ -14,13 +15,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #include @@ -238,12 +240,12 @@ /*@out@*/ extended_cif *, unsigned, unsigned, long long, /*@out@*/ unsigned *, - void (*fn)()); + void (*fn)(void)); /*@=declundef@*/ /*@=exportheader@*/ void ffi_call(/*@dependent@*/ ffi_cif *cif, - void (*fn)(), + void (*fn)(void), /*@out@*/ void *rvalue, /*@dependent@*/ void **avalue) { Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh64/ffitarget.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh64/ffitarget.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh64/ffitarget.h Wed Apr 30 15:57:13 2008 @@ -13,13 +13,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh64/sysv.S ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh64/sysv.S (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sh64/sysv.S Wed Apr 30 15:57:13 2008 @@ -17,7 +17,8 @@ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sparc/ffi.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sparc/ffi.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sparc/ffi.c Wed Apr 30 15:57:13 2008 @@ -1,5 +1,5 @@ /* ----------------------------------------------------------------------- - ffi.c - Copyright (c) 1996, 2003, 2004 Red Hat, Inc. + ffi.c - Copyright (c) 1996, 2003, 2004, 2007, 2008 Red Hat, Inc. SPARC Foreign Function Interface @@ -14,13 +14,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #include @@ -425,10 +426,11 @@ #endif ffi_status -ffi_prep_closure (ffi_closure* closure, - ffi_cif* cif, - void (*fun)(ffi_cif*, void*, void**, void*), - void *user_data) +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + void *codeloc) { unsigned int *tramp = (unsigned int *) &closure->tramp[0]; unsigned long fn; @@ -443,7 +445,7 @@ tramp[3] = 0x01000000; /* nop */ *((unsigned long *) &tramp[4]) = fn; #else - unsigned long ctx = (unsigned long) closure; + unsigned long ctx = (unsigned long) codeloc; FFI_ASSERT (cif->abi == FFI_V8); fn = (unsigned long) ffi_closure_v8; tramp[0] = 0x03000000 | fn >> 10; /* sethi %hi(fn), %g1 */ Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sparc/ffitarget.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sparc/ffitarget.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sparc/ffitarget.h Wed Apr 30 15:57:13 2008 @@ -13,13 +13,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sparc/v8.S ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sparc/v8.S (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sparc/v8.S Wed Apr 30 15:57:13 2008 @@ -1,5 +1,5 @@ /* ----------------------------------------------------------------------- - v8.S - Copyright (c) 1996, 1997, 2003, 2004 Red Hat, Inc. + v8.S - Copyright (c) 1996, 1997, 2003, 2004, 2008 Red Hat, Inc. SPARC Foreign Function Interface @@ -14,13 +14,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #define LIBFFI_ASM @@ -265,3 +266,7 @@ .byte 0x1f ! uleb128 0x1f .align WS .LLEFDE2: + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"", at progbits +#endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sparc/v9.S ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sparc/v9.S (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/sparc/v9.S Wed Apr 30 15:57:13 2008 @@ -1,5 +1,5 @@ /* ----------------------------------------------------------------------- - v9.S - Copyright (c) 2000, 2003, 2004 Red Hat, Inc. + v9.S - Copyright (c) 2000, 2003, 2004, 2008 Red Hat, Inc. SPARC 64-bit Foreign Function Interface @@ -14,13 +14,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #define LIBFFI_ASM @@ -300,3 +301,7 @@ .align 8 .LLEFDE2: #endif + +#ifdef __linux__ + .section .note.GNU-stack,"", at progbits +#endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/darwin.S ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/darwin.S (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/darwin.S Wed Apr 30 15:57:13 2008 @@ -1,8 +1,8 @@ -#ifdef __i386__ /* ----------------------------------------------------------------------- - darwin.S - Copyright (c) 1996, 1998, 2001, 2002, 2003 Red Hat, Inc. - - X86 Foreign Function Interface + darwin.S - Copyright (c) 1996, 1998, 2001, 2002, 2003, 2005 Red Hat, Inc. + Copyright (C) 2008 Free Software Foundation, Inc. + + X86 Foreign Function Interface Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the @@ -18,16 +18,12 @@ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ - -/* - * This file is based on sysv.S and then hacked up by Ronald who hasn't done - * assembly programming in 8 years. - */ #ifndef __x86_64__ @@ -35,18 +31,11 @@ #include #include -#ifdef PyObjC_STRICT_DEBUGGING - /* XXX: Debugging of stack alignment, to be removed */ -#define ASSERT_STACK_ALIGNED movdqa -16(%esp), %xmm0 -#else -#define ASSERT_STACK_ALIGNED -#endif - .text .globl _ffi_prep_args -.align 4 + .align 4 .globl _ffi_call_SYSV _ffi_call_SYSV: @@ -54,15 +43,12 @@ pushl %ebp .LCFI0: movl %esp,%ebp - subl $8,%esp - ASSERT_STACK_ALIGNED .LCFI1: + subl $8,%esp /* Make room for all of the new args. */ movl 16(%ebp),%ecx subl %ecx,%esp - ASSERT_STACK_ALIGNED - movl %esp,%eax /* Place all of the ffi_prep_args in position */ @@ -71,27 +57,20 @@ pushl %eax call *8(%ebp) - ASSERT_STACK_ALIGNED - /* Return stack to previous state and call the function */ - addl $16,%esp - - ASSERT_STACK_ALIGNED + addl $16,%esp call *28(%ebp) - - /* XXX: return returns return with 'ret $4', that upsets the stack! */ - movl 16(%ebp),%ecx - addl %ecx,%esp - /* Load %ecx with the return type code */ movl 20(%ebp),%ecx + /* Protect %esi. We're going to pop it in the epilogue. */ + pushl %esi /* If the return value pointer is NULL, assume no return value. */ cmpl $0,24(%ebp) - jne retint + jne 0f /* Even if there is no space for the return value, we are obliged to handle floating-point values. */ @@ -99,145 +78,366 @@ jne noretval fstp %st(0) - jmp epilogue - -retint: - cmpl $FFI_TYPE_INT,%ecx - jne retfloat - /* Load %ecx with the pointer to storage for the return value */ - movl 24(%ebp),%ecx - movl %eax,0(%ecx) jmp epilogue +0: + .align 4 + call 1f +.Lstore_table: + .long noretval-.Lstore_table /* FFI_TYPE_VOID */ + .long retint-.Lstore_table /* FFI_TYPE_INT */ + .long retfloat-.Lstore_table /* FFI_TYPE_FLOAT */ + .long retdouble-.Lstore_table /* FFI_TYPE_DOUBLE */ + .long retlongdouble-.Lstore_table /* FFI_TYPE_LONGDOUBLE */ + .long retuint8-.Lstore_table /* FFI_TYPE_UINT8 */ + .long retsint8-.Lstore_table /* FFI_TYPE_SINT8 */ + .long retuint16-.Lstore_table /* FFI_TYPE_UINT16 */ + .long retsint16-.Lstore_table /* FFI_TYPE_SINT16 */ + .long retint-.Lstore_table /* FFI_TYPE_UINT32 */ + .long retint-.Lstore_table /* FFI_TYPE_SINT32 */ + .long retint64-.Lstore_table /* FFI_TYPE_UINT64 */ + .long retint64-.Lstore_table /* FFI_TYPE_SINT64 */ + .long retstruct-.Lstore_table /* FFI_TYPE_STRUCT */ + .long retint-.Lstore_table /* FFI_TYPE_POINTER */ + .long retstruct1b-.Lstore_table /* FFI_TYPE_SMALL_STRUCT_1B */ + .long retstruct2b-.Lstore_table /* FFI_TYPE_SMALL_STRUCT_2B */ +1: + pop %esi + add (%esi, %ecx, 4), %esi + jmp *%esi + + /* Sign/zero extend as appropriate. */ +retsint8: + movsbl %al, %eax + jmp retint + +retsint16: + movswl %ax, %eax + jmp retint + +retuint8: + movzbl %al, %eax + jmp retint + +retuint16: + movzwl %ax, %eax + jmp retint retfloat: - cmpl $FFI_TYPE_FLOAT,%ecx - jne retdouble /* Load %ecx with the pointer to storage for the return value */ - movl 24(%ebp),%ecx + movl 24(%ebp),%ecx fstps (%ecx) jmp epilogue retdouble: - cmpl $FFI_TYPE_DOUBLE,%ecx - jne retlongdouble /* Load %ecx with the pointer to storage for the return value */ - movl 24(%ebp),%ecx + movl 24(%ebp),%ecx fstpl (%ecx) jmp epilogue retlongdouble: - cmpl $FFI_TYPE_LONGDOUBLE,%ecx - jne retint64 /* Load %ecx with the pointer to storage for the return value */ - movl 24(%ebp),%ecx + movl 24(%ebp),%ecx fstpt (%ecx) jmp epilogue - -retint64: - cmpl $FFI_TYPE_SINT64,%ecx - jne retstruct1b + +retint64: /* Load %ecx with the pointer to storage for the return value */ - movl 24(%ebp),%ecx + movl 24(%ebp),%ecx movl %eax,0(%ecx) movl %edx,4(%ecx) jmp epilogue retstruct1b: - cmpl $FFI_TYPE_SINT8,%ecx - jne retstruct2b - movl 24(%ebp),%ecx - movb %al,0(%ecx) - jmp epilogue + /* Load %ecx with the pointer to storage for the return value */ + movl 24(%ebp),%ecx + movb %al,0(%ecx) + jmp epilogue retstruct2b: - cmpl $FFI_TYPE_SINT16,%ecx - jne retstruct - movl 24(%ebp),%ecx - movw %ax,0(%ecx) - jmp epilogue - -retstruct: - cmpl $FFI_TYPE_STRUCT,%ecx - jne noretval - /* Nothing to do! */ - - subl $4,%esp + /* Load %ecx with the pointer to storage for the return value */ + movl 24(%ebp),%ecx + movw %ax,0(%ecx) + jmp epilogue - ASSERT_STACK_ALIGNED +retint: + /* Load %ecx with the pointer to storage for the return value */ + movl 24(%ebp),%ecx + movl %eax,0(%ecx) - addl $8,%esp - movl %ebp, %esp - popl %ebp - ret +retstruct: + /* Nothing to do! */ noretval: epilogue: - ASSERT_STACK_ALIGNED - addl $8, %esp - + popl %esi + movl %ebp,%esp + popl %ebp + ret - movl %ebp,%esp - popl %ebp - ret .LFE1: .ffi_call_SYSV_end: -#if 0 - .size ffi_call_SYSV,.ffi_call_SYSV_end-ffi_call_SYSV -#endif -#if 0 - .section .eh_frame,EH_FRAME_FLAGS, at progbits -.Lframe1: - .long .LECIE1-.LSCIE1 /* Length of Common Information Entry */ -.LSCIE1: - .long 0x0 /* CIE Identifier Tag */ - .byte 0x1 /* CIE Version */ -#ifdef __PIC__ - .ascii "zR\0" /* CIE Augmentation */ -#else - .ascii "\0" /* CIE Augmentation */ -#endif - .byte 0x1 /* .uleb128 0x1; CIE Code Alignment Factor */ - .byte 0x7c /* .sleb128 -4; CIE Data Alignment Factor */ - .byte 0x8 /* CIE RA Column */ -#ifdef __PIC__ - .byte 0x1 /* .uleb128 0x1; Augmentation size */ - .byte 0x1b /* FDE Encoding (pcrel sdata4) */ -#endif - .byte 0xc /* DW_CFA_def_cfa */ - .byte 0x4 /* .uleb128 0x4 */ - .byte 0x4 /* .uleb128 0x4 */ - .byte 0x88 /* DW_CFA_offset, column 0x8 */ - .byte 0x1 /* .uleb128 0x1 */ - .align 4 -.LECIE1: -.LSFDE1: - .long .LEFDE1-.LASFDE1 /* FDE Length */ -.LASFDE1: - .long .LASFDE1-.Lframe1 /* FDE CIE offset */ -#ifdef __PIC__ - .long .LFB1-. /* FDE initial location */ -#else - .long .LFB1 /* FDE initial location */ -#endif - .long .LFE1-.LFB1 /* FDE address range */ -#ifdef __PIC__ - .byte 0x0 /* .uleb128 0x0; Augmentation size */ + .align 4 +FFI_HIDDEN (ffi_closure_SYSV) +.globl _ffi_closure_SYSV + +_ffi_closure_SYSV: +.LFB2: + pushl %ebp +.LCFI2: + movl %esp, %ebp +.LCFI3: + subl $40, %esp + leal -24(%ebp), %edx + movl %edx, -12(%ebp) /* resp */ + leal 8(%ebp), %edx + movl %edx, 4(%esp) /* args = __builtin_dwarf_cfa () */ + leal -12(%ebp), %edx + movl %edx, (%esp) /* &resp */ + movl %ebx, 8(%esp) +.LCFI7: + call L_ffi_closure_SYSV_inner$stub + movl 8(%esp), %ebx + movl -12(%ebp), %ecx + cmpl $FFI_TYPE_INT, %eax + je .Lcls_retint + + /* Handle FFI_TYPE_UINT8, FFI_TYPE_SINT8, FFI_TYPE_UINT16, + FFI_TYPE_SINT16, FFI_TYPE_UINT32, FFI_TYPE_SINT32. */ + cmpl $FFI_TYPE_UINT64, %eax + jge 0f + cmpl $FFI_TYPE_UINT8, %eax + jge .Lcls_retint + +0: cmpl $FFI_TYPE_FLOAT, %eax + je .Lcls_retfloat + cmpl $FFI_TYPE_DOUBLE, %eax + je .Lcls_retdouble + cmpl $FFI_TYPE_LONGDOUBLE, %eax + je .Lcls_retldouble + cmpl $FFI_TYPE_SINT64, %eax + je .Lcls_retllong + cmpl $FFI_TYPE_SMALL_STRUCT_1B, %eax + je .Lcls_retstruct1b + cmpl $FFI_TYPE_SMALL_STRUCT_2B, %eax + je .Lcls_retstruct2b + cmpl $FFI_TYPE_STRUCT, %eax + je .Lcls_retstruct +.Lcls_epilogue: + movl %ebp, %esp + popl %ebp + ret +.Lcls_retint: + movl (%ecx), %eax + jmp .Lcls_epilogue +.Lcls_retfloat: + flds (%ecx) + jmp .Lcls_epilogue +.Lcls_retdouble: + fldl (%ecx) + jmp .Lcls_epilogue +.Lcls_retldouble: + fldt (%ecx) + jmp .Lcls_epilogue +.Lcls_retllong: + movl (%ecx), %eax + movl 4(%ecx), %edx + jmp .Lcls_epilogue +.Lcls_retstruct1b: + movsbl (%ecx), %eax + jmp .Lcls_epilogue +.Lcls_retstruct2b: + movswl (%ecx), %eax + jmp .Lcls_epilogue +.Lcls_retstruct: + lea -8(%ebp),%esp + movl %ebp, %esp + popl %ebp + ret $4 +.LFE2: + +#if !FFI_NO_RAW_API + +#define RAW_CLOSURE_CIF_OFFSET ((FFI_TRAMPOLINE_SIZE + 3) & ~3) +#define RAW_CLOSURE_FUN_OFFSET (RAW_CLOSURE_CIF_OFFSET + 4) +#define RAW_CLOSURE_USER_DATA_OFFSET (RAW_CLOSURE_FUN_OFFSET + 4) +#define CIF_FLAGS_OFFSET 20 + + .align 4 +FFI_HIDDEN (ffi_closure_raw_SYSV) +.globl _ffi_closure_raw_SYSV + +_ffi_closure_raw_SYSV: +.LFB3: + pushl %ebp +.LCFI4: + movl %esp, %ebp +.LCFI5: + pushl %esi +.LCFI6: + subl $36, %esp + movl RAW_CLOSURE_CIF_OFFSET(%eax), %esi /* closure->cif */ + movl RAW_CLOSURE_USER_DATA_OFFSET(%eax), %edx /* closure->user_data */ + movl %edx, 12(%esp) /* user_data */ + leal 8(%ebp), %edx /* __builtin_dwarf_cfa () */ + movl %edx, 8(%esp) /* raw_args */ + leal -24(%ebp), %edx + movl %edx, 4(%esp) /* &res */ + movl %esi, (%esp) /* cif */ + call *RAW_CLOSURE_FUN_OFFSET(%eax) /* closure->fun */ + movl CIF_FLAGS_OFFSET(%esi), %eax /* rtype */ + cmpl $FFI_TYPE_INT, %eax + je .Lrcls_retint + + /* Handle FFI_TYPE_UINT8, FFI_TYPE_SINT8, FFI_TYPE_UINT16, + FFI_TYPE_SINT16, FFI_TYPE_UINT32, FFI_TYPE_SINT32. */ + cmpl $FFI_TYPE_UINT64, %eax + jge 0f + cmpl $FFI_TYPE_UINT8, %eax + jge .Lrcls_retint +0: + cmpl $FFI_TYPE_FLOAT, %eax + je .Lrcls_retfloat + cmpl $FFI_TYPE_DOUBLE, %eax + je .Lrcls_retdouble + cmpl $FFI_TYPE_LONGDOUBLE, %eax + je .Lrcls_retldouble + cmpl $FFI_TYPE_SINT64, %eax + je .Lrcls_retllong +.Lrcls_epilogue: + addl $36, %esp + popl %esi + popl %ebp + ret +.Lrcls_retint: + movl -24(%ebp), %eax + jmp .Lrcls_epilogue +.Lrcls_retfloat: + flds -24(%ebp) + jmp .Lrcls_epilogue +.Lrcls_retdouble: + fldl -24(%ebp) + jmp .Lrcls_epilogue +.Lrcls_retldouble: + fldt -24(%ebp) + jmp .Lrcls_epilogue +.Lrcls_retllong: + movl -24(%ebp), %eax + movl -20(%ebp), %edx + jmp .Lrcls_epilogue +.LFE3: #endif - .byte 0x4 /* DW_CFA_advance_loc4 */ - .long .LCFI0-.LFB1 - .byte 0xe /* DW_CFA_def_cfa_offset */ - .byte 0x8 /* .uleb128 0x8 */ - .byte 0x85 /* DW_CFA_offset, column 0x5 */ - .byte 0x2 /* .uleb128 0x2 */ - .byte 0x4 /* DW_CFA_advance_loc4 */ - .long .LCFI1-.LCFI0 - .byte 0xd /* DW_CFA_def_cfa_register */ - .byte 0x5 /* .uleb128 0x5 */ - .align 4 -.LEFDE1: + +.section __IMPORT,__jump_table,symbol_stubs,self_modifying_code+pure_instructions,5 +L_ffi_closure_SYSV_inner$stub: + .indirect_symbol _ffi_closure_SYSV_inner + hlt ; hlt ; hlt ; hlt ; hlt + + +.section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support +EH_frame1: + .set L$set$0,LECIE1-LSCIE1 + .long L$set$0 +LSCIE1: + .long 0x0 + .byte 0x1 + .ascii "zR\0" + .byte 0x1 + .byte 0x7c + .byte 0x8 + .byte 0x1 + .byte 0x10 + .byte 0xc + .byte 0x5 + .byte 0x4 + .byte 0x88 + .byte 0x1 + .align 2 +LECIE1: +.globl _ffi_call_SYSV.eh +_ffi_call_SYSV.eh: +LSFDE1: + .set L$set$1,LEFDE1-LASFDE1 + .long L$set$1 +LASFDE1: + .long LASFDE1-EH_frame1 + .long .LFB1-. + .set L$set$2,.LFE1-.LFB1 + .long L$set$2 + .byte 0x0 + .byte 0x4 + .set L$set$3,.LCFI0-.LFB1 + .long L$set$3 + .byte 0xe + .byte 0x8 + .byte 0x84 + .byte 0x2 + .byte 0x4 + .set L$set$4,.LCFI1-.LCFI0 + .long L$set$4 + .byte 0xd + .byte 0x4 + .align 2 +LEFDE1: +.globl _ffi_closure_SYSV.eh +_ffi_closure_SYSV.eh: +LSFDE2: + .set L$set$5,LEFDE2-LASFDE2 + .long L$set$5 +LASFDE2: + .long LASFDE2-EH_frame1 + .long .LFB2-. + .set L$set$6,.LFE2-.LFB2 + .long L$set$6 + .byte 0x0 + .byte 0x4 + .set L$set$7,.LCFI2-.LFB2 + .long L$set$7 + .byte 0xe + .byte 0x8 + .byte 0x84 + .byte 0x2 + .byte 0x4 + .set L$set$8,.LCFI3-.LCFI2 + .long L$set$8 + .byte 0xd + .byte 0x4 + .align 2 +LEFDE2: + +#if !FFI_NO_RAW_API + +.globl _ffi_closure_raw_SYSV.eh +_ffi_closure_raw_SYSV.eh: +LSFDE3: + .set L$set$10,LEFDE3-LASFDE3 + .long L$set$10 +LASFDE3: + .long LASFDE3-EH_frame1 + .long .LFB3-. + .set L$set$11,.LFE3-.LFB3 + .long L$set$11 + .byte 0x0 + .byte 0x4 + .set L$set$12,.LCFI4-.LFB3 + .long L$set$12 + .byte 0xe + .byte 0x8 + .byte 0x84 + .byte 0x2 + .byte 0x4 + .set L$set$13,.LCFI5-.LCFI4 + .long L$set$13 + .byte 0xd + .byte 0x4 + .byte 0x4 + .set L$set$14,.LCFI6-.LCFI5 + .long L$set$14 + .byte 0x85 + .byte 0x3 + .align 2 +LEFDE3: + #endif #endif /* ifndef __x86_64__ */ - -#endif /* defined __i386__ */ Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/ffi.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/ffi.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/ffi.c Wed Apr 30 15:57:13 2008 @@ -1,10 +1,11 @@ /* ----------------------------------------------------------------------- - ffi.c - Copyright (c) 1996, 1998, 1999, 2001 Red Hat, Inc. + ffi.c - Copyright (c) 1996, 1998, 1999, 2001, 2007, 2008 Red Hat, Inc. Copyright (c) 2002 Ranjit Mathew Copyright (c) 2002 Bo Thorsen Copyright (c) 2002 Roger Sayle - - x86 Foreign Function Interface + Copyright (C) 2008 Free Software Foundation, Inc. + + x86 Foreign Function Interface Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the @@ -17,13 +18,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #ifndef __x86_64__ @@ -36,9 +38,7 @@ /* ffi_prep_args is called by the assembly routine once stack space has been allocated for the function's arguments */ -/*@-exportheader@*/ void ffi_prep_args(char *stack, extended_cif *ecif) -/*@=exportheader@*/ { register unsigned int i; register void **p_argv; @@ -121,9 +121,16 @@ switch (cif->rtype->type) { case FFI_TYPE_VOID: -#if !defined(X86_WIN32) && !defined(__OpenBSD__) && !defined(__FreeBSD__) +#ifdef X86 case FFI_TYPE_STRUCT: #endif +#if defined(X86) || defined(X86_DARWIN) + case FFI_TYPE_UINT8: + case FFI_TYPE_UINT16: + case FFI_TYPE_SINT8: + case FFI_TYPE_SINT16: +#endif + case FFI_TYPE_SINT64: case FFI_TYPE_FLOAT: case FFI_TYPE_DOUBLE: @@ -135,15 +142,15 @@ cif->flags = FFI_TYPE_SINT64; break; -#if defined(X86_WIN32) || defined(__OpenBSD__) || defined(__FreeBSD__) +#ifndef X86 case FFI_TYPE_STRUCT: if (cif->rtype->size == 1) { - cif->flags = FFI_TYPE_SINT8; /* same as char size */ + cif->flags = FFI_TYPE_SMALL_STRUCT_1B; /* same as char size */ } else if (cif->rtype->size == 2) { - cif->flags = FFI_TYPE_SINT16; /* same as short size */ + cif->flags = FFI_TYPE_SMALL_STRUCT_2B; /* same as short size */ } else if (cif->rtype->size == 4) { @@ -165,35 +172,23 @@ break; } +#ifdef X86_DARWIN + cif->bytes = (cif->bytes + 15) & ~0xF; +#endif + return FFI_OK; } -/*@-declundef@*/ -/*@-exportheader@*/ -extern void ffi_call_SYSV(void (*)(char *, extended_cif *), - /*@out@*/ extended_cif *, - unsigned, unsigned, - /*@out@*/ unsigned *, - void (*fn)(void)); -/*@=declundef@*/ -/*@=exportheader@*/ +extern void ffi_call_SYSV(void (*)(char *, extended_cif *), extended_cif *, + unsigned, unsigned, unsigned *, void (*fn)(void)); #ifdef X86_WIN32 -/*@-declundef@*/ -/*@-exportheader@*/ -extern void ffi_call_STDCALL(void (*)(char *, extended_cif *), - /*@out@*/ extended_cif *, - unsigned, unsigned, - /*@out@*/ unsigned *, - void (*fn)(void)); -/*@=declundef@*/ -/*@=exportheader@*/ +extern void ffi_call_STDCALL(void (*)(char *, extended_cif *), extended_cif *, + unsigned, unsigned, unsigned *, void (*fn)(void)); + #endif /* X86_WIN32 */ -void ffi_call(/*@dependent@*/ ffi_cif *cif, - void (*fn)(void), - /*@out@*/ void *rvalue, - /*@dependent@*/ void **avalue) +void ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) { extended_cif ecif; @@ -206,9 +201,7 @@ if ((rvalue == NULL) && (cif->flags == FFI_TYPE_STRUCT)) { - /*@-sysunrecog@*/ ecif.rvalue = alloca(cif->rtype->size); - /*@=sysunrecog@*/ } else ecif.rvalue = rvalue; @@ -217,17 +210,13 @@ switch (cif->abi) { case FFI_SYSV: - /*@-usedef@*/ - ffi_call_SYSV(ffi_prep_args, &ecif, cif->bytes, - cif->flags, ecif.rvalue, fn); - /*@=usedef@*/ + ffi_call_SYSV(ffi_prep_args, &ecif, cif->bytes, cif->flags, ecif.rvalue, + fn); break; #ifdef X86_WIN32 case FFI_STDCALL: - /*@-usedef@*/ - ffi_call_STDCALL(ffi_prep_args, &ecif, cif->bytes, - cif->flags, ecif.rvalue, fn); - /*@=usedef@*/ + ffi_call_STDCALL(ffi_prep_args, &ecif, cif->bytes, cif->flags, + ecif.rvalue, fn); break; #endif /* X86_WIN32 */ default: @@ -247,6 +236,10 @@ __attribute__ ((regparm(1))); void FFI_HIDDEN ffi_closure_raw_SYSV (ffi_raw_closure *) __attribute__ ((regparm(1))); +#ifdef X86_WIN32 +void FFI_HIDDEN ffi_closure_STDCALL (ffi_closure *) + __attribute__ ((regparm(1))); +#endif /* This function is jumped to by the trampoline */ @@ -256,7 +249,7 @@ void **respp; void *args; { - /* our various things... */ + /* our various things... */ ffi_cif *cif; void **arg_area; @@ -276,11 +269,9 @@ return cif->flags; } -/*@-exportheader@*/ -static void -ffi_prep_incoming_args_SYSV(char *stack, void **rvalue, - void **avalue, ffi_cif *cif) -/*@=exportheader@*/ +static void +ffi_prep_incoming_args_SYSV(char *stack, void **rvalue, void **avalue, + ffi_cif *cif) { register unsigned int i; register void **p_argv; @@ -324,27 +315,54 @@ ({ unsigned char *__tramp = (unsigned char*)(TRAMP); \ unsigned int __fun = (unsigned int)(FUN); \ unsigned int __ctx = (unsigned int)(CTX); \ - unsigned int __dis = __fun - ((unsigned int) __tramp + FFI_TRAMPOLINE_SIZE); \ + unsigned int __dis = __fun - (__ctx + 10); \ *(unsigned char*) &__tramp[0] = 0xb8; \ *(unsigned int*) &__tramp[1] = __ctx; /* movl __ctx, %eax */ \ *(unsigned char *) &__tramp[5] = 0xe9; \ *(unsigned int*) &__tramp[6] = __dis; /* jmp __fun */ \ }) +#define FFI_INIT_TRAMPOLINE_STDCALL(TRAMP,FUN,CTX,SIZE) \ +({ unsigned char *__tramp = (unsigned char*)(TRAMP); \ + unsigned int __fun = (unsigned int)(FUN); \ + unsigned int __ctx = (unsigned int)(CTX); \ + unsigned int __dis = __fun - (__ctx + 10); \ + unsigned short __size = (unsigned short)(SIZE); \ + *(unsigned char*) &__tramp[0] = 0xb8; \ + *(unsigned int*) &__tramp[1] = __ctx; /* movl __ctx, %eax */ \ + *(unsigned char *) &__tramp[5] = 0xe8; \ + *(unsigned int*) &__tramp[6] = __dis; /* call __fun */ \ + *(unsigned char *) &__tramp[10] = 0xc2; \ + *(unsigned short*) &__tramp[11] = __size; /* ret __size */ \ + }) /* the cif must already be prep'ed */ ffi_status -ffi_prep_closure (ffi_closure* closure, - ffi_cif* cif, - void (*fun)(ffi_cif*,void*,void**,void*), - void *user_data) +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + void *codeloc) { - FFI_ASSERT (cif->abi == FFI_SYSV); - - FFI_INIT_TRAMPOLINE (&closure->tramp[0], \ - &ffi_closure_SYSV, \ - (void*)closure); + if (cif->abi == FFI_SYSV) + { + FFI_INIT_TRAMPOLINE (&closure->tramp[0], + &ffi_closure_SYSV, + (void*)codeloc); + } +#ifdef X86_WIN32 + else if (cif->abi == FFI_STDCALL) + { + FFI_INIT_TRAMPOLINE_STDCALL (&closure->tramp[0], + &ffi_closure_STDCALL, + (void*)codeloc, cif->bytes); + } +#endif + else + { + return FFI_BAD_ABI; + } closure->cif = cif; closure->user_data = user_data; @@ -358,14 +376,17 @@ #if !FFI_NO_RAW_API ffi_status -ffi_prep_raw_closure (ffi_raw_closure* closure, - ffi_cif* cif, - void (*fun)(ffi_cif*,void*,ffi_raw*,void*), - void *user_data) +ffi_prep_raw_closure_loc (ffi_raw_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*,void*,ffi_raw*,void*), + void *user_data, + void *codeloc) { int i; - FFI_ASSERT (cif->abi == FFI_SYSV); + if (cif->abi != FFI_SYSV) { + return FFI_BAD_ABI; + } // we currently don't support certain kinds of arguments for raw // closures. This should be implemented by a separate assembly language @@ -380,7 +401,7 @@ FFI_INIT_TRAMPOLINE (&closure->tramp[0], &ffi_closure_raw_SYSV, - (void*)closure); + codeloc); closure->cif = cif; closure->user_data = user_data; @@ -400,27 +421,18 @@ * libffi-1.20, this is not the case.) */ -extern void -ffi_call_SYSV(void (*)(char *, extended_cif *), - /*@out@*/ extended_cif *, - unsigned, unsigned, - /*@out@*/ unsigned *, - void (*fn)(void)); +extern void +ffi_call_SYSV(void (*)(char *, extended_cif *), extended_cif *, unsigned, + unsigned, unsigned *, void (*fn)(void)); #ifdef X86_WIN32 extern void -ffi_call_STDCALL(void (*)(char *, extended_cif *), - /*@out@*/ extended_cif *, - unsigned, unsigned, - /*@out@*/ unsigned *, - void (*fn)(void)); +ffi_call_STDCALL(void (*)(char *, extended_cif *), extended_cif *, unsigned, + unsigned, unsigned *, void (*fn)(void)); #endif /* X86_WIN32 */ void -ffi_raw_call(/*@dependent@*/ ffi_cif *cif, - void (*fn)(void), - /*@out@*/ void *rvalue, - /*@dependent@*/ ffi_raw *fake_avalue) +ffi_raw_call(ffi_cif *cif, void (*fn)(void), void *rvalue, ffi_raw *fake_avalue) { extended_cif ecif; void **avalue = (void **)fake_avalue; @@ -434,9 +446,7 @@ if ((rvalue == NULL) && (cif->rtype->type == FFI_TYPE_STRUCT)) { - /*@-sysunrecog@*/ ecif.rvalue = alloca(cif->rtype->size); - /*@=sysunrecog@*/ } else ecif.rvalue = rvalue; @@ -445,17 +455,13 @@ switch (cif->abi) { case FFI_SYSV: - /*@-usedef@*/ - ffi_call_SYSV(ffi_prep_args_raw, &ecif, cif->bytes, - cif->flags, ecif.rvalue, fn); - /*@=usedef@*/ + ffi_call_SYSV(ffi_prep_args_raw, &ecif, cif->bytes, cif->flags, + ecif.rvalue, fn); break; #ifdef X86_WIN32 case FFI_STDCALL: - /*@-usedef@*/ - ffi_call_STDCALL(ffi_prep_args_raw, &ecif, cif->bytes, - cif->flags, ecif.rvalue, fn); - /*@=usedef@*/ + ffi_call_STDCALL(ffi_prep_args_raw, &ecif, cif->bytes, cif->flags, + ecif.rvalue, fn); break; #endif /* X86_WIN32 */ default: Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/ffi64.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/ffi64.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/ffi64.c Wed Apr 30 15:57:13 2008 @@ -1,5 +1,6 @@ /* ----------------------------------------------------------------------- - ffi.c - Copyright (c) 2002 Bo Thorsen + ffi.c - Copyright (c) 2002, 2007 Bo Thorsen + Copyright (c) 2008 Red Hat, Inc. x86-64 Foreign Function Interface @@ -14,13 +15,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #include @@ -433,10 +435,11 @@ extern void ffi_closure_unix64(void); ffi_status -ffi_prep_closure (ffi_closure* closure, - ffi_cif* cif, - void (*fun)(ffi_cif*, void*, void**, void*), - void *user_data) +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + void *codeloc) { volatile unsigned short *tramp; @@ -445,7 +448,7 @@ tramp[0] = 0xbb49; /* mov , %r11 */ *(void * volatile *) &tramp[1] = ffi_closure_unix64; tramp[5] = 0xba49; /* mov , %r10 */ - *(void * volatile *) &tramp[6] = closure; + *(void * volatile *) &tramp[6] = codeloc; /* Set the carry bit iff the function uses any sse registers. This is clc or stc, together with the first byte of the jmp. */ Deleted: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/ffi_darwin.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/ffi_darwin.c Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,594 +0,0 @@ -# ifdef __i386__ -/* ----------------------------------------------------------------------- - ffi.c - Copyright (c) 1996, 1998, 1999, 2001 Red Hat, Inc. - Copyright (c) 2002 Ranjit Mathew - Copyright (c) 2002 Bo Thorsen - Copyright (c) 2002 Roger Sayle - - x86 Foreign Function Interface - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - ``Software''), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be included - in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. - ----------------------------------------------------------------------- */ - -#ifndef __x86_64__ - -#include -#include - -#include - -/* ffi_prep_args is called by the assembly routine once stack space - has been allocated for the function's arguments */ - -/*@-exportheader@*/ -void ffi_prep_args(char *stack, extended_cif *ecif); - -static inline int retval_on_stack(ffi_type* tp) -{ - if (tp->type == FFI_TYPE_STRUCT) { - int sz = tp->size; - if (sz > 8) { - return 1; - } - switch (sz) { - case 1: case 2: case 4: case 8: return 0; - default: return 1; - } - } - return 0; -} - - -void ffi_prep_args(char *stack, extended_cif *ecif) -/*@=exportheader@*/ -{ - register unsigned int i; - register void **p_argv; - register char *argp; - register ffi_type **p_arg; - - argp = stack; - - if (retval_on_stack(ecif->cif->rtype)) { - *(void **) argp = ecif->rvalue; - argp += 4; - } - - - p_argv = ecif->avalue; - - for (i = ecif->cif->nargs, p_arg = ecif->cif->arg_types; - i != 0; - i--, p_arg++) - { - size_t z; - - /* Align if necessary */ - if ((sizeof(int) - 1) & (unsigned) argp) - argp = (char *) ALIGN(argp, sizeof(int)); - - z = (*p_arg)->size; - if (z < sizeof(int)) - { - z = sizeof(int); - switch ((*p_arg)->type) - { - case FFI_TYPE_SINT8: - *(signed int *) argp = (signed int)*(SINT8 *)(* p_argv); - break; - - case FFI_TYPE_UINT8: - *(unsigned int *) argp = (unsigned int)*(UINT8 *)(* p_argv); - break; - - case FFI_TYPE_SINT16: - *(signed int *) argp = (signed int)*(SINT16 *)(* p_argv); - break; - - case FFI_TYPE_UINT16: - *(unsigned int *) argp = (unsigned int)*(UINT16 *)(* p_argv); - break; - - case FFI_TYPE_SINT32: - *(signed int *) argp = (signed int)*(SINT32 *)(* p_argv); - break; - - case FFI_TYPE_UINT32: - *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); - break; - - case FFI_TYPE_STRUCT: - *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); - break; - - default: - FFI_ASSERT(0); - } - } - else - { - memcpy(argp, *p_argv, z); - } - p_argv++; - argp += z; - } - - return; -} - -/* Perform machine dependent cif processing */ -ffi_status ffi_prep_cif_machdep(ffi_cif *cif) -{ - /* Set the return type flag */ - switch (cif->rtype->type) - { - case FFI_TYPE_VOID: -#if !defined(X86_WIN32) && !defined(X86_DARWIN) - case FFI_TYPE_STRUCT: -#endif - case FFI_TYPE_SINT64: - case FFI_TYPE_FLOAT: - case FFI_TYPE_DOUBLE: - case FFI_TYPE_LONGDOUBLE: - cif->flags = (unsigned) cif->rtype->type; - break; - - case FFI_TYPE_UINT64: - cif->flags = FFI_TYPE_SINT64; - break; - -#if defined(X86_WIN32) || defined(X86_DARWIN) - - case FFI_TYPE_STRUCT: - if (cif->rtype->size == 1) - { - cif->flags = FFI_TYPE_SINT8; /* same as char size */ - } - else if (cif->rtype->size == 2) - { - cif->flags = FFI_TYPE_SINT16; /* same as short size */ - } - else if (cif->rtype->size == 4) - { - cif->flags = FFI_TYPE_INT; /* same as int type */ - } - else if (cif->rtype->size == 8) - { - cif->flags = FFI_TYPE_SINT64; /* same as int64 type */ - } - else - { - cif->flags = FFI_TYPE_STRUCT; - } - break; -#endif - - default: - cif->flags = FFI_TYPE_INT; - break; - } - - /* Darwin: The stack needs to be aligned to a multiple of 16 bytes */ -#if 1 - cif->bytes = (cif->bytes + 15) & ~0xF; -#endif - - - return FFI_OK; -} - -/*@-declundef@*/ -/*@-exportheader@*/ -extern void ffi_call_SYSV(void (*)(char *, extended_cif *), - /*@out@*/ extended_cif *, - unsigned, unsigned, - /*@out@*/ unsigned *, - void (*fn)(void)); -/*@=declundef@*/ -/*@=exportheader@*/ - -#ifdef X86_WIN32 -/*@-declundef@*/ -/*@-exportheader@*/ -extern void ffi_call_STDCALL(void (*)(char *, extended_cif *), - /*@out@*/ extended_cif *, - unsigned, unsigned, - /*@out@*/ unsigned *, - void (*fn)(void)); -/*@=declundef@*/ -/*@=exportheader@*/ -#endif /* X86_WIN32 */ - -void ffi_call(/*@dependent@*/ ffi_cif *cif, - void (*fn)(void), - /*@out@*/ void *rvalue, - /*@dependent@*/ void **avalue) -{ - extended_cif ecif; - - ecif.cif = cif; - ecif.avalue = avalue; - - /* If the return value is a struct and we don't have a return */ - /* value address then we need to make one */ - - if ((rvalue == NULL) && retval_on_stack(cif->rtype)) - { - /*@-sysunrecog@*/ - ecif.rvalue = alloca(cif->rtype->size); - /*@=sysunrecog@*/ - } - else - ecif.rvalue = rvalue; - - switch (cif->abi) - { - case FFI_SYSV: - /*@-usedef@*/ - /* To avoid changing the assembly code make sure the size of the argument - * block is a multiple of 16. Then add 8 to compensate for local variables - * in ffi_call_SYSV. - */ - ffi_call_SYSV(ffi_prep_args, &ecif, cif->bytes, - cif->flags, ecif.rvalue, fn); - /*@=usedef@*/ - break; -#ifdef X86_WIN32 - case FFI_STDCALL: - /*@-usedef@*/ - ffi_call_STDCALL(ffi_prep_args, &ecif, cif->bytes, - cif->flags, ecif.rvalue, fn); - /*@=usedef@*/ - break; -#endif /* X86_WIN32 */ - default: - FFI_ASSERT(0); - break; - } -} - - -/** private members **/ - -static void ffi_closure_SYSV (ffi_closure *) - __attribute__ ((regparm(1))); -#if !FFI_NO_RAW_API -static void ffi_closure_raw_SYSV (ffi_raw_closure *) - __attribute__ ((regparm(1))); -#endif - -/*@-exportheader@*/ -static inline void -ffi_prep_incoming_args_SYSV(char *stack, void **rvalue, - void **avalue, ffi_cif *cif) -/*@=exportheader@*/ -{ - register unsigned int i; - register void **p_argv; - register char *argp; - register ffi_type **p_arg; - - argp = stack; - - if (retval_on_stack(cif->rtype)) { - *rvalue = *(void **) argp; - argp += 4; - } - - p_argv = avalue; - - for (i = cif->nargs, p_arg = cif->arg_types; (i != 0); i--, p_arg++) - { - size_t z; - - /* Align if necessary */ - if ((sizeof(int) - 1) & (unsigned) argp) { - argp = (char *) ALIGN(argp, sizeof(int)); - } - - z = (*p_arg)->size; - - /* because we're little endian, this is what it turns into. */ - - *p_argv = (void*) argp; - - p_argv++; - argp += z; - } - - return; -} - -/* This function is jumped to by the trampoline */ - -static void -ffi_closure_SYSV (closure) - ffi_closure *closure; -{ - // this is our return value storage - long double res; - - // our various things... - ffi_cif *cif; - void **arg_area; - void *resp = (void*)&res; - void *args = __builtin_dwarf_cfa (); - - - cif = closure->cif; - arg_area = (void**) alloca (cif->nargs * sizeof (void*)); - - /* this call will initialize ARG_AREA, such that each - * element in that array points to the corresponding - * value on the stack; and if the function returns - * a structure, it will re-set RESP to point to the - * structure return address. */ - - ffi_prep_incoming_args_SYSV(args, (void**)&resp, arg_area, cif); - - (closure->fun) (cif, resp, arg_area, closure->user_data); - - /* now, do a generic return based on the value of rtype */ - if (cif->flags == FFI_TYPE_INT) - { - asm ("movl (%0),%%eax" : : "r" (resp) : "eax"); - } - else if (cif->flags == FFI_TYPE_FLOAT) - { - asm ("flds (%0)" : : "r" (resp) : "st" ); - } - else if (cif->flags == FFI_TYPE_DOUBLE) - { - asm ("fldl (%0)" : : "r" (resp) : "st", "st(1)" ); - } - else if (cif->flags == FFI_TYPE_LONGDOUBLE) - { - asm ("fldt (%0)" : : "r" (resp) : "st", "st(1)" ); - } - else if (cif->flags == FFI_TYPE_SINT64) - { - asm ("movl 0(%0),%%eax;" - "movl 4(%0),%%edx" - : : "r"(resp) - : "eax", "edx"); - } -#if defined(X86_WIN32) || defined(X86_DARWIN) - else if (cif->flags == FFI_TYPE_SINT8) /* 1-byte struct */ - { - asm ("movsbl (%0),%%eax" : : "r" (resp) : "eax"); - } - else if (cif->flags == FFI_TYPE_SINT16) /* 2-bytes struct */ - { - asm ("movswl (%0),%%eax" : : "r" (resp) : "eax"); - } -#endif - - else if (cif->flags == FFI_TYPE_STRUCT) - { - asm ("lea -8(%ebp),%esp;" - "pop %esi;" - "pop %edi;" - "pop %ebp;" - "ret $4"); - } -} - - -/* How to make a trampoline. Derived from gcc/config/i386/i386.c. */ - -#define FFI_INIT_TRAMPOLINE(TRAMP,FUN,CTX) \ -({ unsigned char *__tramp = (unsigned char*)(TRAMP); \ - unsigned int __fun = (unsigned int)(FUN); \ - unsigned int __ctx = (unsigned int)(CTX); \ - unsigned int __dis = __fun - ((unsigned int) __tramp + FFI_TRAMPOLINE_SIZE); \ - *(unsigned char*) &__tramp[0] = 0xb8; \ - *(unsigned int*) &__tramp[1] = __ctx; /* movl __ctx, %eax */ \ - *(unsigned char *) &__tramp[5] = 0xe9; \ - *(unsigned int*) &__tramp[6] = __dis; /* jmp __fun */ \ - }) - - -/* the cif must already be prep'ed */ - -ffi_status -ffi_prep_closure (ffi_closure* closure, - ffi_cif* cif, - void (*fun)(ffi_cif*,void*,void**,void*), - void *user_data) -{ - FFI_ASSERT (cif->abi == FFI_SYSV); - - FFI_INIT_TRAMPOLINE (&closure->tramp[0], \ - &ffi_closure_SYSV, \ - (void*)closure); - - closure->cif = cif; - closure->user_data = user_data; - closure->fun = fun; - - return FFI_OK; -} - -/* ------- Native raw API support -------------------------------- */ - -#if !FFI_NO_RAW_API - -static void -ffi_closure_raw_SYSV (closure) - ffi_raw_closure *closure; -{ - // this is our return value storage - long double res; - - // our various things... - ffi_raw *raw_args; - ffi_cif *cif; - unsigned short rtype; - void *resp = (void*)&res; - - /* get the cif */ - cif = closure->cif; - - /* the SYSV/X86 abi matches the RAW API exactly, well.. almost */ - raw_args = (ffi_raw*) __builtin_dwarf_cfa (); - - (closure->fun) (cif, resp, raw_args, closure->user_data); - - rtype = cif->flags; - - /* now, do a generic return based on the value of rtype */ - if (rtype == FFI_TYPE_INT) - { - asm ("movl (%0),%%eax" : : "r" (resp) : "eax"); - } - else if (rtype == FFI_TYPE_FLOAT) - { - asm ("flds (%0)" : : "r" (resp) : "st" ); - } - else if (rtype == FFI_TYPE_DOUBLE) - { - asm ("fldl (%0)" : : "r" (resp) : "st", "st(1)" ); - } - else if (rtype == FFI_TYPE_LONGDOUBLE) - { - asm ("fldt (%0)" : : "r" (resp) : "st", "st(1)" ); - } - else if (rtype == FFI_TYPE_SINT64) - { - asm ("movl 0(%0),%%eax; movl 4(%0),%%edx" - : : "r"(resp) - : "eax", "edx"); - } -} - - - - -ffi_status -ffi_prep_raw_closure (ffi_raw_closure* closure, - ffi_cif* cif, - void (*fun)(ffi_cif*,void*,ffi_raw*,void*), - void *user_data) -{ - int i; - - FFI_ASSERT (cif->abi == FFI_SYSV); - - // we currently don't support certain kinds of arguments for raw - // closures. This should be implemented by a separate assembly language - // routine, since it would require argument processing, something we - // don't do now for performance. - - for (i = cif->nargs-1; i >= 0; i--) - { - FFI_ASSERT (cif->arg_types[i]->type != FFI_TYPE_STRUCT); - FFI_ASSERT (cif->arg_types[i]->type != FFI_TYPE_LONGDOUBLE); - } - - - FFI_INIT_TRAMPOLINE (&closure->tramp[0], &ffi_closure_raw_SYSV, - (void*)closure); - - closure->cif = cif; - closure->user_data = user_data; - closure->fun = fun; - - return FFI_OK; -} - -static void -ffi_prep_args_raw(char *stack, extended_cif *ecif) -{ - memcpy (stack, ecif->avalue, ecif->cif->bytes); -} - -/* we borrow this routine from libffi (it must be changed, though, to - * actually call the function passed in the first argument. as of - * libffi-1.20, this is not the case.) - */ - -extern void -ffi_call_SYSV(void (*)(char *, extended_cif *), - /*@out@*/ extended_cif *, - unsigned, unsigned, - /*@out@*/ unsigned *, - void (*fn)()); - -#ifdef X86_WIN32 -extern void -ffi_call_STDCALL(void (*)(char *, extended_cif *), - /*@out@*/ extended_cif *, - unsigned, unsigned, - /*@out@*/ unsigned *, - void (*fn)()); -#endif /* X86_WIN32 */ - -void -ffi_raw_call(/*@dependent@*/ ffi_cif *cif, - void (*fn)(), - /*@out@*/ void *rvalue, - /*@dependent@*/ ffi_raw *fake_avalue) -{ - extended_cif ecif; - void **avalue = (void **)fake_avalue; - - ecif.cif = cif; - ecif.avalue = avalue; - - /* If the return value is a struct and we don't have a return */ - /* value address then we need to make one */ - - if ((rvalue == NULL) && retval_on_stack(cif->rtype)) - { - /*@-sysunrecog@*/ - ecif.rvalue = alloca(cif->rtype->size); - /*@=sysunrecog@*/ - } - else - ecif.rvalue = rvalue; - - - switch (cif->abi) - { - case FFI_SYSV: - /*@-usedef@*/ - ffi_call_SYSV(ffi_prep_args_raw, &ecif, cif->bytes, - cif->flags, ecif.rvalue, fn); - /*@=usedef@*/ - break; -#ifdef X86_WIN32 - case FFI_STDCALL: - /*@-usedef@*/ - ffi_call_STDCALL(ffi_prep_args_raw, &ecif, cif->bytes, - cif->flags, ecif.rvalue, fn); - /*@=usedef@*/ - break; -#endif /* X86_WIN32 */ - default: - FFI_ASSERT(0); - break; - } -} - -#endif - -#endif /* __x86_64__ */ - -#endif /* __i386__ */ Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/ffitarget.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/ffitarget.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/ffitarget.h Wed Apr 30 15:57:13 2008 @@ -1,5 +1,7 @@ /* -----------------------------------------------------------------*-C-*- ffitarget.h - Copyright (c) 1996-2003 Red Hat, Inc. + Copyright (C) 2008 Free Software Foundation, Inc. + Target configuration macros for x86 and x86-64. Permission is hereby granted, free of charge, to any person obtaining @@ -13,13 +15,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ @@ -51,7 +54,7 @@ #endif /* ---- Intel x86 and AMD x86-64 - */ -#if !defined(X86_WIN32) && (defined(__i386__) || defined(__x86_64__)) +#if !defined(X86_WIN32) && (defined(__i386__) || defined(__x86_64__)) FFI_SYSV, FFI_UNIX64, /* Unix variants all use the same ABI for x86-64 */ #ifdef __i386__ @@ -68,12 +71,18 @@ /* ---- Definitions for closures ----------------------------------------- */ #define FFI_CLOSURES 1 +#define FFI_TYPE_SMALL_STRUCT_1B (FFI_TYPE_LAST + 1) +#define FFI_TYPE_SMALL_STRUCT_2B (FFI_TYPE_LAST + 2) -#ifdef X86_64 +#if defined (X86_64) || (defined (__x86_64__) && defined (X86_DARWIN)) #define FFI_TRAMPOLINE_SIZE 24 #define FFI_NATIVE_RAW_API 0 #else +#ifdef X86_WIN32 +#define FFI_TRAMPOLINE_SIZE 13 +#else #define FFI_TRAMPOLINE_SIZE 10 +#endif #define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */ #endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/sysv.S ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/sysv.S (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/sysv.S Wed Apr 30 15:57:13 2008 @@ -1,5 +1,5 @@ /* ----------------------------------------------------------------------- - sysv.S - Copyright (c) 1996, 1998, 2001, 2002, 2003, 2005 Red Hat, Inc. + sysv.S - Copyright (c) 1996, 1998, 2001-2003, 2005, 2008 Red Hat, Inc. X86 Foreign Function Interface @@ -14,13 +14,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #ifndef __x86_64__ @@ -59,16 +60,15 @@ call *28(%ebp) - /* Remove the space we pushed for the args */ - movl 16(%ebp),%ecx - addl %ecx,%esp - /* Load %ecx with the return type code */ movl 20(%ebp),%ecx + /* Protect %esi. We're going to pop it in the epilogue. */ + pushl %esi + /* If the return value pointer is NULL, assume no return value. */ cmpl $0,24(%ebp) - jne retint + jne 0f /* Even if there is no space for the return value, we are obliged to handle floating-point values. */ @@ -78,51 +78,84 @@ jmp epilogue -retint: - cmpl $FFI_TYPE_INT,%ecx - jne retfloat - /* Load %ecx with the pointer to storage for the return value */ - movl 24(%ebp),%ecx - movl %eax,0(%ecx) - jmp epilogue +0: + call 1f + +.Lstore_table: + .long noretval-.Lstore_table /* FFI_TYPE_VOID */ + .long retint-.Lstore_table /* FFI_TYPE_INT */ + .long retfloat-.Lstore_table /* FFI_TYPE_FLOAT */ + .long retdouble-.Lstore_table /* FFI_TYPE_DOUBLE */ + .long retlongdouble-.Lstore_table /* FFI_TYPE_LONGDOUBLE */ + .long retuint8-.Lstore_table /* FFI_TYPE_UINT8 */ + .long retsint8-.Lstore_table /* FFI_TYPE_SINT8 */ + .long retuint16-.Lstore_table /* FFI_TYPE_UINT16 */ + .long retsint16-.Lstore_table /* FFI_TYPE_SINT16 */ + .long retint-.Lstore_table /* FFI_TYPE_UINT32 */ + .long retint-.Lstore_table /* FFI_TYPE_SINT32 */ + .long retint64-.Lstore_table /* FFI_TYPE_UINT64 */ + .long retint64-.Lstore_table /* FFI_TYPE_SINT64 */ + .long retstruct-.Lstore_table /* FFI_TYPE_STRUCT */ + .long retint-.Lstore_table /* FFI_TYPE_POINTER */ + +1: + pop %esi + add (%esi, %ecx, 4), %esi + jmp *%esi + + /* Sign/zero extend as appropriate. */ +retsint8: + movsbl %al, %eax + jmp retint + +retsint16: + movswl %ax, %eax + jmp retint + +retuint8: + movzbl %al, %eax + jmp retint + +retuint16: + movzwl %ax, %eax + jmp retint retfloat: - cmpl $FFI_TYPE_FLOAT,%ecx - jne retdouble /* Load %ecx with the pointer to storage for the return value */ movl 24(%ebp),%ecx fstps (%ecx) jmp epilogue retdouble: - cmpl $FFI_TYPE_DOUBLE,%ecx - jne retlongdouble /* Load %ecx with the pointer to storage for the return value */ movl 24(%ebp),%ecx fstpl (%ecx) jmp epilogue retlongdouble: - cmpl $FFI_TYPE_LONGDOUBLE,%ecx - jne retint64 /* Load %ecx with the pointer to storage for the return value */ movl 24(%ebp),%ecx fstpt (%ecx) jmp epilogue retint64: - cmpl $FFI_TYPE_SINT64,%ecx - jne retstruct /* Load %ecx with the pointer to storage for the return value */ movl 24(%ebp),%ecx movl %eax,0(%ecx) movl %edx,4(%ecx) + jmp epilogue +retint: + /* Load %ecx with the pointer to storage for the return value */ + movl 24(%ebp),%ecx + movl %eax,0(%ecx) + retstruct: /* Nothing to do! */ noretval: epilogue: + popl %esi movl %ebp,%esp popl %ebp ret @@ -162,7 +195,15 @@ movl -12(%ebp), %ecx cmpl $FFI_TYPE_INT, %eax je .Lcls_retint - cmpl $FFI_TYPE_FLOAT, %eax + + /* Handle FFI_TYPE_UINT8, FFI_TYPE_SINT8, FFI_TYPE_UINT16, + FFI_TYPE_SINT16, FFI_TYPE_UINT32, FFI_TYPE_SINT32. */ + cmpl $FFI_TYPE_UINT64, %eax + jge 0f + cmpl $FFI_TYPE_UINT8, %eax + jge .Lcls_retint + +0: cmpl $FFI_TYPE_FLOAT, %eax je .Lcls_retfloat cmpl $FFI_TYPE_DOUBLE, %eax je .Lcls_retdouble @@ -170,6 +211,8 @@ je .Lcls_retldouble cmpl $FFI_TYPE_SINT64, %eax je .Lcls_retllong + cmpl $FFI_TYPE_STRUCT, %eax + je .Lcls_retstruct .Lcls_epilogue: movl %ebp, %esp popl %ebp @@ -190,6 +233,10 @@ movl (%ecx), %eax movl 4(%ecx), %edx jmp .Lcls_epilogue +.Lcls_retstruct: + movl %ebp, %esp + popl %ebp + ret $4 .LFE2: .size ffi_closure_SYSV, .-ffi_closure_SYSV @@ -226,6 +273,14 @@ movl CIF_FLAGS_OFFSET(%esi), %eax /* rtype */ cmpl $FFI_TYPE_INT, %eax je .Lrcls_retint + + /* Handle FFI_TYPE_UINT8, FFI_TYPE_SINT8, FFI_TYPE_UINT16, + FFI_TYPE_SINT16, FFI_TYPE_UINT32, FFI_TYPE_SINT32. */ + cmpl $FFI_TYPE_UINT64, %eax + jge 0f + cmpl $FFI_TYPE_UINT8, %eax + jge .Lrcls_retint +0: cmpl $FFI_TYPE_FLOAT, %eax je .Lrcls_retfloat cmpl $FFI_TYPE_DOUBLE, %eax @@ -377,6 +432,6 @@ #endif /* ifndef __x86_64__ */ -#ifdef __ELF__ -.section .note.GNU-stack,"",%progbits +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"", at progbits #endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/unix64.S ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/unix64.S (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/unix64.S Wed Apr 30 15:57:13 2008 @@ -1,5 +1,6 @@ /* ----------------------------------------------------------------------- unix64.S - Copyright (c) 2002 Bo Thorsen + Copyright (c) 2008 Red Hat, Inc x86-64 Foreign Function Interface @@ -14,13 +15,14 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #ifdef __x86_64__ @@ -31,7 +33,7 @@ .text /* ffi_call_unix64 (void *args, unsigned long bytes, unsigned flags, - void *raddr, void (*fnaddr)()); + void *raddr, void (*fnaddr)(void)); Bit o trickiness here -- ARGS+BYTES is the base of the stack frame for this function. This has been allocated by ffi_call. We also @@ -410,3 +412,7 @@ .LEFDE3: #endif /* __x86_64__ */ + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"", at progbits +#endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/win32.S ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/win32.S (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/libffi/src/x86/win32.S Wed Apr 30 15:57:13 2008 @@ -20,7 +20,8 @@ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. @@ -258,6 +259,22 @@ .ffi_call_STDCALL_end: + .globl _ffi_closure_STDCALL +_ffi_closure_STDCALL: + pushl %ebp + movl %esp, %ebp + subl $40, %esp + leal -24(%ebp), %edx + movl %edx, -12(%ebp) /* resp */ + leal 12(%ebp), %edx /* account for stub return address on stack */ + movl %edx, 4(%esp) /* args */ + leal -12(%ebp), %edx + movl %edx, (%esp) /* &resp */ + call _ffi_closure_SYSV_inner + movl -12(%ebp), %ecx + jmp .Lcls_return_result +.ffi_closure_STDCALL_end: + .globl _ffi_closure_SYSV _ffi_closure_SYSV: pushl %ebp @@ -271,6 +288,7 @@ movl %edx, (%esp) /* &resp */ call _ffi_closure_SYSV_inner movl -12(%ebp), %ecx +.Lcls_return_result: cmpl $FFI_TYPE_INT, %eax je .Lcls_retint cmpl $FFI_TYPE_FLOAT, %eax Modified: python/branches/py3k-ctypes-pep3118/Modules/_ctypes/stgdict.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ctypes/stgdict.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ctypes/stgdict.c Wed Apr 30 15:57:13 2008 @@ -440,6 +440,8 @@ return -1; } stgdict->ffi_type_pointer.elements[ffi_ofs + i] = &dict->ffi_type_pointer; + if (dict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER)) + stgdict->flags |= TYPEFLAG_HASPOINTER; dict->flags |= DICTFLAG_FINAL; /* mark field type final */ if (PyTuple_Size(pair) == 3) { /* bits specified */ switch(dict->ffi_type_pointer.type) { Modified: python/branches/py3k-ctypes-pep3118/Modules/_cursesmodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_cursesmodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_cursesmodule.c Wed Apr 30 15:57:13 2008 @@ -1711,11 +1711,20 @@ NoArgTrueFalseFunction(has_ic) NoArgTrueFalseFunction(has_il) NoArgTrueFalseFunction(isendwin) -NoArgNoReturnVoidFunction(filter) NoArgNoReturnVoidFunction(flushinp) NoArgNoReturnVoidFunction(noqiflush) static PyObject * +PyCurses_filter(PyObject *self) +{ + /* not checking for PyCursesInitialised here since filter() must + be called before initscr() */ + filter(); + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject * PyCurses_Color_Content(PyObject *self, PyObject *args) { short color,r,g,b; Modified: python/branches/py3k-ctypes-pep3118/Modules/_fileio.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_fileio.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_fileio.c Wed Apr 30 15:57:13 2008 @@ -104,11 +104,7 @@ if (self->fd < 0) return 0; if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) { -#ifdef HAVE_STRERROR char *msg = strerror(EISDIR); -#else - char *msg = "Is a directory"; -#endif PyObject *exc; internal_close(self); @@ -295,12 +291,8 @@ if (self->fd >= 0 && self->closefd) { errno = internal_close(self); if (errno < 0) { -#ifdef HAVE_STRERROR PySys_WriteStderr("close failed: [Errno %d] %s\n", errno, strerror(errno)); -#else - PySys_WriteStderr("close failed: [Errno %d]\n", errno); -#endif } } Modified: python/branches/py3k-ctypes-pep3118/Modules/_heapqmodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_heapqmodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_heapqmodule.c Wed Apr 30 15:57:13 2008 @@ -196,6 +196,48 @@ item = heapreplace(heap, item)\n"); static PyObject * +heappushpop(PyObject *self, PyObject *args) +{ + PyObject *heap, *item, *returnitem; + int cmp; + + if (!PyArg_UnpackTuple(args, "heappushpop", 2, 2, &heap, &item)) + return NULL; + + if (!PyList_Check(heap)) { + PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); + return NULL; + } + + if (PyList_GET_SIZE(heap) < 1) { + Py_INCREF(item); + return item; + } + + cmp = PyObject_RichCompareBool(item, PyList_GET_ITEM(heap, 0), Py_LE); + if (cmp == -1) + return NULL; + if (cmp == 1) { + Py_INCREF(item); + return item; + } + + returnitem = PyList_GET_ITEM(heap, 0); + Py_INCREF(item); + PyList_SET_ITEM(heap, 0, item); + if (_siftup((PyListObject *)heap, 0) == -1) { + Py_DECREF(returnitem); + return NULL; + } + return returnitem; +} + +PyDoc_STRVAR(heappushpop_doc, +"Push item on the heap, then pop and return the smallest item\n\ +from the heap. The combined action runs more efficiently than\n\ +heappush() followed by a separate call to heappop()."); + +static PyObject * heapify(PyObject *self, PyObject *heap) { Py_ssize_t i, n; @@ -468,6 +510,8 @@ static PyMethodDef heapq_methods[] = { {"heappush", (PyCFunction)heappush, METH_VARARGS, heappush_doc}, + {"heappushpop", (PyCFunction)heappushpop, + METH_VARARGS, heappushpop_doc}, {"heappop", (PyCFunction)heappop, METH_O, heappop_doc}, {"heapreplace", (PyCFunction)heapreplace, Modified: python/branches/py3k-ctypes-pep3118/Modules/_localemodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_localemodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_localemodule.c Wed Apr 30 15:57:13 2008 @@ -1,5 +1,5 @@ /*********************************************************** -Copyright (C) 1997, 2002, 2003, 2007 Martin von Loewis +Copyright (C) 1997, 2002, 2003, 2007, 2008 Martin von Loewis Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, @@ -45,6 +45,35 @@ static PyObject *Error; +/* Convert a char* to a Unicode object according to the current locale */ +static PyObject* +str2uni(const char* s) +{ + size_t needed = mbstowcs(NULL, s, 0); + size_t res1; + wchar_t smallbuf[30]; + wchar_t *dest; + PyObject *res2; + if (needed == (size_t)-1) { + PyErr_SetString(PyExc_ValueError, "Cannot convert byte to string"); + return NULL; + } + if (needed*sizeof(wchar_t) < sizeof(smallbuf)) + dest = smallbuf; + else { + dest = PyMem_Malloc((needed+1)*sizeof(wchar_t)); + if (!dest) + return PyErr_NoMemory(); + } + /* This shouldn't fail now */ + res1 = mbstowcs(dest, s, needed+1); + assert(res1 == needed); + res2 = PyUnicode_FromWideChar(dest, res1); + if (dest != smallbuf) + PyMem_Free(dest); + return res2; +} + /* support functions for formatting floating point numbers */ PyDoc_STRVAR(setlocale__doc__, @@ -107,7 +136,7 @@ PyErr_SetString(Error, "unsupported locale setting"); return NULL; } - result_object = PyUnicode_FromString(result); + result_object = str2uni(result); if (!result_object) return NULL; } else { @@ -117,7 +146,7 @@ PyErr_SetString(Error, "locale query failed"); return NULL; } - result_object = PyUnicode_FromString(result); + result_object = str2uni(result); } return result_object; } @@ -143,7 +172,7 @@ involved herein */ #define RESULT_STRING(s)\ - x = PyUnicode_DecodeUnicodeEscape(l->s, strlen(l->s), "strict");\ + x = str2uni(l->s); \ if (!x) goto failed;\ PyDict_SetItemString(result, #s, x);\ Py_XDECREF(x) @@ -191,29 +220,19 @@ return NULL; } +#if defined(HAVE_WCSCOLL) PyDoc_STRVAR(strcoll__doc__, "string,string -> int. Compares two strings according to the locale."); static PyObject* PyLocale_strcoll(PyObject* self, PyObject* args) { -#if !defined(HAVE_WCSCOLL) - char *s1,*s2; - - if (!PyArg_ParseTuple(args, "ss:strcoll", &s1, &s2)) - return NULL; - return PyLong_FromLong(strcoll(s1, s2)); -#else PyObject *os1, *os2, *result = NULL; wchar_t *ws1 = NULL, *ws2 = NULL; - int len1, len2; + Py_ssize_t len1, len2; - if (!PyArg_UnpackTuple(args, "strcoll", 2, 2, &os1, &os2)) + if (!PyArg_ParseTuple(args, "UU:strcoll", &os1, &os2)) return NULL; - /* Both arguments must be unicode, or it's an error. */ - if (!PyUnicode_Check(os1) || !PyUnicode_Check(os2)) { - PyErr_SetString(PyExc_ValueError, "strcoll arguments must be strings"); - } /* Convert the unicode strings to wchar[]. */ len1 = PyUnicode_GET_SIZE(os1) + 1; ws1 = PyMem_MALLOC(len1 * sizeof(wchar_t)); @@ -240,40 +259,62 @@ if (ws1) PyMem_FREE(ws1); if (ws2) PyMem_FREE(ws2); return result; -#endif } +#endif - +#ifdef HAVE_WCSXFRM PyDoc_STRVAR(strxfrm__doc__, "string -> string. Returns a string that behaves for cmp locale-aware."); static PyObject* PyLocale_strxfrm(PyObject* self, PyObject* args) { - char *s, *buf; + Py_UNICODE *s0; + Py_ssize_t n0; + wchar_t *s, *buf = NULL; size_t n1, n2; - PyObject *result; + PyObject *result = NULL; + Py_ssize_t i; - if (!PyArg_ParseTuple(args, "s:strxfrm", &s)) + if (!PyArg_ParseTuple(args, "u#:strxfrm", &s0, &n0)) return NULL; - /* assume no change in size, first */ - n1 = strlen(s) + 1; - buf = PyMem_Malloc(n1); - if (!buf) +#ifdef HAVE_USABLE_WCHAR_T + s = s0; +#else + s = PyMem_Malloc((n0+1)*sizeof(wchar_t)); + if (!s) return PyErr_NoMemory(); - n2 = strxfrm(buf, s, n1) + 1; - if (n2 > n1) { + for (i=0; i<=n0; i++) + s[i] = s0[i]; +#endif + + /* assume no change in size, first */ + n1 = wcslen(s) + 1; + buf = PyMem_Malloc(n1*sizeof(wchar_t)); + if (!buf) { + PyErr_NoMemory(); + goto exit; + } + n2 = wcsxfrm(buf, s, n1); + if (n2 >= n1) { /* more space needed */ - buf = PyMem_Realloc(buf, n2); - if (!buf) - return PyErr_NoMemory(); - strxfrm(buf, s, n2); + buf = PyMem_Realloc(buf, (n2+1)*sizeof(wchar_t)); + if (!buf) { + PyErr_NoMemory(); + goto exit; + } + n2 = wcsxfrm(buf, s, n2); } - result = PyUnicode_FromString(buf); - PyMem_Free(buf); + result = PyUnicode_FromWideChar(buf, n2); + exit: + if (buf) PyMem_Free(buf); +#ifdef HAVE_USABLE_WCHAR_T + PyMem_Free(s); +#endif return result; } +#endif #if defined(MS_WINDOWS) static PyObject* @@ -472,9 +513,7 @@ instead of an empty string for nl_langinfo(ERA). */ const char *result = nl_langinfo(item); result = result != NULL ? result : ""; - /* XXX may have to convert this to wcs first. */ - return PyUnicode_DecodeUnicodeEscape(result, strlen(result), - "strict"); + return str2uni(result); } PyErr_SetString(PyExc_ValueError, "unsupported langinfo constant"); return NULL; @@ -493,7 +532,7 @@ char *in; if (!PyArg_ParseTuple(args, "z", &in)) return 0; - return PyUnicode_FromString(gettext(in)); + return str2uni(gettext(in)); } PyDoc_STRVAR(dgettext__doc__, @@ -506,7 +545,7 @@ char *domain, *in; if (!PyArg_ParseTuple(args, "zz", &domain, &in)) return 0; - return PyUnicode_FromString(dgettext(domain, in)); + return str2uni(dgettext(domain, in)); } PyDoc_STRVAR(dcgettext__doc__, @@ -520,7 +559,7 @@ int category; if (!PyArg_ParseTuple(args, "zzi", &domain, &msgid, &category)) return 0; - return PyUnicode_FromString(dcgettext(domain,msgid,category)); + return str2uni(dcgettext(domain,msgid,category)); } PyDoc_STRVAR(textdomain__doc__, @@ -538,7 +577,7 @@ PyErr_SetFromErrno(PyExc_OSError); return NULL; } - return PyUnicode_FromString(domain); + return str2uni(domain); } PyDoc_STRVAR(bindtextdomain__doc__, @@ -556,7 +595,7 @@ PyErr_SetFromErrno(PyExc_OSError); return NULL; } - return PyUnicode_FromString(dirname); + return str2uni(dirname); } #ifdef HAVE_BIND_TEXTDOMAIN_CODESET @@ -572,7 +611,7 @@ return NULL; codeset = bind_textdomain_codeset(domain, codeset); if (codeset) - return PyUnicode_FromString(codeset); + return str2uni(codeset); Py_RETURN_NONE; } #endif @@ -584,10 +623,14 @@ METH_VARARGS, setlocale__doc__}, {"localeconv", (PyCFunction) PyLocale_localeconv, METH_NOARGS, localeconv__doc__}, +#ifdef HAVE_WCSCOLL {"strcoll", (PyCFunction) PyLocale_strcoll, METH_VARARGS, strcoll__doc__}, +#endif +#ifdef HAVE_WCSXFRM {"strxfrm", (PyCFunction) PyLocale_strxfrm, METH_VARARGS, strxfrm__doc__}, +#endif #if defined(MS_WINDOWS) || defined(__APPLE__) {"_getdefaultlocale", (PyCFunction) PyLocale_getdefaultlocale, METH_NOARGS}, #endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_sqlite/cache.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_sqlite/cache.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_sqlite/cache.c Wed Apr 30 15:57:13 2008 @@ -1,6 +1,6 @@ /* cache .c - a LRU cache * - * Copyright (C) 2004-2006 Gerhard H?ring + * Copyright (C) 2004-2007 Gerhard H?ring * * This file is part of pysqlite. * Modified: python/branches/py3k-ctypes-pep3118/Modules/_sqlite/cache.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_sqlite/cache.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_sqlite/cache.h Wed Apr 30 15:57:13 2008 @@ -1,6 +1,6 @@ /* cache.h - definitions for the LRU cache * - * Copyright (C) 2004-2006 Gerhard H?ring + * Copyright (C) 2004-2007 Gerhard H?ring * * This file is part of pysqlite. * Modified: python/branches/py3k-ctypes-pep3118/Modules/_sqlite/connection.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_sqlite/connection.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_sqlite/connection.c Wed Apr 30 15:57:13 2008 @@ -1,6 +1,6 @@ /* connection.c - the connection type * - * Copyright (C) 2004-2006 Gerhard H?ring + * Copyright (C) 2004-2007 Gerhard H?ring * * This file is part of pysqlite. * @@ -32,6 +32,9 @@ #include "pythread.h" +#define ACTION_FINALIZE 1 +#define ACTION_RESET 2 + static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level); @@ -63,7 +66,7 @@ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|diOiOi", kwlist, &database, &timeout, &detect_types, &isolation_level, &check_same_thread, &factory, &cached_statements)) { - return -1; + return -1; } self->begin_statement = NULL; @@ -82,7 +85,7 @@ Py_END_ALLOW_THREADS if (rc != SQLITE_OK) { - _pysqlite_seterror(self->db); + _pysqlite_seterror(self->db, NULL); return -1; } @@ -169,7 +172,8 @@ self->statement_cache->decref_factory = 0; } -void pysqlite_reset_all_statements(pysqlite_Connection* self) +/* action in (ACTION_RESET, ACTION_FINALIZE) */ +void pysqlite_do_all_statements(pysqlite_Connection* self, int action) { int i; PyObject* weakref; @@ -179,7 +183,11 @@ weakref = PyList_GetItem(self->statements, i); statement = PyWeakref_GetObject(weakref); if (statement != Py_None) { - (void)pysqlite_statement_reset((pysqlite_Statement*)statement); + if (action == ACTION_RESET) { + (void)pysqlite_statement_reset((pysqlite_Statement*)statement); + } else { + (void)pysqlite_statement_finalize((pysqlite_Statement*)statement); + } } } } @@ -247,7 +255,7 @@ return NULL; } - pysqlite_flush_statement_cache(self); + pysqlite_do_all_statements(self, ACTION_FINALIZE); if (self->db) { Py_BEGIN_ALLOW_THREADS @@ -255,7 +263,7 @@ Py_END_ALLOW_THREADS if (rc != SQLITE_OK) { - _pysqlite_seterror(self->db); + _pysqlite_seterror(self->db, NULL); return NULL; } else { self->db = NULL; @@ -292,7 +300,7 @@ Py_END_ALLOW_THREADS if (rc != SQLITE_OK) { - _pysqlite_seterror(self->db); + _pysqlite_seterror(self->db, statement); goto error; } @@ -300,7 +308,7 @@ if (rc == SQLITE_DONE) { self->inTransaction = 1; } else { - _pysqlite_seterror(self->db); + _pysqlite_seterror(self->db, statement); } Py_BEGIN_ALLOW_THREADS @@ -308,7 +316,7 @@ Py_END_ALLOW_THREADS if (rc != SQLITE_OK && !PyErr_Occurred()) { - _pysqlite_seterror(self->db); + _pysqlite_seterror(self->db, NULL); } error: @@ -335,7 +343,7 @@ rc = sqlite3_prepare(self->db, "COMMIT", -1, &statement, &tail); Py_END_ALLOW_THREADS if (rc != SQLITE_OK) { - _pysqlite_seterror(self->db); + _pysqlite_seterror(self->db, NULL); goto error; } @@ -343,14 +351,14 @@ if (rc == SQLITE_DONE) { self->inTransaction = 0; } else { - _pysqlite_seterror(self->db); + _pysqlite_seterror(self->db, statement); } Py_BEGIN_ALLOW_THREADS rc = sqlite3_finalize(statement); Py_END_ALLOW_THREADS if (rc != SQLITE_OK && !PyErr_Occurred()) { - _pysqlite_seterror(self->db); + _pysqlite_seterror(self->db, NULL); } } @@ -375,13 +383,13 @@ } if (self->inTransaction) { - pysqlite_reset_all_statements(self); + pysqlite_do_all_statements(self, ACTION_RESET); Py_BEGIN_ALLOW_THREADS rc = sqlite3_prepare(self->db, "ROLLBACK", -1, &statement, &tail); Py_END_ALLOW_THREADS if (rc != SQLITE_OK) { - _pysqlite_seterror(self->db); + _pysqlite_seterror(self->db, NULL); goto error; } @@ -389,14 +397,14 @@ if (rc == SQLITE_DONE) { self->inTransaction = 0; } else { - _pysqlite_seterror(self->db); + _pysqlite_seterror(self->db, statement); } Py_BEGIN_ALLOW_THREADS rc = sqlite3_finalize(statement); Py_END_ALLOW_THREADS if (rc != SQLITE_OK && !PyErr_Occurred()) { - _pysqlite_seterror(self->db); + _pysqlite_seterror(self->db, NULL); } } @@ -746,6 +754,33 @@ return rc; } +static int _progress_handler(void* user_arg) +{ + int rc; + PyObject *ret; + PyGILState_STATE gilstate; + + gilstate = PyGILState_Ensure(); + ret = PyObject_CallFunction((PyObject*)user_arg, ""); + + if (!ret) { + if (_enable_callback_tracebacks) { + PyErr_Print(); + } else { + PyErr_Clear(); + } + + /* abort query if error occured */ + rc = 1; + } else { + rc = (int)PyObject_IsTrue(ret); + Py_DECREF(ret); + } + + PyGILState_Release(gilstate); + return rc; +} + PyObject* pysqlite_connection_set_authorizer(pysqlite_Connection* self, PyObject* args, PyObject* kwargs) { PyObject* authorizer_cb; @@ -771,6 +806,30 @@ } } +PyObject* pysqlite_connection_set_progress_handler(pysqlite_Connection* self, PyObject* args, PyObject* kwargs) +{ + PyObject* progress_handler; + int n; + + static char *kwlist[] = { "progress_handler", "n", NULL }; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Oi:set_progress_handler", + kwlist, &progress_handler, &n)) { + return NULL; + } + + if (progress_handler == Py_None) { + /* None clears the progress handler previously set */ + sqlite3_progress_handler(self->db, 0, 0, (void*)0); + } else { + sqlite3_progress_handler(self->db, n, _progress_handler, progress_handler); + PyDict_SetItem(self->function_pinboard, progress_handler, Py_None); + } + + Py_INCREF(Py_None); + return Py_None; +} + int pysqlite_check_thread(pysqlite_Connection* self) { if (self->check_same_thread) { @@ -881,7 +940,8 @@ } else if (rc == PYSQLITE_SQL_WRONG_TYPE) { PyErr_SetString(pysqlite_Warning, "SQL is of wrong type. Must be string or unicode."); } else { - _pysqlite_seterror(self->db); + (void)pysqlite_statement_reset(statement); + _pysqlite_seterror(self->db, NULL); } Py_DECREF(statement); @@ -1069,6 +1129,52 @@ return retval; } +/* Function author: Paul Kippes + * Class method of Connection to call the Python function _iterdump + * of the sqlite3 module. + */ +static PyObject * +pysqlite_connection_iterdump(pysqlite_Connection* self, PyObject* args) +{ + PyObject* retval = NULL; + PyObject* module = NULL; + PyObject* module_dict; + PyObject* pyfn_iterdump; + + if (!pysqlite_check_connection(self)) { + goto finally; + } + + module = PyImport_ImportModule(MODULE_NAME ".dump"); + if (!module) { + goto finally; + } + + module_dict = PyModule_GetDict(module); + if (!module_dict) { + goto finally; + } + + pyfn_iterdump = PyDict_GetItemString(module_dict, "_iterdump"); + if (!pyfn_iterdump) { + PyErr_SetString(pysqlite_OperationalError, "Failed to obtain _iterdump() reference"); + goto finally; + } + + args = PyTuple_New(1); + if (!args) { + goto finally; + } + Py_INCREF(self); + PyTuple_SetItem(args, 0, (PyObject*)self); + retval = PyObject_CallObject(pyfn_iterdump, args); + +finally: + Py_XDECREF(args); + Py_XDECREF(module); + return retval; +} + static PyObject * pysqlite_connection_create_collation(pysqlite_Connection* self, PyObject* args) { @@ -1123,7 +1229,7 @@ (callable != Py_None) ? pysqlite_collation_callback : NULL); if (rc != SQLITE_OK) { PyDict_DelItem(self->collations, uppercase_name); - _pysqlite_seterror(self->db); + _pysqlite_seterror(self->db, NULL); goto finally; } @@ -1140,6 +1246,43 @@ return retval; } +/* Called when the connection is used as a context manager. Returns itself as a + * convenience to the caller. */ +static PyObject * +pysqlite_connection_enter(pysqlite_Connection* self, PyObject* args) +{ + Py_INCREF(self); + return (PyObject*)self; +} + +/** Called when the connection is used as a context manager. If there was any + * exception, a rollback takes place; otherwise we commit. */ +static PyObject * +pysqlite_connection_exit(pysqlite_Connection* self, PyObject* args) +{ + PyObject* exc_type, *exc_value, *exc_tb; + char* method_name; + PyObject* result; + + if (!PyArg_ParseTuple(args, "OOO", &exc_type, &exc_value, &exc_tb)) { + return NULL; + } + + if (exc_type == Py_None && exc_value == Py_None && exc_tb == Py_None) { + method_name = "commit"; + } else { + method_name = "rollback"; + } + + result = PyObject_CallMethod((PyObject*)self, method_name, ""); + if (!result) { + return NULL; + } + Py_DECREF(result); + + Py_RETURN_FALSE; +} + static char connection_doc[] = PyDoc_STR("SQLite database connection object."); @@ -1164,6 +1307,8 @@ PyDoc_STR("Creates a new aggregate. Non-standard.")}, {"set_authorizer", (PyCFunction)pysqlite_connection_set_authorizer, METH_VARARGS|METH_KEYWORDS, PyDoc_STR("Sets authorizer callback. Non-standard.")}, + {"set_progress_handler", (PyCFunction)pysqlite_connection_set_progress_handler, METH_VARARGS|METH_KEYWORDS, + PyDoc_STR("Sets progress handler callback. Non-standard.")}, {"execute", (PyCFunction)pysqlite_connection_execute, METH_VARARGS, PyDoc_STR("Executes a SQL statement. Non-standard.")}, {"executemany", (PyCFunction)pysqlite_connection_executemany, METH_VARARGS, @@ -1174,6 +1319,13 @@ PyDoc_STR("Creates a collation function. Non-standard.")}, {"interrupt", (PyCFunction)pysqlite_connection_interrupt, METH_NOARGS, PyDoc_STR("Abort any pending database operation. Non-standard.")}, + {"iterdump", (PyCFunction)pysqlite_connection_iterdump, METH_NOARGS, + PyDoc_STR("Returns iterator to the dump of the database in an SQL text" + "format.")}, + {"__enter__", (PyCFunction)pysqlite_connection_enter, METH_NOARGS, + PyDoc_STR("For context manager. Non-standard.")}, + {"__exit__", (PyCFunction)pysqlite_connection_exit, METH_VARARGS, + PyDoc_STR("For context manager. Non-standard.")}, {NULL, NULL} }; Modified: python/branches/py3k-ctypes-pep3118/Modules/_sqlite/connection.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_sqlite/connection.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_sqlite/connection.h Wed Apr 30 15:57:13 2008 @@ -1,6 +1,6 @@ /* connection.h - definitions for the connection type * - * Copyright (C) 2004-2006 Gerhard H?ring + * Copyright (C) 2004-2007 Gerhard H?ring * * This file is part of pysqlite. * Modified: python/branches/py3k-ctypes-pep3118/Modules/_sqlite/cursor.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_sqlite/cursor.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_sqlite/cursor.c Wed Apr 30 15:57:13 2008 @@ -1,6 +1,6 @@ /* cursor.c - the cursor type * - * Copyright (C) 2004-2006 Gerhard H?ring + * Copyright (C) 2004-2007 Gerhard H?ring * * This file is part of pysqlite. * @@ -80,7 +80,7 @@ if (!PyArg_ParseTuple(args, "O!", &pysqlite_ConnectionType, &connection)) { - return -1; + return -1; } Py_INCREF(connection); @@ -255,23 +255,6 @@ PyObject* pysqlite_unicode_from_string(const char* val_str, int optimize) { - const char* check; - int is_ascii = 0; - - if (optimize) { - is_ascii = 1; - - check = val_str; - while (*check) { - if (*check & 0x80) { - is_ascii = 0; - break; - } - - check++; - } - } - return PyUnicode_FromString(val_str); } @@ -295,6 +278,8 @@ const char* val_str; char buf[200]; const char* colname; + PyObject* buf_bytes; + PyObject* error_obj; Py_BEGIN_ALLOW_THREADS numcols = sqlite3_data_count(self->statement->st); @@ -363,7 +348,19 @@ } PyOS_snprintf(buf, sizeof(buf) - 1, "Could not decode to UTF-8 column '%s' with text '%s'", colname , val_str); - PyErr_SetString(pysqlite_OperationalError, buf); + buf_bytes = PyBytes_FromStringAndSize(buf, strlen(buf)); + if (!buf_bytes) { + PyErr_SetString(pysqlite_OperationalError, "Could not decode to UTF-8"); + } else { + error_obj = PyUnicode_FromEncodedObject(buf_bytes, "ascii", "replace"); + if (!error_obj) { + PyErr_SetString(pysqlite_OperationalError, "Could not decode to UTF-8"); + } else { + PyErr_SetObject(pysqlite_OperationalError, error_obj); + Py_DECREF(error_obj); + } + Py_DECREF(buf_bytes); + } } } else if (self->connection->text_factory == (PyObject*)&PyString_Type) { converted = PyString_FromString(val_str); @@ -418,10 +415,14 @@ PyObject* descriptor; PyObject* second_argument = NULL; long rowcount = 0; + int allow_8bit_chars; if (!pysqlite_check_thread(self->connection) || !pysqlite_check_connection(self->connection)) { return NULL; } + /* Make shooting yourself in the foot with not utf-8 decodable 8-bit-strings harder */ + allow_8bit_chars = ((self->connection->text_factory != (PyObject*)&PyUnicode_Type) && + (self->connection->text_factory != (PyObject*)&PyUnicode_Type && pysqlite_OptimizedUnicode)); Py_XDECREF(self->next_row); self->next_row = NULL; @@ -429,7 +430,7 @@ if (multiple) { /* executemany() */ if (!PyArg_ParseTuple(args, "OO", &operation, &second_argument)) { - return NULL; + return NULL; } if (!PyUnicode_Check(operation)) { @@ -451,7 +452,7 @@ } else { /* execute() */ if (!PyArg_ParseTuple(args, "O|O", &operation, &second_argument)) { - return NULL; + return NULL; } if (!PyUnicode_Check(operation)) { @@ -493,17 +494,48 @@ if (operation == NULL) goto error; - /* reset description and rowcount */ + /* reset description */ Py_DECREF(self->description); Py_INCREF(Py_None); self->description = Py_None; - Py_DECREF(self->rowcount); - self->rowcount = PyLong_FromLong(-1L); - if (!self->rowcount) { + func_args = PyTuple_New(1); + if (!func_args) { + goto error; + } + Py_INCREF(operation); + if (PyTuple_SetItem(func_args, 0, operation) != 0) { + goto error; + } + + if (self->statement) { + (void)pysqlite_statement_reset(self->statement); + Py_DECREF(self->statement); + } + + self->statement = (pysqlite_Statement*)pysqlite_cache_get(self->connection->statement_cache, func_args); + Py_DECREF(func_args); + + if (!self->statement) { goto error; } + if (self->statement->in_use) { + Py_DECREF(self->statement); + self->statement = PyObject_New(pysqlite_Statement, &pysqlite_StatementType); + if (!self->statement) { + goto error; + } + rc = pysqlite_statement_create(self->statement, self->connection, operation); + if (rc != SQLITE_OK) { + self->statement = 0; + goto error; + } + } + + pysqlite_statement_reset(self->statement); + pysqlite_statement_mark_dirty(self->statement); + statement_type = detect_statement_type(operation_cstr); if (self->connection->begin_statement) { switch (statement_type) { @@ -585,7 +617,7 @@ pysqlite_statement_mark_dirty(self->statement); - pysqlite_statement_bind_parameters(self->statement, parameters); + pysqlite_statement_bind_parameters(self->statement, parameters, allow_8bit_chars); if (PyErr_Occurred()) { goto error; } @@ -613,7 +645,8 @@ continue; } else { /* If the database gave us an error, promote it to Python. */ - _pysqlite_seterror(self->connection->db); + (void)pysqlite_statement_reset(self->statement); + _pysqlite_seterror(self->connection->db, NULL); goto error; } } else { @@ -625,17 +658,27 @@ PyErr_Clear(); } } - _pysqlite_seterror(self->connection->db); + (void)pysqlite_statement_reset(self->statement); + _pysqlite_seterror(self->connection->db, NULL); goto error; } } + if (pysqlite_build_row_cast_map(self) != 0) { + PyErr_SetString(pysqlite_OperationalError, "Error while building row_cast_map"); + goto error; + } + if (rc == SQLITE_ROW || (rc == SQLITE_DONE && statement_type == STATEMENT_SELECT)) { Py_BEGIN_ALLOW_THREADS numcols = sqlite3_column_count(self->statement->st); Py_END_ALLOW_THREADS if (self->description == Py_None) { + Py_BEGIN_ALLOW_THREADS + numcols = sqlite3_column_count(self->statement->st); + Py_END_ALLOW_THREADS + Py_DECREF(self->description); self->description = PyTuple_New(numcols); if (!self->description) { @@ -676,15 +719,11 @@ case STATEMENT_DELETE: case STATEMENT_INSERT: case STATEMENT_REPLACE: - Py_BEGIN_ALLOW_THREADS rowcount += (long)sqlite3_changes(self->connection->db); - Py_END_ALLOW_THREADS - Py_DECREF(self->rowcount); - self->rowcount = PyLong_FromLong(rowcount); } Py_DECREF(self->lastrowid); - if (statement_type == STATEMENT_INSERT) { + if (!multiple && statement_type == STATEMENT_INSERT) { Py_BEGIN_ALLOW_THREADS lastrowid = sqlite3_last_insert_rowid(self->connection->db); Py_END_ALLOW_THREADS @@ -701,13 +740,26 @@ } error: + /* just to be sure (implicit ROLLBACKs with ON CONFLICT ROLLBACK/OR + * ROLLBACK could have happened */ + #ifdef SQLITE_VERSION_NUMBER + #if SQLITE_VERSION_NUMBER >= 3002002 + self->connection->inTransaction = !sqlite3_get_autocommit(self->connection->db); + #endif + #endif + Py_XDECREF(parameters); Py_XDECREF(parameters_iter); Py_XDECREF(parameters_list); if (PyErr_Occurred()) { + Py_DECREF(self->rowcount); + self->rowcount = PyLong_FromLong(-1L); return NULL; } else { + Py_DECREF(self->rowcount); + self->rowcount = PyLong_FromLong(rowcount); + Py_INCREF(self); return (PyObject*)self; } @@ -734,7 +786,7 @@ int statement_completed = 0; if (!PyArg_ParseTuple(args, "O", &script_obj)) { - return NULL; + return NULL; } if (!pysqlite_check_thread(self->connection) || !pysqlite_check_connection(self->connection)) { @@ -770,7 +822,7 @@ &statement, &script_cstr); if (rc != SQLITE_OK) { - _pysqlite_seterror(self->connection->db); + _pysqlite_seterror(self->connection->db, NULL); goto error; } @@ -778,17 +830,18 @@ rc = SQLITE_ROW; while (rc == SQLITE_ROW) { rc = _sqlite_step_with_busyhandler(statement, self->connection); + /* TODO: we probably need more error handling here */ } if (rc != SQLITE_DONE) { (void)sqlite3_finalize(statement); - _pysqlite_seterror(self->connection->db); + _pysqlite_seterror(self->connection->db, NULL); goto error; } rc = sqlite3_finalize(statement); if (rc != SQLITE_OK) { - _pysqlite_seterror(self->connection->db); + _pysqlite_seterror(self->connection->db, NULL); goto error; } } @@ -846,8 +899,9 @@ if (self->statement) { rc = _sqlite_step_with_busyhandler(self->statement->st, self->connection); if (rc != SQLITE_DONE && rc != SQLITE_ROW) { + (void)pysqlite_statement_reset(self->statement); Py_DECREF(next_row); - _pysqlite_seterror(self->connection->db); + _pysqlite_seterror(self->connection->db, NULL); return NULL; } @@ -872,15 +926,17 @@ return row; } -PyObject* pysqlite_cursor_fetchmany(pysqlite_Cursor* self, PyObject* args) +PyObject* pysqlite_cursor_fetchmany(pysqlite_Cursor* self, PyObject* args, PyObject* kwargs) { + static char *kwlist[] = {"size", NULL, NULL}; + PyObject* row; PyObject* list; int maxrows = self->arraysize; int counter = 0; - if (!PyArg_ParseTuple(args, "|i", &maxrows)) { - return NULL; + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i:fetchmany", kwlist, &maxrows)) { + return NULL; } list = PyList_New(0); @@ -974,7 +1030,7 @@ PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")}, {"fetchone", (PyCFunction)pysqlite_cursor_fetchone, METH_NOARGS, PyDoc_STR("Fetches one row from the resultset.")}, - {"fetchmany", (PyCFunction)pysqlite_cursor_fetchmany, METH_VARARGS, + {"fetchmany", (PyCFunction)pysqlite_cursor_fetchmany, METH_VARARGS|METH_KEYWORDS, PyDoc_STR("Fetches several rows from the resultset.")}, {"fetchall", (PyCFunction)pysqlite_cursor_fetchall, METH_NOARGS, PyDoc_STR("Fetches all rows from the resultset.")}, Modified: python/branches/py3k-ctypes-pep3118/Modules/_sqlite/cursor.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_sqlite/cursor.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_sqlite/cursor.h Wed Apr 30 15:57:13 2008 @@ -1,6 +1,6 @@ /* cursor.h - definitions for the cursor type * - * Copyright (C) 2004-2006 Gerhard H?ring + * Copyright (C) 2004-2007 Gerhard H?ring * * This file is part of pysqlite. * @@ -60,7 +60,7 @@ PyObject* pysqlite_cursor_getiter(pysqlite_Cursor *self); PyObject* pysqlite_cursor_iternext(pysqlite_Cursor *self); PyObject* pysqlite_cursor_fetchone(pysqlite_Cursor* self, PyObject* args); -PyObject* pysqlite_cursor_fetchmany(pysqlite_Cursor* self, PyObject* args); +PyObject* pysqlite_cursor_fetchmany(pysqlite_Cursor* self, PyObject* args, PyObject* kwargs); PyObject* pysqlite_cursor_fetchall(pysqlite_Cursor* self, PyObject* args); PyObject* pysqlite_noop(pysqlite_Connection* self, PyObject* args); PyObject* pysqlite_cursor_close(pysqlite_Cursor* self, PyObject* args); Modified: python/branches/py3k-ctypes-pep3118/Modules/_sqlite/microprotocols.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_sqlite/microprotocols.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_sqlite/microprotocols.h Wed Apr 30 15:57:13 2008 @@ -28,10 +28,6 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - /** adapters registry **/ extern PyObject *psyco_adapters; Modified: python/branches/py3k-ctypes-pep3118/Modules/_sqlite/module.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_sqlite/module.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_sqlite/module.c Wed Apr 30 15:57:13 2008 @@ -1,25 +1,25 @@ - /* module.c - the module itself - * - * Copyright (C) 2004-2006 Gerhard H?ring - * - * This file is part of pysqlite. - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - */ +/* module.c - the module itself + * + * Copyright (C) 2004-2007 Gerhard H?ring + * + * This file is part of pysqlite. + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any damages + * arising from the use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software + * in a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * 3. This notice may not be removed or altered from any source distribution. + */ #include "connection.h" #include "statement.h" @@ -41,6 +41,7 @@ PyObject* converters; int _enable_callback_tracebacks; +int pysqlite_BaseTypeAdapted; static PyObject* module_connect(PyObject* self, PyObject* args, PyObject* kwargs) @@ -133,6 +134,13 @@ return NULL; } + /* a basic type is adapted; there's a performance optimization if that's not the case + * (99 % of all usages) */ + if (type == &PyLong_Type || type == &PyFloat_Type + || type == &PyUnicode_Type || type == &PyBytes_Type) { + pysqlite_BaseTypeAdapted = 1; + } + microprotocols_add(type, (PyObject*)&pysqlite_PrepareProtocolType, caster); Py_INCREF(Py_None); @@ -379,6 +387,8 @@ _enable_callback_tracebacks = 0; + pysqlite_BaseTypeAdapted = 0; + /* Original comment form _bsddb.c in the Python core. This is also still * needed nowadays for Python 2.3/2.4. * Modified: python/branches/py3k-ctypes-pep3118/Modules/_sqlite/module.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_sqlite/module.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_sqlite/module.h Wed Apr 30 15:57:13 2008 @@ -1,6 +1,6 @@ /* module.h - definitions for the module * - * Copyright (C) 2004-2006 Gerhard H?ring + * Copyright (C) 2004-2007 Gerhard H?ring * * This file is part of pysqlite. * @@ -25,7 +25,7 @@ #define PYSQLITE_MODULE_H #include "Python.h" -#define PYSQLITE_VERSION "2.3.3" +#define PYSQLITE_VERSION "2.4.1" extern PyObject* pysqlite_Error; extern PyObject* pysqlite_Warning; @@ -51,6 +51,7 @@ extern PyObject* converters; extern int _enable_callback_tracebacks; +extern int pysqlite_BaseTypeAdapted; #define PARSE_DECLTYPES 1 #define PARSE_COLNAMES 2 Modified: python/branches/py3k-ctypes-pep3118/Modules/_sqlite/prepare_protocol.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_sqlite/prepare_protocol.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_sqlite/prepare_protocol.h Wed Apr 30 15:57:13 2008 @@ -1,6 +1,6 @@ /* prepare_protocol.h - the protocol for preparing values for SQLite * - * Copyright (C) 2005 Gerhard H?ring + * Copyright (C) 2005-2007 Gerhard H?ring * * This file is part of pysqlite. * Modified: python/branches/py3k-ctypes-pep3118/Modules/_sqlite/row.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_sqlite/row.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_sqlite/row.c Wed Apr 30 15:57:13 2008 @@ -154,6 +154,11 @@ return list; } +static int pysqlite_row_print(pysqlite_Row* self, FILE *fp, int flags) +{ + return (&PyTuple_Type)->tp_print(self->data, fp, flags); +} + static PyObject* pysqlite_iter(pysqlite_Row* self) { return PyObject_GetIter(self->data); @@ -178,7 +183,7 @@ sizeof(pysqlite_Row), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)pysqlite_row_dealloc, /* tp_dealloc */ - 0, /* tp_print */ + (printfunc)pysqlite_row_print, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ Modified: python/branches/py3k-ctypes-pep3118/Modules/_sqlite/row.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_sqlite/row.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_sqlite/row.h Wed Apr 30 15:57:13 2008 @@ -1,6 +1,6 @@ /* row.h - an enhanced tuple for database rows * - * Copyright (C) 2005 Gerhard H?ring + * Copyright (C) 2005-2007 Gerhard H?ring * * This file is part of pysqlite. * Modified: python/branches/py3k-ctypes-pep3118/Modules/_sqlite/statement.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_sqlite/statement.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_sqlite/statement.c Wed Apr 30 15:57:13 2008 @@ -1,6 +1,6 @@ /* statement.c - the statement type * - * Copyright (C) 2005-2006 Gerhard H?ring + * Copyright (C) 2005-2007 Gerhard H?ring * * This file is part of pysqlite. * @@ -40,6 +40,15 @@ NORMAL } parse_remaining_sql_state; +typedef enum { + TYPE_LONG, + TYPE_FLOAT, + TYPE_STRING, + TYPE_UNICODE, + TYPE_BUFFER, + TYPE_UNKNOWN +} parameter_type; + int pysqlite_statement_create(pysqlite_Statement* self, pysqlite_Connection* connection, PyObject* sql) { const char* tail; @@ -77,52 +86,102 @@ return rc; } -int pysqlite_statement_bind_parameter(pysqlite_Statement* self, int pos, PyObject* parameter) +int pysqlite_statement_bind_parameter(pysqlite_Statement* self, int pos, PyObject* parameter, int allow_8bit_chars) { int rc = SQLITE_OK; + long longval; #ifdef HAVE_LONG_LONG PY_LONG_LONG longlongval; -#else - long longval; #endif const char* buffer; char* string; Py_ssize_t buflen; + parameter_type paramtype; + char* c; if (parameter == Py_None) { rc = sqlite3_bind_null(self->st, pos); -#ifdef HAVE_LONG_LONG - } else if (PyLong_Check(parameter)) { - longlongval = PyLong_AsLongLong(parameter); - /* in the overflow error case, longlongval is -1, and an exception is set */ - rc = sqlite3_bind_int64(self->st, pos, (sqlite_int64)longlongval); -#else + goto final; + } + + if (PyLong_CheckExact(parameter)) { + paramtype = TYPE_LONG; + } else if (PyFloat_CheckExact(parameter)) { + paramtype = TYPE_FLOAT; + } else if (PyUnicode_CheckExact(parameter)) { + paramtype = TYPE_UNICODE; } else if (PyLong_Check(parameter)) { - longval = PyLong_AsLong(parameter); - /* in the overflow error case, longval is -1, and an exception is set */ - rc = sqlite3_bind_int64(self->st, pos, (sqlite_int64)longval); -#endif + paramtype = TYPE_LONG; } else if (PyFloat_Check(parameter)) { - rc = sqlite3_bind_double(self->st, pos, PyFloat_AsDouble(parameter)); - } else if PyUnicode_Check(parameter) { - string = PyUnicode_AsString(parameter); - - rc = sqlite3_bind_text(self->st, pos, string, -1, SQLITE_TRANSIENT); + paramtype = TYPE_FLOAT; + } else if (PyUnicode_Check(parameter)) { + paramtype = TYPE_STRING; } else if (PyObject_CheckBuffer(parameter)) { - if (PyObject_AsCharBuffer(parameter, &buffer, &buflen) == 0) { - rc = sqlite3_bind_blob(self->st, pos, buffer, buflen, SQLITE_TRANSIENT); - } else { - PyErr_SetString(PyExc_ValueError, "could not convert BLOB to buffer"); - rc = -1; - } + paramtype = TYPE_BUFFER; } else { - rc = -1; + paramtype = TYPE_UNKNOWN; } + if (paramtype == TYPE_STRING && !allow_8bit_chars) { + string = PyString_AS_STRING(parameter); + for (c = string; *c != 0; c++) { + if (*c & 0x80) { + PyErr_SetString(pysqlite_ProgrammingError, "You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings."); + rc = -1; + goto final; + } + } + } + + switch (paramtype) { + case TYPE_LONG: + /* in the overflow error case, longval/longlongval is -1, and an exception is set */ +#ifdef HAVE_LONG_LONG + longlongval = PyLong_AsLongLong(parameter); + rc = sqlite3_bind_int64(self->st, pos, (sqlite_int64)longlongval); +#else + rc = sqlite3_bind_int64(self->st, pos, (sqlite_int64)longval); +#endif + break; + case TYPE_FLOAT: + rc = sqlite3_bind_double(self->st, pos, PyFloat_AsDouble(parameter)); + break; + case TYPE_UNICODE: + string = PyUnicode_AsString(parameter); + rc = sqlite3_bind_text(self->st, pos, string, -1, SQLITE_TRANSIENT); + break; + case TYPE_BUFFER: + if (PyObject_AsCharBuffer(parameter, &buffer, &buflen) == 0) { + rc = sqlite3_bind_blob(self->st, pos, buffer, buflen, SQLITE_TRANSIENT); + } else { + PyErr_SetString(PyExc_ValueError, "could not convert BLOB to buffer"); + rc = -1; + } + break; + case TYPE_UNKNOWN: + rc = -1; + } + +final: return rc; } -void pysqlite_statement_bind_parameters(pysqlite_Statement* self, PyObject* parameters) +/* returns 0 if the object is one of Python's internal ones that don't need to be adapted */ +static int _need_adapt(PyObject* obj) +{ + if (pysqlite_BaseTypeAdapted) { + return 1; + } + + if (PyLong_CheckExact(obj) || PyFloat_CheckExact(obj) + || PyUnicode_CheckExact(obj) || PyBytes_CheckExact(obj)) { + return 0; + } else { + return 1; + } +} + +void pysqlite_statement_bind_parameters(pysqlite_Statement* self, PyObject* parameters, int allow_8bit_chars) { PyObject* current_param; PyObject* adapted; @@ -136,7 +195,57 @@ num_params_needed = sqlite3_bind_parameter_count(self->st); Py_END_ALLOW_THREADS - if (PyDict_Check(parameters)) { + if (PyTuple_CheckExact(parameters) || PyList_CheckExact(parameters) || (!PyDict_Check(parameters) && PySequence_Check(parameters))) { + /* parameters passed as sequence */ + if (PyTuple_CheckExact(parameters)) { + num_params = PyTuple_GET_SIZE(parameters); + } else if (PyList_CheckExact(parameters)) { + num_params = PyList_GET_SIZE(parameters); + } else { + num_params = PySequence_Size(parameters); + } + if (num_params != num_params_needed) { + PyErr_Format(pysqlite_ProgrammingError, "Incorrect number of bindings supplied. The current statement uses %d, and there are %d supplied.", + num_params_needed, num_params); + return; + } + for (i = 0; i < num_params; i++) { + if (PyTuple_CheckExact(parameters)) { + current_param = PyTuple_GET_ITEM(parameters, i); + Py_XINCREF(current_param); + } else if (PyList_CheckExact(parameters)) { + current_param = PyList_GET_ITEM(parameters, i); + Py_XINCREF(current_param); + } else { + current_param = PySequence_GetItem(parameters, i); + } + if (!current_param) { + return; + } + + if (!_need_adapt(current_param)) { + adapted = current_param; + } else { + adapted = microprotocols_adapt(current_param, (PyObject*)&pysqlite_PrepareProtocolType, NULL); + if (adapted) { + Py_DECREF(current_param); + } else { + PyErr_Clear(); + adapted = current_param; + } + } + + rc = pysqlite_statement_bind_parameter(self, i + 1, adapted, allow_8bit_chars); + Py_DECREF(adapted); + + if (rc != SQLITE_OK) { + if (!PyErr_Occurred()) { + PyErr_Format(pysqlite_InterfaceError, "Error binding parameter %d - probably unsupported type.", i); + } + return; + } + } + } else if (PyDict_Check(parameters)) { /* parameters passed as dictionary */ for (i = 1; i <= num_params_needed; i++) { Py_BEGIN_ALLOW_THREADS @@ -148,59 +257,41 @@ } binding_name++; /* skip first char (the colon) */ - current_param = PyDict_GetItemString(parameters, binding_name); + if (PyDict_CheckExact(parameters)) { + current_param = PyDict_GetItemString(parameters, binding_name); + Py_XINCREF(current_param); + } else { + current_param = PyMapping_GetItemString(parameters, (char*)binding_name); + } if (!current_param) { PyErr_Format(pysqlite_ProgrammingError, "You did not supply a value for binding %d.", i); return; } - Py_INCREF(current_param); - adapted = microprotocols_adapt(current_param, (PyObject*)&pysqlite_PrepareProtocolType, NULL); - if (adapted) { - Py_DECREF(current_param); - } else { - PyErr_Clear(); + if (!_need_adapt(current_param)) { adapted = current_param; + } else { + adapted = microprotocols_adapt(current_param, (PyObject*)&pysqlite_PrepareProtocolType, NULL); + if (adapted) { + Py_DECREF(current_param); + } else { + PyErr_Clear(); + adapted = current_param; + } } - rc = pysqlite_statement_bind_parameter(self, i, adapted); + rc = pysqlite_statement_bind_parameter(self, i, adapted, allow_8bit_chars); Py_DECREF(adapted); if (rc != SQLITE_OK) { - PyErr_Format(pysqlite_InterfaceError, "Error binding parameter :%s - probably unsupported type.", binding_name); + if (!PyErr_Occurred()) { + PyErr_Format(pysqlite_InterfaceError, "Error binding parameter :%s - probably unsupported type.", binding_name); + } return; } } } else { - /* parameters passed as sequence */ - num_params = PySequence_Length(parameters); - if (num_params != num_params_needed) { - PyErr_Format(pysqlite_ProgrammingError, "Incorrect number of bindings supplied. The current statement uses %d, and there are %d supplied.", - num_params_needed, num_params); - return; - } - for (i = 0; i < num_params; i++) { - current_param = PySequence_GetItem(parameters, i); - if (!current_param) { - return; - } - adapted = microprotocols_adapt(current_param, (PyObject*)&pysqlite_PrepareProtocolType, NULL); - - if (adapted) { - Py_DECREF(current_param); - } else { - PyErr_Clear(); - adapted = current_param; - } - - rc = pysqlite_statement_bind_parameter(self, i + 1, adapted); - Py_DECREF(adapted); - - if (rc != SQLITE_OK) { - PyErr_Format(pysqlite_InterfaceError, "Error binding parameter %d - probably unsupported type.", i); - return; - } - } + PyErr_SetString(PyExc_ValueError, "parameters are of unsupported type"); } } @@ -400,7 +491,7 @@ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ Modified: python/branches/py3k-ctypes-pep3118/Modules/_sqlite/statement.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_sqlite/statement.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_sqlite/statement.h Wed Apr 30 15:57:13 2008 @@ -1,6 +1,6 @@ /* statement.h - definitions for the statement type * - * Copyright (C) 2005 Gerhard H?ring + * Copyright (C) 2005-2007 Gerhard H?ring * * This file is part of pysqlite. * @@ -46,8 +46,8 @@ int pysqlite_statement_create(pysqlite_Statement* self, pysqlite_Connection* connection, PyObject* sql); void pysqlite_statement_dealloc(pysqlite_Statement* self); -int pysqlite_statement_bind_parameter(pysqlite_Statement* self, int pos, PyObject* parameter); -void pysqlite_statement_bind_parameters(pysqlite_Statement* self, PyObject* parameters); +int pysqlite_statement_bind_parameter(pysqlite_Statement* self, int pos, PyObject* parameter, int allow_8bit_chars); +void pysqlite_statement_bind_parameters(pysqlite_Statement* self, PyObject* parameters, int allow_8bit_chars); int pysqlite_statement_recompile(pysqlite_Statement* self, PyObject* parameters); int pysqlite_statement_finalize(pysqlite_Statement* self); Modified: python/branches/py3k-ctypes-pep3118/Modules/_sqlite/util.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_sqlite/util.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_sqlite/util.c Wed Apr 30 15:57:13 2008 @@ -1,6 +1,6 @@ /* util.c - various utility functions * - * Copyright (C) 2005-2006 Gerhard H?ring + * Copyright (C) 2005-2007 Gerhard H?ring * * This file is part of pysqlite. * @@ -45,10 +45,15 @@ * Checks the SQLite error code and sets the appropriate DB-API exception. * Returns the error code (0 means no error occurred). */ -int _pysqlite_seterror(sqlite3* db) +int _pysqlite_seterror(sqlite3* db, sqlite3_stmt* st) { int errorcode; + /* SQLite often doesn't report anything useful, unless you reset the statement first */ + if (st != NULL) { + (void)sqlite3_reset(st); + } + errorcode = sqlite3_errcode(db); switch (errorcode) Modified: python/branches/py3k-ctypes-pep3118/Modules/_sqlite/util.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_sqlite/util.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_sqlite/util.h Wed Apr 30 15:57:13 2008 @@ -1,6 +1,6 @@ /* util.h - various utility functions * - * Copyright (C) 2005-2006 Gerhard H?ring + * Copyright (C) 2005-2007 Gerhard H?ring * * This file is part of pysqlite. * @@ -34,5 +34,5 @@ * Checks the SQLite error code and sets the appropriate DB-API exception. * Returns the error code (0 means no error occurred). */ -int _pysqlite_seterror(sqlite3* db); +int _pysqlite_seterror(sqlite3* db, sqlite3_stmt* st); #endif Modified: python/branches/py3k-ctypes-pep3118/Modules/_ssl.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_ssl.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_ssl.c Wed Apr 30 15:57:13 2008 @@ -684,7 +684,7 @@ } p = ext->value->data; - if(method->it) + if (method->it) names = (GENERAL_NAMES*) (ASN1_item_d2i(NULL, &p, @@ -1518,7 +1518,7 @@ */ if ((_ssl_locks == NULL) || - (n < 0) || (n >= _ssl_locks_count)) + (n < 0) || ((unsigned)n >= _ssl_locks_count)) return; if (mode & CRYPTO_LOCK) { @@ -1530,7 +1530,7 @@ static int _setup_ssl_threads(void) { - int i; + unsigned int i; if (_ssl_locks == NULL) { _ssl_locks_count = CRYPTO_num_locks(); Modified: python/branches/py3k-ctypes-pep3118/Modules/_struct.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_struct.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_struct.c Wed Apr 30 15:57:13 2008 @@ -797,7 +797,7 @@ {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong}, {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong}, #endif - {'t', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool}, + {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool}, {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float}, {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double}, {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p}, @@ -1034,7 +1034,7 @@ {'L', 4, 0, bu_uint, bp_uint}, {'q', 8, 0, bu_longlong, bp_longlong}, {'Q', 8, 0, bu_ulonglong, bp_ulonglong}, - {'t', 1, 0, bu_bool, bp_bool}, + {'?', 1, 0, bu_bool, bp_bool}, {'f', 4, 0, bu_float, bp_float}, {'d', 8, 0, bu_double, bp_double}, {0} @@ -1253,7 +1253,7 @@ {'L', 4, 0, lu_uint, lp_uint}, {'q', 8, 0, lu_longlong, lp_longlong}, {'Q', 8, 0, lu_ulonglong, lp_ulonglong}, - {'t', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep, + {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep, but potentially different from native rep -- reuse bx_bool funcs. */ {'f', 4, 0, lu_float, lp_float}, {'d', 8, 0, lu_double, lp_double}, @@ -1486,7 +1486,7 @@ return -1; } - Py_XDECREF(soself->s_format); + Py_CLEAR(soself->s_format); soself->s_format = o_format; ret = prepare_s(soself); Modified: python/branches/py3k-ctypes-pep3118/Modules/_testcapimodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_testcapimodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_testcapimodule.c Wed Apr 30 15:57:13 2008 @@ -308,6 +308,22 @@ return Py_BuildValue("iii", a, b, c); } +/* test PyArg_ParseTupleAndKeywords */ +static PyObject *getargs_keywords(PyObject *self, PyObject *args, PyObject *kwargs) +{ + static char *keywords[] = {"arg1","arg2","arg3","arg4","arg5", NULL}; + static char *fmt="(ii)i|(i(ii))(iii)i"; + int int_args[10]={-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords, + &int_args[0], &int_args[1], &int_args[2], &int_args[3], &int_args[4], + &int_args[5], &int_args[6], &int_args[7], &int_args[8], &int_args[9])) + return NULL; + return Py_BuildValue("iiiiiiiiii", + int_args[0], int_args[1], int_args[2], int_args[3], int_args[4], + int_args[5], int_args[6], int_args[7], int_args[8], int_args[9]); +} + /* Functions to call PyArg_ParseTuple with integer format codes, and return the result. */ @@ -898,6 +914,8 @@ PyDoc_STR("This is a pretty normal docstring.")}, {"getargs_tuple", getargs_tuple, METH_VARARGS}, + {"getargs_keywords", (PyCFunction)getargs_keywords, + METH_VARARGS|METH_KEYWORDS}, {"getargs_b", getargs_b, METH_VARARGS}, {"getargs_B", getargs_B, METH_VARARGS}, {"getargs_H", getargs_H, METH_VARARGS}, Modified: python/branches/py3k-ctypes-pep3118/Modules/_tkinter.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_tkinter.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/_tkinter.c Wed Apr 30 15:57:13 2008 @@ -583,7 +583,7 @@ static void DisableEventHook(void); /* Forward */ static TkappObject * -Tkapp_New(char *screenName, char *baseName, char *className, +Tkapp_New(char *screenName, char *className, int interactive, int wantobjects, int wantTk, int sync, char *use) { TkappObject *v; @@ -2812,7 +2812,8 @@ Tkinter_Create(PyObject *self, PyObject *args) { char *screenName = NULL; - char *baseName = NULL; + char *baseName = NULL; /* XXX this is not used anymore; + try getting rid of it. */ char *className = NULL; int interactive = 0; int wantobjects = 0; @@ -2820,11 +2821,6 @@ int sync = 0; /* pass -sync to wish */ char *use = NULL; /* pass -use to wish */ - baseName = strrchr(Py_GetProgramName(), '/'); - if (baseName != NULL) - baseName++; - else - baseName = Py_GetProgramName(); className = "Tk"; if (!PyArg_ParseTuple(args, "|zssiiiiz:create", @@ -2833,7 +2829,7 @@ &sync, &use)) return NULL; - return (PyObject *) Tkapp_New(screenName, baseName, className, + return (PyObject *) Tkapp_New(screenName, className, interactive, wantobjects, wantTk, sync, use); } @@ -3016,7 +3012,7 @@ PyMODINIT_FUNC init_tkinter(void) { - PyObject *m, *d; + PyObject *m, *d, *uexe, *cexe; Py_TYPE(&Tkapp_Type) = &PyType_Type; @@ -3069,7 +3065,16 @@ /* This helps the dynamic loader; in Unicode aware Tcl versions it also helps Tcl find its encodings. */ - Tcl_FindExecutable(Py_GetProgramName()); + uexe = PyUnicode_FromWideChar(Py_GetProgramName(), -1); + if (uexe) { + cexe = PyUnicode_AsEncodedString(uexe, + Py_FileSystemDefaultEncoding, + NULL); + if (cexe) + Tcl_FindExecutable(PyString_AsString(cexe)); + Py_XDECREF(cexe); + Py_DECREF(uexe); + } if (PyErr_Occurred()) return; Deleted: python/branches/py3k-ctypes-pep3118/Modules/_typesmodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/_typesmodule.c Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,93 +0,0 @@ -/* This extension module exposes some types that are only available at the - * C level. It should not be used directly, but instead through the Python - * level types modules, which imports this. - */ - -#include "Python.h" -#include "structmember.h" - -typedef struct -{ - PyObject_HEAD - int member; -} Helper; - -static PyMemberDef helper_members[] = { - { "member", T_INT, offsetof(Helper, member), READONLY, - PyDoc_STR("A member descriptor") - }, - { NULL } -}; - -static PyObject * -helper_getter(Helper *self, void *unused) -{ - Py_RETURN_NONE; -} - -static PyGetSetDef helper_getset[] = { - { "getter", (getter)helper_getter, NULL, - PyDoc_STR("A getset descriptor"), - }, - { NULL } -}; - -static PyTypeObject HelperType = { - PyVarObject_HEAD_INIT(NULL, 0) - "_types.Helper", /* tp_name */ - sizeof(Helper), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - helper_members, /* tp_members */ - helper_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ -}; - -PyMODINIT_FUNC -init_types(void) -{ - PyObject *m; - - m = Py_InitModule3("_types", NULL, "A types module helper"); - if (!m) - return; - - if (PyType_Ready(&HelperType) < 0) - return; - - Py_INCREF(&HelperType); - PyModule_AddObject(m, "Helper", (PyObject *)&HelperType); -} - - Modified: python/branches/py3k-ctypes-pep3118/Modules/arraymodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/arraymodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/arraymodule.c Wed Apr 30 15:57:13 2008 @@ -1241,7 +1241,7 @@ "fromfile(f, n)\n\ \n\ Read n objects from the file object f and append them to the end of the\n\ -array. Also called as read."); +array."); static PyObject * @@ -1281,8 +1281,7 @@ PyDoc_STRVAR(tofile_doc, "tofile(f)\n\ \n\ -Write all items (as machine values) to the file object f. Also called as\n\ -write."); +Write all items (as machine values) to the file object f."); static PyObject * @@ -1523,8 +1522,6 @@ insert_doc}, {"pop", (PyCFunction)array_pop, METH_VARARGS, pop_doc}, - {"read", (PyCFunction)array_fromfile, METH_VARARGS, - fromfile_doc}, {"__reduce__", (PyCFunction)array_reduce, METH_NOARGS, array_doc}, {"remove", (PyCFunction)array_remove, METH_O, @@ -1541,8 +1538,6 @@ tostring_doc}, {"tounicode", (PyCFunction)array_tounicode, METH_NOARGS, tounicode_doc}, - {"write", (PyCFunction)array_tofile, METH_O, - tofile_doc}, {NULL, NULL} /* sentinel */ }; @@ -2010,13 +2005,11 @@ index() -- return index of first occurence of an object\n\ insert() -- insert a new item into the array at a provided position\n\ pop() -- remove and return item (default last)\n\ -read() -- DEPRECATED, use fromfile()\n\ remove() -- remove first occurence of an object\n\ reverse() -- reverse the order of the items in the array\n\ tofile() -- write all items to a file object\n\ tolist() -- return the array converted to an ordinary list\n\ tostring() -- return the array converted to a string\n\ -write() -- DEPRECATED, use tofile()\n\ \n\ Attributes:\n\ \n\ Modified: python/branches/py3k-ctypes-pep3118/Modules/binascii.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/binascii.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/binascii.c Wed Apr 30 15:57:13 2008 @@ -56,6 +56,9 @@ #define PY_SSIZE_T_CLEAN #include "Python.h" +#ifdef USE_ZLIB_CRC32 +#include "zlib.h" +#endif static PyObject *Error; static PyObject *Incomplete; @@ -776,6 +779,22 @@ PyDoc_STRVAR(doc_crc32, "(data, oldcrc = 0) -> newcrc. Compute CRC-32 incrementally"); +#ifdef USE_ZLIB_CRC32 +/* This was taken from zlibmodule.c PyZlib_crc32 (but is PY_SSIZE_T_CLEAN) */ +static PyObject * +binascii_crc32(PyObject *self, PyObject *args) +{ + unsigned int crc32val = 0; /* crc32(0L, Z_NULL, 0) */ + Byte *buf; + Py_ssize_t len; + int signed_val; + + if (!PyArg_ParseTuple(args, "s#|I:crc32", &buf, &len, &crc32val)) + return NULL; + signed_val = crc32(crc32val, buf, len); + return PyLong_FromUnsignedLong(signed_val & 0xffffffffU); +} +#else /* USE_ZLIB_CRC32 */ /* Crc - 32 BIT ANSI X3.66 CRC checksum files Also known as: ISO 3307 **********************************************************************| @@ -839,93 +858,82 @@ using byte-swap instructions. ********************************************************************/ -static unsigned long crc_32_tab[256] = { -0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, -0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL, -0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL, -0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL, -0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL, -0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL, -0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL, -0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL, -0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL, -0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL, -0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL, -0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL, -0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL, -0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL, -0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL, -0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL, -0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL, -0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL, -0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL, -0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL, -0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL, -0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL, -0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL, -0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL, -0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL, -0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL, -0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL, -0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL, -0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL, -0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL, -0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL, -0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL, -0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL, -0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL, -0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL, -0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL, -0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL, -0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL, -0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL, -0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL, -0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL, -0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL, -0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL, -0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL, -0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL, -0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL, -0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL, -0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL, -0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL, -0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL, -0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL, -0x2d02ef8dUL +static unsigned int crc_32_tab[256] = { +0x00000000U, 0x77073096U, 0xee0e612cU, 0x990951baU, 0x076dc419U, +0x706af48fU, 0xe963a535U, 0x9e6495a3U, 0x0edb8832U, 0x79dcb8a4U, +0xe0d5e91eU, 0x97d2d988U, 0x09b64c2bU, 0x7eb17cbdU, 0xe7b82d07U, +0x90bf1d91U, 0x1db71064U, 0x6ab020f2U, 0xf3b97148U, 0x84be41deU, +0x1adad47dU, 0x6ddde4ebU, 0xf4d4b551U, 0x83d385c7U, 0x136c9856U, +0x646ba8c0U, 0xfd62f97aU, 0x8a65c9ecU, 0x14015c4fU, 0x63066cd9U, +0xfa0f3d63U, 0x8d080df5U, 0x3b6e20c8U, 0x4c69105eU, 0xd56041e4U, +0xa2677172U, 0x3c03e4d1U, 0x4b04d447U, 0xd20d85fdU, 0xa50ab56bU, +0x35b5a8faU, 0x42b2986cU, 0xdbbbc9d6U, 0xacbcf940U, 0x32d86ce3U, +0x45df5c75U, 0xdcd60dcfU, 0xabd13d59U, 0x26d930acU, 0x51de003aU, +0xc8d75180U, 0xbfd06116U, 0x21b4f4b5U, 0x56b3c423U, 0xcfba9599U, +0xb8bda50fU, 0x2802b89eU, 0x5f058808U, 0xc60cd9b2U, 0xb10be924U, +0x2f6f7c87U, 0x58684c11U, 0xc1611dabU, 0xb6662d3dU, 0x76dc4190U, +0x01db7106U, 0x98d220bcU, 0xefd5102aU, 0x71b18589U, 0x06b6b51fU, +0x9fbfe4a5U, 0xe8b8d433U, 0x7807c9a2U, 0x0f00f934U, 0x9609a88eU, +0xe10e9818U, 0x7f6a0dbbU, 0x086d3d2dU, 0x91646c97U, 0xe6635c01U, +0x6b6b51f4U, 0x1c6c6162U, 0x856530d8U, 0xf262004eU, 0x6c0695edU, +0x1b01a57bU, 0x8208f4c1U, 0xf50fc457U, 0x65b0d9c6U, 0x12b7e950U, +0x8bbeb8eaU, 0xfcb9887cU, 0x62dd1ddfU, 0x15da2d49U, 0x8cd37cf3U, +0xfbd44c65U, 0x4db26158U, 0x3ab551ceU, 0xa3bc0074U, 0xd4bb30e2U, +0x4adfa541U, 0x3dd895d7U, 0xa4d1c46dU, 0xd3d6f4fbU, 0x4369e96aU, +0x346ed9fcU, 0xad678846U, 0xda60b8d0U, 0x44042d73U, 0x33031de5U, +0xaa0a4c5fU, 0xdd0d7cc9U, 0x5005713cU, 0x270241aaU, 0xbe0b1010U, +0xc90c2086U, 0x5768b525U, 0x206f85b3U, 0xb966d409U, 0xce61e49fU, +0x5edef90eU, 0x29d9c998U, 0xb0d09822U, 0xc7d7a8b4U, 0x59b33d17U, +0x2eb40d81U, 0xb7bd5c3bU, 0xc0ba6cadU, 0xedb88320U, 0x9abfb3b6U, +0x03b6e20cU, 0x74b1d29aU, 0xead54739U, 0x9dd277afU, 0x04db2615U, +0x73dc1683U, 0xe3630b12U, 0x94643b84U, 0x0d6d6a3eU, 0x7a6a5aa8U, +0xe40ecf0bU, 0x9309ff9dU, 0x0a00ae27U, 0x7d079eb1U, 0xf00f9344U, +0x8708a3d2U, 0x1e01f268U, 0x6906c2feU, 0xf762575dU, 0x806567cbU, +0x196c3671U, 0x6e6b06e7U, 0xfed41b76U, 0x89d32be0U, 0x10da7a5aU, +0x67dd4accU, 0xf9b9df6fU, 0x8ebeeff9U, 0x17b7be43U, 0x60b08ed5U, +0xd6d6a3e8U, 0xa1d1937eU, 0x38d8c2c4U, 0x4fdff252U, 0xd1bb67f1U, +0xa6bc5767U, 0x3fb506ddU, 0x48b2364bU, 0xd80d2bdaU, 0xaf0a1b4cU, +0x36034af6U, 0x41047a60U, 0xdf60efc3U, 0xa867df55U, 0x316e8eefU, +0x4669be79U, 0xcb61b38cU, 0xbc66831aU, 0x256fd2a0U, 0x5268e236U, +0xcc0c7795U, 0xbb0b4703U, 0x220216b9U, 0x5505262fU, 0xc5ba3bbeU, +0xb2bd0b28U, 0x2bb45a92U, 0x5cb36a04U, 0xc2d7ffa7U, 0xb5d0cf31U, +0x2cd99e8bU, 0x5bdeae1dU, 0x9b64c2b0U, 0xec63f226U, 0x756aa39cU, +0x026d930aU, 0x9c0906a9U, 0xeb0e363fU, 0x72076785U, 0x05005713U, +0x95bf4a82U, 0xe2b87a14U, 0x7bb12baeU, 0x0cb61b38U, 0x92d28e9bU, +0xe5d5be0dU, 0x7cdcefb7U, 0x0bdbdf21U, 0x86d3d2d4U, 0xf1d4e242U, +0x68ddb3f8U, 0x1fda836eU, 0x81be16cdU, 0xf6b9265bU, 0x6fb077e1U, +0x18b74777U, 0x88085ae6U, 0xff0f6a70U, 0x66063bcaU, 0x11010b5cU, +0x8f659effU, 0xf862ae69U, 0x616bffd3U, 0x166ccf45U, 0xa00ae278U, +0xd70dd2eeU, 0x4e048354U, 0x3903b3c2U, 0xa7672661U, 0xd06016f7U, +0x4969474dU, 0x3e6e77dbU, 0xaed16a4aU, 0xd9d65adcU, 0x40df0b66U, +0x37d83bf0U, 0xa9bcae53U, 0xdebb9ec5U, 0x47b2cf7fU, 0x30b5ffe9U, +0xbdbdf21cU, 0xcabac28aU, 0x53b39330U, 0x24b4a3a6U, 0xbad03605U, +0xcdd70693U, 0x54de5729U, 0x23d967bfU, 0xb3667a2eU, 0xc4614ab8U, +0x5d681b02U, 0x2a6f2b94U, 0xb40bbe37U, 0xc30c8ea1U, 0x5a05df1bU, +0x2d02ef8dU }; static PyObject * binascii_crc32(PyObject *self, PyObject *args) { /* By Jim Ahlstrom; All rights transferred to CNRI */ unsigned char *bin_data; - unsigned long crc = 0UL; /* initial value of CRC */ + unsigned int crc = 0; /* initial value of CRC */ Py_ssize_t len; - long result; + unsigned int result; - if ( !PyArg_ParseTuple(args, "s#|l:crc32", &bin_data, &len, &crc) ) + if ( !PyArg_ParseTuple(args, "s#|I:crc32", &bin_data, &len, &crc) ) return NULL; crc = ~ crc; -#if SIZEOF_LONG > 4 - /* only want the trailing 32 bits */ - crc &= 0xFFFFFFFFUL; -#endif - while (len--) - crc = crc_32_tab[(crc ^ *bin_data++) & 0xffUL] ^ (crc >> 8); + while (len--) { + crc = crc_32_tab[(crc ^ *bin_data++) & 0xff] ^ (crc >> 8); /* Note: (crc >> 8) MUST zero fill on left */ + } - result = (long)(crc ^ 0xFFFFFFFFUL); -#if SIZEOF_LONG > 4 - /* Extend the sign bit. This is one way to ensure the result is the - * same across platforms. The other way would be to return an - * unbounded unsigned long, but the evidence suggests that lots of - * code outside this treats the result as if it were a signed 4-byte - * integer. - */ - result |= -(result & (1L << 31)); -#endif - return PyLong_FromLong(result); + result = (crc ^ 0xFFFFFFFF); + return PyLong_FromUnsignedLong(result & 0xffffffff); } +#endif /* USE_ZLIB_CRC32 */ static PyObject * Modified: python/branches/py3k-ctypes-pep3118/Modules/cStringIO.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/cStringIO.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/cStringIO.c Wed Apr 30 15:57:13 2008 @@ -566,8 +566,7 @@ static PyObject * I_close(Iobject *self, PyObject *unused) { - Py_XDECREF(self->pbuf); - self->pbuf = NULL; + Py_CLEAR(self->pbuf); self->buf = NULL; self->pos = self->string_size = 0; Modified: python/branches/py3k-ctypes-pep3118/Modules/cjkcodecs/_codecs_hk.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/cjkcodecs/_codecs_hk.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/cjkcodecs/_codecs_hk.c Wed Apr 30 15:57:13 2008 @@ -26,6 +26,16 @@ return 0; } +/* + * There are four possible pair unicode -> big5hkscs maps as in HKSCS 2004: + * U+00CA U+0304 -> 8862 (U+00CA alone is mapped to 8866) + * U+00CA U+030C -> 8864 + * U+00EA U+0304 -> 88a3 (U+00EA alone is mapped to 88a7) + * U+00EA U+030C -> 88a5 + * These are handled by not mapping tables but a hand-written code. + */ +static const DBCHAR big5hkscs_pairenc_table[4] = {0x8862, 0x8864, 0x88a3, 0x88a5}; + ENCODER(big5hkscs) { while (inleft > 0) { @@ -46,7 +56,27 @@ REQUIRE_OUTBUF(2) if (c < 0x10000) { - TRYMAP_ENC(big5hkscs_bmp, code, c); + TRYMAP_ENC(big5hkscs_bmp, code, c) { + if (code == MULTIC) { + if (inleft >= 2 && + ((c & 0xffdf) == 0x00ca) && + (((*inbuf)[1] & 0xfff7) == 0x0304)) { + code = big5hkscs_pairenc_table[ + ((c >> 4) | + ((*inbuf)[1] >> 3)) & 3]; + insize = 2; + } + else if (inleft < 2 && + !(flags & MBENC_FLUSH)) + return MBERR_TOOFEW; + else { + if (c == 0xca) + code = 0x8866; + else /* c == 0xea */ + code = 0x88a7; + } + } + } else TRYMAP_ENC(big5, code, c); else return 1; } @@ -67,7 +97,7 @@ return 0; } -#define BH2S(c1, c2) (((c1) - 0x88) * (0xfe - 0x40 + 1) + ((c2) - 0x40)) +#define BH2S(c1, c2) (((c1) - 0x87) * (0xfe - 0x40 + 1) + ((c2) - 0x40)) DECODER(big5hkscs) { @@ -96,19 +126,19 @@ int s = BH2S(c, IN2); const unsigned char *hintbase; - assert(0x88 <= c && c <= 0xfe); + assert(0x87 <= c && c <= 0xfe); assert(0x40 <= IN2 && IN2 <= 0xfe); - if (BH2S(0x88, 0x40) <= s && s <= BH2S(0xa0, 0xfe)) { + if (BH2S(0x87, 0x40) <= s && s <= BH2S(0xa0, 0xfe)) { hintbase = big5hkscs_phint_0; - s -= BH2S(0x88, 0x40); + s -= BH2S(0x87, 0x40); } else if (BH2S(0xc6,0xa1) <= s && s <= BH2S(0xc8,0xfe)){ - hintbase = big5hkscs_phint_11939; + hintbase = big5hkscs_phint_12130; s -= BH2S(0xc6, 0xa1); } else if (BH2S(0xf9,0xd6) <= s && s <= BH2S(0xfe,0xfe)){ - hintbase = big5hkscs_phint_21733; + hintbase = big5hkscs_phint_21924; s -= BH2S(0xf9, 0xd6); } else @@ -123,7 +153,17 @@ NEXT(2, 1) } } - else return 2; + else { + switch ((c << 8) | IN2) { + case 0x8862: WRITE2(0x00ca, 0x0304); break; + case 0x8864: WRITE2(0x00ca, 0x030c); break; + case 0x88a3: WRITE2(0x00ea, 0x0304); break; + case 0x88a5: WRITE2(0x00ea, 0x030c); break; + default: return 2; + } + + NEXT(2, 2) /* all decoded codepoints are pairs, above. */ + } } return 0; Modified: python/branches/py3k-ctypes-pep3118/Modules/cjkcodecs/mappings_hk.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/cjkcodecs/mappings_hk.h (original) +++ python/branches/py3k-ctypes-pep3118/Modules/cjkcodecs/mappings_hk.h Wed Apr 30 15:57:13 2008 @@ -1,262 +1,271 @@ -static const ucs2_t __big5hkscs_decmap[6095] = { -62211,62212,62213,62214,62215,268,62217,209,205,62220,62221,203,8168,62224, -202,62226,62227,62228,62229,270,62231,62232,256,193,461,192,274,201,282,200, -332,211,465,210,62245,7870,62247,7872,202,257,225,462,224,593,275,233,283,232, -299,237,464,236,333,243,466,242,363,250,468,249,470,472,474,U,U,U,U,U,U,U,U,U, -U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,476,252,62276,7871,62278, -7873,234,609,62282,62283,41897,4421,U,25866,U,U,20029,28381,40270,37343,U,U, -30517,25745,20250,20264,20392,20822,20852,20892,20964,21153,21160,21307,21326, -21457,21464,22242,22768,22788,22791,22834,22836,23398,23454,23455,23706,24198, -24635,25993,26622,26628,26725,27982,28860,30005,32420,32428,32442,32455,32463, -32479,32518,32567,33402,33487,33647,35270,35774,35810,36710,36711,36718,U,U,U, -U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,29713,31996, -32205,26950,31433,21031,U,U,U,U,37260,30904,37214,32956,U,36107,33014,2535,U, -U,32927,40647,19661,40393,40460,19518,40438,28686,40458,41267,13761,U,28314, -33342,29977,U,18705,39532,39567,40857,31111,33900,7626,1488,10982,20004,20097, -20096,20103,20159,20203,20279,13388,20413,15944,20483,20616,13437,13459,13477, -20870,22789,20955,20988,20997,20105,21113,21136,21287,13767,21417,13649,21424, -13651,21442,21539,13677,13682,13953,21651,21667,21684,21689,21712,21743,21784, -21795,21800,13720,21823,13733,13759,21975,13765,32132,21797,U,3138,3349,20779, -21904,11462,14828,833,36422,19896,38117,16467,32958,30586,11320,14900,18389, -33117,27122,19946,25821,3452,4020,3285,4340,25741,36478,3734,3083,3940,11433, -33366,17619,U,3398,39501,33001,18420,20135,11458,39602,14951,38388,16365, -13574,21191,38868,30920,11588,40302,38933,U,17369,24741,25780,21731,11596, -11210,4215,14843,4207,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, -U,U,U,U,U,U,26330,26390,31136,25834,20562,3139,36456,8609,35660,1841,U,18443, -425,16378,22643,11661,U,17864,1276,24727,3916,3478,21881,16571,17338,U,19124, -10854,4253,33194,39157,3484,25465,14846,10101,36288,22177,25724,15939,U,42497, -3593,10959,11465,U,4296,14786,14738,14854,33435,13688,24137,8391,22098,3889, -11442,38688,13500,27709,20027,U,U,30068,11915,8712,42587,36045,3706,3124, -26652,32659,4303,10243,10553,13819,20963,3724,3981,3754,16275,3888,3399,4431, -3660,U,3755,2985,3400,4288,4413,16377,9878,25650,4013,13300,30265,11214,3454, -3455,11345,11349,14872,3736,4295,3886,42546,27472,36050,36249,36042,38314, -21708,33476,21945,U,40643,39974,39606,30558,11758,28992,33133,33004,23580, -25970,33076,14231,21343,32957,37302,3834,3599,3703,3835,13789,19947,13833, -3286,22191,10165,4297,3600,3704,4216,4424,33287,5205,3705,20048,11684,23124, -4125,4126,4341,4342,22428,3601,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, -U,U,U,U,U,U,U,U,U,U,U,30356,33485,4021,3707,20862,14083,4022,4480,21208,41661, -18906,6202,16759,33404,22681,21096,13850,22333,31666,23400,18432,19244,40743, -18919,39967,39821,23412,12605,22011,13810,22153,20008,22786,7105,63608,38737, -134,20059,20155,13630,23587,24401,24516,14586,25164,25909,27514,27701,27706, -28780,29227,20012,29357,18665,32594,31035,31993,32595,25194,13505,U,25419, -32770,32896,26130,26961,21341,34916,35265,30898,35744,36125,38021,38264,38271, -38376,36367,38886,39029,39118,39134,39267,38928,40060,40479,40644,27503,63751, -20023,135,38429,25143,38050,20539,28158,40051,62842,15817,34959,16718,28791, -23797,19232,20941,13657,23856,24866,35378,36775,37366,29073,26393,29626,12929, -41223,15499,6528,19216,30948,29698,20910,34575,16393,27235,41658,16931,34319, -U,31274,39239,35562,38741,28749,21284,8318,37876,30425,35299,62884,30685, -20131,20464,20668,20015,20247,62891,21556,32139,22674,22736,7606,24210,24217, -24514,10002,25995,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, -U,U,U,U,13305,26905,27203,15459,27903,U,29184,17669,29580,16091,18963,23317, -29881,35715,23716,22165,31379,31724,31939,32364,33528,34199,62924,34960,62926, -36537,62928,36815,34143,39392,37409,62933,36281,5183,16497,17058,23066,U,U,U, -39016,26475,17014,22333,U,34262,18811,33471,28941,19585,28020,23931,27413, -28606,62956,62957,23446,62959,U,32347,23870,23880,23894,15868,14351,23972, -23993,14368,14392,24130,24253,24357,24451,14600,14612,14655,14669,24791,24893, -23781,14729,25015,25017,25039,14776,25132,25232,25317,25368,14840,22193,U,U,U, -U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,14851,25570, -25595,25607,25690,14923,25792,23829,22049,40863,14999,25990,15037,26111,26195, -15090,26258,15138,26390,15170,26532,26624,15192,26698,26756,15218,15217,15227, -26889,26947,29276,26980,27039,27013,15292,27094,15325,27237,27252,27249,27266, -15340,27289,15346,27307,27317,27348,27382,27521,27585,27626,27765,27818,15563, -27906,27910,27942,28033,15599,28068,28081,28181,28184,28201,28294,35264,28347, -28386,28378,40831,28392,28393,28452,28468,15686,16193,28545,28606,15722,15733, -29111,23705,15754,28716,15761,28752,28756,28783,28799,28809,805,17345,13809, -3800,16087,22462,28371,28990,22496,13902,27042,35817,23412,31305,22753,38105, -31333,31357,22956,31419,31408,31426,31427,29137,25741,16842,31450,31453,31466, -16879,21682,23553,31499,31573,31529,21262,23806,31650,31599,33692,23476,27775, -31696,33825,31634,U,23840,15789,23653,33938,31738,U,31797,23745,31812,31875, -18562,31910,26237,17784,31945,31943,31974,31860,31987,31989,U,U,U,U,U,U,U,U,U, -U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,32359,17693,28228,32093, -28374,29837,32137,32171,28981,32179,U,16471,24617,32228,15635,32245,6137, -32229,33645,U,24865,24922,32366,32402,17195,37996,32295,32576,32577,32583, -31030,25296,39393,32663,25425,32675,5729,104,17756,14182,17667,33594,32762, -25737,U,32776,32797,U,32815,41095,27843,32827,32828,32865,10004,18825,26150, -15843,26344,26405,32935,35400,33031,33050,22704,9974,27775,25752,20408,25831, -5258,33304,6238,27219,19045,19093,17530,33321,2829,27218,15742,20473,5373, -34018,33634,27402,18855,13616,6003,15864,33450,26907,63892,16859,34123,33488, -33562,3606,6068,14017,12669,13658,33403,33506,33560,16011,28067,27397,27543, -13774,15807,33565,21996,33669,17675,28069,33708,U,33747,13438,28372,27223, -34138,13462,28226,12015,33880,23524,33905,15827,17636,27303,33866,15541,31064, -U,27542,28279,28227,34014,U,33681,17568,33939,34020,23697,16960,23744,17731, -34100,23282,28313,17703,34163,17686,26559,34326,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, -U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,34341,34363,34241,28808,34306,5506, -28877,63922,17770,34344,13896,6306,21495,29594,34430,34673,41208,34798,11303, -34737,34778,34831,22113,34412,26710,17935,34885,34886,30176,15801,30180,34910, -34972,18011,34996,34997,25537,35013,30583,30479,35207,35210,U,U,35239,35260, -35365,35303,31012,31421,35484,30611,37374,35472,31321,31465,31546,16271,18195, -31544,29052,35596,35615,21552,21861,35647,35660,35661,35497,19066,35728,35739, -35503,5855,17941,34895,35995,32084,32143,63956,14117,32083,36054,32152,32189, -36114,36099,6416,36059,28764,36113,19657,16080,36265,32770,4116,18826,15228, -33212,28940,31463,36525,36534,36547,37588,36633,36653,33637,33810,36773,37635, -41631,2640,36787,18730,35294,34109,15803,24312,12898,36857,40980,34492,34049, -8997,14720,28375,36919,34108,31422,36961,34156,34315,37032,34579,37060,34534, -37038,U,37223,15088,37289,37316,31916,35123,7817,37390,27807,37441,37474, -21945,U,35526,15515,35596,21979,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, -U,U,U,U,U,U,U,U,U,U,U,3377,37676,37739,35553,35819,28815,23235,35554,35557, -18789,37444,35820,35897,35839,37747,37979,36540,38277,38310,37926,38304,28662, -17081,9850,34520,4732,15918,18911,27676,38523,38550,16748,38563,28373,25050, -38582,30965,35552,38589,21452,18849,27832,628,25616,37039,37093,19153,6421, -13066,38705,34370,38710,18959,17725,17797,19177,28789,23361,38683,U,37333, -38743,23370,37355,38751,37925,20688,12471,12476,38793,38815,38833,38846,38848, -38866,38880,21612,38894,29724,37939,U,38901,37917,31098,19153,38964,38963, -38987,39014,15118,29045,15697,1584,16732,22278,39114,39095,39112,39111,19199, -27943,5843,21936,39137,39142,39148,37752,39225,18985,19314,38999,39173,39413, -39436,39483,39440,39512,22309,14020,37041,39893,39648,39650,39685,39668,19470, -39700,39725,34304,20532,39732,27048,14531,12413,39760,39744,40254,23109,6243, -39822,16971,39938,39935,39948,40552,40404,40887,41362,41387,41185,41251,41439, -40318,40323,41268,40462,26760,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, -U,U,U,U,U,U,U,U,U,U,40388,8539,41363,41504,6459,41523,40249,41145,41652,40592, -40597,40606,40610,19764,40618,40623,17252,40641,15200,14821,15645,20274,14270, -35883,40706,40712,19350,37924,28066,40727,U,40761,22175,22154,40773,39352, -37003,38898,33919,40802,40809,31452,40846,29206,19390,18805,18875,29047,18936, -17224,19025,29598,35802,6394,31135,35198,36406,37737,37875,35396,37612,37761, -37835,35180,17593,29207,16107,30578,31299,28880,17523,17400,29054,6127,28835, -6334,13721,16071,6277,21551,6136,14114,5883,6201,14049,6004,6353,24395,14115, -5824,22363,18981,5118,4776,5062,5302,34051,13990,U,33877,18836,29029,15921, -21852,16123,28754,17652,14062,39325,28454,26617,14131,15381,15847,22636,6434, -26640,16471,14143,16609,16523,16655,27681,21707,22174,26289,22162,4063,2984, -3597,37830,35603,37788,20216,20779,14361,17462,20156,1125,895,20299,20362, -22097,23144,427,971,14745,778,1044,13365,20265,704,36531,629,35546,524,20120, -U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,20685, -20749,20386,20227,18958,16010,20290,20526,20588,20609,20428,20453,20568,20732, -U,U,U,U,28278,13717,15929,16063,28018,6276,16009,20904,20931,1504,17629,1187, -1170,1169,36218,35484,1806,21081,21156,2163,21217,U,18042,29068,17292,3104, -18860,4324,27089,3613,U,16094,29849,29716,29782,29592,19342,19132,16525,21456, -13700,29199,16585,21940,837,21709,3014,22301,37469,38644,37734,22493,22413, -22399,13886,22731,23193,35398,5882,5999,5904,23084,22968,37519,23166,23247, -23058,22854,6643,6241,17045,14069,27909,29763,23073,24195,23169,35799,1043, -37856,29836,4867,28933,18802,37896,35323,37821,14240,23582,23710,24158,24136, -6550,6524,15086,24269,23375,6403,6404,14081,6304,14045,5886,14035,33066,35399, -7610,13426,35240,24332,24334,6439,6059,23147,5947,23364,34324,30205,34912, -24702,10336,9771,24539,16056,9647,9662,37000,28531,25024,62,70,9755,24985, -24984,24693,11419,11527,18132,37197,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, -U,U,U,U,U,U,U,U,U,U,U,U,U,25713,18021,11114,14889,11042,13392,39146,11896, -25399,42075,25782,25393,25553,18915,11623,25252,11425,25659,25963,26994,15348, -12430,12973,18825,12971,21773,13024,6361,37951,26318,12937,12723,15072,16784, -21892,35618,21903,5884,21851,21541,30958,12547,6186,12852,13412,12815,12674, -17097,26254,27940,26219,19347,26160,30832,7659,26211,13010,13025,26142,22642, -14545,14394,14268,15257,14242,13310,29904,15254,26511,17962,26806,26654,15300, -27326,14435,14293,17543,27187,27218,27337,27397,6418,25873,26776,27212,15319, -27258,27479,16320,15514,37792,37618,35818,35531,37513,32798,35292,37991,28069, -28427,18924,U,16255,15759,28164,16444,23101,28170,22599,27940,30786,28987, -17178,17014,28913,29264,29319,29332,18319,18213,20857,19108,1515,29818,16120, -13919,19018,18711,24545,16134,16049,19167,35875,16181,24743,16115,29900,29756, -37767,29751,17567,28138,17745,30083,16227,19673,19718,16216,30037,30323,42438, -15129,29800,35532,18859,18830,15099,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, -U,U,U,U,U,U,U,U,U,U,U,U,U,15821,19022,16127,18885,18675,37370,22322,37698, -35555,6244,20703,21025,20967,30584,12850,30478,30479,30587,18071,14209,14942, -18672,29752,29851,16063,19130,19143,16584,19094,25006,37639,21889,30750,30861, -30856,30930,29648,31065,30529,22243,16654,U,33942,31141,27181,16122,31290, -31220,16750,5862,16690,37429,31217,3404,18828,665,15802,5998,13719,21867, -13680,13994,468,3085,31458,23129,9973,23215,23196,23053,603,30960,23082,23494, -31486,16889,31837,31853,16913,23475,24252,24230,31949,18937,6064,31886,31868, -31918,27314,32220,32263,32211,32590,25185,24924,31560,32151,24194,17002,27509, -2326,26582,78,13775,22468,25618,25592,18786,32733,31527,2092,23273,23875, -31500,24078,39398,34373,39523,27164,13375,14818,18935,26029,39455,26016,33920, -28967,27857,17642,33079,17410,32966,33033,33090,26548,39107,27202,33378,33381, -27217,33875,28071,34320,29211,23174,16767,6208,23339,6305,23268,6360,34464, -63932,15759,34861,29730,23042,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, -U,U,U,U,U,U,U,U,U,U,34926,20293,34951,35007,35046,35173,35149,22147,35156, -30597,30596,35829,35801,35740,35321,16045,33955,18165,18127,14322,35389,35356, -37960,24397,37419,17028,26068,28969,28868,6213,40301,35999,36073,32220,22938, -30659,23024,17262,14036,36394,36519,19465,36656,36682,17140,27736,28603,8993, -18587,28537,28299,6106,39913,14005,18735,37051,U,21873,18694,37307,37892, -35403,16482,35580,37927,35869,35899,34021,35371,38297,38311,38295,38294,36148, -29765,16066,18687,19010,17386,16103,12837,38543,36583,36454,36453,16076,18925, -19064,16366,29714,29803,16124,38721,37040,26695,18973,37011,22495,U,37736, -35209,35878,35631,25534,37562,23313,35689,18748,29689,16923,38811,38769,39224, -3878,24001,35781,19122,38943,38106,37622,38359,37349,17600,35664,19047,35684, -39132,35397,16128,37418,18725,33812,39227,39245,31494,15869,39323,19311,39338, -39516,35685,22728,27279,39457,23294,39471,39153,19344,39240,39356,19389,19351, -37757,22642,4866,22562,18872,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, -U,U,U,U,U,U,U,U,U,U,5352,30788,10015,15800,26821,15741,37976,14631,24912, -10113,10603,24839,40015,40019,40059,39989,39952,39807,39887,40493,39839,41461, -41214,40225,19630,16644,40472,19632,40204,41396,41197,41203,39215,40357,33981, -28178,28639,27522,34300,17715,28068,28292,28144,33824,34286,28160,14295,24676, -31202,13724,13888,18733,18910,15714,37851,37566,37704,703,30905,37495,37965, -20452,13376,36964,21853,30781,30804,30902,30795,5975,12745,18753,13978,20338, -28634,28633,U,28702,21524,16821,22459,22771,22410,40214,22487,28980,13487, -16812,29163,27712,20375,U,6069,35401,24844,23246,23051,17084,17544,14124, -19323,35324,37819,37816,6358,3869,33906,27840,5139,17146,11302,17345,22932, -15799,26433,32168,24923,24740,18873,18827,35322,37605,29666,16105,29876,35683, -6303,16097,19123,27352,29683,29691,16086,19006,19092,6105,19046,935,5156, -18917,29768,18710,28837,18806,37508,29670,37727,1278,37681,35534,35350,37766, -35815,21973,18741,35458,29035,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, -U,U,U,U,U,U,U,U,U,U,18755,3327,22180,1562,3051,3256,21762,31172,6138,32254, -5826,19024,6226,17710,37889,14090,35520,18861,22960,6335,6275,29828,23201, -14050,15707,14000,37471,23161,35457,6242,37748,15565,2740,19094,14730,20724, -15721,15692,5020,29045,17147,33304,28175,37092,17643,27991,32335,28775,27823, -15574,16365,15917,28162,28428,15727,1013,30033,14012,13512,18048,16090,18545, -22980,37486,18750,36673,35868,27584,22546,22472,14038,5202,28926,17250,19057, -12259,4784,9149,26809,26983,5016,13541,31732,14047,35459,14294,13306,19615, -27162,13997,27831,33854,17631,17614,27942,27985,27778,28638,28439,28937,33597, -5946,33773,27776,28755,6107,22921,23170,6067,23137,23153,6405,16892,14125, -23023,5948,14023,29070,37776,26266,17061,23150,23083,17043,27179,16121,30518, -17499,17098,28957,16985,35297,20400,27944,23746,17614,32333,17341,27148,16982, -4868,28838,28979,17385,15781,27871,63525,19023,32357,23019,23855,15859,24412, -19037,6111,32164,33830,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, -U,U,U,U,U,U,U,21637,15098,13056,532,22398,2261,1561,16357,8094,41654,28675, -37211,23920,29583,31955,35417,37920,20424,32743,29389,29456,31476,29496,29497, -22262,29505,29512,16041,31512,36972,29173,18674,29665,33270,16074,30476,16081, -27810,22269,29721,29726,29727,16098,16112,16116,16122,29907,16142,16211,30018, -30061,30066,30093,16252,30152,30172,16320,30285,16343,30324,16348,30330,20316, -29064,22051,35200,22633,16413,30531,16441,26465,16453,13787,30616,16490,16495, -23646,30654,30667,22770,30744,28857,30748,16552,30777,30791,30801,30822,33864, -21813,31027,26627,31026,16643,16649,31121,31129,36795,31238,36796,16743,31377, -16818,31420,33401,16836,31439,31451,16847,20001,31586,31596,31611,31762,31771, -16992,17018,31867,31900,17036,31928,17044,31981,36755,28864,3279,32207,32212, -32208,32253,32686,32692,29343,17303,32800,32805,31545,32814,32817,32852,15820, -22452,28832,32951,33001,17389,33036,29482,33038,33042,30048,33044,17409,15161, -33110,33113,33114,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, -U,U,U,U,17427,22586,33148,33156,17445,33171,17453,33189,22511,33217,33252, -33364,17551,33446,33398,33482,33496,33535,17584,33623,38505,27018,33797,28917, -33892,24803,33928,17668,33982,34017,34040,34064,34104,34130,17723,34159,34160, -34272,17783,34418,34450,34482,34543,38469,34699,17926,17943,34990,35071,35108, -35143,35217,31079,35369,35384,35476,35508,35921,36052,36082,36124,18328,22623, -36291,18413,20206,36410,21976,22356,36465,22005,36528,18487,36558,36578,36580, -36589,36594,36791,36801,36810,36812,36915,39364,18605,39136,37395,18718,37416, -37464,37483,37553,37550,37567,37603,37611,37619,37620,37629,37699,37764,37805, -18757,18769,40639,37911,21249,37917,37933,37950,18794,37972,38009,38189,38306, -18855,38388,38451,18917,26528,18980,38720,18997,38834,38850,22100,19172,24808, -39097,19225,39153,22596,39182,39193,20916,39196,39223,39234,39261,39266,19312, -39365,19357,39484,39695,31363,39785,39809,39901,39921,39924,19565,39968,14191, -7106,40265,39994,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, -U,U,U,U,40702,22096,40339,40381,40384,40444,38134,36790,40571,40620,40625, -40637,40646,38108,40674,40689,40696,31432,40772,148,695,928,26906,38083,22956, -1239,22592,38081,14265,1493,1557,1654,5818,22359,29043,2754,2765,3007,21610, -63547,3019,21662,3067,3131,3155,3173,3196,24807,3213,22138,3253,3293,3309, -3439,3506,3528,26965,39983,34725,3588,3598,3799,3984,3885,3699,23584,4028, -24075,4188,4175,4214,26398,4219,4232,4246,13895,4287,4307,4399,4411,21348, -33965,4835,4981,4918,35713,5495,5657,6083,6087,20088,28859,6189,6506,6701, -6725,7210,7280,7340,7880,25283,7893,7957,29080,26709,8261,27113,14024,8828, -9175,9210,10026,10353,10575,33533,10599,10643,10965,35237,10984,36768,11022, -38840,11071,38983,39613,11340,U,11400,11447,23528,11528,11538,11703,11669, -11842,12148,12236,12339,12390,13087,13278,24497,26184,26303,31353,13671,13811, -U,18874,U,13850,14102,U,838,22709,26382,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, -U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,26904,15015,30295,24546,15889,16057,30206,8346, -18640,19128,16665,35482,17134,17165,16443,17204,17302,19013,1482,20946,1553, -22943,7848,15294,15615,17412,17622,22408,18036,14747,18223,34280,39369,14178, -8643,35678,35662,U,18450,18683,18965,29193,19136,3192,22885,20133,20358,1913, -36570,20524,21135,22335,29041,21145,21529,16202,19111,21948,21574,21614,27474, -U,13427,21823,30258,21854,18200,21858,21862,22471,18751,22621,20582,13563, -13260,U,22787,18300,35144,23214,23433,23558,7568,22433,29009,U,24834,31762, -36950,25010,20378,35682,25602,25674,23899,27639,U,25732,6428,35562,18934, -25736,16367,25874,19392,26047,26293,10011,37989,22497,24981,23079,63693,U, -22201,17697,26364,20074,18740,38486,28047,27837,13848,35191,26521,26734,25617, -26718,U,26823,31554,37056,2577,26918,U,26937,31301,U,27130,39462,27181,13919, -25705,33,31107,27188,27483,23852,13593,U,27549,18128,27812,30011,34917,28078, -22710,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, -14108,9613,28747,29133,15444,29312,29317,37505,8570,29323,37680,29414,18896, -27705,38047,29776,3832,34855,35061,10534,33907,6065,28344,18986,6176,14756, -14009,U,U,17727,26294,40109,39076,35139,30668,30808,22230,16607,5642,14753, -14127,33000,5061,29101,33638,31197,37288,U,19639,28847,35243,31229,31242, -31499,32102,16762,31555,31102,32777,28597,41695,27139,33560,21410,28167,37823, -26678,38749,33135,32803,27061,5101,12847,32840,23941,35888,32899,22293,38947, -35145,23979,18824,26046,27093,21458,19109,16257,15377,26422,32912,33012,33070, -8097,33103,33161,33199,33306,33542,33583,33674,13770,33896,34474,18682,25574, -35158,30728,37461,35256,17394,35303,17375,35304,35654,35796,23032,35849,U, -36805,37100,U,37136,37180,15863,37214,19146,36816,29327,22155,38119,38377, +static const ucs2_t __big5hkscs_decmap[6219] = { +17392,19506,17923,17830,17784,29287,19831,17843,31921,19682,31941,15253,18230, +18244,19527,19520,17087,13847,29522,28299,28882,19543,41809,18255,17882,19589, +31852,19719,19108,18081,27427,29221,23124,6755,15878,16225,26189,22267,U, +32149,22813,35769,15860,38708,31727,23515,7518,23204,13861,40624,23249,23479, +23804,26478,34195,39237,29793,29853,12736,12737,12738,12739,12740,268,12741, +209,205,12742,12743,203,8168,12744,202,12745,12746,12747,12748,270,12749, +12750,256,193,461,192,274,201,282,200,332,211,465,210,U,7870,U,7872,202,257, +225,462,224,593,275,233,283,232,299,237,464,236,333,243,466,242,363,250,468, +249,470,472,474,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, +U,U,U,476,252,U,7871,U,7873,234,609,9178,9179,41897,4421,U,25866,U,U,20029, +28381,40270,37343,U,U,30517,25745,20250,20264,20392,20822,20852,20892,20964, +21153,21160,21307,21326,21457,21464,22242,22768,22788,22791,22834,22836,23398, +23454,23455,23706,24198,24635,25993,26622,26628,26725,27982,28860,30005,32420, +32428,32442,32455,32463,32479,32518,32567,33402,33487,33647,35270,35774,35810, +36710,36711,36718,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, +U,U,U,U,29713,31996,32205,26950,31433,21031,U,U,U,U,37260,30904,37214,32956,U, +36107,33014,2535,U,U,32927,40647,19661,40393,40460,19518,40438,28686,40458, +41267,13761,U,28314,33342,29977,U,18705,39532,39567,40857,31111,33900,7626, +1488,10982,20004,20097,20096,20103,20159,20203,20279,13388,20413,15944,20483, +20616,13437,13459,13477,20870,22789,20955,20988,20997,20105,21113,21136,21287, +13767,21417,13649,21424,13651,21442,21539,13677,13682,13953,21651,21667,21684, +21689,21712,21743,21784,21795,21800,13720,21823,13733,13759,21975,13765,32132, +21797,U,3138,3349,20779,21904,11462,14828,833,36422,19896,38117,16467,32958, +30586,11320,14900,18389,33117,27122,19946,25821,3452,4020,3285,4340,25741, +36478,3734,3083,3940,11433,33366,17619,U,3398,39501,33001,18420,20135,11458, +39602,14951,38388,16365,13574,21191,38868,30920,11588,40302,38933,U,17369, +24741,25780,21731,11596,11210,4215,14843,4207,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, +U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,26330,26390,31136,25834,20562,3139,36456, +8609,35660,1841,U,18443,425,16378,22643,11661,U,17864,1276,24727,3916,3478, +21881,16571,17338,U,19124,10854,4253,33194,39157,3484,25465,14846,10101,36288, +22177,25724,15939,U,42497,3593,10959,11465,U,4296,14786,14738,14854,33435, +13688,24137,8391,22098,3889,11442,38688,13500,27709,20027,U,U,30068,11915, +8712,42587,36045,3706,3124,26652,32659,4303,10243,10553,13819,20963,3724,3981, +3754,16275,3888,3399,4431,3660,U,3755,2985,3400,4288,4413,16377,9878,25650, +4013,13300,30265,11214,3454,3455,11345,11349,14872,3736,4295,3886,42546,27472, +36050,36249,36042,38314,21708,33476,21945,U,40643,39974,39606,30558,11758, +28992,33133,33004,23580,25970,33076,14231,21343,32957,37302,3834,3599,3703, +3835,13789,19947,13833,3286,22191,10165,4297,3600,3704,4216,4424,33287,5205, +3705,20048,11684,23124,4125,4126,4341,4342,22428,3601,U,U,U,U,U,U,U,U,U,U,U,U, +U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,30356,33485,4021,3707,20862,14083, +4022,4480,21208,41661,18906,6202,16759,33404,22681,21096,13850,22333,31666, +23400,18432,19244,40743,18919,39967,39821,23412,12605,22011,13810,22153,20008, +22786,7105,63608,38737,134,20059,20155,13630,23587,24401,24516,14586,25164, +25909,27514,27701,27706,28780,29227,20012,29357,18665,32594,31035,31993,32595, +25194,13505,U,25419,32770,32896,26130,26961,21341,34916,35265,30898,35744, +36125,38021,38264,38271,38376,36367,38886,39029,39118,39134,39267,38928,40060, +40479,40644,27503,63751,20023,135,38429,25143,38050,20539,28158,40051,40870, +15817,34959,16718,28791,23797,19232,20941,13657,23856,24866,35378,36775,37366, +29073,26393,29626,12929,41223,15499,6528,19216,30948,29698,20910,34575,16393, +27235,41658,16931,34319,2671,31274,39239,35562,38741,28749,21284,8318,37876, +30425,35299,40871,30685,20131,20464,20668,20015,20247,40872,21556,32139,22674, +22736,7606,24210,24217,24514,10002,25995,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, +U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,13305,26905,27203,15459,27903,U,29184,17669, +29580,16091,18963,23317,29881,35715,23716,22165,31379,31724,31939,32364,33528, +34199,40873,34960,40874,36537,40875,36815,34143,39392,37409,40876,36281,5183, +16497,17058,23066,U,U,U,39016,26475,17014,22333,U,34262,18811,33471,28941, +19585,28020,23931,27413,28606,40877,40878,23446,40879,26343,32347,28247,31178, +15752,17603,12886,10134,17306,17718,U,23765,15130,35577,23672,15634,13649, +23928,40882,29015,17752,16620,7715,19575,14712,13386,420,27713,35532,20404, +569,22975,33132,38998,39162,24379,2975,U,8641,35181,16642,18107,36985,16135, +40883,41397,16632,14294,18167,27718,16764,34482,29695,17773,14548,21658,17761, +17691,19849,19579,19830,17898,16328,19215,13921,17630,17597,16877,23870,23880, +23894,15868,14351,23972,23993,14368,14392,24130,24253,24357,24451,14600,14612, +14655,14669,24791,24893,23781,14729,25015,25017,25039,14776,25132,25232,25317, +25368,14840,22193,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, +U,U,U,U,14851,25570,25595,25607,25690,14923,25792,23829,22049,40863,14999, +25990,15037,26111,26195,15090,26258,15138,26390,15170,26532,26624,15192,26698, +26756,15218,15217,15227,26889,26947,29276,26980,27039,27013,15292,27094,15325, +27237,27252,27249,27266,15340,27289,15346,27307,27317,27348,27382,27521,27585, +27626,27765,27818,15563,27906,27910,27942,28033,15599,28068,28081,28181,28184, +28201,28294,35264,28347,28386,28378,40831,28392,28393,28452,28468,15686,16193, +28545,28606,15722,15733,29111,23705,15754,28716,15761,28752,28756,28783,28799, +28809,805,17345,13809,3800,16087,22462,28371,28990,22496,13902,27042,35817, +23412,31305,22753,38105,31333,31357,22956,31419,31408,31426,31427,29137,25741, +16842,31450,31453,31466,16879,21682,23553,31499,31573,31529,21262,23806,31650, +31599,33692,23476,27775,31696,33825,31634,U,23840,15789,23653,33938,31738,U, +31797,23745,31812,31875,18562,31910,26237,17784,31945,31943,31974,31860,31987, +31989,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, +32359,17693,28228,32093,28374,29837,32137,32171,28981,32179,U,16471,24617, +32228,15635,32245,6137,32229,33645,U,24865,24922,32366,32402,17195,37996, +32295,32576,32577,32583,31030,25296,39393,32663,25425,32675,5729,104,17756, +14182,17667,33594,32762,25737,U,32776,32797,U,32815,41095,27843,32827,32828, +32865,10004,18825,26150,15843,26344,26405,32935,35400,33031,33050,22704,9974, +27775,25752,20408,25831,5258,33304,6238,27219,19045,19093,17530,33321,2829, +27218,15742,20473,5373,34018,33634,27402,18855,13616,6003,15864,33450,26907, +63892,16859,34123,33488,33562,3606,6068,14017,12669,13658,33403,33506,33560, +16011,28067,27397,27543,13774,15807,33565,21996,33669,17675,28069,33708,U, +33747,13438,28372,27223,34138,13462,28226,12015,33880,23524,33905,15827,17636, +27303,33866,15541,31064,U,27542,28279,28227,34014,U,33681,17568,33939,34020, +23697,16960,23744,17731,34100,23282,28313,17703,34163,17686,26559,34326,U,U,U, +U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,34341,34363, +34241,28808,34306,5506,28877,63922,17770,34344,13896,6306,21495,29594,34430, +34673,41208,34798,11303,34737,34778,34831,22113,34412,26710,17935,34885,34886, +30176,15801,30180,34910,34972,18011,34996,34997,25537,35013,30583,30479,35207, +35210,U,U,35239,35260,35365,35303,31012,31421,35484,30611,37374,35472,31321, +31465,31546,16271,18195,31544,29052,35596,35615,21552,21861,35647,35660,35661, +35497,19066,35728,35739,35503,5855,17941,34895,35995,32084,32143,63956,14117, +32083,36054,32152,32189,36114,36099,6416,36059,28764,36113,19657,16080,36265, +32770,4116,18826,15228,33212,28940,31463,36525,36534,36547,37588,36633,36653, +33637,33810,36773,37635,41631,2640,36787,18730,35294,34109,15803,24312,12898, +36857,40980,34492,34049,8997,14720,28375,36919,34108,31422,36961,34156,34315, +37032,34579,37060,34534,37038,U,37223,15088,37289,37316,31916,35123,7817, +37390,27807,37441,37474,21945,U,35526,15515,35596,21979,U,U,U,U,U,U,U,U,U,U,U, +U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,3377,37676,37739,35553,35819, +28815,23235,35554,35557,18789,37444,35820,35897,35839,37747,37979,36540,38277, +38310,37926,38304,28662,17081,9850,34520,4732,15918,18911,27676,38523,38550, +16748,38563,28373,25050,38582,30965,35552,38589,21452,18849,27832,628,25616, +37039,37093,19153,6421,13066,38705,34370,38710,18959,17725,17797,19177,28789, +23361,38683,U,37333,38743,23370,37355,38751,37925,20688,12471,12476,38793, +38815,38833,38846,38848,38866,38880,21612,38894,29724,37939,U,38901,37917, +31098,19153,38964,38963,38987,39014,15118,29045,15697,1584,16732,22278,39114, +39095,39112,39111,19199,27943,5843,21936,39137,39142,39148,37752,39225,18985, +19314,38999,39173,39413,39436,39483,39440,39512,22309,14020,37041,39893,39648, +39650,39685,39668,19470,39700,39725,34304,20532,39732,27048,14531,12413,39760, +39744,40254,23109,6243,39822,16971,39938,39935,39948,40552,40404,40887,41362, +41387,41185,41251,41439,40318,40323,41268,40462,26760,U,U,U,U,U,U,U,U,U,U,U,U, +U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,40388,8539,41363,41504,6459,41523, +40249,41145,41652,40592,40597,40606,40610,19764,40618,40623,17252,40641,15200, +14821,15645,20274,14270,35883,40706,40712,19350,37924,28066,40727,U,40761, +22175,22154,40773,39352,37003,38898,33919,40802,40809,31452,40846,29206,19390, +18805,18875,29047,18936,17224,19025,29598,35802,6394,31135,35198,36406,37737, +37875,35396,37612,37761,37835,35180,17593,29207,16107,30578,31299,28880,17523, +17400,29054,6127,28835,6334,13721,16071,6277,21551,6136,14114,5883,6201,14049, +6004,6353,24395,14115,5824,22363,18981,5118,4776,5062,5302,34051,13990,U, +33877,18836,29029,15921,21852,16123,28754,17652,14062,39325,28454,26617,14131, +15381,15847,22636,6434,26640,16471,14143,16609,16523,16655,27681,21707,22174, +26289,22162,4063,2984,3597,37830,35603,37788,20216,20779,14361,17462,20156, +1125,895,20299,20362,22097,23144,427,971,14745,778,1044,13365,20265,704,36531, +629,35546,524,20120,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, +U,U,U,U,U,20685,20749,20386,20227,18958,16010,20290,20526,20588,20609,20428, +20453,20568,20732,U,U,U,U,28278,13717,15929,16063,28018,6276,16009,20904, +20931,1504,17629,1187,1170,1169,36218,35484,1806,21081,21156,2163,21217,U, +18042,29068,17292,3104,18860,4324,27089,3613,U,16094,29849,29716,29782,29592, +19342,19132,16525,21456,13700,29199,16585,21940,837,21709,3014,22301,37469, +38644,37734,22493,22413,22399,13886,22731,23193,35398,5882,5999,5904,23084, +22968,37519,23166,23247,23058,22854,6643,6241,17045,14069,27909,29763,23073, +24195,23169,35799,1043,37856,29836,4867,28933,18802,37896,35323,37821,14240, +23582,23710,24158,24136,6550,6524,15086,24269,23375,6403,6404,14081,6304, +14045,5886,14035,33066,35399,7610,13426,35240,24332,24334,6439,6059,23147, +5947,23364,34324,30205,34912,24702,10336,9771,24539,16056,9647,9662,37000, +28531,25024,62,70,9755,24985,24984,24693,11419,11527,18132,37197,U,U,U,U,U,U, +U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,25713,18021,11114, +14889,11042,13392,39146,11896,25399,42075,25782,25393,25553,18915,11623,25252, +11425,25659,25963,26994,15348,12430,12973,18825,12971,21773,13024,6361,37951, +26318,12937,12723,15072,16784,21892,35618,21903,5884,21851,21541,30958,12547, +6186,12852,13412,12815,12674,17097,26254,27940,26219,19347,26160,30832,7659, +26211,13010,13025,26142,22642,14545,14394,14268,15257,14242,13310,29904,15254, +26511,17962,26806,26654,15300,27326,14435,14293,17543,27187,27218,27337,27397, +6418,25873,26776,27212,15319,27258,27479,16320,15514,37792,37618,35818,35531, +37513,32798,35292,37991,28069,28427,18924,U,16255,15759,28164,16444,23101, +28170,22599,27940,30786,28987,17178,17014,28913,29264,29319,29332,18319,18213, +20857,19108,1515,29818,16120,13919,19018,18711,24545,16134,16049,19167,35875, +16181,24743,16115,29900,29756,37767,29751,17567,28138,17745,30083,16227,19673, +19718,16216,30037,30323,42438,15129,29800,35532,18859,18830,15099,U,U,U,U,U,U, +U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,15821,19022,16127, +18885,18675,37370,22322,37698,35555,6244,20703,21025,20967,30584,12850,30478, +30479,30587,18071,14209,14942,18672,29752,29851,16063,19130,19143,16584,19094, +25006,37639,21889,30750,30861,30856,30930,29648,31065,30529,22243,16654,U, +33942,31141,27181,16122,31290,31220,16750,5862,16690,37429,31217,3404,18828, +665,15802,5998,13719,21867,13680,13994,468,3085,31458,23129,9973,23215,23196, +23053,603,30960,23082,23494,31486,16889,31837,31853,16913,23475,24252,24230, +31949,18937,6064,31886,31868,31918,27314,32220,32263,32211,32590,25185,24924, +31560,32151,24194,17002,27509,2326,26582,78,13775,22468,25618,25592,18786, +32733,31527,2092,23273,23875,31500,24078,39398,34373,39523,27164,13375,14818, +18935,26029,39455,26016,33920,28967,27857,17642,33079,17410,32966,33033,33090, +26548,39107,27202,33378,33381,27217,33875,28071,34320,29211,23174,16767,6208, +23339,6305,23268,6360,34464,63932,15759,34861,29730,23042,U,U,U,U,U,U,U,U,U,U, +U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,34926,20293,34951,35007,35046, +35173,35149,22147,35156,30597,30596,35829,35801,35740,35321,16045,33955,18165, +18127,14322,35389,35356,37960,24397,37419,17028,26068,28969,28868,6213,40301, +35999,36073,32220,22938,30659,23024,17262,14036,36394,36519,19465,36656,36682, +17140,27736,28603,8993,18587,28537,28299,6106,39913,14005,18735,37051,U,21873, +18694,37307,37892,35403,16482,35580,37927,35869,35899,34021,35371,38297,38311, +38295,38294,36148,29765,16066,18687,19010,17386,16103,12837,38543,36583,36454, +36453,16076,18925,19064,16366,29714,29803,16124,38721,37040,26695,18973,37011, +22495,U,37736,35209,35878,35631,25534,37562,23313,35689,18748,29689,16923, +38811,38769,39224,3878,24001,35781,19122,38943,38106,37622,38359,37349,17600, +35664,19047,35684,39132,35397,16128,37418,18725,33812,39227,39245,31494,15869, +39323,19311,39338,39516,35685,22728,27279,39457,23294,39471,39153,19344,39240, +39356,19389,19351,37757,22642,4866,22562,18872,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, +U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,5352,30788,10015,15800,26821,15741, +37976,14631,24912,10113,10603,24839,40015,40019,40059,39989,39952,39807,39887, +40493,39839,41461,41214,40225,19630,16644,40472,19632,40204,41396,41197,41203, +39215,40357,33981,28178,28639,27522,34300,17715,28068,28292,28144,33824,34286, +28160,14295,24676,31202,13724,13888,18733,18910,15714,37851,37566,37704,703, +30905,37495,37965,20452,13376,36964,21853,30781,30804,30902,30795,5975,12745, +18753,13978,20338,28634,28633,U,28702,21524,16821,22459,22771,22410,40214, +22487,28980,13487,16812,29163,27712,20375,U,6069,35401,24844,23246,23051, +17084,17544,14124,19323,35324,37819,37816,6358,3869,33906,27840,5139,17146, +11302,17345,22932,15799,26433,32168,24923,24740,18873,18827,35322,37605,29666, +16105,29876,35683,6303,16097,19123,27352,29683,29691,16086,19006,19092,6105, +19046,935,5156,18917,29768,18710,28837,18806,37508,29670,37727,1278,37681, +35534,35350,37766,35815,21973,18741,35458,29035,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, +U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,18755,3327,22180,1562,3051,3256,21762, +31172,6138,32254,5826,19024,6226,17710,37889,14090,35520,18861,22960,6335, +6275,29828,23201,14050,15707,14000,37471,23161,35457,6242,37748,15565,2740, +19094,14730,20724,15721,15692,5020,29045,17147,33304,28175,37092,17643,27991, +32335,28775,27823,15574,16365,15917,28162,28428,15727,1013,30033,14012,13512, +18048,16090,18545,22980,37486,18750,36673,35868,27584,22546,22472,14038,5202, +28926,17250,19057,12259,4784,9149,26809,26983,5016,13541,31732,14047,35459, +14294,13306,19615,27162,13997,27831,33854,17631,17614,27942,27985,27778,28638, +28439,28937,33597,5946,33773,27776,28755,6107,22921,23170,6067,23137,23153, +6405,16892,14125,23023,5948,14023,29070,37776,26266,17061,23150,23083,17043, +27179,16121,30518,17499,17098,28957,16985,35297,20400,27944,23746,17614,32333, +17341,27148,16982,4868,28838,28979,17385,15781,27871,63525,19023,32357,23019, +23855,15859,24412,19037,6111,32164,33830,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, +U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,21637,15098,13056,532,22398,2261,1561,16357, +8094,41654,28675,37211,23920,29583,31955,35417,37920,20424,32743,29389,29456, +31476,29496,29497,22262,29505,29512,16041,31512,36972,29173,18674,29665,33270, +16074,30476,16081,27810,22269,29721,29726,29727,16098,16112,16116,16122,29907, +16142,16211,30018,30061,30066,30093,16252,30152,30172,16320,30285,16343,30324, +16348,30330,20316,29064,22051,35200,22633,16413,30531,16441,26465,16453,13787, +30616,16490,16495,23646,30654,30667,22770,30744,28857,30748,16552,30777,30791, +30801,30822,33864,21813,31027,26627,31026,16643,16649,31121,31129,36795,31238, +36796,16743,31377,16818,31420,33401,16836,31439,31451,16847,20001,31586,31596, +31611,31762,31771,16992,17018,31867,31900,17036,31928,17044,31981,36755,28864, +3279,32207,32212,32208,32253,32686,32692,29343,17303,32800,32805,31545,32814, +32817,32852,15820,22452,28832,32951,33001,17389,33036,29482,33038,33042,30048, +33044,17409,15161,33110,33113,33114,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, +U,U,U,U,U,U,U,U,U,U,U,U,U,17427,22586,33148,33156,17445,33171,17453,33189, +22511,33217,33252,33364,17551,33446,33398,33482,33496,33535,17584,33623,38505, +27018,33797,28917,33892,24803,33928,17668,33982,34017,34040,34064,34104,34130, +17723,34159,34160,34272,17783,34418,34450,34482,34543,38469,34699,17926,17943, +34990,35071,35108,35143,35217,31079,35369,35384,35476,35508,35921,36052,36082, +36124,18328,22623,36291,18413,20206,36410,21976,22356,36465,22005,36528,18487, +36558,36578,36580,36589,36594,36791,36801,36810,36812,36915,39364,18605,39136, +37395,18718,37416,37464,37483,37553,37550,37567,37603,37611,37619,37620,37629, +37699,37764,37805,18757,18769,40639,37911,21249,37917,37933,37950,18794,37972, +38009,38189,38306,18855,38388,38451,18917,26528,18980,38720,18997,38834,38850, +22100,19172,24808,39097,19225,39153,22596,39182,39193,20916,39196,39223,39234, +39261,39266,19312,39365,19357,39484,39695,31363,39785,39809,39901,39921,39924, +19565,39968,14191,7106,40265,39994,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, +U,U,U,U,U,U,U,U,U,U,U,U,U,40702,22096,40339,40381,40384,40444,38134,36790, +40571,40620,40625,40637,40646,38108,40674,40689,40696,31432,40772,148,695,928, +26906,38083,22956,1239,22592,38081,14265,1493,1557,1654,5818,22359,29043,2754, +2765,3007,21610,63547,3019,21662,3067,3131,3155,3173,3196,24807,3213,22138, +3253,3293,3309,3439,3506,3528,26965,39983,34725,3588,3598,3799,3984,3885,3699, +23584,4028,24075,4188,4175,4214,26398,4219,4232,4246,13895,4287,4307,4399, +4411,21348,33965,4835,4981,4918,35713,5495,5657,6083,6087,20088,28859,6189, +6506,6701,6725,7210,7280,7340,7880,25283,7893,7957,29080,26709,8261,27113, +14024,8828,9175,9210,10026,10353,10575,33533,10599,10643,10965,35237,10984, +36768,11022,38840,11071,38983,39613,11340,U,11400,11447,23528,11528,11538, +11703,11669,11842,12148,12236,12339,12390,13087,13278,24497,26184,26303,31353, +13671,13811,U,18874,U,13850,14102,U,838,22709,26382,U,U,U,U,U,U,U,U,U,U,U,U,U, +U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,26904,15015,30295,24546,15889,16057, +30206,8346,18640,19128,16665,35482,17134,17165,16443,17204,17302,19013,1482, +20946,1553,22943,7848,15294,15615,17412,17622,22408,18036,14747,18223,34280, +39369,14178,8643,35678,35662,U,18450,18683,18965,29193,19136,3192,22885,20133, +20358,1913,36570,20524,21135,22335,29041,21145,21529,16202,19111,21948,21574, +21614,27474,U,13427,21823,30258,21854,18200,21858,21862,22471,18751,22621, +20582,13563,13260,U,22787,18300,35144,23214,23433,23558,7568,22433,29009,U, +24834,31762,36950,25010,20378,35682,25602,25674,23899,27639,U,25732,6428, +35562,18934,25736,16367,25874,19392,26047,26293,10011,37989,22497,24981,23079, +63693,U,22201,17697,26364,20074,18740,38486,28047,27837,13848,35191,26521, +26734,25617,26718,U,26823,31554,37056,2577,26918,U,26937,31301,U,27130,39462, +27181,13919,25705,33,31107,27188,27483,23852,13593,U,27549,18128,27812,30011, +34917,28078,22710,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, +U,U,U,U,14108,9613,28747,29133,15444,29312,29317,37505,8570,29323,37680,29414, +18896,27705,38047,29776,3832,34855,35061,10534,33907,6065,28344,18986,6176, +14756,14009,U,U,17727,26294,40109,39076,35139,30668,30808,22230,16607,5642, +14753,14127,33000,5061,29101,33638,31197,37288,U,19639,28847,35243,31229, +31242,31499,32102,16762,31555,31102,32777,28597,41695,27139,33560,21410,28167, +37823,26678,38749,33135,32803,27061,5101,12847,32840,23941,35888,32899,22293, +38947,35145,23979,18824,26046,27093,21458,19109,16257,15377,26422,32912,33012, +33070,8097,33103,33161,33199,33306,33542,33583,33674,13770,33896,34474,18682, +25574,35158,30728,37461,35256,17394,35303,17375,35304,35654,35796,23032,35849, +U,36805,37100,U,37136,37180,15863,37214,19146,36816,29327,22155,38119,38377, 38320,38328,38706,39121,39241,39274,39363,39464,39694,40282,40347,32415,40696, 40739,19620,38215,41619,29090,41727,19857,36882,42443,19868,3228,36798,21953, U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,36794, @@ -277,7 +286,7 @@ 19972,13687,23309,27826,21351,13996,14812,21373,13989,17944,22682,19310,33325, 21579,22442,23189,2425,U,14930,9317,29556,40620,19721,39917,15614,40752,19547, 20393,38302,40926,33884,15798,29362,26547,14112,25390,32037,16119,15916,14890, -36872,21196,15988,13946,17897,1166,30272,23280,3766,30842,18358,22695,16575, +36872,21196,15988,13946,17897,1166,30272,23280,3766,30842,32558,22695,16575, 22140,39819,23924,30292,42036,40581,19681,U,14331,24857,12506,17394,U,22109, 4777,22439,18787,40454,21044,28846,13741,U,40316,31830,39737,22494,5996,23635, 25811,38096,25397,29028,34477,3368,27938,19170,3441,U,20990,7951,23950,38659, @@ -327,9 +336,9 @@ 1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067, 1068,1069,1070,1071,1072,1073,1074,1075,1076,1077,1105,1078,1079,1080,1081, 1082,1083,1084,1085,1086,1087,1088,1089,1090,1091,1092,1093,1094,1095,1096, -1097,1098,1099,1100,1101,1102,1103,8679,8632,8633,63461,204,20058,138,20994, -63466,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, -63467,20872,63469,30215,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, +1097,1098,1099,1100,1101,1102,1103,8679,8632,8633,12751,204,20058,138,20994, +17553,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, +40880,20872,40881,30215,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U,U, U,U,U,U,U,U,U,U,U,U,U,U,U,65506,65508,65287,65282,12849,8470,8481,12443,12444, 11904,11908,11910,11911,11912,11914,11916,11917,11925,11932,11933,11941,11943, 11946,11948,11950,11958,11964,11966,11974,11978,11980,11981,11983,11990,11991, @@ -417,67 +426,68 @@ },{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0, 0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{ 0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0 -},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0, -0,0},{__big5hkscs_decmap+0,64,170},{__big5hkscs_decmap+107,64,254},{ -__big5hkscs_decmap+298,64,254},{__big5hkscs_decmap+489,64,253},{ -__big5hkscs_decmap+679,64,220},{__big5hkscs_decmap+836,96,254},{ -__big5hkscs_decmap+995,64,254},{__big5hkscs_decmap+1186,64,253},{ -__big5hkscs_decmap+1376,64,254},{__big5hkscs_decmap+1567,64,254},{ -__big5hkscs_decmap+1758,64,254},{__big5hkscs_decmap+1949,64,254},{ -__big5hkscs_decmap+2140,64,254},{__big5hkscs_decmap+2331,64,254},{ -__big5hkscs_decmap+2522,64,254},{__big5hkscs_decmap+2713,64,254},{ -__big5hkscs_decmap+2904,64,254},{__big5hkscs_decmap+3095,64,254},{ -__big5hkscs_decmap+3286,64,254},{__big5hkscs_decmap+3477,64,254},{ -__big5hkscs_decmap+3668,64,254},{__big5hkscs_decmap+3859,64,254},{ -__big5hkscs_decmap+4050,64,254},{__big5hkscs_decmap+4241,64,254},{ -__big5hkscs_decmap+4432,64,254},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0 -},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0, +},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{ +__big5hkscs_decmap+0,64,121},{__big5hkscs_decmap+58,64,170},{ +__big5hkscs_decmap+165,64,254},{__big5hkscs_decmap+356,64,254},{ +__big5hkscs_decmap+547,64,253},{__big5hkscs_decmap+737,64,254},{ +__big5hkscs_decmap+928,64,254},{__big5hkscs_decmap+1119,64,254},{ +__big5hkscs_decmap+1310,64,253},{__big5hkscs_decmap+1500,64,254},{ +__big5hkscs_decmap+1691,64,254},{__big5hkscs_decmap+1882,64,254},{ +__big5hkscs_decmap+2073,64,254},{__big5hkscs_decmap+2264,64,254},{ +__big5hkscs_decmap+2455,64,254},{__big5hkscs_decmap+2646,64,254},{ +__big5hkscs_decmap+2837,64,254},{__big5hkscs_decmap+3028,64,254},{ +__big5hkscs_decmap+3219,64,254},{__big5hkscs_decmap+3410,64,254},{ +__big5hkscs_decmap+3601,64,254},{__big5hkscs_decmap+3792,64,254},{ +__big5hkscs_decmap+3983,64,254},{__big5hkscs_decmap+4174,64,254},{ +__big5hkscs_decmap+4365,64,254},{__big5hkscs_decmap+4556,64,254},{0,0,0},{0,0, +0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0, 0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{ 0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0 -},{0,0,0},{0,0,0},{__big5hkscs_decmap+4623,161,254},{__big5hkscs_decmap+4717, -64,254},{__big5hkscs_decmap+4908,64,254},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0, -0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0, +},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{__big5hkscs_decmap+4747, +161,254},{__big5hkscs_decmap+4841,64,254},{__big5hkscs_decmap+5032,64,254},{0, 0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{ 0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0 },{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0, -0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{__big5hkscs_decmap+5099,214,254},{ -__big5hkscs_decmap+5140,64,254},{__big5hkscs_decmap+5331,64,254},{ -__big5hkscs_decmap+5522,64,254},{__big5hkscs_decmap+5713,64,254},{ -__big5hkscs_decmap+5904,64,254},{0,0,0}, +0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{ +0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{ +__big5hkscs_decmap+5223,214,254},{__big5hkscs_decmap+5264,64,254},{ +__big5hkscs_decmap+5455,64,254},{__big5hkscs_decmap+5646,64,254},{ +__big5hkscs_decmap+5837,64,254},{__big5hkscs_decmap+6028,64,254},{0,0,0}, }; static const unsigned char big5hkscs_phint_0[] = { -160,89,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,1,8,0,0,0,0,0,0,0,0,0,0, -0,0,2,44,0,30,0,0,0,0,0,64,174,86,238,249,221,228,33,23,0,0,0,128,219,73,31, -76,130,55,237,228,223,189,247,245,239,31,100,136,94,253,223,11,0,0,0,192,247, -143,0,131,5,0,8,201,8,4,129,64,68,5,11,9,35,1,32,2,0,0,0,32,145,24,0,96,0,168, -6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,128,0,64,86,50,65,32,198, -80,72,2,0,0,0,0,160,192,168,1,164,85,48,58,209,106,46,159,176,241,65,136,5,57, -80,4,0,0,0,0,172,163,20,192,1,2,13,45,134,136,107,34,110,192,204,245,218,10, -24,122,0,0,0,0,50,115,0,15,68,252,3,33,49,32,25,232,96,160,65,19,82,42,250,9, -0,0,0,0,190,1,129,16,16,96,183,137,193,218,237,250,242,59,200,167,11,77,155, -11,0,0,0,0,24,0,220,116,19,94,192,168,0,60,240,208,68,224,172,60,75,230,29,15, -0,0,0,128,189,88,120,55,191,187,216,218,8,134,192,108,148,192,176,125,14,136, -145,3,0,0,0,64,99,139,197,22,24,68,124,152,75,112,3,92,219,185,208,26,40,149, -106,1,0,0,0,0,232,7,36,34,32,136,4,106,32,215,29,50,15,162,149,11,4,67,65,1,0, -0,0,104,48,64,19,207,57,183,16,8,7,4,180,33,217,183,15,11,127,69,91,0,0,0,0, -236,116,236,196,4,41,49,2,48,250,252,27,175,78,38,164,183,110,50,24,0,0,0,0, -220,22,67,34,1,0,0,128,0,0,0,4,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,0,0,0, -0,0,0,0,0,0,0,0,0,4,0,0,0,0,0,0,28,241,220,190,126,252,186,123,238,249,55,249, -93,165,255,31,215,2,0,0,0,128,63,255,213,117,117,187,120,231,62,245,177,173, -189,75,150,188,46,181,85,2,0,0,0,192,109,51,55,176,233,204,159,42,126,83,204, -255,77,234,218,198,255,55,165,0,0,0,0,160,192,252,222,50,83,161,28,0,0,33,176, -71,0,74,32,32,233,215,235,0,0,0,0,160,183,1,64,49,101,247,12,36,64,48,45,144, -123,18,0,0,2,0,0,0,0,0,0,0,8,80,144,69,0,4,0,0,32,64,4,161,128,96,2,0,32,0,8, -0,0,0,0,148,8,2,32,40,0,0,1,8,254,251,73, +32,5,95,68,15,82,130,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,208,44,4,0,0,0,0,0,0,0, +0,0,0,0,0,0,0,0,0,0,0,0,0,192,0,4,0,0,0,0,0,0,0,0,0,0,0,0,1,22,0,15,0,0,0,0,0, +32,87,43,247,252,110,242,144,11,0,0,0,192,237,164,15,38,193,155,118,242,239, +222,251,250,247,15,50,68,175,254,239,5,0,0,0,224,251,71,128,193,2,0,132,100,4, +130,64,32,162,130,133,164,145,0,16,1,0,0,0,144,72,12,0,48,0,84,3,48,68,24,19, +53,137,38,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,64,0,32,43,153,32,16,99,40,36, +1,0,0,0,0,80,96,212,0,210,42,24,157,104,53,151,79,216,248,32,196,130,28,40,2, +0,0,0,0,214,81,10,224,0,129,134,22,67,196,53,17,55,96,230,122,109,5,12,61,0,0, +0,0,153,57,128,7,34,254,129,144,24,144,12,116,48,208,160,9,41,21,253,4,0,0,0, +0,223,128,64,8,8,176,219,196,96,237,118,125,249,29,228,211,133,166,205,5,0,0, +0,0,12,0,110,186,9,47,96,84,0,30,120,104,34,112,86,158,37,243,142,7,0,0,0,192, +94,44,188,155,223,93,108,109,4,67,96,54,74,96,216,62,7,196,200,1,0,0,0,160, +177,197,98,11,12,34,62,204,37,184,1,174,237,92,104,13,148,74,181,0,0,0,0,0, +244,3,18,17,16,68,2,53,144,235,14,153,7,209,202,5,130,161,160,0,0,0,0,52,24, +160,137,231,156,91,8,132,3,2,218,144,236,219,135,133,191,162,45,0,0,0,0,118, +58,118,98,130,148,24,1,24,125,254,141,87,39,19,210,91,55,25,12,0,0,0,0,110, +139,33,145,0,0,0,64,0,0,0,2,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0, +0,0,0,0,0,0,0,2,0,0,0,0,0,0,142,120,110,95,63,126,221,61,247,252,155,252,174, +210,255,143,107,1,0,0,0,192,159,255,234,186,186,93,188,115,159,250,216,214, +222,37,75,94,151,218,42,1,0,0,0,224,182,153,27,216,116,230,79,21,191,41,230, +255,38,117,109,227,255,155,82,0,0,0,0,80,96,126,111,153,169,80,14,0,128,16, +216,35,0,37,16,144,244,235,117,0,0,0,0,208,219,0,160,152,178,123,6,82,32,152, +22,200,61,9,0,0,1,0,0,0,0,0,0,0,4,40,200,34,0,2,0,0,16,32,130,80,64,48,1,0,16, +0,4,0,0,0,0,74,4,1,16,20,0,128,0,4,255,253,36, }; -static const unsigned char big5hkscs_phint_11939[] = { +static const unsigned char big5hkscs_phint_12130[] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,128,2,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0, }; -static const unsigned char big5hkscs_phint_21733[] = { +static const unsigned char big5hkscs_phint_21924[] = { 0,0,0,0,0,26,172,248,250,90,192,250,51,0,0,0,0,0,129,0,160,156,130,144,9,1, 180,192,176,3,86,2,160,66,45,136,1,0,0,0,0,146,119,139,96,5,201,33,6,70,56,96, 72,192,180,36,222,132,224,192,36,0,0,0,0,205,80,197,52,192,40,162,173,124,153, @@ -485,33 +495,33 @@ 5,72,8,22,230,28,165,0,8,0,0,0,192,45,22,20,128,24,58,212,25,136,28,138,4, }; -static const DBCHAR __big5hkscs_bmp_encmap[26537] = { +static const DBCHAR __big5hkscs_bmp_encmap[26401] = { 50904,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,34905,34903,N,N,N,N,N,N, -34909,34907,34918,N,N,N,N,N,N,N,34913,34911,N,N,N,N,N,N,N,N,N,N,N,N,34922, -34920,N,N,N,N,N,N,34927,34925,34983,N,34931,34929,N,N,N,N,34935,34933,N,N,N,N, -51451,34939,34937,N,34978,34902,34919,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,34906, -34924,N,N,N,N,N,N,34908,34926,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,34928,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,51452,34910,34932,N,N,N,N,N, -51450,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,34936,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,34904,34921,N,34930,34912,34934,N,34938,N,34940,N,34941,N, -34942,N,34977,51446,34923,N,N,51448,N,N,N,N,N,N,51447,N,N,N,N,N,34984,N,N,N,N, -N,N,N,N,51454,N,N,N,N,N,N,N,N,N,N,51449,N,N,N,N,N,N,N,N,N,N,N,N,N,51445,N,N,N, -N,N,N,51453,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,50905,51193,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,51187,51188,51189,51190,51191,51192,51194,51195,51196,51197, -51198,51264,51265,51266,51267,51268,51269,51270,51271,51272,51273,51274,51275, -51276,51277,51278,51279,51280,51281,51282,51283,51284,51285,51286,51287,51288, -51289,51290,51292,51293,51294,51295,51296,51297,51298,51299,51300,51301,51302, -51303,51304,51305,51306,51307,51308,51309,51310,51311,51312,51313,51314,51315, -51316,51317,N,51291,34915,34980,34917,34982,51410,N,N,N,N,N,N,N,N,N,N,51411,N, +34909,34907,M,N,N,N,N,N,N,N,34913,34911,N,N,N,N,N,N,N,N,N,N,N,N,34922,34920,N, +N,N,N,N,N,34927,34925,M,N,34931,34929,N,N,N,N,34935,34933,N,N,N,N,51451,34939, +34937,N,34978,34902,34919,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,34906,34924,N,N,N,N, +N,N,34908,34926,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,34928,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,51452,34910,34932,N,N,N,N,N,51450,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,34936,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,34904,34921,N,34930,34912,34934,N,34938,N,34940,N,34941,N,34942,N,34977, +51446,34923,N,N,51448,N,N,N,N,N,N,51447,N,N,N,N,N,34984,N,N,N,N,N,N,N,N,51454, +N,N,N,N,N,N,N,N,N,N,51449,N,N,N,N,N,N,N,N,N,N,N,N,N,51445,N,N,N,N,N,N,51453,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,50905,51193,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +51187,51188,51189,51190,51191,51192,51194,51195,51196,51197,51198,51264,51265, +51266,51267,51268,51269,51270,51271,51272,51273,51274,51275,51276,51277,51278, +51279,51280,51281,51282,51283,51284,51285,51286,51287,51288,51289,51290,51292, +51293,51294,51295,51296,51297,51298,51299,51300,51301,51302,51303,51304,51305, +51306,51307,51308,51309,51310,51311,51312,51313,51314,51315,51316,51317,N, +51291,34915,34980,34917,34982,51410,N,N,N,N,N,N,N,N,N,N,51411,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -50869,50870,50871,50872,50873,50874,50875,50876,50877,50878,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,50869,50870, +50871,50872,50873,50874,50875,50876,50877,50878,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,51319,51320,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,51318,50849,50850,50851, +N,N,N,N,N,N,N,N,51319,51320,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,51318,34985,34986,50849,50850,50851, 50852,50853,50854,50855,50856,50857,50858,N,N,N,N,N,N,N,N,N,N,50859,50860, 50861,50862,50863,50864,50865,50866,50867,50868,63993,63992,63974,63983,63965, 63976,63985,63967,63980,63989,63971,63982,63991,63973,63977,63986,63968,63979, @@ -536,231 +546,235 @@ 51153,51154,51155,51156,51157,51158,51159,51160,51161,51162,51163,51164,51165, 51166,51167,51168,51169,51170,51171,51172,51173,51174,51175,51176,51177,51178, 51179,51180,51181,51182,51183,51184,51185,51186,N,N,N,N,N,50915,50906,50907, -51409,37495,N,N,N,N,N,N,N,N,N,N,38623,N,N,N,N,N,N,N,N,N,N,N,35285,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37837,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39903,N,N, -N,N,N,N,64104,N,N,35290,36697,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35291,N, -N,36701,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35292,N,N,N,N,N,N,N,N,N,38647,N,N,N,N,N,N, -N,N,N,N,N,N,35546,N,N,N,N,35804,N,N,N,N,N,N,38875,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,40531,N,N,N,N,40362,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,39914,35438,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35784,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,35304,N,35306,N,N,N,N,N,35915,N,N,N,N,N,N,N,64368,N,N,N,N,N,N,N,N,N, -N,N,35309,N,N,38109,N,35310,N,N,N,N,40628,35539,N,N,N,N,N,N,N,N,N,N,N,37595,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38107,35321,N,N,N,N,N,N,N,N,64378,N,N,N, -35323,N,N,N,N,N,N,N,40700,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35324,N,35263,N,N, -N,35326,N,35302,N,N,40262,N,N,N,40430,N,N,N,41086,N,N,N,41064,N,N,N,N,39145,N, -35688,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36349,35774,40921,N,N,N,N,N,N,N, -35563,N,N,40919,35690,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40028,N,35761,N,N,N,N,N,N,N, -N,64350,N,N,N,N,N,N,N,N,N,40435,N,N,N,N,N,N,N,41168,N,N,N,64614,N,N,N,N,37609, -N,N,N,N,N,N,N,N,39660,36779,64072,N,N,N,N,36421,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,40047,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40670,N,N,N,N,N,N, -35311,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38633,N,N,N,N,N,N,N,N,N, -N,40635,N,N,N,N,38110,N,40632,N,N,N,38842,64357,N,N,N,38358,N,N,N,40123,N,N, -38874,N,N,N,N,36677,N,64381,37208,65124,N,38998,39757,N,N,N,N,N,N,N,N,N,N, -37723,38343,N,38887,N,N,N,N,N,N,37721,N,N,N,37365,38840,N,N,64930,64438,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,37626,37719,N,35750,N,N,N,N,64441,N,38832,N,N,64964,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,40097,N,N,N,N,N,37362,37369,N,36849,N,N,N,N,N,N,38725, -38995,N,N,65144,N,64449,37457,N,N,N,N,N,N,40365,N,N,N,N,N,64876,N,N,64107,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39874,N,N,N,N,N,N,N,N, -N,N,N,N,39547,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,35680,N,N,N,N,N,N,N,N,37707,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,39613,N,N,N,N,37303,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38324,N,N,N,N,N,65221, -N,N,40688,36196,N,N,N,N,N,N,N,N,N,37481,N,N,N,N,N,N,36199,N,N,N,N,N,N,N,N,N,N, -N,N,64490,N,N,N,N,N,N,N,N,64495,N,36200,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37867,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,64578,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,37222,N,N,N,N,N,N,N,N,64205,N,N,N,N,37853,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35788,36205,N,N,N,N,N, -N,N,N,N,N,N,36206,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38568,N,N,N,N,N,N,N,N,N, -N,64678,N,N,N,N,N,N,N,N,N,N,N,N,36207,N,N,N,N,N,N,N,N,N,N,N,N,N,36208,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64612,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,36960,N,N,N,N,N,N,N,N,36212,38851,N,N,N,N,N,N,N,35536,N,N,N, -N,N,N,37492,N,39870,N,N,N,N,N,40136,N,N,40122,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,36216,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,40633,N,N,N,N,N,38234,N,N,37300,N,N,N,N,N,N,35400,N,N,N,N,N,N,N,N,N,N,N, -36221,N,N,35453,N,N,35522,64842,N,36257,N,N,35537,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,64692,35655,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37796,40666,N,N,N,N,N,N,N,N,N, -35409,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36262,N,N,N,N,N,N,40645,N,N, -N,N,64708,N,N,N,N,41080,N,38069,N,N,N,N,N,N,N,64706,35435,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -36267,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64232,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,36269,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -64585,N,37825,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36975,N,36272,N,N,N,N,N,N,N,N, -38014,37114,N,N,N,N,N,N,N,N,N,N,38009,N,N,N,N,N,N,N,N,36274,N,N,N,N,N,N,N,N, -64750,N,N,N,N,N,N,N,N,N,N,N,N,N,39291,N,N,N,N,N,N,N,N,36276,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,36279,N,N,N,N,N,N,N,37299,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,36283,36282,N,N,N,N,N,N,N,N,36284,36932,N,N,N,64844,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,37860,N,N,37856,N,N,N,N,N,N,N,64851,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36291,N,39864,N,N,N,64496,N,37865,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,37878,N,N,N,N,N,36293,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36298, -N,N,N,N,N,36300,64861,37813,64865,N,N,N,40184,N,N,N,37458,N,N,41192,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40101,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35926,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36310,N,38848,N,N,N,41182,N,N,N,N, -38866,N,N,N,N,N,64165,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64931,N,N,N,36315,36527,N,N, -N,N,N,N,N,N,N,37301,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64841,N,N,N,N,N,N, -N,N,64977,N,N,N,N,N,N,N,N,N,N,36331,N,N,N,N,N,38854,N,64974,N,N,37116,N,N,N,N, -N,N,N,N,N,N,N,N,N,64601,N,N,38614,N,N,N,N,N,N,38853,36335,N,N,N,N,38871,N,N,N, -N,N,36336,N,N,N,N,N,N,N,38566,N,N,N,N,N,N,N,64447,N,N,N,N,36339,N,N,N,N,37961, -N,36341,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39026,N,N,N,N,N,N,N,36459,N,N,N, -N,N,N,64253,N,N,N,N,N,N,N,N,N,N,36688,N,N,N,N,N,N,40396,64613,N,35908,N,N, -39278,38049,N,N,N,N,N,36707,N,N,N,N,N,N,N,41178,N,N,N,N,N,N,N,N,N,N,N,37459, -65001,N,N,40373,N,N,N,N,N,N,N,39033,N,N,N,40285,N,N,N,N,36195,38505,40816,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64618,N,N,35527,N,N,N,N,35287,N,N,N,N,N,N,N,N, -N,N,N,N,65101,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -40669,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65275,39100,64204,N,N,38320,N,N,N,37988,N,N,N,N, -N,N,37743,N,N,N,N,N,N,38073,N,N,38380,N,N,N,N,37358,N,N,39107,N,38390,N,N,N, -36861,39109,N,N,N,N,38758,65134,N,N,38877,36010,N,N,37586,N,N,38753,39115,N,N, -N,N,38384,N,38749,N,37347,N,N,N,N,39116,N,N,37993,39117,N,N,N,N,N,39118,N, -38396,N,N,38051,38498,N,N,N,65206,N,37987,N,N,N,N,N,N,N,39120,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39121,N,N,N,N,38005,64224,N,N,N,N,N, -N,N,N,N,38002,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39126,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35568,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39129,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,39131,N,N,N,N,39133,N,N,N,N,N,N,N,N,39080,N,N,N,N,N,N,N, -35437,N,N,N,N,N,N,N,N,N,N,N,35579,35502,64457,N,N,N,N,35933,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,39140,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,39142,N,N,N,N,N,N,N,N,N,N,N,39144,N,N,N,N,N,N,N,N,N,N,N,N,N,35405,N,N,N, -37463,N,N,N,N,N,N,N,N,N,N,38367,N,N,41132,N,N,N,N,39147,N,N,N,N,39148,N,36035, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39156,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35512, -N,N,N,40679,N,N,N,N,N,N,N,N,38076,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64721,N,N,N,N, -N,N,40134,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40574,39166, -65000,N,N,N,N,39232,N,N,N,N,38089,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,38099,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39238,N,N,N,N,37056, -N,38097,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38259,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -37826,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39240, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39243,N,N,N,N,N,36437,N,N,N,N,39246,N,N,N,N, -N,N,N,N,N,N,N,36606,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36441,N,N,N,N,N,N,N, -N,N,38124,38127,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35936,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36724,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,39253,N,N,N,N,N,N,N,N,N,38212,N,N,N,N,N,N,N,N,N,N,N, -36043,N,N,N,39254,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39257,N,N,N,N,N,N,N,39259, -N,N,N,N,N,N,N,N,N,N,N,N,N,36036,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64069,N,N, -N,37047,N,N,38723,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38349,N,N,N,N,N,N,38857, -64848,36537,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38342,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -39271,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -35513,N,N,N,N,N,N,36348,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35446,N, -N,N,N,N,40273,N,N,N,N,N,N,N,N,N,N,N,N,N,39283,N,N,N,N,40271,39290,38244,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,39329,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39333,N,N,N, -N,N,N,N,39335,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +34880,34881,34882,34883,34884,34886,34889,34890,34893,34895,34896,34897,34898, +34900,34901,51321,51409,37495,N,N,N,N,N,N,N,N,N,N,38623,N,N,N,N,N,N,N,N,N, +36084,N,35285,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37837,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,39903,N,N,N,N,N,N,64104,N,N,35290,36697,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,35291,N,N,36701,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35292,N,N,N,N,N, +N,N,N,N,38647,N,N,N,N,N,N,N,N,N,N,N,N,35546,N,N,N,N,35804,N,N,N,N,N,N,38875,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40531,N,N,N,N,40362,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,39914,35438,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35784, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35304,N,35306,N,N,N,N,N,35915,N,N,N,N,N,N, +N,64368,N,N,N,N,N,N,N,N,N,N,N,35309,N,N,38109,N,35310,N,N,N,N,40628,35539,N,N, +N,N,N,N,N,N,N,N,N,37595,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38107,35321,N,N,N, +N,N,N,N,N,64378,N,N,N,35323,N,N,N,N,N,N,N,40700,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,35324,N,35263,N,N,N,35326,N,35302,N,N,40262,N,N,N,40430,N,N,N,41086,N,N,N, +41064,N,N,N,N,39145,N,35688,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36349,35774, +40921,N,N,N,N,N,N,N,35563,N,N,40919,35690,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40028,N, +35761,N,N,N,N,N,N,N,N,64350,N,34672,N,N,N,N,N,N,N,40435,N,N,N,N,N,N,N,41168,N, +N,N,64614,N,N,N,N,37609,N,N,N,N,N,N,N,N,39660,36779,64072,N,N,N,N,36421,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,40047,N,36188,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,40670,N,N,N,N,N,N,35311,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,38633,N,N,N,N,N,N,N,N,N,N,40635,N,N,N,N,38110,N,40632,N,N,N,38842,64357,N, +N,N,38358,N,N,N,40123,N,N,38874,N,N,N,N,36677,N,64381,37208,65124,N,38998, +39757,N,N,N,N,N,N,N,N,N,N,37723,38343,N,38887,N,N,N,N,N,N,37721,N,N,N,37365, +38840,N,N,64930,64438,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37626,37719,N,35750,N,N,N,N, +64441,N,38832,N,N,64964,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40097,N,N,N,N,N,37362, +37369,N,36849,N,N,N,N,N,N,38725,38995,N,N,65144,N,64449,37457,N,N,N,N,N,N, +40365,N,N,N,N,N,64876,N,N,64107,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,39874,N,N,N,N,N,N,N,N,N,N,N,N,39547,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35680,N,N,N,N,N,N,N,N,37707, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39613,N,N,N,N,37303,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36171,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,38324,N,N,N,N,N,65221,N,N,40688,36196,N,N,N,N,N,N,N,N,N, +37481,N,N,N,N,N,N,36199,N,N,N,N,N,N,N,N,N,N,N,N,64490,N,N,N,N,N,N,N,N,64495,N, +36200,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,37867,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64578,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37222,N,N,N,N,N,N,N,N, +64205,N,N,N,N,37853,N,N,36178,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,35788,36205,N,N,N,N,N,N,N,N,N,N,N,36206,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,38568,N,N,N,N,N,N,N,N,N,N,64678,N,N,N,N,N,N,N,N,N,N,N, +N,36207,N,N,N,N,N,N,N,N,N,N,N,N,N,36208,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,64612,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36083,N,N,N,N,N,N,N,36960,N, +N,N,N,N,N,N,N,36212,38851,N,N,N,N,N,N,N,35536,N,N,N,N,N,N,37492,N,39870,N,N,N, +N,N,40136,N,N,40122,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36216,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40633,N,N,N,N,N,38234, +N,N,37300,N,N,N,N,N,N,35400,N,N,N,N,N,N,N,N,N,N,N,36221,N,N,35453,N,N,35522, +64842,N,36257,N,N,35537,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64692,35655,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,37796,40666,N,N,N,N,N,N,N,N,N,35409,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,36262,N,N,N,N,N,N,40645,N,N,N,N,64708,N,N,N,N,41080,N, +38069,N,N,N,N,N,N,N,64706,35435,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36267,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,64232,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36269,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64585,N,37825,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,36975,N,36272,N,N,N,N,N,N,N,N,38014,37114,N,N,N,N,N,N,N,N,N,N, +38009,N,N,N,N,N,N,N,N,36274,N,N,N,N,N,N,N,N,64750,N,N,N,N,N,N,N,N,N,N,N,N,N, +39291,N,N,N,N,N,N,N,N,36276,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36279,N, +N,N,N,N,N,N,37299,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36283,36282,N,N,N,N,N,N,N,N, +36284,36932,N,N,N,64844,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,34635,37860,N, +N,37856,N,N,N,N,N,N,N,64851,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,36291,N,39864,N,N,N,64496,N,37865,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37878, +N,N,N,N,N,36293,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36298,N,N,N,N,N,36300,64861,37813, +64865,N,N,N,40184,N,N,N,37458,N,N,41192,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,40101,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35926,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,36310,N,38848,N,N,N,41182,N,N,N,N,38866,N,N,N,N,N,64165,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,64931,N,N,N,36315,36074,36527,N,N,N,N,N,N,N,N,N,37301,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64841,N,N,N,N,N,N,N,N,64977,N,N,N,N,N,N,N, +N,N,N,36331,N,N,N,N,N,38854,N,64974,N,N,37116,N,N,N,N,N,N,N,N,N,N,N,N,N,64601, +N,N,38614,N,N,N,N,N,N,38853,36335,N,N,N,N,38871,N,N,N,N,N,36336,N,N,N,N,N,N,N, +38566,N,N,N,N,N,N,N,64447,N,N,36063,N,36339,N,N,N,N,37961,N,36341,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,39026,N,N,N,N,N,N,N,36459,N,N,N,N,N,N,64253,N,N,N,N, +N,N,N,N,N,N,36688,N,N,N,N,N,N,40396,64613,N,35908,N,N,39278,38049,N,N,N,N,N, +36707,N,N,N,N,N,N,N,41178,N,N,N,N,N,N,N,N,N,N,N,37459,65001,N,N,40373,N,N,N,N, +N,N,N,39033,34666,N,N,40285,N,N,N,N,36195,38505,40816,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,64618,N,N,35527,N,N,N,N,35287,N,N,N,N,N,N,N,N,N,N,N,N,65101,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40669,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,65275,39100,64204,N,N,38320,N,N,N,37988,N,N,N,N,N,N,37743,N,N,N,N,N,N, +38073,N,N,38380,N,N,N,N,37358,N,N,39107,N,38390,N,N,N,36861,39109,N,N,N,N, +38758,65134,N,N,38877,36010,N,N,37586,N,N,38753,39115,N,N,N,N,38384,N,38749,N, +37347,N,N,N,N,39116,N,N,37993,39117,N,N,N,N,N,39118,N,38396,N,N,38051,38498,N, +N,N,65206,N,37987,36167,N,N,N,N,N,N,39120,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,39121,N,N,N,N,38005,64224,N,N,N,N,N,N,N,N,N,38002,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39126,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,35568,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39129,N,N,N,N,N,N,N,36186,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,39131,N,N,N,N,39133,N,N,N,N,N,N,N,N,39080,N,N,N,N,N,N,N,35437,N,N,N,N,N, +N,N,N,N,N,N,35579,35502,64457,N,N,N,N,35933,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,39140,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39142,N,N,N,N, +N,N,N,N,N,N,N,39144,N,N,N,N,N,N,N,N,N,N,N,N,N,35405,N,N,N,37463,N,N,N,N,N,N,N, +N,N,N,38367,N,N,41132,N,N,N,N,39147,N,N,N,N,39148,N,36035,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,39156,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35512,N,N,N,40679,N,N,N,N, +N,N,N,N,38076,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64721,N,N,N,N,N,N,40134,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36170,N,40574,36164,39166,65000,N,N,N,N, +39232,N,N,N,N,38089,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,38099,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39238,N,N,N,N,37056,N,38097,N,N,N, +N,N,N,N,N,N,N,N,N,N,36174,N,N,38259,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37826,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39240,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,39243,N,N,N,N,N,36437,N,N,N,N,39246,N,N,N,N,N,N,N,N,N, +N,N,36606,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36191,N,36441,N,N,N,N,N,N,N,N,N, +38124,38127,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35936,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36724,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,39253,N,N,N,N,N,N,N,N,N,38212,N,N,N,N,N,N,N,N,N,N,N,36043, +N,N,N,39254,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39257,N,N,N,N,N,N,N,39259,N,N,N, +N,N,N,N,N,N,N,N,N,N,36036,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64069,N,N,N, +37047,N,N,38723,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38349,N,N,N,N,N,N,38857,64848, +36537,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38342,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39271,N,N, +36067,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35513,N,N, +N,N,N,N,36348,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35446,N,N,N,N,N, +40273,N,N,N,N,N,N,N,N,N,N,N,N,N,39283,N,N,34624,N,40271,39290,38244,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,39329,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39333,N,N,N,N,N, +N,N,39335,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,36589,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39341,N,N,N,N,N,N,N,N, +N,N,N,36589,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39341,N,51326,N,N,N,N,N,N, N,N,N,N,N,N,N,37998,36720,N,64208,N,N,N,N,N,N,N,N,N,N,N,N,N,39347,N,N,N,N,N,N, -41043,N,N,N,N,N,N,N,N,38492,N,N,N,N,64890,N,N,N,N,N,N,N,N,38910,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,37565,N,38909,N,N,N,N,36708,N,N,N,N,64759,38242,38861,40548,N,N, -N,N,N,N,N,37452,36553,39356,N,N,N,N,40357,N,36692,N,N,N,N,N,N,N,N,N,N,36732,N, -N,N,N,N,N,36514,N,N,N,N,N,N,N,N,N,36730,N,N,N,N,N,N,38830,N,N,N,N,38600,N,N,N, -N,N,N,N,39363,N,37078,N,40126,N,N,N,36726,N,N,N,N,N,N,N,N,N,N,N,N,N,38000, -64331,N,N,64970,N,N,N,N,N,N,36551,N,N,N,N,N,41209,N,N,N,N,N,N,N,36777,N,N,N,N, -N,N,N,N,N,N,N,N,39367,N,N,N,N,N,N,N,N,N,N,N,N,N,37079,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,40671,39374,N,N,N,N,N,N,N,N,36794,N,N,N,N,N,36843,N,39375,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36802,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37577,N,N,N,N,N,38876,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38323,40057,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38322, -36827,N,N,N,N,39907,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40570,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39918,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39390,N,N,N,N,N,N,N,N,N,N,N,N, -N,64250,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40677,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,35410,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -39393,N,N,N,N,N,N,35431,35765,N,N,N,N,N,N,N,N,N,N,35500,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39401,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64458,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38878,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38353,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,39413,64586,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,39849,N,N,N,N,N,N,N,N,N,N,N,N,64476,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65110,N, -N,N,N,N,40612,N,N,N,N,N,N,40265,38363,N,N,N,N,N,N,N,N,N,N,35269,N,N,N,N,N,N,N, -N,N,N,N,N,39416,N,N,N,N,N,N,38500,N,N,N,N,36949,N,N,38612,N,N,N,N,N,N,N,38780, -N,N,N,N,N,N,38477,N,38881,N,N,N,N,N,N,39496,N,N,N,N,N,N,N,N,N,N,N,39497,N, -65149,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37034,N,N,N,N,39504,N,N,N,N,N,N,N, -37703,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36568,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,37065,N,N,N,N,N,39509,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -37052,N,N,N,N,N,39512,N,35768,37077,N,N,N,N,N,N,N,N,N,N,N,N,N,38465,N,N,N,N,N, -N,39514,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39516,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,38850,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35515,N,N, -N,39850,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37109,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,39520,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -37189,35928,N,N,N,N,N,N,N,N,39523,N,N,N,N,N,N,35913,N,N,N,N,N,N,N,N,N,N,N, -35766,N,N,N,N,N,N,N,N,N,N,64719,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38507,39534,N, -37199,N,N,N,N,N,N,N,N,38726,N,N,41190,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37591,N, -38517,N,N,37844,N,N,37307,38521,N,N,N,N,N,39536,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38520,37325,N,40010,41071,N,N,41066,N,N,N,N,N, -N,37215,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,40869,N,N,35258,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,40653,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39545,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,40398,N,N,N,36050,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,40307,N,N,N,N,N,N,N,N,N,38585,N,38588,N,N,N,N,N,N,40145,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35255,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,40686,N,N,N,N,N,N,N,N,N,N,N,64323,40649,N,N,N,N,N,N,64467,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37294,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,40312,N,N,N,N,N,N,N,N,N,N,40315,40627,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,40626,N,40406,N,N,N,N,39247,N,N,35278,N,N,N,35776,N,40900,N,35796, -N,N,35954,N,N,N,N,N,N,50879,35833,N,N,N,N,N,35142,N,50880,N,N,N,N,N,N,N,N,N, -64229,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,51323,35782,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -40023,N,N,N,N,N,N,N,N,N,N,N,N,N,39675,N,N,N,N,N,N,N,35280,35279,N,N,N,50881,N, -35281,N,35298,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37502,N,40378,N,N,N,N,N,50882,N,N, -35951,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64504,N,N,N,35783,37483,N,N,35282, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,40911,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,40361,35283,N,N,39394,N,N,N,N,N,N,N,N,N,37479,37540,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,35955,N,N,35150,N,N,N,N,N,N,N,N,N,N,N,N,N,35151,37496,N, -N,N,N,N,N,N,N,37302,N,N,N,N,35284,N,40914,N,N,N,N,N,N,N,N,37543,N,N,38306,N,N, -N,N,N,37486,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,38634,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37487,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37539,N,N,N,N,N,35152,N,N,64087,N,N,N,N, -39014,N,N,N,N,N,N,N,N,N,N,N,N,35286,N,N,N,N,N,N,N,N,N,N,39090,N,N,N,37547,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38622,37548,N,N,N,N,N,N,N,N,N,N, -35952,N,40814,N,N,N,N,N,N,36594,N,N,N,40812,35288,N,N,N,N,64089,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37544,N,N,N,N,N, -37219,N,N,N,N,N,N,35904,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -40819,N,37549,N,N,N,N,N,N,N,N,N,N,N,N,N,39913,N,N,N,N,N,37545,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,37546,N,N,N,N,N,N,35289,N,N,N,N,N,N,N,64854,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40872,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,35953,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37537,N,N,37091,N,N,N,N,N,N,N,N,41126, -N,N,N,N,N,38059,N,64626,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38852,N,N,N,N,N,N, -N,37550,64103,N,N,N,N,N,N,N,N,N,N,N,37538,64105,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,37480,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35153,N,N,N,N,N,N,N,N,N,64111,N,N,N,N,N, -N,N,N,N,64113,N,N,N,N,N,N,N,N,N,35154,N,N,N,N,37978,N,N,N,N,N,N,N,N,50883,N,N, -N,35293,N,51362,N,N,N,N,N,N,N,N,N,N,N,N,N,50884,N,N,N,40530,N,35155,N,N,N,N,N, -N,N,N,N,N,40533,37562,N,N,50885,N,N,35931,N,N,N,64125,64168,39528,64071,N,N, -64126,N,N,N,N,N,N,N,N,N,N,37563,N,N,N,64950,N,64162,N,N,N,N,N,64163,N,64164, -39860,64166,N,N,N,N,N,N,N,35295,N,N,N,64987,N,N,64169,N,35156,N,N,N,N,N,N,N,N, -64171,N,N,N,N,N,N,64634,N,N,N,N,N,N,N,35296,N,40783,51325,N,N,35297,N,N,N,N,N, -64176,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40909,41191,N,N,N,N,N,64177,35238, -N,N,N,N,N,N,N,N,N,N,N,N,40698,N,N,N,N,N,N,N,64178,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,64180,N,37572,N,N,N,N,N,N,40815,N,N,N,N,N,N,N,35760,N, -N,N,N,N,N,N,N,N,N,40876,N,N,N,N,N,35299,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,39891,35300,N,N,N,64181,N,N,N,N,N,40917,N,N,N,N,N,N,35157,N,N,37573,N,N,N, -35158,N,N,N,N,N,N,N,N,N,N,N,N,64179,N,N,N,64182,N,N,N,N,N,N,N,N,N,N,N,64183,N, -N,N,N,N,N,40668,N,N,N,64452,40817,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64186,37575,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,50886,39500,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35944,N,N,35301,N,N,N,N,40829,N,N, -N,N,N,41129,64196,N,N,N,N,50887,N,N,35159,N,N,N,N,N,N,64170,N,N,N,N,N,N,N,N,N, -N,N,35160,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35811,N,35681,N,N,N,N,39665,N,N,40631,N, +41043,N,N,N,N,N,36190,N,N,38492,N,N,36064,N,64890,N,N,N,N,N,N,N,N,38910,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,37565,36189,38909,N,N,N,N,36708,N,N,N,N,64759,38242, +38861,40548,N,N,N,N,N,N,N,37452,36553,39356,N,N,N,N,40357,N,36692,N,N,N,N,N,N, +N,N,N,N,36732,N,N,N,N,36181,N,36514,N,N,N,N,N,N,N,N,N,36730,N,N,N,N,N,N,38830, +N,N,N,N,38600,N,N,36068,N,N,N,N,39363,N,37078,N,40126,N,N,N,36726,N,N,N,N,N,N, +N,N,N,N,N,N,N,38000,64331,N,N,64970,N,N,36079,N,N,N,36551,N,N,N,N,36180,41209, +N,N,N,N,N,N,N,36777,N,N,36177,N,N,N,N,N,N,N,N,N,39367,34628,N,N,N,N,N,N,N,N,N, +N,N,N,37079,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +34627,N,N,N,N,N,N,N,N,N,N,N,N,34631,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,34648,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40671, +36185,34626,N,N,39374,N,N,N,N,N,N,N,N,36794,N,N,N,N,N,36843,N,39375,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36802,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37577,N,N,N,N,N,38876,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,34653,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,36165,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38323,40057,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38322,N, +36172,36827,N,N,N,N,39907,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,34636,N,N,N,N,N,N,N,N,N,N,N,N,N,34637,N,N,N,N,N,N,N,N,N,40570,34647,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,39918,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39390,N,N,N, +N,N,N,N,N,N,N,N,N,N,64250,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35410,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,39393,N,N,N,N,N,N,35431,35765,N,N,N,N,N,N,N,N,N,N,35500,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +39401,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,64458,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38878,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38353,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,39413,64586,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,39849,N,N,N,N,N,N,N,N,N,N,N,N,64476,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,65110,N,N,N,N,N,40612,N,N,N,N,N,N,40265,38363,N,N,N,N,N,N,N,N,N,N,35269, +N,N,N,N,N,N,N,N,N,N,N,N,39416,N,N,N,N,N,N,38500,N,N,N,N,36949,N,N,38612,N,N,N, +N,N,N,N,38780,N,N,N,N,N,N,38477,N,38881,N,N,N,N,N,N,39496,N,N,N,N,N,N,N,N,N,N, +N,39497,N,65149,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37034,N,N,N,N,39504,N,N,N,N, +N,N,N,37703,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36568,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37065,N,N,N,N,N,39509,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,37052,N,N,N,N,N,39512,N,35768,37077,N,N,N,N,N,N,N,N,N,N,N,N,N,38465,N,N, +N,N,N,N,39514,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39516,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,38850,N,N,N,N,N,N,N,N,N,N,N,N,N,34652,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +35515,N,N,N,39850,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37109,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39520,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,37189,35928,N,N,N,N,N,N,N,N,39523,N,N,N,N,N,N,35913,N,N,N,N,N,N,N,N, +N,N,N,35766,N,N,N,N,N,N,N,N,N,N,64719,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38507, +39534,N,37199,N,N,N,N,N,N,N,N,38726,N,N,41190,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +37591,N,38517,N,N,37844,N,N,37307,38521,N,N,N,N,N,39536,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38520,37325,N,40010,41071,N,N,41066,N, +N,N,N,N,N,37215,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,34625,N,N,N,N,N,N,N,N,40869,N,N,35258,N,34639,N,N,N,N,N,N,34638,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,34645,N,N,N,40653,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +39545,N,N,N,N,N,N,N,N,N,36082,N,N,N,36183,N,40398,N,N,N,36050,N,N,N,34649,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40307,N,N,N,N,N,N,N,N, +N,38585,N,38588,N,N,N,N,N,N,40145,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +35255,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40686,34633,N,N,N,N,N,N,N,N,N,N, +64323,34651,N,40649,N,N,N,N,N,N,64467,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37294,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,36184,34630,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36182,N,N,N,N,N,N,N, +40312,N,N,N,N,N,N,N,N,N,N,40315,40627,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,40626,N,40406,N,N,N,N,39247,N,N,35278,N,N,N,35776,N,40900,N,35796,N,N,35954, +N,N,N,N,N,N,50879,35833,N,N,N,N,N,35142,N,50880,N,N,N,N,N,N,N,N,N,64229,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,51323,35782,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40023,N,N,N, +N,N,N,N,N,N,N,N,N,N,39675,N,N,N,N,N,N,N,35280,35279,N,N,N,50881,N,35281,N, +35298,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37502,N,40378,N,N,N,N,N,50882,N,N,35951,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64504,N,N,N,35783,37483,N,N,35282,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,40911,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +40361,35283,N,N,39394,N,N,N,N,N,N,N,N,N,37479,37540,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,35955,N,N,35150,N,N,N,N,N,N,N,N,N,N,N,N,N,35151,37496,N,N,N,N,N,N, +N,N,37302,N,N,N,N,35284,N,40914,N,N,N,N,N,N,N,N,37543,N,N,38306,N,N,N,N,N, +37486,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,38634,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37487,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37539,N,N,N,N,N,35152,N,N,64087,N,N,N,N,39014,N, +N,N,36088,N,N,N,N,N,N,N,N,35286,N,N,N,N,N,N,N,N,N,N,39090,N,N,N,37547,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38622,37548,N,N,N,N,N,N,N,N,N,N,35952,N, +40814,N,N,N,N,N,N,36594,N,N,N,40812,35288,N,N,N,N,64089,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37544,N,N,N,N,N,37219,N,N, +N,N,N,N,35904,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40819,N, +37549,N,N,N,N,N,N,N,N,N,N,N,N,N,39913,N,N,N,N,N,37545,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,37546,N,N,N,N,N,N,35289,N,N,N,N,N,N,N,64854,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,40872,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35953, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37537,N,N,37091,N,N,N,N,N,N,N,N,41126,N,N,N,N, +N,38059,N,64626,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38852,N,N,N,N,N,N,N,37550, +64103,N,N,N,N,N,N,N,N,N,N,N,37538,64105,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,37480,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35153,N,N,N,N,N,N,N,N,N,64111,N,N,N,N,N,N,N,N,N, +64113,N,N,N,N,N,N,N,N,N,35154,N,N,N,N,37978,N,N,N,N,N,N,N,N,50883,N,N,N,35293, +N,51362,N,N,N,N,N,N,N,N,N,N,N,N,N,50884,N,N,N,40530,N,35155,N,N,N,N,N,N,N,N,N, +N,40533,37562,N,N,50885,N,N,35931,N,N,N,64125,64168,39528,64071,N,N,64126,N,N, +N,N,N,N,N,N,N,N,37563,N,N,N,64950,N,64162,N,N,N,N,N,64163,N,64164,39860,64166, +N,N,N,N,N,N,N,35295,N,N,N,64987,N,N,64169,N,35156,N,N,N,N,N,N,N,N,64171,N,N,N, +N,N,N,64634,N,N,N,N,N,N,N,35296,N,40783,51325,N,N,35297,N,N,N,N,N,64176,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40909,41191,N,N,N,N,N,64177,35238,N,N,N,N,N,N, +N,N,N,N,N,N,40698,N,N,N,N,N,N,N,64178,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,64180,N,37572,N,N,N,N,N,N,40815,N,N,N,N,N,N,N,35760,N,N,N,N,N,N,N, +N,N,N,40876,N,N,N,N,N,35299,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39891, +35300,N,N,N,64181,N,N,N,N,N,40917,N,N,N,N,N,N,35157,N,N,37573,N,N,N,35158,N,N, +N,N,N,N,N,N,N,N,N,N,64179,N,N,N,64182,N,N,N,N,N,N,N,N,N,N,N,64183,N,N,N,N,N,N, +40668,N,N,N,64452,40817,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64186,37575,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,50886,39500,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35944,N,N,35301,N,N,N,N,40829,N,N,N,N,N, +41129,64196,N,N,N,N,50887,N,N,35159,N,N,N,N,N,N,64170,N,N,N,N,N,N,N,N,N,N,N, +35160,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35811,N,35681,N,N,N,N,39665,N,N,40631,N, 50888,N,N,N,64209,N,N,N,N,N,N,64210,N,N,N,N,N,N,N,N,40634,64212,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,64217,N,N,N,N,N,N,N,N,N,N,N,N,64219,N,40160,N,N,N, 64503,N,64506,35303,41082,64220,N,N,64221,N,35305,N,N,N,N,N,50889,N,N,N,N,N,N, @@ -790,17 +804,17 @@ N,N,N,N,N,N,37472,N,N,N,N,N,N,N,N,N,N,N,37470,37313,N,35525,N,N,38819,N,N,N,N, N,N,N,N,N,N,35692,N,36222,N,N,N,N,N,N,N,40020,N,N,N,N,N,40381,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,40133,N,N,N,N,N,N,N,N,N,N,N,35163,N,N,N,N,N,N,N,N, -N,N,64348,N,64347,N,64343,N,N,N,N,N,N,N,N,N,N,N,39111,64346,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,40174,N,N,N,N,N,N,N,37602,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,38055,N,N,N,N,N,N,N,N,N,N,36044,N,39892,N,N,64356,64374,N,N,64352,N, -N,N,N,N,N,N,N,N,N,N,N,N,39397,N,N,39618,N,N,N,37371,N,N,N,41075,N,N,N,N,N,N,N, -40818,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40908,N,N,N,39077,37608,N,N,N,N,N,N, -N,N,39868,N,38643,N,N,37607,N,N,64615,N,N,N,N,N,N,N,N,N,N,N,35709,N,N,N,N, -39924,N,N,N,N,N,40695,N,N,40641,N,N,N,N,N,N,N,N,N,39279,N,N,N,N,N,N,38641,N,N, -36417,N,N,N,N,N,38218,N,N,N,38886,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38645,N,N,N,N,N, -37606,40770,N,N,N,N,N,N,N,64359,N,N,N,N,N,N,N,N,39337,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,64230,64361,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38885,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,38525,N,N,N,64364,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39330,N,N,N,N,N, +N,N,64348,N,64347,N,64343,N,N,N,N,N,N,N,N,N,34661,N,39111,64346,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,40174,N,N,N,N,N,N,N,37602,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,38055,N,N,N,N,N,N,N,N,N,N,36044,N,39892,N,N,64356,64374,N,N, +64352,N,N,N,N,N,N,N,N,N,N,N,N,N,39397,N,N,39618,N,N,N,37371,N,N,N,41075,N,N,N, +N,N,N,N,40818,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40908,N,N,N,39077,37608,N,N, +N,N,N,N,N,N,39868,N,38643,N,N,37607,N,N,64615,N,N,N,N,N,N,N,N,N,N,N,35709,N,N, +N,N,39924,N,N,N,N,N,40695,N,N,40641,N,N,N,N,N,N,N,N,N,39279,N,N,N,N,N,N,38641, +N,N,36417,N,N,N,N,N,38218,N,N,N,38886,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38645,N,N,N, +N,N,37606,40770,N,N,N,N,N,N,N,64359,N,N,N,N,N,N,N,N,39337,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,64230,64361,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38885,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,38525,N,N,N,64364,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39330,N,N,N,N,N, 39611,N,N,N,39525,N,N,37966,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64366,N,N, 39391,N,N,N,N,N,N,N,N,N,39139,N,N,37460,N,N,N,N,N,38523,35503,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35959,N,N,N,N,N,N,35759,40637,N,N, @@ -808,405 +822,407 @@ N,63961,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37610,N,N,N,N,35960,N,N,N,N,N,N,N,N,N,N, N,64370,N,N,N,64369,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35164,N,39152,38642,N,N,N,N, N,N,N,64372,35777,N,35165,35294,N,35166,N,N,50890,N,N,N,N,N,N,65090,N,N,N,N,N, -N,N,N,N,N,N,N,N,64379,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35167,N,35168,N,N,N, +N,N,N,N,N,N,34664,N,64379,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35167,N,35168,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,39885,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40403,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,38988,N,N,N,N,N,N,N,N,N,N,38738,N,N,N,N,N,38339,N,N,N,N,39862,N, -N,N,N,N,N,N,N,N,N,N,N,39609,N,N,N,38835,N,N,N,N,N,N,40820,37617,N,N,N,N,N,N,N, -N,N,N,N,38879,N,N,N,N,64422,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64427,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,39031,N,N,N,38996,38341,N,N,N,N,N,N,N,40277,64434,38270,N, -N,N,N,N,N,N,N,38722,N,38118,N,N,N,N,37621,N,N,N,N,N,N,N,36037,N,N,N,N,N,N, -37629,N,N,64418,N,N,40017,N,N,38121,39004,37616,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,37964,N,N,N,N,N,N,N,37227,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35704,N,N,N,N,38114,N, -N,N,N,N,N,N,38991,N,64437,N,N,N,N,37489,N,N,37733,N,N,39003,N,N,38992,N,N,N,N, -N,N,N,38844,N,N,N,N,37619,N,N,37696,38989,N,N,N,38258,N,65007,N,N,N,N,N,N,N,N, -64961,N,N,N,N,64442,N,N,37611,N,N,N,N,N,N,64627,38839,N,N,N,N,N,N,N,N,N,64436, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37031,N,N,N,N,N,N,N,N,N,N,38721, -37620,N,N,N,64444,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38263,N,N,N,N,N,N,N,N,N,N,N, -40674,N,36728,N,N,N,N,N,N,N,63964,N,N,N,38514,40629,N,N,N,38475,N,N,N,36012,N, -N,N,N,N,N,N,N,N,41210,N,N,N,N,N,N,N,N,N,N,N,38261,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,37082,N,N,37735,N,65188,N,N,N,37087,N,N,N,N,37716,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35169,N,35764,N,N,N,N,40384,N,N,N,N,N,N,36424,N, -64453,N,N,N,N,N,64455,N,N,N,50891,N,64121,N,N,N,N,N,N,N,N,N,N,N,N,N,40551,N,N, -N,N,N,36057,N,N,N,N,N,N,64466,35170,35171,N,N,N,N,N,N,N,N,N,N,64637,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40811,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -64460,N,65198,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64465,N,N, -N,N,N,N,N,N,N,N,N,64373,64468,N,N,N,N,N,N,N,N,N,N,N,N,N,64470,64472,N,N,N,N,N, -N,N,35677,N,37708,N,39650,N,N,35785,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64475,40905,N,N,N,N,N,N,N,N,40772,N,N,N,N,N,N, -N,N,N,N,39149,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,64477,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36338,35172,N,65010,N, -37709,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64487,N,N,N,N,N,N, -41202,39016,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40792,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,36211,N,N,N,64478,N,N,N,N,N,64479,N,N,N,N,N,35912,64483,N,N,N,N,36264,N, -N,64484,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40053,N,N,39032,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,36192,N,N,N,N,N,N,N,64485,N,36193,N,N,N,N,N,N,N,N,N,N,N,N,N,36194, -41121,N,N,N,40000,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39085,N,N,N,40682,N, -N,N,N,N,N,36052,N,N,N,N,N,N,N,N,N,40171,N,N,N,N,N,64480,N,N,40785,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36197,N,N,N,N,N,N,40177,N,N,N,N,N,N,N,N,N,N, -64600,N,N,36198,N,N,N,N,N,N,N,38484,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -64488,N,N,N,50892,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40910, -64508,N,39652,N,N,N,N,N,N,40821,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,64497,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36201,N,N,N,N,N,37711,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37710,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,64500,N,N,N,N,50894,N,N,N,64451,N,N,35173,N,N,N,N,N,N,N,N, -N,N,N,35962,N,N,N,N,N,N,35963,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,36202,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37715,N,N,40443,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64509,N,N,N, -36953,64576,N,64577,64579,37729,64582,37730,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,36203,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64588,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,38328,N,N,50896,35786,N,N,N,N,N,N,N,N,N,N,39034,N,N,N,N, -50897,N,64593,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64596,N,N,N,N,N,N,N,N,64175,N,N,N,N, -N,N,N,36204,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -64097,N,N,64599,N,N,N,N,N,N,N,N,N,39792,N,N,N,N,N,N,N,N,41041,N,N,N,N,N,N,N, -35964,N,35787,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37742,N,N,N,64725, -64681,N,N,N,N,N,N,N,N,N,N,N,N,N,64609,N,N,N,N,N,N,N,N,N,35174,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,64203,N,N,N,N,N,N,N,63962,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,37754,N,41184,N,N,N,N,N,N,37739,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64619,N,N,N,N,N,41180,N,N,37992,N, -N,N,N,N,N,N,N,N,N,N,64621,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,36209,N,N,N,N,N,N,64868,N,N,N,N,39354,N,N,N,39632,39521, -41189,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41051,38572,N,N,N,N,38720,N,N,N,N, -N,N,N,N,N,N,N,N,40689,N,N,N,N,N,N,N,N,35917,N,N,N,N,N,N,N,N,N,N,N,N,N,40830,N, -N,N,N,N,N,N,N,N,N,N,N,36210,N,N,N,N,64630,N,N,N,N,N,N,N,N,N,N,N,N,N,38569,N,N, -N,N,N,N,N,N,41070,N,N,64682,N,N,N,64461,N,N,N,64628,N,N,N,N,N,N,N,N,N,N,41076, -N,N,N,N,N,N,N,N,N,N,N,N,N,41073,N,N,N,64633,N,N,N,N,N,64636,N,N,N,N,N,N,N,N,N, -N,N,N,N,40016,N,N,37753,37752,N,N,41181,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,36213,N,36214,N,N,N,N,N,N,37748,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -36215,64677,N,N,64674,N,N,N,N,N,N,37059,N,N,N,N,N,N,N,41081,36217,N,N,N,N,N,N, -N,N,N,N,35836,N,41078,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35789,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40794,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,40948,N,N,40890,N,N,N,N,N,N,N,N,N,N,36218,N,N,N,N,N,N,N,N,N, -N,N,N,40517,N,N,N,N,N,N,37808,N,41077,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,39750,N,64686,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64688,N,N,N,N,N,N, -N,N,N,64081,N,N,N,N,N,36219,36220,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -40662,N,N,37804,N,N,N,40795,N,37801,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41084,N,N,N,N,N,N,N,64690,N,N,N, -N,N,N,N,N,N,N,N,N,35521,N,N,N,N,N,40884,N,N,N,N,N,N,N,N,N,N,N,64684,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,40524,N,N,N,N,N,N,N,36805,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37805,N,N,N,N,N,N,N, -N,N,N,N,N,40387,N,N,N,36258,N,N,N,40266,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -64694,N,N,36259,40523,N,40525,36260,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35581,N,N,N,N,N,64693,N,64707,37810, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36261,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37793,N,N,N,N,N,N,N,N,N,N,35526,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,35419,N,N,N,35149,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,65236,N,N,N,N,35448,N,37803,N,N,N,N,N,N,N,N,N,36263,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,40773,N,N,N,N,N,N,N,N,N,35414,N,N,N,64703,N,N,N, -64704,N,36582,N,N,35492,35139,N,N,N,N,N,N,37875,N,N,N,N,N,N,N,N,N,N,N,N,64683, -40610,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40391,N,N,N,50898,35790,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64709,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64715,N, -N,N,N,N,N,N,N,N,N,N,37811,N,64714,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,64713,36268,N,64454,35175,N,35966,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64717,N,N,N,N,N,N,N,N,40179,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,64720,N,N,38331,N,N,N,N,N,N,N,N,N,N,N,64723,N,N, -64724,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36270,64727,N,N,N, -N,N,37851,N,N,N,N,65123,N,N,N,N,N,N,N,N,N,N,N,N,37845,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,64730,N,N,N,39793,N,N,64733,N,N,N,N,N,N,N,36271,N,N,N,64242,N,N, -N,N,N,N,N,N,N,N,N,37848,N,N,N,64735,N,N,N,37843,N,N,N,N,N,N,N,64737,N,N,N,N,N, -N,N,N,N,36470,N,N,N,N,N,N,N,64610,N,N,N,N,N,N,N,N,37841,N,N,N,36273,N,N,N,N,N, -N,N,39001,N,N,N,N,N,N,N,N,N,64338,N,N,N,N,N,N,N,N,64339,N,N,N,N,N,64333,N,N, -40127,N,N,N,N,N,N,N,N,39794,N,N,N,N,N,N,N,N,N,N,N,N,N,64336,37822,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40433,64747,N,N,N,N,N, -N,N,N,N,41147,N,39806,N,N,N,N,N,N,N,36275,N,N,35922,N,N,N,N,39656,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,39885,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40403,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,38988,N,N,N,N,N,N,N,N,N,N,38738,N,N,N,N,N,38339,N,N,N,N, +39862,N,N,N,N,N,N,N,N,N,N,N,N,39609,N,N,N,38835,N,N,N,N,N,N,40820,37617,N,N,N, +N,N,N,36090,N,N,N,N,38879,N,N,N,N,64422,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64427,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39031,N,N,N,38996,38341,N,N,N,N,N,N,N,40277, +64434,38270,N,N,N,N,N,N,N,N,38722,N,38118,N,N,N,N,37621,N,N,N,N,N,N,N,36037,N, +N,N,N,N,N,37629,N,N,64418,N,N,40017,N,N,38121,39004,37616,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,37964,N,N,N,N,N,N,N,37227,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35704,N,N,N, +N,38114,N,N,N,N,N,N,N,38991,N,64437,N,N,N,N,37489,N,N,37733,N,N,39003,N,N, +38992,N,N,N,N,N,N,N,38844,N,N,N,N,37619,N,N,37696,38989,N,N,N,38258,N,65007,N, +N,N,N,N,N,N,N,64961,N,N,N,N,64442,N,N,37611,N,N,N,N,N,N,64627,38839,N,N,34671, +N,N,N,N,N,N,64436,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37031,N,N,N,N, +N,N,N,N,N,N,38721,37620,N,34674,N,64444,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38263, +N,N,N,N,N,N,N,N,N,N,N,40674,N,36728,N,N,N,N,N,N,N,63964,N,N,N,38514,40629,N,N, +N,38475,N,N,N,36012,N,N,N,N,N,N,N,N,N,41210,N,N,N,N,N,N,N,N,N,N,N,38261,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37082,N,N,37735,N,65188,N,N,N,37087,N,N,N, +N,37716,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35169,N,35764,N,N,N,N, +40384,N,N,N,N,N,N,36424,N,64453,N,N,N,N,N,64455,N,N,N,50891,N,64121,N,N,N,N,N, +N,N,N,N,N,N,N,N,40551,N,N,N,N,N,36057,N,N,N,N,N,N,64466,35170,35171,N,N,N,N,N, +N,N,N,N,N,64637,N,N,N,N,N,N,N,N,N,N,N,N,34675,N,N,N,N,N,N,N,N,N,N,N,40811,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64460,N,65198,N,N,N,34669,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,64465,N,N,N,N,N,N,N,N,N,N,N,64373,64468,N,N,N,N,N,N,N, +N,N,N,N,N,N,64470,64472,N,N,N,N,N,N,N,35677,N,37708,N,39650,N,N,35785,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64475,40905, +N,N,N,N,N,N,N,N,40772,N,N,N,N,N,N,N,N,N,N,39149,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,36073,N,N,N,N,N,N,N,N,N,N,N,N,64477,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,36338,35172,N,65010,N,37709,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,64487,N,N,N,N,N,N,41202,39016,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +40792,N,N,N,36070,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36211,N,N,N,64478,N,N,N,N,N, +64479,N,N,N,N,N,35912,N,N,N,N,N,N,34676,64483,N,N,N,N,36264,N,N,64484,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40053,N,N,39032,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +36192,N,N,N,N,N,N,N,64485,N,36193,N,N,N,N,N,N,N,N,N,N,N,N,N,36194,41121,N,N,N, +40000,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39085,N,N,N,40682,N,N,N,36076,N, +N,36052,N,N,N,N,N,N,N,N,N,40171,N,N,N,N,N,64480,N,N,40785,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,36197,N,N,N,N,N,N,40177,N,N,N,N,N,N,N,N,N,N,64600,N,N, +36198,N,N,N,N,N,N,N,38484,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64488,N,N, +N,50892,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40910,64508,N,39652, +N,N,N,N,N,N,40821,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64497, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36201,N,N,N,N,N,37711,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,37710,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,64500,N,N,N,N,50894,N,N,N,64451,N,N,35173,N,N,N,N,N,N,N,N,N,N,N,35962,N, +N,N,N,N,N,35963,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,36202,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37715,N,N,40443,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64509,N,N,N,36953,64576,N, +64577,64579,37729,64582,37730,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +36203,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64588,36094,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,38328,N,N,50896,35786,N,N,N,N,N,N,N,N,N,N,39034,N,N,N,N,50897,N, +64593,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64596,N,N,N,N,N,N,N,N,64175,N,N,N,N,N,N,N, +36204,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64097,N, +N,64599,N,N,N,N,N,N,N,N,N,39792,N,N,N,N,N,N,N,N,41041,N,N,N,N,N,N,N,35964,N, +35787,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37742,N,N,N,64725,64681,N,N, +N,N,N,N,N,N,N,N,N,N,N,64609,N,N,N,N,N,N,N,N,N,35174,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,64203,N,N,N,N,N,N,N,63962,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,37754,N,41184,N,N,N,N,N,N,37739,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64619,N,N,N,N,N,41180,N,N,37992,N,N,N,N,N,N, +N,N,N,N,N,64621,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,36209,N,N,N,N,N,N,64868,N,N,N,N,39354,N,N,N,39632,39521,41189,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41051,38572,N,N,N,N,38720,N,N,N,N,N,N,N,N,N,N,N, +N,40689,N,N,N,N,N,N,N,N,35917,N,N,N,N,N,N,N,N,N,N,N,N,N,40830,N,N,N,N,N,N,N,N, +N,N,N,N,36210,N,N,N,N,64630,N,N,N,N,N,N,N,N,N,N,N,N,N,38569,N,N,N,N,N,N,N,N, +41070,N,N,64682,N,N,N,64461,N,N,N,64628,N,N,N,N,N,N,N,N,N,N,41076,N,N,N,N,N,N, +N,N,N,N,N,N,N,41073,N,N,N,64633,N,N,N,N,N,64636,N,N,N,N,N,N,N,N,N,N,N,N,N, +40016,N,N,37753,37752,N,N,41181,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,36213,N,36214,N,N,N,N,N,N,37748,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36215,64677, +N,N,64674,N,N,N,N,N,N,37059,N,N,N,N,N,N,N,41081,36217,N,N,N,N,N,N,N,N,N,N, +35836,N,41078,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35789,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40794,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,40948,N,N,40890,N,N,N,N,N,N,N,N,N,N,36218,N,N,N,N,N,N,N,N,N,N,N,N, +40517,N,N,N,N,N,N,37808,N,41077,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,39750,N,64686,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64688,N,N,N,N,N,N,N,N,N, +64081,N,N,N,N,N,36219,36220,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40662,N, +N,37804,N,N,N,40795,N,37801,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41084,N,N,N,N,N,N,N,64690,N,N,N,N,N,N,N, +N,N,N,N,N,35521,N,N,N,N,N,40884,N,N,N,N,N,N,N,N,N,N,N,64684,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40524, +N,N,N,N,N,N,N,36805,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37805,N,N,N,N,N,N,N,N,N,N,N, +N,40387,N,N,N,36258,N,N,N,40266,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64694,N,N, +36259,40523,N,40525,36260,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35581,N,N,N,N,N,64693,N,64707,37810,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36261,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,37793,N,N,N,N,N,N,N,N,N,N,35526,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,35419,N,N,N,35149,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,65236,N,N,N,N,35448,N,37803,N,N,N,N,N,N,N,N,N,36263,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,40773,N,N,N,N,N,N,N,N,N,35414,N,N,N,64703,N,N,N,64704,N,36582, +N,N,35492,35139,N,N,N,N,N,N,37875,N,N,N,N,N,N,N,N,N,N,N,N,64683,40610,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,40391,N,N,N,50898,35790,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,64709,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64715,N,N,N,N,N,N,N,N, +N,N,N,37811,N,64714,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64713,36268, +N,64454,35175,N,35966,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,64717,N,N,N,N,N,N,N,N,40179,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,64720,N,N,38331,N,N,N,N,N,N,N,N,N,N,N,64723,N,N,64724,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36270,64727,N,N,N,N,N,37851,N,N,N,N, +65123,N,N,N,N,N,N,N,N,N,N,N,N,37845,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +64730,N,N,N,39793,N,N,64733,N,34660,N,N,N,N,N,36271,N,N,N,64242,N,N,N,N,N,N,N, +N,N,N,N,37848,N,N,N,64735,N,N,N,37843,N,N,N,N,N,N,N,64737,N,N,N,N,N,N,N,N,N, +36470,N,N,N,N,N,N,N,64610,N,N,N,N,N,N,N,N,37841,N,N,N,36273,N,N,N,N,N,N,N, +39001,N,N,N,N,N,N,N,N,N,64338,N,N,N,N,N,N,N,N,64339,N,N,N,N,N,64333,N,N,40127, +N,N,N,N,N,N,N,N,39794,N,N,N,N,N,N,N,N,N,N,N,N,N,64336,37822,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36059,N,N,N,N,N,N,N,N,N,40433,64747,N,N,N,N,N,N, +N,N,N,41147,N,39806,N,N,N,N,N,N,N,36275,N,N,35922,N,N,N,N,39656,N,N,N,N,N,N, 36572,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40185,N,N,N,N,N,N,N,N,N,N,N,N,N,64080,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39143,64755,N,N,N,N, -64754,N,N,N,36042,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,37861,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39513,N,N,N,36277,N,N,N,N,N,N, -N,64845,N,N,N,N,64862,N,N,N,N,N,N,N,N,N,N,N,N,N,36733,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,38215,64758,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,37456,N,N,N,N,35176,36278,64763,41085,39164,35177,N,N,N,N, -N,N,N,N,65103,N,N,37462,N,N,N,N,N,N,N,N,N,N,64201,N,N,37864,N,N,N,64760,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40163,64937,N,N,N,N,N,N,64580,N,N,N,N,N,N,N,N, -38464,N,N,36280,N,N,N,N,N,N,N,N,N,N,39754,36793,N,N,N,N,N,N,64766,N,N,N,N,N,N, -N,35178,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36281,N,N, -N,37246,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37876,N,N,N,N,N,N,N,N,N,N,N,N,N,64380,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,37863,N,N,38895,N,N,N,65098,N,N,N,N,N,64837,N, -38565,N,N,N,N,65248,64840,64839,65266,65130,N,N,N,N,N,36285,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,39841,36002,39607,36604,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40865,N,N,N, -N,N,N,N,N,N,64849,N,N,N,N,N,N,N,64173,N,N,N,N,36286,N,N,35236,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,39641,N,N,N,N,N,N,N,N,N,N,N,64846,N,N,36288,N,N,38896,N,N,N,N,N,N, -N,N,N,N,37812,64836,N,N,N,N,N,N,N,N,N,N,N,N,40871,N,N,N,N,36290,N,N,N,N,39350, -N,N,N,N,N,N,N,N,N,N,N,N,N,64850,N,N,N,N,N,N,36289,N,N,36422,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,41169,N,N,N,N,N,N,N,N,N,N,N,N,N,40906,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,37583,N,N,N,40180,36292,N,N,N,N,N,N,N,N,N,N,64833,N,N,N,N,N,N,N,39756,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,64855,64751,40158,N,N,N,N,N,N,N,64834,39020,N,N,N,N, -N,N,N,N,N,N,N,N,N,38905,N,38232,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39006,65147,38093, -N,N,N,N,N,37870,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36003,N,64858,N,N,N,N,N,N,37877, -N,N,N,N,N,37871,36586,N,N,N,36699,N,N,N,N,N,N,N,N,N,N,N,35934,N,36294,N,N,N,N, -N,N,N,N,N,N,N,36296,N,N,36295,N,N,N,N,N,37879,N,N,N,N,N,N,N,36297,N,N,N,N,N,N, -N,64498,N,N,N,N,38512,N,N,N,N,N,N,N,N,N,36299,N,N,N,64860,N,N,N,N,N,N,N,N,N, -36709,N,N,N,36301,N,N,N,N,N,40360,38137,N,N,36302,N,N,N,N,N,N,N,N,37866,N,N,N, -N,N,N,N,N,N,64863,37872,40886,N,N,N,N,N,N,N,N,N,36303,N,N,N,38755,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36304,37873,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,64866,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -64869,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40923,N,N,N,N, -37880,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35831,N,N,N,N,64870,N,N,N, -N,N,35791,N,N,N,N,N,N,36305,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +64754,N,N,N,36042,N,N,34677,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,37861,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39513,N,N,N,36277,N,N,N,N, +N,N,N,64845,N,N,N,N,64862,N,N,N,N,N,N,N,N,N,N,N,N,N,36733,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,38215,64758,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,37456,N,N,N,N,35176,36278,64763,41085,39164,35177,N,N, +N,N,N,N,N,N,65103,N,N,37462,N,N,N,N,N,N,N,N,N,N,64201,N,N,37864,N,N,N,64760,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40163,64937,N,N,N,N,N,N,64580,N,N,N,N,N,N, +N,N,38464,N,N,36280,N,N,N,N,N,N,N,N,N,N,39754,36793,N,N,N,N,N,N,64766,N,N,N,N, +N,N,N,35178,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36281, +N,N,N,37246,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37876,N,N,N,N,N,N,N,N,N,N,N,N,N, +64380,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37863,N,N,38895,N,N,N,65098,N,N,N,N,N, +64837,N,38565,N,N,N,N,65248,64840,64839,65266,65130,N,N,N,N,N,36285,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,39841,36002,39607,36604,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +40865,N,N,N,N,N,N,N,N,N,64849,N,N,N,N,N,N,N,64173,N,N,N,N,36286,N,N,35236,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,39641,N,N,N,N,N,N,N,N,N,N,N,64846,N,N,36288,N,N,38896, +N,N,N,N,N,N,N,N,N,N,37812,64836,N,N,N,N,N,N,N,N,N,N,N,N,40871,N,N,N,N,36290,N, +N,N,N,39350,N,N,N,N,N,N,N,N,N,N,N,N,N,64850,N,N,N,N,N,N,36289,N,N,36422,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,41169,N,N,N,N,N,N,N,N,N,N,N,N,N,40906,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,37583,N,N,N,40180,36292,N,N,N,N,N,N,N,N,N,N,64833,N,N,N,N,N,N, +N,39756,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64855,64751,40158,N,N,N,N,N,N,N,64834, +39020,N,N,N,N,N,N,N,N,N,N,N,N,N,38905,N,38232,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +39006,65147,38093,N,N,N,N,N,37870,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36003,N,64858, +N,N,N,N,N,N,37877,N,N,N,N,N,37871,36586,N,N,N,36699,N,N,N,N,N,N,N,N,N,N,N, +35934,N,36294,N,N,N,N,N,N,N,N,N,N,N,36296,N,N,36295,N,N,N,N,N,37879,N,N,N,N,N, +N,N,36297,N,N,N,N,N,N,N,64498,N,N,N,N,38512,N,N,N,N,N,N,N,N,N,36299,N,N,N, +64860,N,N,N,N,N,N,N,N,N,36709,N,N,N,36301,N,N,N,N,N,40360,38137,N,N,36302,N,N, +N,N,N,N,N,N,37866,N,N,N,N,N,N,N,N,N,64863,37872,40886,N,N,N,N,N,N,N,N,N,36303, +N,N,N,38755,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36304, +37873,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64866,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,64869,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,40923,N,N,N,N,37880,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +35831,N,N,N,N,64870,N,N,N,N,N,35791,N,N,N,N,N,N,36305,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,36306,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,64881,N,N,N,N,64879,N,N,N,N,N,N,N,N,36307,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +40935,37053,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40912,N,N,N,35792,N,64882, +N,40110,35793,N,N,35547,N,N,N,N,N,N,N,N,N,N,N,64228,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,38350,N,64886,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64354,N,N,N,N,N,N,36308, +N,N,N,64888,N,N,N,N,N,36579,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,36982,N,N,39110,N,N,N,N,N,N,N,36309,N,N,N,N,38865,N,N,40630,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64199,N,N,41026,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,39027,N,N,N,N,N,N,N,N,N,N,40956,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,36005,36311,N,N,37627,36312,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,37967,N,36313,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,35179,N,N,N,N,N,N,N,N,38862,N,N,N,64243,64942,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64431,37559,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +36314,N,N,N,N,N,N,N,N,N,N,N,N,N,40026,N,N,N,N,N,N,64941,N,N,N,N,N,N,N,N,N,N,N, +N,N,36316,37956,N,N,N,N,N,N,N,N,N,N,N,36317,N,N,N,N,N,N,N,41174,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35905,38869,N,37962,N,N,N,N,N, +37965,N,N,N,N,38859,N,N,N,N,N,36318,N,N,36319,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +36320,65273,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,64960,64761,N,N,N,N,N,N,36061,N,64382,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,37555,N,N,N,N,N,64943,N,N,N,N,N,N,N,N,N,36321,N,N,N,N, +38355,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35265,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,64872,N,N,40119,N,N,36323,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,64192,36325,64100,N,35143,N,N,N,N,36324,N,N,N,N,N,36327, +36328,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64967,64944,N,N,N,N,N,N,37957,38870,N,N, +N,N,N,N,N,N,N,64710,38980,N,N,N,N,N,N,N,N,N,N,N,N,36329,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,36330,N,N,N,N,N,N,N,N,65104,N,N,N,N,N,N,64972,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,40359,N,N,N,N,N,64973,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +64975,N,N,N,N,38354,N,N,N,N,N,N,N,36333,N,N,N,N,N,N,N,N,64698,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,64965,N,64978,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +40156,N,N,N,N,N,38351,N,N,36334,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64980, +N,N,N,N,N,38636,38635,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +37046,N,64963,39083,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38638, +N,N,N,N,N,N,N,N,N,N,N,N,N,36340,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,64992,N,35943,N,N,36342,N,N,N,36343,N,N,N,N,N,N,N,36858,N,N,N,N, +N,N,N,N,N,N,38864,N,N,N,N,35794,N,N,36344,N,N,N,N,N,37081,N,35911,N,64240,N,N, +N,N,64993,36345,N,64995,N,N,N,N,N,N,N,36346,N,64355,N,N,N,37030,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,39280,N,N,37355,N,38768,39023,64994,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,39154,N,39676,35180,65021,N,N,39262,N,N,N,38333,N,N,N,N,N,N,N,64996, +N,N,N,37350,N,N,N,N,64997,64998,N,N,N,N,N,N,N,N,64999,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,37972,N,N,N,39352,N,N,N,N,N,N,N,N,38889,37702,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,39011,N,N,N,N,N,N,N,N,N,N,N,38332,N,65005,65015,N,N,N, +N,N,N,39024,38646,36521,N,N,N,N,N,37969,N,N,36419,N,35674,N,N,N,N,65006,N,N,N, +N,65008,N,N,N,N,65012,N,39925,N,N,N,N,N,36078,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,38782,N,N,N,N,N,39893,N,39619,N,38856,41179,37328,N,N,40932,N,36829,N, +37353,N,N,N,N,N,N,N,N,N,39136,N,N,N,37578,N,38999,N,N,35921,N,N,N,N,65003,N, +39753,N,N,N,N,N,N,N,N,N,40310,40623,N,N,N,N,N,N,N,N,N,40140,N,N,N,N,N,N,65002, +N,N,36337,N,N,65019,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36435,N,N,N,N, +N,N,N,N,N,N,N,64207,N,N,N,N,N,N,N,N,N,N,N,N,N,38649,N,N,N,N,N,N,N,N,N,39103, +40521,36007,N,N,N,N,N,N,N,N,39882,N,N,N,N,65022,37596,N,N,N,N,N,65089,37324, +37346,N,N,N,N,N,N,N,N,N,N,N,N,65092,34655,N,N,N,N,N,35795,N,N,65095,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,65096,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37973,N,N,N,N, +65099,N,65100,N,N,N,N,36287,N,N,N,N,N,N,N,N,N,40568,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,65105,N,N,N,N,37974,N,N,N,N,N,N,N,40289,N,N,N,N, +37975,N,N,N,N,N,N,N,N,N,N,39270,N,N,N,N,N,N,N,N,N,N,N,N,N,35797,N,N,N,N,41065, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39092,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,41033,41036,N,40549,N,N,N,N,N,N,N,N,N,N,N,39093,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65112,N,39285,65107,41061,N,65113,N,N,N,N, +N,N,N,N,N,39095,39096,N,N,N,N,N,N,N,39098,N,N,N,N,N,N,39099,N,N,N,N,N,N,40892, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41034,N,N, +40647,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36009,N,N,39086,N,N,N,N,N, +N,N,N,37590,N,N,N,64225,N,37332,N,N,N,N,N,N,N,N,64222,N,N,65115,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,35923,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65118,N,N,N,N,64471,65114, +38085,N,N,N,N,64202,N,N,N,N,N,N,N,N,N,N,N,39105,38748,N,65140,N,38771,N,N,N,N, +N,N,N,N,64070,N,N,N,38756,N,N,N,65128,N,38478,N,38757,35930,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,35233,38394,N,37588,65129,N,64325,N,39112,N,N,37103,N,39113,39114,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37997,38071,65132,N,N,37995,N,N,N, +N,N,N,37628,N,38379,N,65139,38766,65119,N,N,N,N,N,N,N,N,N,64957,N,N,37589,N,N, +N,N,N,N,65209,N,N,65137,34680,N,N,N,64443,N,N,38010,N,N,38395,65143,N,N,N,N,N, +N,N,65145,N,65141,N,N,N,37981,N,N,N,N,N,N,N,65148,N,N,N,N,N,N,N,N,N,37700, +36518,N,N,N,N,N,N,N,N,N,N,N,37587,N,38072,N,34681,N,N,N,N,N,N,64625,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,38750,N,N,N,N,36013,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65191,N,N, +N,37994,N,N,N,37859,N,N,39119,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41177,N,N, +N,N,N,N,N,N,41151,41037,41144,N,N,N,N,N,41166,41143,N,N,N,N,N,N,N,N,65193,N,N, +N,N,N,N,N,N,N,N,35267,N,N,N,N,65195,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +40436,35181,N,N,N,N,N,40059,N,N,N,N,N,N,39122,N,N,N,40873,N,N,N,65202,N,N, +65201,N,N,N,38873,N,41156,N,38006,N,N,N,N,N,N,N,N,N,N,39288,N,N,N,N,N,N,65203, +N,N,N,N,N,39123,65204,N,N,N,39124,N,N,N,N,N,N,N,40889,N,N,N,N,N,N,N,N,38001,N, +N,N,N,N,N,N,N,N,39125,65208,N,N,N,50900,N,N,N,N,N,N,N,N,N,N,N,65210,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,40540,N,N,65211,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41028,N, +N,N,N,39127,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39128,65212,N,N,N,N,40958,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65213,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,40413,N,N,N,N,40673,N,N,N,N,N,N,N,N,N,N,N,N,39130, +40415,65215,N,65214,N,N,40683,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40537,41052,N, +N,N,N,N,N,N,65216,N,N,N,38007,39132,N,65217,N,N,N,39134,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,65219,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65224,N,N,N,65225,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65226,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +65227,N,N,N,N,N,N,N,N,N,40898,N,N,35947,39108,N,38064,38065,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,65233,N,N,N,N,N,41153,N,65234,N,N,N,N,41165,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,65235,N,N,39141,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65238, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37348,N,N,N,N,36807,38062,N, +35407,38066,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36820,N,N,N,N,39146, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65240,N,N,N,N,N,N,N,N,N,40416,N,N, +N,N,39150,N,N,N,N,38340,N,64744,N,N,N,N,N,39151,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,35950,N,N,N,N,N,N,N,N,64216,N,N,N,N,N,N,N,N,N,N,N,N,N,65244,N,N,N,N,N,N,N, +N,N,41134,40268,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39153,N,N,N,39155,N,38081,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39157,N,N,64079,38626,N,N,N,N, +37968,N,38562,N,N,39158,N,N,N,38629,N,N,N,N,N,39159,N,41030,38627,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,39160,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40676,N,N,N, +N,N,N,63958,N,N,N,N,N,N,38083,N,N,N,N,38082,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65249,N,65257,N,N,N,N,38628,N,35244,38619,N,N, +N,N,N,N,N,N,N,N,N,N,N,65250,N,N,N,N,N,N,N,N,N,N,38084,65251,N,N,N,65255,40955, +N,N,N,N,N,N,N,N,N,N,N,35929,N,N,N,N,N,N,N,N,N,37833,N,38120,64342,N,N,N,37061, +41128,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,65253,N,N,N,39165,39163,65256,N,36543,N,N,N,N,35800,65271,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36712,38086,N,N,N,N,N,N,N,N,40426,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,64617,N,N,N,N,N,N,N,N,N,N,N,N,40154,N,65267,N,N,40050, +N,N,65264,35273,N,N,N,N,N,N,N,N,N,39233,N,N,N,N,N,N,N,39234,N,N,N,65269,N, +37335,N,N,N,N,N,38092,N,N,N,65272,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,38824,N,65276,N,N,N,36062,N,64959,N,N,N,N,N,N,N,65278,N,N,N,N,N,N,N,N, +N,N,N,N,N,38609,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38101,N,N,38096,39236,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35939,N,N,41139,N,N, +N,N,N,N,N,N,N,N,N,N,38095,N,N,N,40954,N,N,N,N,37349,N,40042,N,N,N,36425,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36428,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,36429,N,N,N,N,N,39539,N,N,N,N,N,N,N,N,N,N,N,N,N,39239,N, +36017,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36432,N,N,N,N,N, +N,N,N,N,N,36431,39241,N,N,N,N,N,36433,36434,N,N,N,N,39602,35237,N,N,N,N,N, +39244,N,N,N,40952,N,N,N,N,N,N,36438,39245,37322,36439,N,N,N,N,38113,N,N,N,N, +36935,N,36824,36440,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38123,36444,38227,N, +N,N,N,N,N,N,40933,N,N,N,N,N,N,N,N,N,N,40790,N,N,N,N,N,N,N,38223,N,36446,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,39274,N,N,N,N,N,N,N,N,40036,40153,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,36445,N,N,N,N,N,N,N,N,N,N,N,N,39248,N,N,N,N,N,N,N,N,N,39249,N,N, +36450,N,N,N,N,N,N,N,N,N,N,N,39250,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +36456,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36449,40793,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +35763,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40797,36454,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36018,N,N,N,N,N,N,N,N,N,N,N, +N,N,36462,N,40804,39251,N,N,64184,N,N,N,N,N,39252,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,36464,N,N,N,N,N,N,N,N,N,N,N,N,40801,N,36466,N,N,N,N,N,N, +N,N,N,N,N,N,41067,N,N,N,N,40768,N,N,N,N,N,N,38125,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,38126,N,N,40893,N,N,N,36475,N,N,N,N,N,N,39255,38135,N,40799,N,N,N,N,36467,N, +N,40802,N,N,N,N,N,N,N,38134,N,N,N,N,N,N,N,N,N,N,N,N,N,39256,N,N,N,N,N,N,N,N,N, +36469,63963,N,N,N,N,36978,N,38136,N,N,N,N,N,N,N,N,N,39258,N,N,N,N,N,N,N,N,N, +41136,36019,N,N,N,36473,N,36472,N,N,N,38131,N,N,N,N,N,39087,N,N,N,N,N,N,41138, +N,N,N,N,N,N,N,N,N,N,N,36474,N,N,N,N,N,N,39260,N,N,N,N,N,36476,N,36477,N,N,N, +35801,N,N,35234,40663,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,41142,N,N,N,N,N,N,N,N,N,N,N,N,40514,N,N,36516,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -36306,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64881,N,N,N,N,64879, -N,N,N,N,N,N,N,N,36307,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40935,37053,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,40912,N,N,N,35792,N,64882,N,40110,35793,N,N,35547,N, -N,N,N,N,N,N,N,N,N,N,64228,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38350,N,64886,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,64354,N,N,N,N,N,N,36308,N,N,N,64888,N,N,N,N,N, -36579,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36982,N,N, -39110,N,N,N,N,N,N,N,36309,N,N,N,N,38865,N,N,40630,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,64199,N,N,41026,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39027,N,N, -N,N,N,N,N,N,N,N,40956,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36005,36311,N,N, -37627,36312,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37967,N, -36313,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,35179,N,N,N,N,N,N,N,N,38862,N,N,N,64243,64942,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,64431,37559,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36314,N,N,N,N,N,N,N,N,N, -N,N,N,N,40026,N,N,N,N,N,N,64941,N,N,N,N,N,N,N,N,N,N,N,N,N,36316,37956,N,N,N,N, -N,N,N,N,N,N,N,36317,N,N,N,N,N,N,N,41174,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,35905,38869,N,37962,N,N,N,N,N,37965,N,N,N,N,38859,N,N,N,N, -N,36318,N,N,36319,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36320,65273,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64960,64761,N,N,N,N,N, -N,N,N,64382,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37555,N,N, -N,N,N,64943,N,N,N,N,N,N,N,N,N,36321,N,N,N,N,38355,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -35265,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64872,N,N,40119,N,N, -36323,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64192,36325, -64100,N,35143,N,N,N,N,36324,N,N,N,N,N,36327,36328,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,64967,64944,N,N,N,N,N,N,37957,38870,N,N,N,N,N,N,N,N,N,64710,38980,N,N,N,N, -N,N,N,N,N,N,N,N,36329,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36330,N,N,N,N,N,N,N,N, -65104,N,N,N,N,N,N,64972,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40359,N,N,N,N,N, -64973,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64975,N,N,N,N,38354,N,N,N, -N,N,N,N,36333,N,N,N,N,N,N,N,N,64698,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64965, -N,64978,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40156,N,N,N,N,N,38351,N,N, -36334,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64980,N,N,N,N,N,38636,38635,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37046,N,64963,39083,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38638,N,N,N,N,N,N,N,N,N,N,N,N,N, -36340,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64992,N, -35943,N,N,36342,N,N,N,36343,N,N,N,N,N,N,N,36858,N,N,N,N,N,N,N,N,N,N,38864,N,N, -N,N,35794,N,N,36344,N,N,N,N,N,37081,N,35911,N,64240,N,N,N,N,64993,36345,N, -64995,N,N,N,N,N,N,N,36346,N,64355,N,N,N,37030,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -39280,N,N,37355,N,38768,39023,64994,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39154,N, -39676,35180,65021,N,N,39262,N,N,N,38333,N,N,N,N,N,N,N,64996,N,N,N,37350,N,N,N, -N,64997,64998,N,N,N,N,N,N,N,N,64999,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37972,N, -N,N,39352,N,N,N,N,N,N,N,N,38889,37702,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,39011,N,N,N,N,N,N,N,N,N,N,N,38332,N,65005,65015,N,N,N,N,N,N,39024,38646, -36521,N,N,N,N,N,37969,N,N,36419,N,35674,N,N,N,N,65006,N,N,N,N,65008,N,N,N,N, -65012,N,39925,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38782,N,N,N,N, -N,39893,N,39619,N,38856,41179,37328,N,N,40932,N,36829,N,37353,N,N,N,N,N,N,N,N, -N,39136,N,N,N,37578,N,38999,N,N,35921,N,N,N,N,65003,N,39753,N,N,N,N,N,N,N,N,N, -40310,40623,N,N,N,N,N,N,N,N,N,40140,N,N,N,N,N,N,65002,N,N,36337,N,N,65019,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36435,N,N,N,N,N,N,N,N,N,N,N,64207,N,N, -N,N,N,N,N,N,N,N,N,N,N,38649,N,N,N,N,N,N,N,N,N,39103,40521,36007,N,N,N,N,N,N,N, -N,39882,N,N,N,N,65022,37596,N,N,N,N,N,65089,37324,37346,N,N,N,N,N,N,N,N,N,N,N, -N,65092,N,N,N,N,N,N,35795,N,N,65095,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65096,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,37973,N,N,N,N,65099,N,65100,N,N,N,N,36287,N,N,N,N, -N,N,N,N,N,40568,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65105,N, -N,N,N,37974,N,N,N,N,N,N,N,40289,N,N,N,N,37975,N,N,N,N,N,N,N,N,N,N,39270,N,N,N, -N,N,N,N,N,N,N,N,N,N,35797,N,N,N,N,41065,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,39092,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41033,41036,N, -40549,N,N,N,N,N,N,N,N,N,N,N,39093,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,65112,N,39285,65107,41061,N,65113,N,N,N,N,N,N,N,N,N,39095,39096,N,N,N,N,N,N, -N,39098,N,N,N,N,N,N,39099,N,N,N,N,N,N,40892,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41034,N,N,40647,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,36009,N,N,39086,N,N,N,N,N,N,N,N,37590,N,N,N,64225,N,37332,N,N, -N,N,N,N,N,N,64222,N,N,65115,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35923,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,65118,N,N,N,N,64471,65114,38085,N,N,N,N,64202,N,N,N,N,N,N,N,N,N, -N,N,39105,38748,N,65140,N,38771,N,N,N,N,N,N,N,N,64070,N,N,N,38756,N,N,N,65128, -N,38478,N,38757,35930,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35233,38394,N,37588,65129,N, -64325,N,39112,N,N,37103,N,39113,39114,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,37997,38071,65132,N,N,37995,N,N,N,N,N,N,37628,N,38379,N,65139,38766, -65119,N,N,N,N,N,N,N,N,N,64957,N,N,37589,N,N,N,N,N,N,65209,N,N,65137,N,N,N,N, -64443,N,N,38010,N,N,38395,65143,N,N,N,N,N,N,N,65145,N,65141,N,N,N,37981,N,N,N, -N,N,N,N,65148,N,N,N,N,N,N,N,N,N,37700,36518,N,N,N,N,N,N,N,N,N,N,N,37587,N, -38072,N,N,N,N,N,N,N,N,64625,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38750,N,N,N,N,36013, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,65191,N,N,N,37994,N,N,N,37859,N,N,39119,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,41177,N,N,N,N,N,N,N,N,41151,41037,41144,N,N,N,N,N, -41166,41143,N,N,N,N,N,N,N,N,65193,N,N,N,N,N,N,N,N,N,N,35267,N,N,N,N,65195,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40436,35181,N,N,N,N,N,40059,N,N,N,N,N,N, -39122,N,N,N,40873,N,N,N,65202,N,N,65201,N,N,N,38873,N,41156,N,38006,N,N,N,N,N, -N,N,N,N,N,39288,N,N,N,N,N,N,65203,N,N,N,N,N,39123,65204,N,N,N,39124,N,N,N,N,N, -N,N,40889,N,N,N,N,N,N,N,N,38001,N,N,N,N,N,N,N,N,N,39125,65208,N,N,N,50900,N,N, -N,N,N,N,N,N,N,N,N,65210,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40540,N,N,65211,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,41028,N,N,N,N,39127,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,39128,65212,N,N,N,N,40958,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,65213,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40413,N,N,N,N, -40673,N,N,N,N,N,N,N,N,N,N,N,N,39130,40415,65215,N,65214,N,N,40683,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,40537,41052,N,N,N,N,N,N,N,65216,N,N,N,38007,39132,N, -65217,N,N,N,39134,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65219,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,65224,N,N,N,65225,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65226, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65227,N,N,N,N,N,N,N,N,N,40898,N,N, -35947,39108,N,38064,38065,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65233,N,N,N,N,N,41153,N, -65234,N,N,N,N,41165,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65235,N,N,39141,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65238,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,37348,N,N,N,N,36807,38062,N,35407,38066,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,36820,N,N,N,N,39146,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,65240,N,N,N,N,N,N,N,N,N,40416,N,N,N,N,39150,N,N,N,N,38340,N,64744,N, -N,N,N,N,39151,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35950,N,N,N,N,N,N,N,N,64216,N, -N,N,N,N,N,N,N,N,N,N,N,N,65244,N,N,N,N,N,N,N,N,N,41134,40268,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,39153,N,N,N,39155,N,38081,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,39157,N,N,64079,38626,N,N,N,N,37968,N,38562,N,N,39158,N,N,N,38629, -N,N,N,N,N,39159,N,41030,38627,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39160,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40676,N,N,N,N,N,N,63958,N,N,N,N,N,N,38083,N,N,N, -N,38082,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -65249,N,65257,N,N,N,N,38628,N,35244,38619,N,N,N,N,N,N,N,N,N,N,N,N,N,65250,N,N, -N,N,N,N,N,N,N,N,38084,65251,N,N,N,65255,40955,N,N,N,N,N,N,N,N,N,N,N,35929,N,N, -N,N,N,N,N,N,N,37833,N,38120,64342,N,N,N,37061,41128,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65253,N,N,N,39165,39163, -65256,N,36543,N,N,N,N,35800,65271,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,36712,38086,N,N,N,N,N,N,N,N,40426,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64617, -N,N,N,N,N,N,N,N,N,N,N,N,40154,N,65267,N,N,40050,N,N,65264,35273,N,N,N,N,N,N,N, -N,N,39233,N,N,N,N,N,N,N,39234,N,N,N,65269,N,37335,N,N,N,N,N,38092,N,N,N,65272, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38824,N,65276,N,N,N,N,N, -64959,N,N,N,N,N,N,N,65278,N,N,N,N,N,N,N,N,N,N,N,N,N,38609,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,38101,N,N,38096,39236,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,35939,N,N,41139,N,N,N,N,N,N,N,N,N,N,N,N,38095,N,N,N, -40954,N,N,N,N,37349,N,40042,N,N,N,36425,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,36428,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36429,N,N, -N,N,N,39539,N,N,N,N,N,N,N,N,N,N,N,N,N,39239,N,36017,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36432,N,N,N,N,N,N,N,N,N,N,36431,39241,N,N,N,N,N, -36433,36434,N,N,N,N,39602,35237,N,N,N,N,N,39244,N,N,N,40952,N,N,N,N,N,N,36438, -39245,37322,36439,N,N,N,N,38113,N,N,N,N,36935,N,36824,36440,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,38123,36444,38227,N,N,N,N,N,N,N,40933,N,N,N,N,N,N,N,N,N,N, -40790,N,N,N,N,N,N,N,38223,N,36446,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39274,N,N,N,N, -N,N,N,N,40036,40153,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36445,N,N,N,N,N,N,N,N,N, -N,N,N,39248,N,N,N,N,N,N,N,N,N,39249,N,N,36450,N,N,N,N,N,N,N,N,N,N,N,39250,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36456,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -36449,40793,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35763,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,40797,36454,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,36018,N,N,N,N,N,N,N,N,N,N,N,N,N,36462,N,40804,39251,N,N,64184,N,N, -N,N,N,39252,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36464,N,N,N,N,N, -N,N,N,N,N,N,N,40801,N,36466,N,N,N,N,N,N,N,N,N,N,N,N,41067,N,N,N,N,40768,N,N,N, -N,N,N,38125,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38126,N,N,40893,N,N,N,36475,N,N,N,N, -N,N,39255,38135,N,40799,N,N,N,N,36467,N,N,40802,N,N,N,N,N,N,N,38134,N,N,N,N,N, -N,N,N,N,N,N,N,N,39256,N,N,N,N,N,N,N,N,N,36469,63963,N,N,N,N,36978,N,38136,N,N, -N,N,N,N,N,N,N,39258,N,N,N,N,N,N,N,N,N,41136,36019,N,N,N,36473,N,36472,N,N,N, -38131,N,N,N,N,N,39087,N,N,N,N,N,N,41138,N,N,N,N,N,N,N,N,N,N,N,36474,N,N,N,N,N, -N,39260,N,N,N,N,N,36476,N,36477,N,N,N,35801,N,N,35234,40663,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41142,N,N,N,N,N,N, -N,N,N,N,N,N,40514,N,N,36516,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36519,N,35958,N,N,N,N,N,N,N,N,N,N,N,38210, -N,N,N,N,N,N,N,N,N,N,N,N,39037,N,N,N,38741,N,N,36520,N,N,N,N,N,N,N,36522,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35235,N,39264,39266,N,N,38140, -39265,N,N,N,N,N,N,N,38138,N,N,N,N,N,N,N,36526,36530,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,36528,N,N,N,N,N,N,N,39267,38826,38139,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,36539,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36060,N,N,N,N,N,N,N,N, -N,39030,N,36513,N,N,N,N,36020,N,36535,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40358,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,40624,N,N,N,36536,N,N,N,N,N,N,N,N,N,N,N,N,40304,N,N, -N,N,35182,N,N,N,N,N,N,N,35183,N,N,N,N,N,N,N,N,N,N,N,N,N,35184,N,N,N,N,N,N,N,N, -N,N,N,N,35185,N,N,N,N,N,N,N,35186,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35187,35188,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,35189,N,N,N,N,N,N,N,N,36540,36541,N,N,N,N,N,36542,N,40401,N,N, -N,N,38141,N,N,N,35799,35802,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,41186,N,N,N,N,N,N,40937,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -64936,N,N,N,35559,N,N,N,36546,N,N,N,N,N,N,N,N,N,N,N,36548,N,N,N,N,N,N,N,N,N,N, -39268,N,N,N,N,N,39269,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,38222,N,N,N,N,N,N,N,N,N,39091,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,36555,35807,N,N,N,N,N,36558,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,36559,N,N,39272,N,N,N,N,39273,N,N,N,N,N,N,N,N,39275,36561,N,39276,N,N,N,N,N, -N,N,N,N,36564,36565,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39277,N,N,N, -N,N,N,41150,N,N,N,N,N,36566,41148,41141,N,N,41140,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,35808,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,35253,N,N,N,N,N,N,N,36573,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40541,39281,N, -N,N,N,35246,40424,N,N,N,N,N,N,N,N,38245,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39282,N,N,35676,N,N,N,N,N,N,N,N,N,35249,41152,N, -N,N,36575,N,38246,N,N,39284,N,39286,N,N,N,39287,N,39289,N,N,40410,N,N,36576,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,37724,N,N,N,N,N,N,N,40422,N,35679,N,N,38243,N,N,N, -N,N,N,N,N,N,N,38247,N,N,N,N,N,40419,N,N,N,N,N,N,N,N,N,N,N,N,N,39292,N,N,39293, -39294,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35675,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -39331,N,N,N,N,N,N,N,39332,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39334,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,39336,N,N,N,N,35518,N,N,N,N,N,N,N,N,N,N,N,40545,N,N,N,N,N,N,N, -N,N,N,39338,N,N,N,N,N,N,41160,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,39339,N,N,N,N,N,N,N,N,N,N,65220,N,N,N,N,N,N,39106,36584,N,41146,N,N,N,N, -N,N,N,N,N,N,N,64887,N,N,36590,N,N,N,40639,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -35266,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39340,N,N,N,N,N,N,N,N,N,N,N,N, -N,38251,N,N,38252,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39343,N,N,39242,35190,36680, -N,N,N,N,N,N,N,N,N,N,N,64494,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,39342,N,N,N,36603,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36048,N,N, -N,N,35666,N,N,N,N,N,39344,N,N,N,N,35191,36673,N,N,N,N,N,N,N,39345,N,N,N,N,N,N, -N,N,N,36681,N,N,N,N,N,N,N,N,N,N,N,64077,N,N,N,N,N,N,N,N,40420,36021,N,N,N, -64489,39764,N,39346,40552,N,N,N,N,N,N,N,N,N,N,N,N,36682,N,36674,N,N,36689,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38982,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39348,N,N,N,N,N,N,N,N,N,N,36597,64853,N,N, -40141,N,N,N,N,N,N,N,N,35192,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36691,N, -N,N,N,N,N,N,N,N,N,N,36719,N,N,N,N,N,N,N,N,N,N,36451,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,36694,N,N,N,N,N,N,N,N,N,N,N,N,65142,N,N,N,N,40902,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,64172,N,N,N,N,N,36696,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -38984,39351,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38501,N,64108,N,40423,N,N,N,40546,N,N, -N,38604,36455,N,N,64629,N,39038,N,N,N,N,N,N,N,64953,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,38908,N,N,N,N,N,N,N,N,N,39161,N,36710,N,N,N,N,N,N,N,N,38254,N,37445,N,N, -36704,N,N,N,40657,N,N,N,N,N,65229,N,39353,N,N,N,N,N,N,N,N,N,N,N,N,36706,38732, -N,N,N,N,N,N,N,N,N,N,N,N,37319,38239,N,N,N,N,N,N,N,39355,N,N,N,N,N,N,N,N,N, -36461,36721,N,N,38091,N,N,N,N,N,N,N,N,N,N,N,N,38321,N,N,N,N,N,N,N,N,N,39666,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,38595,39357,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,41167,N,N,N,36717,N,N,39358,36596,N,36722,38372,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,39359,37442,N,64421,N,N,N,N,N,N,N,N,N,N,39360,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64948,36727,N,N,N, -39361,N,N,N,N,N,N,N,N,N,64185,N,N,N,N,N,N,N,N,36672,64068,N,N,N,N,N,39362,N,N, -N,N,N,N,N,36700,N,N,N,N,36029,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39364,39365,N,N, -36731,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -36022,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,36771,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36046,N,N,N,N,N,N,N,N, -N,39366,N,N,N,N,N,N,N,N,N,N,N,N,N,38605,N,N,N,N,N,N,N,N,N,N,N,N,N,38599,36773, -N,N,N,N,N,N,N,N,N,N,64187,N,35937,38256,N,N,N,37736,N,36734,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,36778,N,N,N,N,N,N,41040,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -37075,N,N,38230,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,36792,N,N,N,N,N,39368,N,N,N,N,N,N,N,N,N,N,N,36783,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,39369,N,N,N,N,N,N,N,N,N,N,N,N,N,38265,N,N,N,N,N,N,N,N, -N,N,N,N,40777,N,N,N,N,39370,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39371, -40405,36784,N,N,N,N,N,N,N,N,N,N,N,64122,N,N,N,N,N,N,N,N,40543,N,N,N,N,39373, -41161,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39643,N,N,N,41158,N,N,N, -N,N,N,N,36788,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41175,N,N,N,N,N,N,N,N,N,N,N,N, -41159,N,N,N,N,N,N,N,41027,N,N,N,36789,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -36786,N,N,N,N,N,N,41057,40542,N,N,N,N,N,N,N,N,N,N,36790,N,N,N,N,N,N,N,N,40936, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,40114,N,N,N,N,N,38268,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,40903,N,N,36795,36796,N,N,N,N,N,N,N,N,36844,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,36800,N,37738,N,N,N,35812,40060,N,N,N,N,N,N,N,N,38305,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,65260,N,N,38307,N,N,N,N,N,N,N,35909,36024,N,N,N,N,N,N, -N,N,N,N,N,36801,N,N,N,41042,N,N,N,N,N,N,N,N,N,N,N,N,N,39376,N,N,N,N,N,36803, -36804,N,N,N,N,N,N,N,N,N,38308,N,N,N,N,N,36806,N,40544,N,N,N,N,N,N,N,63960,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38309,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -40115,N,N,N,N,N,N,N,N,N,39377,65265,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,39378,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,40130,N,N,N,39379,N,N,N,N,N,38311,N,N,N,N,N,N,38313,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,38310,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40029,N,N,N,N,N, -N,N,N,39138,N,N,N,N,N,N,36809,N,41154,36810,N,N,N,N,N,N,39380,N,N,41145,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,39768,N,36813,N,41172,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,36814,N,N,N,N,35813,N,N,N,N,35193,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,36816,38326,N,N,N,N,N,N,N,N,N,N,N,N,39382,N,38373,N, -N,N,N,N,N,N,N,N,N,N,N,39383,N,N,N,N,38325,N,N,N,N,N,N,N,N,N,N,N,41162,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40957,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,41048,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36822,N,N,N, -39384,N,N,N,N,N,N,N,36819,N,N,N,N,N,N,N,N,N,N,N,N,36837,N,N,N,N,N,36841,N,N,N, -N,39385,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,37500,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40005,36830,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,36831,N,N,N,N,N,N,N,N,N,N,N,N,N,41035,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,36834,N,N,N,41164,N,N,N,N,N,N,N,N,36835,36836,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,39876,N,N,N,39932,N,N,N,N,N,N,38476,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,39670,N,36014,N,N,N,N,N,N,N,N,N,N,N,N,36839,N,N,N,N,N,N,N,N,N,N,36840, -N,N,N,N,35815,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35194, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35195, -39386,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +36519,N,35958,N,N,N,N,N,N,N,N,N,34663,N,38210,N,N,N,N,N,N,N,N,N,N,N,N,39037,N, +N,N,38741,N,N,36520,N,N,N,N,N,N,N,36522,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,35235,N,39264,39266,N,N,38140,39265,N,N,N,N,N,N,N,38138,N,N,N,N,N, +N,N,36526,36530,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36528,N,N,N,N,N,N,N,39267,38826, +38139,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36539,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,36060,N,N,N,N,N,N,N,N,N,39030,N,36513,N,N,N,N,36020,N, +36535,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40358,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40624, +N,N,N,36536,N,N,N,N,N,N,N,N,N,N,N,N,40304,N,N,N,N,35182,N,N,N,N,N,N,N,35183,N, +N,N,N,N,N,N,N,N,N,N,N,N,35184,N,N,N,N,N,N,N,N,N,N,N,N,35185,N,N,N,N,N,N,N, +35186,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35187,35188,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35189,N,N,N, +N,N,N,N,N,36540,36541,N,N,N,N,N,36542,N,40401,N,N,N,N,38141,N,N,N,35799,35802, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41186,N,N,N,N,N,N, +40937,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64936,N,N,N,35559,N,N,N, +36546,N,N,N,N,N,N,N,N,N,N,N,36548,N,N,N,N,N,N,N,N,N,N,39268,N,N,N,N,N,39269,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +38222,N,N,N,N,N,N,N,N,N,39091,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36555,35807, +N,N,N,N,N,36558,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36559,N,N,39272,N,N,N, +N,39273,N,N,N,N,N,N,N,N,39275,36561,N,39276,N,N,N,N,N,N,N,N,N,36564,36565,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39277,N,N,N,N,N,N,41150,N,N,N,N,N, +36566,41148,41141,N,N,41140,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +35808,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35253,N,N,N, +N,N,N,N,36573,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40541,39281,N,N,N,N,35246,40424,N,N, +N,N,N,N,N,N,38245,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,39282,N,N,35676,N,N,N,N,N,N,N,N,N,35249,41152,N,N,N,36575,N,38246,N,N, +39284,N,39286,N,N,N,39287,N,39289,N,N,40410,N,N,36576,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,37724,N,N,N,N,N,N,N,40422,N,35679,N,N,38243,N,N,N,N,N,N,N,N,N,N,38247,N, +N,N,N,N,40419,N,N,N,N,N,N,N,N,N,N,N,N,N,39292,N,N,39293,39294,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,36091,35675,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39331,N,N,N,N,N,N,N, +39332,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39334,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +39336,N,N,N,N,35518,N,N,N,N,N,N,N,N,N,N,N,40545,N,N,N,N,N,N,N,N,N,N,39338,N,N, +N,N,N,N,41160,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39339,N,N, +N,N,N,N,N,N,N,N,65220,N,N,N,N,N,N,39106,36584,N,41146,N,N,N,N,N,N,N,N,N,N,N, +64887,N,N,36590,N,N,N,40639,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35266,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39340,N,N,N,N,N,N,N,N,N,N,N,N,N,38251,N,N,38252, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39343,N,N,39242,35190,36680,N,N,N,N,N,N,N,N,N, +N,N,64494,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39342,N, +N,N,36603,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36048,N,N,N,N,35666,N,N,N,N, +N,39344,N,N,N,N,35191,36673,N,N,N,N,N,N,N,39345,N,N,N,N,N,N,N,N,N,36681,N,N,N, +N,N,N,N,N,N,N,N,64077,N,N,N,N,N,N,N,N,40420,36021,N,N,N,64489,39764,N,39346, +40552,N,N,N,N,N,N,N,N,N,N,N,N,36682,N,36674,N,N,36689,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38982,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,39348,N,N,N,N,N,N,N,N,N,N,36597,64853,N,N,40141,N,N,N,N,N,N,N, +N,35192,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36691,N,N,N,N,N,N,N,N,N,N,N, +36719,N,N,N,N,N,N,N,N,N,N,36451,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36694,N,N,N,N,N, +N,N,N,N,N,N,N,65142,N,N,N,N,40902,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64172,N,N,N,N,N, +36696,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38984,39351,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,38501,N,64108,N,40423,N,N,N,40546,N,N,N,38604,36455,N,N, +64629,N,39038,N,N,N,N,N,N,N,64953,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38908,N,N,N,N, +N,N,N,N,N,39161,N,36710,N,N,N,N,N,N,N,N,38254,N,37445,N,N,36704,N,N,N,40657,N, +N,N,N,N,65229,N,39353,N,N,N,N,N,N,N,N,N,N,N,N,36706,38732,N,N,N,N,N,N,N,N,N,N, +N,N,37319,38239,N,N,N,N,N,N,N,39355,N,N,N,N,N,N,N,N,N,36461,36721,N,N,38091,N, +N,N,N,N,N,N,N,N,N,N,N,38321,N,N,N,N,N,N,N,N,N,39666,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,38595,39357,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41167,N, +N,N,36717,N,N,39358,36596,N,36722,38372,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +39359,37442,N,64421,N,N,N,N,N,N,N,N,N,N,39360,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64948,36727,N,N,N,39361,N,N,N,N,N,N,N,N,N, +64185,N,N,N,N,N,N,N,N,36672,64068,N,N,N,N,N,39362,N,N,N,N,N,N,N,36700,N,N,N,N, +36029,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39364,39365,N,N,36731,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,34678,N,N,N,36022,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36771,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36046,N,N,N,N,N,N,N,N,N,39366,N,N,N,N,N,N,N,N, +N,N,N,N,N,38605,N,N,N,N,N,N,N,N,N,N,N,N,N,38599,36773,N,N,N,N,N,N,N,N,N,N, +64187,N,35937,38256,N,N,N,37736,N,36734,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +36778,N,N,N,N,N,N,41040,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37075,N,N,38230,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -36845,N,N,N,38336,N,N,N,N,N,N,N,N,N,N,N,N,N,41163,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40520,N,N,N,N,N,N,39387,N,36851,N,N,N,N, -36857,N,N,N,N,N,N,N,N,N,N,N,N,N,38337,N,41038,N,N,N,N,N,N,39388,N,N,N,N,41060, -36855,N,N,N,N,N,N,N,35248,41032,N,N,N,N,36859,36854,N,N,N,N,N,40412,N,N,N, -39389,35816,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37569,N,N,N,N,N,N,N,40918,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41170,N,N,36928,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35524,N,N,39392,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,40944,40947,N,N,N,N,N,N,N,N,N,N,N,N,40383,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,40950,N,38344,N,N,40538,N,N,N,N,N,N,N,N,N,N,N,N,39395, -N,N,N,N,N,N,N,N,N,N,N,35402,N,N,N,N,N,N,N,N,40945,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,35495,N,N,N,N,N,N,N,N,39398,N,N,N,40951,N,40941,N,N,N,N,N, -N,35420,N,40366,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,38345,N,N,N,N,N,36936,N,N,39400,N,N,N,N,N,36937,N,N,36026,N,N, -37041,N,N,N,N,N,N,36938,N,N,N,N,N,N,N,N,N,N,39402,N,N,N,N,N,N,N,N,N,N,N,39889, -N,N,N,N,N,N,N,39403,N,39404,N,N,N,N,N,N,N,N,39405,N,N,N,N,39406,36940,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36941,N,N,38347,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -38882,N,N,N,N,N,N,N,N,38348,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40824,N,N,N,N,N, -N,N,N,N,35196,35197,N,N,N,N,N,N,35198,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39261,N,N,N,N,N,N,N,N,N,N,N,N,39770,N,N,N,N, -36944,N,35919,N,N,N,N,N,N,N,N,N,N,N,36948,N,50902,39592,39407,65259,40355, +36792,N,N,N,N,N,39368,N,N,N,N,N,N,N,N,N,N,N,36783,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,39369,N,N,N,N,N,N,N,N,N,N,N,N,N,38265,N,N,N,N,N,N,N,N,N,N,N,N,40777, +N,N,N,N,39370,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39371,40405,36784,N,N, +N,N,N,N,N,N,N,N,N,64122,N,N,N,N,N,N,N,N,40543,N,N,N,N,39373,41161,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39643,N,N,N,41158,N,N,N,N,N,N,N,36788,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,41175,N,N,N,N,N,N,N,N,N,N,N,N,41159,N,N,N,N,N,N,N, +41027,N,N,N,36789,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36786,N,N,N,N,N,N, +41057,40542,N,N,N,N,N,N,N,N,N,N,36790,N,N,N,N,N,N,N,N,40936,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,40114,N,N,N,N,N,38268,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40903, +N,N,36795,36796,N,N,N,N,N,N,N,N,36844,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36800,N, +37738,N,N,N,35812,40060,N,N,N,N,N,N,N,N,38305,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,65260,N,N,38307,N,N,N,N,N,N,N,35909,36024,N,N,N,N,N,N,N,N,N,N,N, +36801,N,N,N,41042,N,N,N,N,N,N,N,N,N,N,N,N,N,39376,N,N,N,N,N,36803,36804,N,N,N, +N,N,N,N,N,N,38308,N,N,N,N,N,36806,N,40544,N,N,N,N,N,N,N,63960,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,38309,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40115,N,N,N,N,N, +N,N,N,N,39377,65265,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,39378,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +40130,N,N,N,39379,N,N,N,N,N,38311,N,N,N,N,N,N,38313,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,38310,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40029,N,N,N,N,N,N,N,N,39138,N,N, +N,N,N,N,36809,N,41154,36810,N,N,N,N,N,N,39380,N,N,41145,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,39768,N,36813,N,41172,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36814,N,N, +N,N,35813,N,N,N,N,35193,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,36816,38326,N,N,N,N,N,N,N,N,N,N,N,N,39382,N,38373,N,N,N,N,N,N,N,N,N, +N,N,N,39383,N,N,N,N,38325,N,N,N,N,N,N,N,N,N,N,N,41162,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40957,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,41048,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36822,N,N,N,39384,N,N,N,N,N,N,N, +36819,N,N,N,N,N,N,N,N,N,N,N,N,36837,N,N,N,N,N,36841,N,N,N,N,39385,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36087,N,N,N,N,N,N,N,N,N,N,N,N,N,37500,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,40005,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36072,36830,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,36831,N,N,N,N,N,N,N,N,N,N,N,N,N,41035,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,36834,N,N,N,41164,N,N,N,N,N,N,N,N,36835,36836,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,39876,N,N,N,39932,N,N,N,N,N,N,38476,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,39670,N,36014,N,N,N,N,N,N,N,N,N,N,N,N,36839,N,N,N,N, +N,N,N,N,N,N,36840,N,N,N,N,35815,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,35194,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,35195,39386,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,36845,N,N,N,38336,N,N,N,N,N,N,N,N,N,N,N,N,N,41163,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40520,N,N,N,N,N,N,39387,N,36851, +N,N,N,N,36857,N,N,N,N,N,N,N,N,N,N,N,N,N,38337,N,41038,N,N,N,N,N,N,39388,N,N,N, +N,41060,36855,N,N,N,N,N,N,N,35248,41032,N,N,N,N,36859,36854,N,N,N,N,N,40412,N, +N,N,39389,35816,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37569,N,N,N,N,N,N,N,40918,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41170,N,N,36928, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35524,N,N,39392,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,40944,40947,N,N,N,N,N,N,N,N,N,N,N,N,40383,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,40950,N,38344,N,N,40538,N,N,N,N,N,N,N,N,N,N,N,N, +39395,N,N,N,N,N,N,N,N,N,N,N,35402,N,N,N,N,N,N,N,N,40945,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,35495,N,N,N,N,N,N,N,N,39398,N,N,N,40951,N,40941,N,N, +N,N,N,N,35420,N,40366,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,38345,N,N,N,N,N,36936,N,N,39400,N,N,N,N,N,36937,N,N,36026, +N,N,37041,N,N,N,N,N,N,36938,N,N,N,N,N,N,N,N,N,N,39402,N,N,N,N,N,N,N,N,N,N,N, +39889,N,N,N,N,N,N,N,39403,N,39404,N,N,N,N,N,N,N,N,39405,N,N,N,N,39406,36940,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36941,N,N,38347,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,38882,N,N,N,N,N,N,N,N,38348,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40824,N,N, +N,N,N,N,N,N,N,35196,35197,N,N,N,N,N,N,35198,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39261,N,N,N,N,N,N,N,N,N,N,N,N,39770,N,N, +N,N,36944,N,35919,N,N,N,N,N,N,N,N,N,N,N,36948,N,50902,39592,39407,65259,40355, 40353,39235,39237,N,40317,N,N,39408,N,N,N,N,N,N,N,N,39409,N,39410,N,N,36028, 40288,N,N,N,N,N,N,N,N,N,41123,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,36955,40667,N,N,N,N,N,N,N,N,N,40313,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, @@ -1259,82 +1275,76 @@ N,N,N,N,37063,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37604,40786,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,37083,N,N,N,N,N,41062,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -37074,N,N,N,N,37076,N,N,N,N,N,N,N,N,N,39515,38397,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,35780,N,N,N,35942,N,37086,N,N,N,N,N,40164,N,37089,N,N,N,N,N,N,N,N,N,N,N,N,N, -40518,N,N,N,38481,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64344,N,37094,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38480,N,N,N,37095,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,37096,39517,N,40826,N,N,N,39772,N,40828,N,N,64594,37097,N,37098,N,39518,N, -N,N,N,N,40822,N,N,N,N,N,N,N,N,N,37099,N,N,N,N,N,N,N,N,N,N,N,N,N,37100,N,N,N,N, -N,35822,N,N,N,N,N,N,N,37102,N,N,N,37318,N,N,37106,64700,35444,N,N,N,N,N,N,N,N, -N,38487,N,N,N,40175,N,N,N,N,N,N,N,N,N,N,40927,N,N,N,N,37111,37110,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,39774,N,N,N,37112,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,37113,N,36041,N,N,N,64106,N,N,N,N,N,N,N,N,35823,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40928,N,N,37186,N,39522,N,N,N,N,N,N,N,N,N, -38249,N,N,N,37188,37187,N,37185,N,N,N,35824,N,N,N,N,N,N,N,N,N,N,N,N,N,38496,N, -35825,N,39414,37193,N,N,N,N,37194,N,N,N,N,N,37195,N,N,N,N,39524,N,N,N,35519, -39526,N,N,N,N,N,N,N,N,N,N,39527,N,N,39529,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,39530,38482,37197,N,38502,N,N,N,N,40827,N,39531,N,N,N,N,N,N,N, -41068,N,N,38503,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39532,N,N,N,N,39533,35826,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,38506,N,N,N,N,N,N,N,N,64746,N,N,N,N,N,38508,N,N,N,N, -N,N,N,N,N,N,N,N,N,37316,N,N,N,38519,N,N,N,N,N,N,N,39412,39535,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,40875,N,N,N,N,N,36030,36545,N,N,N,N,38229,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,37202,37203,N,N,N,37205,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38237,N, -38513,N,N,N,N,40045,N,N,N,N,N,N,N,N,38515,N,N,N,N,N,N,N,N,N,N,N,37204,39537,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37206,N,N,N,38509,N,N,N,N, -N,N,38231,N,N,N,N,N,N,N,N,35270,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,35271,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,35434,N,N,N,35671,N,N,N,40929,N,N,39775,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41053,N,N,N,N,N,N,N,N,37211,N,37212,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,37214,N,N,N,N,N,N,N,N,N,N,40796,40791,N,N,N,N,N,N,40805, -N,N,N,N,N,39538,N,N,N,N,37216,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40798, -N,N,37217,N,N,N,N,N,N,37220,N,N,N,N,40769,N,N,N,N,N,N,37225,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,37224,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39540,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38578,N,39541,N,64933,N,N,N,N,N,N,N,40681, -N,35770,37229,41056,N,N,N,N,N,N,N,40926,N,N,N,N,N,40899,N,38581,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,41063,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,38579,N,N,N,N,N,N,N,N,N,N,N,N,N,39542,N,N,N,N,N,N,N,N,N,N,N,38357,N,N,N, -40650,N,N,N,39543,N,N,39544,N,N,N,N,N,N,N,N,N,N,37232,37231,N,N,N,N,N,N,N, -40867,N,37233,N,N,N,38577,N,N,N,N,40803,N,N,N,N,N,40807,N,N,N,35769,39546,N,N, -N,N,N,35670,N,N,N,N,N,N,N,N,39642,N,N,N,N,N,38576,N,N,N,N,39550,N,N,N,N,N,N,N, -N,N,N,40414,N,N,N,N,N,N,N,N,N,38573,N,N,N,38574,N,N,N,N,N,N,N,N,N,40609,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40528,N,N,N,N,N,N,N,N,38575,35828,40868,N,N, -N,N,N,N,N,N,N,38589,N,N,N,N,N,N,N,N,N,38644,N,N,N,N,N,N,N,N,N,N,38584,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,64161,N,N,N,N,37287,N,N,N,N,N,N,N,N,N,N,41054,N,N, -N,N,39549,N,N,N,N,35144,N,40625,N,N,N,N,N,N,N,N,N,N,N,N,N,40411,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,38335,35443,N,N,N,N,N,N,N,N,N,N,N,N,N,40702,N,37242,N,N,N,N, -37243,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39587,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -38594,N,N,N,N,N,40823,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39588,N,N,39589,N,N,N, -37281,N,N,N,N,35256,N,N,N,N,N,N,N,N,N,N,37235,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39590,35261,N,35257,N,37245,N,N, -N,N,N,N,N,N,N,38587,N,N,N,40946,N,N,35829,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39593,N,N, -N,N,N,40788,N,N,40931,40685,N,N,N,N,N,N,N,N,N,N,37290,N,N,N,N,37291,41072,N, -40813,N,N,N,N,N,37292,N,N,N,37293,N,N,N,41213,N,40930,N,37295,40513,39594,N,N, -37296,N,39595,N,N,N,N,N,N,N,N,N,N,N,39596,N,39498,N,37298,N,N,35830,N,39597, -35254,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39599,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,39600,N,N,N,N,N,N,39601,N,N,N,N,N,39585,37305,N,N,N,N,N,37306,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,37310,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41025,35767,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,37312,N,N,N,N,N,N,N,N,N,N,39603,37315,N,N,N,N,N,N, -N,N,N,N,41212,N,N,40942,N,N,N,N,N,N,40809,N,N,N,N,N,N,N,37320,N,N,N,N,N,N, -37321,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36326,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,37323,N,N,N,N,N,N,N,N,N,N,35272,N,N,N,N,N,36266,N,N,N,N,N,40925,34880, -34881,34882,34883,34884,N,34886,N,N,34889,34890,N,N,34893,N,34895,34896,34897, -34898,N,34900,34901,N,N,N,N,N,N,N,N,N,N,N,N,34914,N,34916,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,34979,N,34981,N,N,N,34985,34986,35907,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -35949,N,N,N,N,N,N,35956,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,36023,N,36025,N,36027,N,N,N,N,36032,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,36055,36056,N,36058,51321,N,N,N,N,51326,51361,N,51363,35832,51408, -N,N,N,N,51407,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,50916,N,50917,N,N,N,N,N,N,N,N,N,N,N,N,N, +37074,N,N,34667,N,37076,N,N,N,N,N,N,N,N,N,39515,38397,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,35780,N,N,N,35942,N,37086,N,N,N,N,N,40164,N,37089,N,N,N,N,N,N,N,N,N,N,N, +N,N,40518,N,N,N,38481,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64344,N,37094, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38480,N,N,N,37095,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,37096,39517,N,40826,N,N,N,39772,N,40828,N,N,64594,37097,N,37098,N, +39518,N,N,N,N,N,40822,N,N,N,N,N,N,N,N,N,37099,N,N,N,N,N,N,N,N,N,N,N,N,N,37100, +N,N,N,N,N,35822,N,N,N,N,N,N,N,37102,N,N,N,37318,N,N,37106,64700,35444,N,N,N,N, +N,N,N,N,N,38487,N,N,N,40175,N,N,N,N,N,N,N,N,N,N,40927,N,N,N,N,37111,37110,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39774,N,N,N,37112,N,N,N,N,N,N,N,N,N,N,36092,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,37113,N,36041,N,N,N,64106,N,N,N,N,N,N,N,N,35823,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40928,N,N,37186,N,39522,N,N,N,N,N, +N,N,N,N,38249,N,N,N,37188,37187,N,37185,N,N,N,35824,N,N,N,N,N,N,N,N,N,N,N,N,N, +38496,N,35825,N,39414,37193,N,N,N,N,37194,N,N,N,N,N,37195,N,N,N,N,39524,N,N,N, +35519,39526,N,N,N,N,N,N,N,N,N,N,39527,N,N,39529,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,39530,38482,37197,N,38502,N,N,N,N,40827,N,39531,N,N,N,N, +N,N,N,41068,N,N,38503,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39532,N,N,N,N,39533,35826, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38506,N,N,N,N,N,N,N,N,64746,N,N,N,N,N,38508,N, +N,N,N,N,N,N,N,N,N,N,N,N,37316,N,N,N,38519,N,N,N,N,N,N,N,39412,39535,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40875,N,N,N,N,N,36030,36545,N,N,N,N,38229,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,37202,37203,N,N,N,37205,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +38237,N,38513,N,N,N,N,40045,N,N,N,N,N,N,N,N,38515,N,N,N,N,N,N,N,N,N,N,N,37204, +39537,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37206,N,N,N,38509, +N,N,N,N,N,N,38231,N,N,N,N,N,N,N,N,35270,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35271,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,35434,N,N,N,35671,N,N,N,40929,N,N,39775,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41053,N,N,N,N,N,N,N,N,37211,N,37212,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37214,N,N,N,N,N,N,N,N,N,N,40796,40791,N,N,N,N,N, +N,40805,N,N,N,N,N,39538,N,N,N,N,37216,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,40798,N,N,37217,N,N,N,N,N,N,37220,N,N,N,N,40769,N,N,N,N,N,N,37225,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,37224,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +39540,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38578,N,39541,N,64933,N,N,N,N, +N,N,N,40681,N,35770,37229,41056,N,N,N,N,N,N,N,40926,N,N,N,N,N,40899,N,38581,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41063,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,38579,N,N,N,N,N,N,N,N,N,N,N,N,N,39542,N,N,N,N,N,N,N,N,N,N,N, +38357,N,N,N,40650,N,N,N,39543,N,N,39544,N,N,N,N,N,N,N,N,N,N,37232,37231,N,N,N, +N,N,N,N,40867,N,37233,N,N,N,38577,N,N,N,N,40803,N,N,N,N,N,40807,N,N,N,35769, +39546,N,N,N,N,N,35670,N,N,N,N,N,N,N,N,39642,N,N,N,N,N,38576,N,N,N,N,39550,N,N, +N,N,N,N,N,N,N,N,40414,N,N,N,N,N,N,N,N,N,38573,N,N,N,38574,N,N,N,N,N,N,N,N,N, +40609,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40528,N,N,N,N,N,N,N,N,38575, +35828,40868,N,N,N,N,N,N,N,N,N,38589,N,N,N,N,N,N,N,N,N,38644,N,N,N,N,N,N,N,N,N, +N,38584,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64161,N,N,N,N,37287,N,N,N,N,N,N,N, +N,N,N,41054,N,N,N,N,39549,N,N,N,N,35144,N,40625,N,N,N,N,N,N,N,N,N,N,N,N,N, +40411,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38335,35443,N,N,N,N,N,N,N,N,N,N,N,N,N,40702, +N,37242,N,N,N,N,37243,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39587,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,38594,N,N,N,N,N,40823,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39588,N, +N,39589,N,N,N,37281,N,N,N,N,35256,N,N,N,N,N,N,N,N,N,N,37235,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39590,35261,N, +35257,N,37245,N,N,N,N,N,N,N,N,N,38587,N,N,N,40946,N,N,35829,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,39593,N,N,N,N,N,40788,N,N,40931,40685,N,N,N,N,N,N,N,N,N,N,37290,N,N,N, +N,37291,41072,N,40813,N,N,N,N,N,37292,N,N,N,37293,N,N,N,41213,N,40930,N,37295, +40513,39594,N,N,37296,N,39595,N,N,N,N,N,N,N,N,N,N,N,39596,N,39498,N,37298,N,N, +35830,N,39597,35254,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39599, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,39600,N,N,N,N,N,N,39601,N,N,N,N,N,39585,37305,N,N, +N,N,N,37306,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37310,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +41025,35767,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37312,N,N,N,N,N,N,N,N,N,N,39603, +37315,N,N,N,N,N,N,N,N,N,N,41212,N,N,40942,N,N,N,N,N,N,40809,N,N,N,N,N,N,N, +37320,N,N,N,N,N,N,37321,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36326,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,37323,N,N,N,N,N,N,N,N,N,N,35272,N,N,N,N,N,36266,N,N,N,N, +N,40925,35907,35949,35956,36023,36025,36027,36032,36055,36056,36058,51361, +51363,36077,36168,35832,51408,N,N,N,N,51407,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,50916,N, +50917,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,51405,N, -51406,N,N,N,N,N,N,N,N,63998, +N,N,N,N,N,N,N,N,N,N,N,51405,N,51406,N,N,N,N,N,N,N,N,63998, }; static const struct unim_index big5hkscs_bmp_encmap[256] = { @@ -1343,65 +1353,66 @@ 0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0 },{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0, 0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{__big5hkscs_bmp_encmap+506,190, -193},{0,0,0},{0,0,0},{__big5hkscs_bmp_encmap+510,22,231},{0,0,0},{0,0,0},{ -__big5hkscs_bmp_encmap+720,96,125},{__big5hkscs_bmp_encmap+750,80,112},{0,0,0 -},{__big5hkscs_bmp_encmap+783,61,61},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{ -0,0,0},{__big5hkscs_bmp_encmap+784,128,227},{__big5hkscs_bmp_encmap+884,51,51 -},{__big5hkscs_bmp_encmap+885,5,254},{0,0,0},{__big5hkscs_bmp_encmap+1135,49, -49},{0,0,0},{__big5hkscs_bmp_encmap+1136,53,251},{__big5hkscs_bmp_encmap+1335, -6,254},{__big5hkscs_bmp_encmap+1584,9,245},{__big5hkscs_bmp_encmap+1821,1,251 -},{__big5hkscs_bmp_encmap+2072,15,250},{__big5hkscs_bmp_encmap+2308,8,254},{ -__big5hkscs_bmp_encmap+2555,1,251},{__big5hkscs_bmp_encmap+2806,14,244},{ -__big5hkscs_bmp_encmap+3037,13,239},{__big5hkscs_bmp_encmap+3264,19,253},{ -__big5hkscs_bmp_encmap+3499,6,255},{__big5hkscs_bmp_encmap+3749,0,250},{ -__big5hkscs_bmp_encmap+4000,4,250},{__big5hkscs_bmp_encmap+4247,3,249},{ -__big5hkscs_bmp_encmap+4494,17,252},{__big5hkscs_bmp_encmap+4730,43,242},{ -__big5hkscs_bmp_encmap+4930,1,244},{__big5hkscs_bmp_encmap+5174,3,233},{ -__big5hkscs_bmp_encmap+5405,6,245},{__big5hkscs_bmp_encmap+5645,19,244},{ -__big5hkscs_bmp_encmap+5871,0,250},{__big5hkscs_bmp_encmap+6122,6,231},{ -__big5hkscs_bmp_encmap+6348,15,255},{__big5hkscs_bmp_encmap+6589,16,192},{ -__big5hkscs_bmp_encmap+6766,4,237},{__big5hkscs_bmp_encmap+7000,9,156},{ -__big5hkscs_bmp_encmap+7148,4,248},{__big5hkscs_bmp_encmap+7393,3,253},{ -__big5hkscs_bmp_encmap+7644,3,252},{__big5hkscs_bmp_encmap+7894,1,254},{ -__big5hkscs_bmp_encmap+8148,2,249},{__big5hkscs_bmp_encmap+8396,1,254},{ -__big5hkscs_bmp_encmap+8650,19,239},{__big5hkscs_bmp_encmap+8871,2,251},{ -__big5hkscs_bmp_encmap+9121,5,253},{__big5hkscs_bmp_encmap+9370,0,254},{ -__big5hkscs_bmp_encmap+9625,3,251},{__big5hkscs_bmp_encmap+9874,2,249},{ -__big5hkscs_bmp_encmap+10122,2,254},{__big5hkscs_bmp_encmap+10375,13,255},{ -__big5hkscs_bmp_encmap+10618,5,245},{__big5hkscs_bmp_encmap+10859,16,245},{ -__big5hkscs_bmp_encmap+11089,9,252},{__big5hkscs_bmp_encmap+11333,12,223},{ -__big5hkscs_bmp_encmap+11545,35,253},{__big5hkscs_bmp_encmap+11764,7,226},{ -__big5hkscs_bmp_encmap+11984,44,229},{__big5hkscs_bmp_encmap+12170,24,254},{ -__big5hkscs_bmp_encmap+12401,7,234},{__big5hkscs_bmp_encmap+12629,10,255},{ -__big5hkscs_bmp_encmap+12875,24,241},{__big5hkscs_bmp_encmap+13093,2,254},{ -__big5hkscs_bmp_encmap+13346,0,202},{__big5hkscs_bmp_encmap+13549,0,250},{ -__big5hkscs_bmp_encmap+13800,3,246},{__big5hkscs_bmp_encmap+14044,5,250},{ -__big5hkscs_bmp_encmap+14290,28,255},{__big5hkscs_bmp_encmap+14518,2,254},{ -__big5hkscs_bmp_encmap+14771,2,250},{__big5hkscs_bmp_encmap+15020,4,248},{ -__big5hkscs_bmp_encmap+15265,3,254},{__big5hkscs_bmp_encmap+15517,5,246},{ -__big5hkscs_bmp_encmap+15759,0,226},{__big5hkscs_bmp_encmap+15986,2,251},{ -__big5hkscs_bmp_encmap+16236,2,248},{__big5hkscs_bmp_encmap+16483,5,220},{ -__big5hkscs_bmp_encmap+16699,2,217},{__big5hkscs_bmp_encmap+16915,12,254},{ -__big5hkscs_bmp_encmap+17158,8,245},{__big5hkscs_bmp_encmap+17396,6,244},{ -__big5hkscs_bmp_encmap+17635,6,254},{__big5hkscs_bmp_encmap+17884,11,252},{ -__big5hkscs_bmp_encmap+18126,18,252},{__big5hkscs_bmp_encmap+18361,37,254},{ -__big5hkscs_bmp_encmap+18579,7,223},{__big5hkscs_bmp_encmap+18796,6,250},{ -__big5hkscs_bmp_encmap+19041,2,246},{__big5hkscs_bmp_encmap+19286,3,246},{ -__big5hkscs_bmp_encmap+19530,24,255},{__big5hkscs_bmp_encmap+19762,11,237},{ -__big5hkscs_bmp_encmap+19989,5,248},{__big5hkscs_bmp_encmap+20233,3,252},{ -__big5hkscs_bmp_encmap+20483,2,239},{__big5hkscs_bmp_encmap+20721,112,245},{ -__big5hkscs_bmp_encmap+20855,4,255},{__big5hkscs_bmp_encmap+21107,0,231},{ -__big5hkscs_bmp_encmap+21339,28,234},{__big5hkscs_bmp_encmap+21546,12,226},{ -__big5hkscs_bmp_encmap+21761,81,247},{__big5hkscs_bmp_encmap+21928,3,212},{ -__big5hkscs_bmp_encmap+22138,1,242},{__big5hkscs_bmp_encmap+22380,25,249},{ -__big5hkscs_bmp_encmap+22605,8,196},{__big5hkscs_bmp_encmap+22794,81,254},{ -__big5hkscs_bmp_encmap+22968,8,253},{__big5hkscs_bmp_encmap+23214,3,244},{ -__big5hkscs_bmp_encmap+23456,1,246},{__big5hkscs_bmp_encmap+23702,45,244},{ -__big5hkscs_bmp_encmap+23902,29,244},{__big5hkscs_bmp_encmap+24118,3,245},{ -__big5hkscs_bmp_encmap+24361,20,245},{__big5hkscs_bmp_encmap+24587,14,245},{ -__big5hkscs_bmp_encmap+24819,12,255},{__big5hkscs_bmp_encmap+25063,2,255},{ -__big5hkscs_bmp_encmap+25317,2,124},{__big5hkscs_bmp_encmap+25440,2,252},{ -__big5hkscs_bmp_encmap+25691,10,254},{__big5hkscs_bmp_encmap+25936,2,165},{0, +193},{0,0,0},{0,0,0},{__big5hkscs_bmp_encmap+510,22,231},{0,0,0},{ +__big5hkscs_bmp_encmap+720,218,219},{__big5hkscs_bmp_encmap+722,96,125},{ +__big5hkscs_bmp_encmap+752,80,112},{0,0,0},{__big5hkscs_bmp_encmap+785,61,61}, +{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{__big5hkscs_bmp_encmap+786, +128,227},{__big5hkscs_bmp_encmap+886,51,51},{__big5hkscs_bmp_encmap+887,5,254 +},{__big5hkscs_bmp_encmap+1137,192,207},{__big5hkscs_bmp_encmap+1153,49,49},{ +0,0,0},{__big5hkscs_bmp_encmap+1154,53,251},{__big5hkscs_bmp_encmap+1353,6,254 +},{__big5hkscs_bmp_encmap+1602,9,245},{__big5hkscs_bmp_encmap+1839,1,251},{ +__big5hkscs_bmp_encmap+2090,15,250},{__big5hkscs_bmp_encmap+2326,8,254},{ +__big5hkscs_bmp_encmap+2573,1,251},{__big5hkscs_bmp_encmap+2824,14,244},{ +__big5hkscs_bmp_encmap+3055,13,239},{__big5hkscs_bmp_encmap+3282,18,253},{ +__big5hkscs_bmp_encmap+3518,6,255},{__big5hkscs_bmp_encmap+3768,0,250},{ +__big5hkscs_bmp_encmap+4019,4,250},{__big5hkscs_bmp_encmap+4266,2,249},{ +__big5hkscs_bmp_encmap+4514,17,252},{__big5hkscs_bmp_encmap+4750,43,242},{ +__big5hkscs_bmp_encmap+4950,1,244},{__big5hkscs_bmp_encmap+5194,3,234},{ +__big5hkscs_bmp_encmap+5426,3,247},{__big5hkscs_bmp_encmap+5671,19,244},{ +__big5hkscs_bmp_encmap+5897,0,250},{__big5hkscs_bmp_encmap+6148,6,231},{ +__big5hkscs_bmp_encmap+6374,15,255},{__big5hkscs_bmp_encmap+6615,16,192},{ +__big5hkscs_bmp_encmap+6792,4,237},{__big5hkscs_bmp_encmap+7026,7,156},{ +__big5hkscs_bmp_encmap+7176,4,248},{__big5hkscs_bmp_encmap+7421,3,253},{ +__big5hkscs_bmp_encmap+7672,3,252},{__big5hkscs_bmp_encmap+7922,1,254},{ +__big5hkscs_bmp_encmap+8176,2,249},{__big5hkscs_bmp_encmap+8424,1,254},{ +__big5hkscs_bmp_encmap+8678,19,239},{__big5hkscs_bmp_encmap+8899,2,251},{ +__big5hkscs_bmp_encmap+9149,5,253},{__big5hkscs_bmp_encmap+9398,0,254},{ +__big5hkscs_bmp_encmap+9653,3,251},{__big5hkscs_bmp_encmap+9902,2,249},{ +__big5hkscs_bmp_encmap+10150,2,254},{__big5hkscs_bmp_encmap+10403,13,255},{ +__big5hkscs_bmp_encmap+10646,5,252},{__big5hkscs_bmp_encmap+10894,16,245},{ +__big5hkscs_bmp_encmap+11124,9,252},{__big5hkscs_bmp_encmap+11368,12,223},{ +__big5hkscs_bmp_encmap+11580,35,253},{__big5hkscs_bmp_encmap+11799,7,226},{ +__big5hkscs_bmp_encmap+12019,44,229},{__big5hkscs_bmp_encmap+12205,24,254},{ +__big5hkscs_bmp_encmap+12436,7,234},{__big5hkscs_bmp_encmap+12664,10,255},{ +__big5hkscs_bmp_encmap+12910,24,241},{__big5hkscs_bmp_encmap+13128,2,254},{ +__big5hkscs_bmp_encmap+13381,0,202},{__big5hkscs_bmp_encmap+13584,0,250},{ +__big5hkscs_bmp_encmap+13835,3,246},{__big5hkscs_bmp_encmap+14079,5,250},{ +__big5hkscs_bmp_encmap+14325,28,255},{__big5hkscs_bmp_encmap+14553,2,254},{ +__big5hkscs_bmp_encmap+14806,2,250},{__big5hkscs_bmp_encmap+15055,4,248},{ +__big5hkscs_bmp_encmap+15300,3,254},{__big5hkscs_bmp_encmap+15552,5,246},{ +__big5hkscs_bmp_encmap+15794,0,226},{__big5hkscs_bmp_encmap+16021,2,251},{ +__big5hkscs_bmp_encmap+16271,2,248},{__big5hkscs_bmp_encmap+16518,5,220},{ +__big5hkscs_bmp_encmap+16734,2,217},{__big5hkscs_bmp_encmap+16950,12,254},{ +__big5hkscs_bmp_encmap+17193,8,245},{__big5hkscs_bmp_encmap+17431,6,244},{ +__big5hkscs_bmp_encmap+17670,6,254},{__big5hkscs_bmp_encmap+17919,11,252},{ +__big5hkscs_bmp_encmap+18161,18,252},{__big5hkscs_bmp_encmap+18396,37,254},{ +__big5hkscs_bmp_encmap+18614,7,223},{__big5hkscs_bmp_encmap+18831,6,250},{ +__big5hkscs_bmp_encmap+19076,2,246},{__big5hkscs_bmp_encmap+19321,3,246},{ +__big5hkscs_bmp_encmap+19565,24,255},{__big5hkscs_bmp_encmap+19797,11,237},{ +__big5hkscs_bmp_encmap+20024,5,248},{__big5hkscs_bmp_encmap+20268,3,252},{ +__big5hkscs_bmp_encmap+20518,2,239},{__big5hkscs_bmp_encmap+20756,112,245},{ +__big5hkscs_bmp_encmap+20890,4,255},{__big5hkscs_bmp_encmap+21142,0,231},{ +__big5hkscs_bmp_encmap+21374,28,249},{__big5hkscs_bmp_encmap+21596,12,226},{ +__big5hkscs_bmp_encmap+21811,81,247},{__big5hkscs_bmp_encmap+21978,3,212},{ +__big5hkscs_bmp_encmap+22188,1,242},{__big5hkscs_bmp_encmap+22430,25,249},{ +__big5hkscs_bmp_encmap+22655,8,196},{__big5hkscs_bmp_encmap+22844,81,254},{ +__big5hkscs_bmp_encmap+23018,8,253},{__big5hkscs_bmp_encmap+23264,3,244},{ +__big5hkscs_bmp_encmap+23506,1,246},{__big5hkscs_bmp_encmap+23752,45,244},{ +__big5hkscs_bmp_encmap+23952,29,244},{__big5hkscs_bmp_encmap+24168,3,245},{ +__big5hkscs_bmp_encmap+24411,20,245},{__big5hkscs_bmp_encmap+24637,14,245},{ +__big5hkscs_bmp_encmap+24869,12,255},{__big5hkscs_bmp_encmap+25113,2,255},{ +__big5hkscs_bmp_encmap+25367,2,124},{__big5hkscs_bmp_encmap+25490,2,252},{ +__big5hkscs_bmp_encmap+25741,10,254},{__big5hkscs_bmp_encmap+25986,2,179},{0, 0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{ 0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0 },{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0, @@ -1410,13 +1421,12 @@ },{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0, 0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{ 0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0 -},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{__big5hkscs_bmp_encmap+26100,3,75}, -{0,0,0},{__big5hkscs_bmp_encmap+26173,122,239},{0,0,0},{__big5hkscs_bmp_encmap -+26291,229,237},{0,0,0},{__big5hkscs_bmp_encmap+26300,7,7},{0,0,0},{0,0,0},{0, -0,0},{0,0,0},{0,0,0},{__big5hkscs_bmp_encmap+26301,2,237}, +},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0, +0,0},{0,0,0},{__big5hkscs_bmp_encmap+26164,7,7},{0,0,0},{0,0,0},{0,0,0},{0,0,0 +},{0,0,0},{__big5hkscs_bmp_encmap+26165,2,237}, }; -static const DBCHAR __big5hkscs_nonbmp_encmap[28325] = { +static const DBCHAR __big5hkscs_nonbmp_encmap[29306] = { 40049,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37749,N,N,N,N,N, N,N,37750,N,N,N,N,N,N,N,38216,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,36550,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35781,35834, @@ -1427,34 +1437,34 @@ N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,35501,N,37490,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -64583,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38111,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,40913,64459,N,N,N,N,N,N,N,37501,N,N,N,N,N,N,N, +N,N,N,N,N,N,36085,N,N,N,N,35501,N,37490,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,64583,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38111,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40913,64459,N,N,N,N,N,N,N,37501,N,N,N,N,N,N,N, 39076,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38119,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37067,37499,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38104,N,N,N,N,64607,N,64084,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39605,N,N,N,N,N,N,N,38618,37497,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64116, -37493,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36347,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35401,N,N,N,37599,39804,64099,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,64096,37485,64098,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,39606,N,N,N,N,N,N,38763,N,N,N,N,N,N,N,N,N,N,N,N,N, -64874,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64852,N,37491,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38872,N,N,N,N,N, -N,40891,37698,37494,N,N,N,N,N,N,N,N,N,N,64101,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,37484,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,64110,N,N,N,N,N,N,40672,N,N,37568,37567,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,37566,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39610,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35507,N,38773,64064,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64118,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,64464,N,N,N,N,N,N,N,N,N,N,N,N,N,64123,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,65133,N,N,N,N,N,N,39859,N,N,N,N,N,35276,N,N,N,N,39614,N,N,N,N,N,N, -N,N,N,64066,37564,N,N,N,N,N,N,N,N,N,N,37980,39861,N,N,N,39615,N,N,N,39079, +36089,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38119, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37067,37499,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38104,N,N,N,N,64607,N, +64084,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39605,N,N,N,N,N,N,N,38618, +37497,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +64116,37493,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36347,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35401,N,N,N,37599,39804,64099,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,64096,37485,64098,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39606,N,N,N,N,N,N,38763,N,N,N,N,N,N,N,N,N,N,N,N, +N,64874,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64852,N,37491,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38872,N,N,N,N, +N,N,40891,37698,37494,N,N,N,N,N,N,N,N,N,N,64101,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37484,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,64110,N,N,N,N,N,N,40672,N,N,37568,37567,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,37566,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39610,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35507,N,38773,64064,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64118,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,64464,N,N,N,N,N,N,N,N,N,N,N,N,N,64123,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,65133,N,N,N,N,N,N,39859,N,N,N,N,N,35276,N,N,N,N,39614,N,N,N,N,N, +N,N,N,N,64066,37564,N,N,N,N,N,N,N,N,N,N,37980,39861,N,N,N,39615,N,N,N,39079, 38820,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37117,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64635,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39616,37571,N,N,N,N,N,N,N,N,N,N,N,N,N, @@ -1473,38 +1483,38 @@ N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35250,40038,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36947,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,35938,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,38849,N,N,N,N,N,N,N,N,N,N,N,N,N,39620,N,N,N,N,N,N,N,N,N,N,39621,36591,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -38849,N,N,N,N,N,N,N,N,N,N,N,N,N,39620,N,N,N,N,N,N,N,N,N,N,39621,36591,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,64233,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37474, -35575,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39622,N,N,N,N,N,N,37601,N,N,N, -N,39625,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64198,N,N,N,N,N,N,N,N, -38821,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39627,N,N,N,64114,35422,N,38112,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,37580,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35557,N, -N,N,N,N,65116,39628,N,N,N,N,N,40441,35395,35494,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -39629,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39630,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,64238,39884,N,N,N,39631,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39633,N,N,N,N,N,N,N, -N,40442,N,N,N,N,N,40316,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39635, -N,N,38822,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39263,N,N,N,64502,40901, -35417,35691,N,N,N,N,N,N,39636,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39637,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,38818,35396,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40778,N, -N,N,N,N,N,N,N,37025,64932,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35428,35570, -35576,40408,N,N,38102,64254,64423,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,39638,N,40781,N,N,64246,N,N,N,N,N,N,N,35415,N,35651,35652, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35510,N,N,N,N,N,35520,N,N,N,N,N,N, -N,N,N,N,40532,N,N,N,N,N,N,N,N,N,N,39639,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,39640,39644,N,N,N,N,35530,40616,N,N,37475,39645,35685,35695,35710,N,N,N,N, -36675,N,N,N,N,N,N,37584,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35572,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40382,N,N,N,N,N,39649,N,64734,40445,35686,35696, -35701,35556,35748,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35565,N,N,N,N,N,N,N,N,N, -35421,N,35656,N,N,N,N,40429,N,N,N,N,40512,N,N,N,N,N,N,N,35567,35574,40566,N,N, -N,N,N,N,N,N,N,40675,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,39646,36350,N,N,N,N,64252,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,40113,40567,35684,35687,38731,N,N,N,N,N,N,N,N,38483,N,N,N,N,N,N,39648, +N,N,N,N,N,N,N,N,N,N,64233,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36160,N,N,N,N,N,N,N,N, +37474,35575,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39622,N,N,N,N,N,N,37601, +N,N,N,N,39625,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64198,N,N,N,N,N,N,N, +N,38821,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39627,N,N,N,64114,35422,N,38112,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,37580,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35557, +N,N,N,N,N,65116,39628,N,N,N,N,N,40441,35395,35494,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,39629,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39630,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,64238,39884,N,N,N,39631,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39633,N,N,N,N,N,N, +N,N,40442,N,N,N,N,N,40316,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +39635,N,N,38822,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39263,N,N,N,64502, +40901,35417,35691,N,N,N,N,N,N,39636,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39637,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,38818,35396,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +40778,N,N,N,N,N,N,N,N,37025,64932,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35428, +35570,35576,40408,N,N,38102,64254,64423,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,39638,N,40781,N,N,64246,N,N,N,N,N,N,N,35415,N,35651, +35652,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35510,N,N,N,N,N,35520,N,N,N, +N,N,N,N,N,N,N,40532,N,N,N,N,N,N,N,N,N,N,39639,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,39640,39644,N,N,N,N,35530,40616,N,N,37475,39645,35685,35695,35710,N, +N,N,N,36675,N,N,N,N,N,N,37584,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35572,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40382,N,N,N,N,N,39649,N,64734,40445,35686, +35696,35701,35556,35748,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35565,N,N,N,N,N,N,N,N, +N,35421,N,35656,N,N,N,N,40429,N,N,N,N,40512,N,N,N,N,N,N,N,35567,35574,40566,N, +N,N,N,N,N,N,N,N,40675,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,39646,36350,N,N,N,N,64252,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,40113,40567,35684,35687,38731,N,N,N,N,N,N,N,N,38483,N,N,N,N,N,N,39648, 35658,N,35569,35543,N,N,N,N,N,N,N,N,N,41131,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, 35509,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35423,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35566,N,N,39647,N, @@ -1574,151 +1584,152 @@ N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64076,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37623,39744,N,N,N,N,N,N,64462,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,39745,N,N,N,N,N,65197,64469,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,39745,N,N,N,N,N,65197,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,34657,64469,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35778,39548,39746,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39747,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35778,39548,39746,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,40569,N,N,64473,N,N,N,N,N,N,39748,41127,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39747,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40569,N,N,64473,N,N, +N,N,N,N,39748,41127,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,34670,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39923,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35961,N,N,N,37726,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,35275,N,N,N,N,N,N,40787,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,37847,N,N,N,N,N,N,N,N,N,N,N,N,N,64481,65232,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,64482,N,N,N,N,N,64739,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,39923,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,35961,N,N,N,37726,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35275,N,N,N,N, +N,N,40787,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37847,N,N,N,N,N,N, +N,N,N,N,N,N,N,64481,65232,N,N,N,N,N,N,36081,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,64482,N,N,N,N,N,64739,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36980,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,64486,N,N,N,39863,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,39749,N,N,N,N,N,N,N,N,N,N,N,N,39751,40784,N,N,N,N,N,39752, +N,N,N,N,N,N,N,N,N,N,36980,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +64486,N,N,N,39863,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,39749,N,N,N,N,N,N,N,N,N,N,N,N,39751,40784,N,N,N,N,N,39752,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64603, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,64603,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39081,N,N,40189,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,39081,N,N,40189,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,34892,39755,N,N,N,64492,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,35945,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -39848,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,35541,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64115,64857,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -37282,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64493,N,N,N,N,N,N,40105,N, +N,N,N,N,N,N,N,N,N,N,N,N,34892,39755,N,N,N,64492,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -35496,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39875, -35553,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +35945,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39848,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +35541,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64115,64857,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37282,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64493,N,N,N,N,N,N,40105,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35496,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36162,N,39875,35553,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,39758,38352,N,N,N,36959,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39758,38352,N, +N,N,36959,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,38894,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64590,N,N,N,N,N,N, -39759,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -39760,40646,N,N,N,N,N,N,N,N,N,N,N,64592,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,64883,N,N,N,N,N,64935,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,40354,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64088,64094,N, -N,N,N,N,N,N,41049,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64117,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64446,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,40098,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,37744,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37745,37751,65263,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,37741,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64605,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,37048,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,35580,N,64321,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40555,38115,36578,35965,N,36567, -N,N,N,N,N,N,40013,N,N,N,38563,N,N,N,N,N,N,N,N,N,N,39761,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35523,N,N,N,N,N,N,N,N,N,N,N, -38570,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,64616,35693,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,64871,35561,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64673,37740,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,39762,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65136,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,64680,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64745,40116,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,35562,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -39763,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39765,N,N,N,38571,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64679,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -39766,35516,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35531,N,N,N,N, -N,39767,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35277,N,39769,39771,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,37797,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,39773,N,N,N,40527,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,37795,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35451,N,N,N,35650, -38736,36787,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35408,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,39776,N,N,N,N,35653,N,N,N,35654,N,N,N,N,N,N,N,N,N,N,N,N,40446,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39778,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37755,N,N,N,N,N,37809,N,N,N,N,N,N,N,35424,N,N, -N,N,N,N,N,N,35544,N,N,N,N,39779,N,N,N,N,N,N,N,N,N,N,35433,N,N,N,35399,N,N, -35532,37756,39781,N,N,N,N,N,N,N,N,N,39782,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35442,N,N,N,N,N, -N,N,35450,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37807,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35504,N,N,N,N, -N,N,N,39784,N,N,N,N,N,N,N,N,N,N,40611,N,N,64236,35703,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,39783,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35673,64689,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64699,N,N,N,N,N, -N,N,N,N,N,N,39785,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37800,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,35552,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,40529,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36703,39786,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,39787,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38892,39788,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65102,N,N,N,N,N,N,64962,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,39789,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -37223,64716,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37814,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37092,N,N,N,N,37093,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40690,37834,N,N,N,N,N,N,N,N, +38894,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64590,N,N,N,N,N,N,39759,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39760,40646,N,N,N,N,N, +N,N,N,N,N,N,64592,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64883,N,N, +N,N,N,64935,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40354, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,35772,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64088,64094,N,N,N,N,N,N,N,41049,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64117,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64446,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -36678,N,N,N,N,37839,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,64731,64732,N,N,N,N,N,N,N,N,N,N,N,N,N,37824,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,64742,38631,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64728,64729,64934,37838,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,38385,N,N,N,N,N,N,N,N,N,40169,N,64740,38063,64119, -37836,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,36954,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,35924,N,N,N,N,N,N,N,37823,64337,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,37817,65239,37815,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37849,N,N,N,N,N,N,N,N,N,N,N,N,N,37819, -37850,39075,N,N,N,N,N,N,N,N,N,37073,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -39790,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64112,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39915,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,39791,N,N,N,N,N,N,N,64764,N,N,N,N,N,N,N,N,N,N,N,N,N,35648,41083,N,N,N, -36001,38903,N,N,N,37858,64726,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -38233,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37798,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,64832,N,N,37727,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38898,40054,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,36600,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,36679,N,N,N,N,N,N,N,N,N,N,N,N,39796,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37556, -N,N,N,37357,N,N,38610,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64838,36687,38217,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39797,64092,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39801,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,64843,N,N,N,38611,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,64856,N,N,N,N,N,37983,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,41205,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,37443,N,N,N,N,N,N,38906,N,N,N,N,N,N,N,N,N,N,N,N, +40098,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37744, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,37745,37751,65263,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +37741,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64605,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,37048,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35580,N, +64321,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40555,38115,36578,35965,N,36567,N,N,N,N,N,N, +40013,N,N,N,38563,N,N,N,N,N,N,N,N,N,N,39761,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35523,N,N,N,N,N,N,N,N,N,N,N,38570,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36066,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,64616,35693,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +64871,35561,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64673,37740,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,39762,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65136,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,64680,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64745,40116,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,35562,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39763,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39765,N,N,N,38571,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,64679,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39766,35516,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35531,N,N,N,N,N,39767,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,35277,N,39769,39771,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,37797,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39773,N,N, +N,40527,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,37795,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35451,N,N,N,35650,38736,36787,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35408,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +39776,N,N,N,N,35653,N,N,N,35654,N,N,N,N,N,N,N,N,N,N,N,N,40446,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39778,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,37755,N,N,N,N,N,37809,N,N,N,N,N,N,N,35424,N,N,N,N,N,N,N, +N,35544,N,N,N,N,39779,N,N,N,N,N,N,N,N,N,N,35433,N,N,N,35399,N,N,35532,37756, +39781,N,N,N,N,N,N,N,N,N,39782,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35442,N,N,N,N,N,N,N,35450,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37807,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35504,N,N,N,N,N,N,N,39784, +N,N,N,N,N,N,N,N,N,N,40611,N,N,64236,35703,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +39783,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35673,64689,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64699,N,N,N,N,N,N,N,N,N,N,N, +39785,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37800,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +35552,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,40529,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36703,39786,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,39787,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38892,39788,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,65102,N,N,N,N,N,N,64962,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,39789,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37223, +64716,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37814,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37092,N,N,N,N,37093,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40690,37834,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,35772,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36678,N,N, +N,N,37839,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +64731,64732,N,N,N,N,N,N,N,N,N,N,N,N,N,37824,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,64742,38631,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64728,64729,64934,37838,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,38385,N,N,N,N,N,N,N,N,N,40169,N,64740,38063,64119,37836,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36065,N,N,N,N,N, +N,N,N,N,N,N,36954,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +35924,N,N,N,N,N,N,N,37823,64337,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,37817,65239,37815,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37849,N,N,N,N,N,N,N,N,N,N,N,N,N,37819,37850, +39075,N,N,N,N,N,N,N,N,N,37073,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39790,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64112,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39915,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +39791,N,N,N,N,N,N,N,64764,N,N,N,N,N,N,N,N,N,N,N,N,N,35648,41083,N,N,N,36001, +38903,N,N,N,37858,64726,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38233,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37798,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,64832,N,N,37727,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,38898,40054,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,36600,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +36075,N,N,N,N,N,N,N,N,36679,N,N,N,N,N,N,N,N,N,N,N,N,39796,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37556,N, +N,N,37357,N,N,38610,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64838,36687,38217,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39797,64092,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,34641,N,N,39801,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64843,N,N,N,38611,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,64856,N,N,N,N,N,37983,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,41205,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,37443,N,N,N,N,N,N,38906,N,N,N,N,N,N,N,N,N,N,N,N, 40409,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, 38900,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37453,64859,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,39802,N,N,N,N,N,N,N,N,N,40661,N,N,N,N,N,N,N,N,N,N,N,N,64174,N,40137,N,N,N, @@ -1729,418 +1740,442 @@ N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37868,38902,38607,37854,35535,39842,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,64873,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37714,N,N,N,N,N,N, -N,N,N,N,N,39074,64878,36004,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64124,37882,36988,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36711,N,40375,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,41193,64078,64929,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40564,40895,40651,39865, -40404,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38841,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36593,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,38267,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,40658,38739,38564,36798,38105,36952,64889,64891,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36570,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36602,39845,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,40665,38868,37051,64956,64966,37448,N,N,N,N,N,N,N,37557,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40385, -37561,37542,36683,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39846,N,N,N,N,N,37558,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,36416,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,40664,37982,39007,38094,37450,64880,37991,N,N,N,N,N,N,N,N,N,N,N, -36332,N,N,N,N,N,N,N,N,39896,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37960,64193,40183,64958, -N,N,N,N,N,N,N,N,N,N,N,N,36826,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,64985,N,N,64638,N,N,N,N,N,N,N,N,37881,N,N,N,N,64067,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64235, -64195,38867,38393,40008,64984,41176,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64983,64330,39855,37963,64969,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36524,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64946,N,N,N,N,N,37466, -64701,37593,N,N,N,64981,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37597,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37465,38586,N,N,N,N,N,N,N,N,N,N,37467,N,N,N,N,N, -N,N,N,N,39851,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,64986,64990,N,N,N,64979,N,N,N,N,N,N,N,N,N,35910,N,N,N,N,N,N,64982, -64988,64989,N,N,N,N,37118,N,N,65185,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,35757,N,N,40152,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,40557,64892,64353,N,N,N,N,N,N,38648,N,N,N,N,N,N,N,N, -38640,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64756,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,65120,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -38994,38479,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,37230,N,N,N,N,N,N,N,N,N,N,39021,N,N,39012,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37971,65004,64376,N,N,N,N,N,N, -N,N,N,N,N,38330,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39005,N,37625,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,39002,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65014,N, -N,N,N,N,N,N,37840,39010,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,39853,N,N,N,N,N,N,N,N,N,N,N,38735,39854,N,N,N,N,N,N,N,N,N,N,N, -N,37970,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39856,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,37330,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,38890,64363,37297,65011,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,37579,N,N,N,N,N,N,N,N,N,39857,N,N,N,N,N,64748,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39019,N,N,N,38737,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -39025,38383,N,N,N,N,N,N,N,40691,N,N,N,N,N,37352,39866,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64332, -37482,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -65016,39009,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37351,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,37869,38724,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37345,N,N,64501,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,39017,N,N,N,N,35426,N,N,39867,36008,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40021,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36471,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35506, -40636,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37862,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,39074,36071,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64878, +36004,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64124,37882,36988,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,36711,N,40375,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41193, +64078,64929,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40564,40895,40651,39865,40404,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38841,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36593,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38267, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +40658,38739,38564,36798,38105,36952,64889,64891,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36570,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,36602,34658,N,N,N,N,N,N,N,N,N,N,39845,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,40665,38868,37051,64956,64966,37448,N,N,N,N,N,N,N, +37557,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,40385,37561,37542,36683,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39846,N,N,N,N,N,37558,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36416,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,40664,37982,39007,38094,37450,64880,37991,N,N,N,N,N,N,N, +N,N,N,N,36332,N,N,N,N,N,N,N,N,39896,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,34659,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37960,64193, +40183,64958,N,N,N,N,N,N,N,N,N,N,N,N,36826,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64985,N,N,64638,N,N,N,N,N,N,N,N,37881,N,N, +N,N,64067,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,64235,64195,38867,38393,40008,64984,41176,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64983,64330,39855,37963,64969, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36524,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64946,N,N, +N,N,N,37466,64701,37593,N,N,N,64981,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37597,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37465,N,N,N,N,N,N,N,N,N,N,36080, +38586,N,N,N,N,N,N,N,N,N,N,37467,N,N,N,N,N,N,N,N,N,39851,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64986,64990,N,N,N,64979,N, +N,N,N,N,N,N,N,N,35910,N,N,N,N,N,N,64982,64988,64989,N,N,N,N,37118,N,N,65185,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35757,N,N,40152,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40557,64892, +64353,N,N,N,N,N,N,38648,N,N,N,N,N,N,N,N,38640,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,64756,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65120,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38994,38479,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37230,N,N,N, +N,N,N,N,N,N,N,39021,N,N,39012,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,37971,65004,64376,N,N,N,N,N,N,N,N,N,N,N,38330,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,39005,N,37625,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39002,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,34640,N,65014,N,N,N,N,N,N,N,37840,39010,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39853,N,N,N,N,N,N,N, +N,N,N,N,38735,39854,N,N,N,N,N,N,N,N,N,N,N,N,37970,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,39856,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37330,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38890,64363,37297,65011,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37579,N,N,N, +N,N,N,N,N,N,39857,N,N,N,N,N,64748,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,39019,N,N,N,38737,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39025,38383,N,N,N,N,N,N,N,40691,N,N,N,N, +N,37352,39866,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64332,37482,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65016,39009,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,37351,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37869,38724,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,37345,N,N,64501,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39017,N,N,N,N, +35426,N,N,39867,36008,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +40021,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,36471,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35506,40636,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +37862,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37794,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +39869,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +38067,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37757,40550,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37977,N,N,N,N,N,N,N,N,N,39871,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,37976,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40613,39879,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,65108,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36468,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,35798,N,N,N,N,N,N,38070,64884,39104,38053,N,N,N,N,N,N,N, +39880,N,N,N,38381,64894,64491,N,N,N,N,N,N,N,N,N,N,64893,N,N,N,N,N,N,N,N,N, +38767,37985,N,40897,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38359,N,N,N, +64082,40024,N,N,N,N,N,N,N,N,N,40808,39911,64718,38632,64073,38817,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38221,40696,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,65097,37326,38769,N,N,N,N,36047,N,N,N,64945,N,N,64622,N,N,N,N,N, +40178,37816,36931,38745,38103,65126,38013,64623,N,N,N,N,37446,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,64109,N,N,36599,N,64439,N,38012,37581,38834,N,N,N,N,N,N,N,N,N, +65125,38526,38744,39799,37327,N,N,N,N,N,N,N,N,N,38052,N,N,N,N,N,N,N,N,N,N, +40109,N,N,N,N,N,N,N,N,N,35755,N,N,N,38613,64691,N,N,N,37806,N,38765,N,N,N,N,N, +N,37958,38391,N,N,N,N,N,N,N,N,40006,38235,37329,38132,N,65127,37541,N,N,N, +65247,36011,N,39881,N,N,N,N,N,N,N,N,N,N,N,64749,65018,64712,65122,37372,65131, +65017,64711,37198,40120,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38759,N,N,N, +38382,N,N,39858,N,N,N,N,37984,N,N,N,38050,39029,38828,37331,N,N,N,N,N,N,N,N,N, +N,N,39035,N,N,N,N,N,N,N,36587,38762,38494,N,N,N,N,N,N,N,N,N,38891,N,N,N,N,N, +40953,38392,65186,36838,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65150,N,N,N,N,N,N, +40356,38760,36588,38077,N,N,N,N,N,N,N,N,N,N,N,N,N,37979,40182,64167,39897,N,N, +N,N,N,N,N,N,N,64093,38486,38754,N,N,N,N,N,N,38074,41039,37592,N,N,N,39883,N,N, +N,N,N,N,38075,N,N,40287,N,N,N,N,N,N,37071,N,N,N,N,N,N,N,N,N,N,N,N,N,37989,N,N, +40780,N,N,N,N,N,N,37080,36187,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40638,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,64365,38346,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,40386,38904,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36860,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38003, +38004,N,N,N,N,N,N,N,N,N,N,N,N,65207,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,37794,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39869,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38067,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,37757,40550,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -37977,N,N,N,N,N,N,N,N,N,39871,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35403,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37976,N,N,N,N, +35413,35689,35548,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35702,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +39886,N,35432,41208,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,39135,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,65205,N,N,N,39887,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38651,N, +N,39931,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40654,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36581,N, +N,N,N,N,N,N,N,N,40571,39890,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,35493,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,65230,35397,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,40444,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65231,35749,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35914,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,35564,N,N,64736,38061,65237,38060,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -40613,39879,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65108,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +64602,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39894, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,35439,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35753,36447,N,N,40395,N, +64743,39895,N,N,N,N,N,N,N,N,N,N,N,37832,N,N,N,N,N,N,N,N,N,37360,36832,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39899,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37101,N,39900,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36179,41196,N,N,N, +39162,N,N,N,N,N,N,N,N,N,39904,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,37831,37449,38625,39906,N,N,N,39908,N,N,36833,39909,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38080,N,N,37827,N,N,N,N,N,N,N,N,N,N,37829,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +36985,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38779,N,N,N,N,N, +36990,N,N,N,N,65254,65094,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40376,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,37488,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38312,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,36016,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,38088,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39097,37184,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64702,N,N,N,N,N,N,N,37207,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35762,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64223,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,36468,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35798,N,N,N,N,N,N, -38070,64884,39104,38053,N,N,N,N,N,N,N,39880,N,N,N,38381,64894,64491,N,N,N,N,N, -N,N,N,N,N,64893,N,N,N,N,N,N,N,N,N,38767,37985,N,40897,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,38359,N,N,N,64082,40024,N,N,N,N,N,N,N,N,N,40808,39911,64718, -38632,64073,38817,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -38221,40696,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65097,37326,38769,N,N,N,N,36047,N, -N,N,64945,N,N,64622,N,N,N,N,N,40178,37816,36931,38745,38103,65126,38013,64623, -N,N,N,N,37446,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64109,N,N,36599,N,64439,N,38012, -37581,38834,N,N,N,N,N,N,N,N,N,65125,38526,38744,39799,37327,N,N,N,N,N,N,N,N,N, -38052,N,N,N,N,N,N,N,N,N,N,40109,N,N,N,N,N,N,N,N,N,35755,N,N,N,38613,64691,N,N, -N,37806,N,38765,N,N,N,N,N,N,37958,38391,N,N,N,N,N,N,N,N,40006,38235,37329, -38132,N,65127,37541,N,N,N,65247,36011,N,39881,N,N,N,N,N,N,N,N,N,N,N,64749, -65018,64712,65122,37372,65131,65017,64711,37198,40120,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,38759,N,N,N,38382,N,N,39858,N,N,N,N,37984,N,N,N,38050,39029, -38828,37331,N,N,N,N,N,N,N,N,N,N,N,39035,N,N,N,N,N,N,N,36587,38762,38494,N,N,N, -N,N,N,N,N,N,38891,N,N,N,N,N,40953,38392,65186,36838,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,65150,N,N,N,N,N,N,40356,38760,36588,38077,N,N,N,N,N,N,N,N,N,N,N,N,N, -37979,40182,64167,39897,N,N,N,N,N,N,N,N,N,64093,38486,38754,N,N,N,N,N,N,38074, -41039,37592,N,N,N,39883,N,N,N,N,N,N,38075,N,N,40287,N,N,N,N,N,N,37071,N,N,N,N, -N,N,N,N,N,N,N,N,N,37989,N,N,40780,N,N,N,N,N,N,37080,40638,N,N,N,N,N,N,N,N,N,N, +N,39910,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38467,36420,40015,65268, +N,N,N,N,N,39912,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37852,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +38511,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36426,39917,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37622,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +40377,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,64365,38346,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,36430,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,64463,34656,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40642, +N,N,N,N,N,N,38117,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39920,38116,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,38225,35771,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +39921,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,38128,36452,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38122,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36705,N,N,N,39780,36443,N,N,N,N, +39922,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40894,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40393,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36460,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36723,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,36015,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,36725,36465,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36448,36458,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,35916,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38226,38228, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35540,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +40379,38211,37630,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,38130,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38129,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41194,40402,41137,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37368, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,40386,38904,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,36860,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38003,38004,N,N, -N,N,N,N,N,N,N,N,N,N,65207,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37986,39844, +36525,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40621,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38608,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65262,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,35508,N,N,N,N,N,N,N,N,N,N,N,N,38743,35447,39927,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36533,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41069, +36534,38742,38208,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,41203,38078,N,N,N,39930,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64991,40380,N,N,N,N,N,N,N, +N,38142,N,N,N,N,N,N,N,N,35803,41214,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,36544,40775,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35806,41211,N,N,N,N, +36547,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38473,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,65218,N,N,38220,39933,N,N,N,N,N,N,N,N,N,N,N,N,N,37068, +40032,38219,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39934,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40048,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,40003,N,N,N,40007,36556,N,N,N,36436,N,N,N,N,N,N,N,N,N,N,36580, +40009,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35678,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38238,N,N,N,N,N,N,N, +N,N,N,N,N,38236,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40011,35809,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,36569,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40372,N, +37471,N,N,N,40012,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,35489,N,N,N,N,N,N,N,N,N,N,N,N,N,36571,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,40022,35490,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,38740,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40030,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40660,38248,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,41155,35558,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,41207,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +40033,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40031,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,64589,N,40539,N,N,N,N,N,N,N,N,40553,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +40035,65223,N,N,65222,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40039,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,40041,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +35810,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,37221,N,N,N,N,N,N,N,N,N,N,N,N,40167,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,35412,N,N,N,N,N,N,N,40044,40046,65117,N,N,N,N,N,40051,N, +N,N,N,N,N,N,N,N,N,N,N,N,38250,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38253,36592,36685,N, +N,N,N,36598,N,N,N,N,N,N,N,N,64188,N,36053,N,N,N,N,N,N,N,N,N,N,N,N,N,34654,N,N, +N,N,64474,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,35660,64885,39901,64245,N,N,N,N,N,N,N,40052,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,38213,N,N,N,N,N,N,N,N,N,N,N,N,38598,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,36714,36686,N,N,N,N,N,40056,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,64085,N,N,N,N,N,N,N,N,N,N,N,N,38884,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,40001,37468,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +38650,36086,N,N,N,N,36173,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64358,36453,38985, +64424,38978,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +40058,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38907,37066,N,N,N,N,40027,N,N,38733, +N,N,36563,N,N,N,N,N,N,N,N,N,N,N,N,N,38241,40779,40885,37842,64938,38976,37190, +39015,64090,64425,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,38977,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,36051,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,64765,64939,37309,36684,38601,36693,64430,38255,N,N, +N,N,N,N,40061,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,41200,N,N,N,N,N,N,N,N,N,N,N,N,N,37999,64940,N,N,N,N, +38603,38606,N,N,N,N,41046,N,40161,N,N,N,N,N,N,N,N,N,N,38596,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +36702,36716,36515,64435,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,64595,N,N,N,64947,N,N,N,N,36715,N,N,N,N,N,N,N,N,N,N, +N,N,38602,N,N,N,N,N,N,34643,N,N,N,N,N,N,N,N,N,N,N,N,N,36729,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,40559,41157,64632,36418,36698,37058,36517,36961,37455,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35403,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35413, -35689,35548,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35702,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37747,64949,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39886,N, -35432,41208,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,65228,N,64445,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36054, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38979,38597, +35260,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40099,N,N,N,N,N,N,37451,38986, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,39135,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,65205,N,N,N,39887,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38651,N,N,39931, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,40654,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36581,N,N,N,N,N, -N,N,N,N,40571,39890,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,35493,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,36772,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,41201,40699,40146,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,36775,N,N,N,N,34644,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64604,38981,N,N,36934,36049,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65274,38240,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,65230,35397,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,40444,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65231,35749,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,40776,37447,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37115,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35914,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,35564,N,N,64736,38061,65237,38060,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64602,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39894,N,N,N,N,N,N, +N,40100,38257,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -35439,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35753,36447,N,N,40395,N,64743,39895,N,N, -N,N,N,N,N,N,N,N,N,37832,N,N,N,N,N,N,N,N,N,37360,36832,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,39899,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,37101,N,39900,41196,N,N,N,39162,N,N,N,N,N,N,N,N,N,39904,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37831,37449,38625,39906,N, -N,N,39908,N,N,36833,39909,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -38080,N,N,37827,N,N,N,N,N,N,N,N,N,N,37829,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36985,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,38779,N,N,N,N,N,36990,N,N,N,N,65254,65094,N,N,N,N, +N,N,N,N,34629,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40102,N,N,N,N, +40103,N,N,N,N,N,40106,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,40659,N,N,N,40560,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40108,34642,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,40376,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37488,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36782,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,38312,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36016,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38088,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,39097,37184,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,64702,N,N,N,N,N,N,N,37207,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -35762,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64223,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,36176,38269,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40112,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39910,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,38467,36420,40015,65268,N,N,N,N,N,39912,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,37852,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +38838,N,41149,35551,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40618,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38511,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,36426,39917,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,36797,N,N,N,36799,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37737, +39847,51364,N,N,N,N,65258,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,39905,N,N,N,N,N,N,35649,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,40374,41195,39843,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,37622,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40377,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,35745,36808,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,35148,39008,N,N,N,N,N,N,N,N,N,N,38087,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,35672,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38315,38314,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36430,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64463,40642,N,N,N,N,N, -N,38117,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39920,38116,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,40131,40132,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,37846,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,40364,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35814,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35441,36817,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,38225,35771,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39921,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -38128,36452,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38122,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36705,N,N,N,39780,36443,N,N,N,N,39922,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40894,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40393,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36460,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36723,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,36015,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36725, -36465,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36448,36458,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,35916,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38226,38228,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,35540,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40379,38211, -37630,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -38130,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38129,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,41194,40402,41137,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37368,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37986,39844,36525,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40621,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38608,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,65262,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35508,N, -N,N,N,N,N,N,N,N,N,N,N,38743,35447,39927,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,36533,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41069,36534,38742, -38208,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,41203,38078,N,N,N,39930,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64991,40380,N,N,N,N,N,N,N,N,38142,N,N, -N,N,N,N,N,N,35803,41214,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36544, -40775,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35806,41211,N,N,N,N,36547,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38473,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,65218,N,N,38220,39933,N,N,N,N,N,N,N,N,N,N,N,N,N,37068,40032, -38219,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39934,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,40048,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,40003,N,N,N,40007,36556,N,N,N,36436,N,N,N,N,N,N,N,N,N,N,36580,40009,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35678,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38238,N,N,N,N,N,N,N,N,N,N,N,N, -38236,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40011,35809,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,36569,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40372,N,37471,N,N,N, -40012,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -35489,N,N,N,N,N,N,N,N,N,N,N,N,N,36571,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -40022,35490,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,38740,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40030,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,40660,38248,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -41155,35558,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,41207,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40033,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,40031,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,64589,N,40539,N,N,N,N,N,N,N,N,40553,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40035,65223,N, -N,65222,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40039,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,40041,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35810,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,37221,N,N,N,N,N,N,N,N,N,N,N,N,40167,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,35412,N,N,N,N,N,N,N,40044,40046,65117,N,N,N,N,N,40051,N,N,N,N,N,N,N,N, -N,N,N,N,N,38250,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38253,36592,36685,N,N,N,N,36598,N, -N,N,N,N,N,N,N,64188,N,36053,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64474,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35660, -64885,39901,64245,N,N,N,N,N,N,N,40052,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,38213,N,N,N,N,N,N,N,N,N,N,N,N,38598,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,36714,36686,N,N,N,N,N,40056,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -64085,N,N,N,N,N,N,N,N,N,N,N,N,38884,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40001,37468, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38650,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64358,36453,38985,64424,38978,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40058,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,38907,37066,N,N,N,N,40027,N,N,38733,N,N,36563,N,N,N,N,N,N,N,N,N, -N,N,N,N,38241,40779,40885,37842,64938,38976,37190,39015,64090,64425,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38977,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36051,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -64765,64939,37309,36684,38601,36693,64430,38255,N,N,N,N,N,N,40061,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,39381,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37108,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35491,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -41200,N,N,N,N,N,N,N,N,N,N,N,N,N,37999,64940,N,N,N,N,38603,38606,N,N,N,N,41046, -N,40161,N,N,N,N,N,N,N,N,N,N,38596,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36702,36716,36515,64435,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -64595,N,N,N,64947,N,N,N,N,36715,N,N,N,N,N,N,N,N,N,N,N,N,38602,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,36729,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40559,41157,64632, -36418,36698,37058,36517,36961,37455,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37747,64949,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65228,N,64445,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36054,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38979,38597,35260,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,40099,N,N,N,N,N,N,37451,38986,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36772,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41201, -40699,40146,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36775,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,64604,38981,N,N,36934,36049,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,65274,38240,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40776,37447,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,37115,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40100,38257,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,40102,N,N,N,N,40103,N,N,N,N,N,40106,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40659,N,N,N,40560,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,40108,36782,38269,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40112,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38838, -N,41149,35551,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,40618,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -36797,N,N,N,36799,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37737,39847, -51364,N,N,N,N,65258,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,39905,N,N,N,N,N,N,35649,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,40374,41195,39843,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -35745,36808,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,35148,39008,N,N,N,N,N,N,N,N,N,N,38087,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,35672,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,38315,38314,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,40131,40132,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,37846,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,40364,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35814,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35441,36817,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,39381,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37108,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35491,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40142,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,40148,40149,N,N,N,64456,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40371,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64624,N,N,N,N,N,36823,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39795,N,N,N,N,N,N,N,N,N,N,64091,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40142,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40148,40149,N,N,N,64456,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40371,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64624,N,N,N,N,N,36823,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39795,N,N,N,N,N,N,N,N,N,N,64091,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,36818,36964,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39094, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36818,36964,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39094, 38504,N,N,N,N,40150,N,N,N,N,N,N,N,N,N,N,N,N,39101,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36828,65270,36825,N,N,N,N,N,N,N,N,N,N,N,N,N, 38209,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38899,39928,40556,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36850,36846,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,40151,N,N,N,N,N,N,N,N,N,N,N,N,40558,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,35392,N,N,N,N,N,N,N,N,N,N,36847,N,N,N,N,N,N,N,N,36852,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36853,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38338,39018,N,38863,40572,36929,N,N,N, -N,N,N,40155,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37953,N,N,N,N,40166,40368, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40170,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40173,N,N,N,N,N,N,N,N,N,N,N,N,40186,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,35682,35406,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,40138,35430,N,N,N,N,N,N,N,N,N,N,40187,40188,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40190,N,N,N,N,N,N,N,N,N,N,N, -N,N,35411,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40165,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,40256,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,40257,N,N,N,N,N,N,N,N,N,N,N,N,36933,35699,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,38858,N,40258,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -35425,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,35758,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35538,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,35746,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40434,40259,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40159,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,40260,N,N,N,N,N,N,N,N,N,N,36554,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36942,N,N,N,N,N,N,N,36531,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,40949,N,N,N,N,N,N,N,N,N,N,N,N,40261,36943,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,34668,N,N,N,N,38899,39928,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -40263,N,N,N,35274,N,N,N,N,N,N,40117,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64510,36958,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36963,36951,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36966,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,39872,N,N,N,N,N,N,N,N,N,N,N,64741,37218,N,N,N,N,N,N,N,N,N,N,36967,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36769,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,36770,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,40264,64211,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36957,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,37049,N,N,N,N,N,N,N,N,N,N,N,N,N,36971,35932,N,N,N, -36969,65111,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,65109,36979,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39919,40176,N,N, -N,N,N,N,N,N,N,N,N,N,40267,N,N,N,N,N,N,N,N,N,N,N,N,N,65241,N,N,N,65242,N,N,N, -37344,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37336,N,N,N,N,N,N,N,N,N,N,38470,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37728,N,64083,40147,N,N, -N,N,N,N,N,N,N,N,N,N,40270,N,N,N,64320,N,N,N,36322,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,37954,N,36950,N,N,39013,N,35948,64074,N,N,40272, -40274,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38319,38746,37705,38727,41204,N,N,N,N,N, -N,38776,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36815,N,N,N,64608,N,N,N,N,N,N,N,N,35918,N, -N,N,64598,N,N,N,N,N,N,N,N,N,N,N,N,N,37340,38497,37612,37725,36574,38654,64847, -38366,N,N,N,N,N,N,N,N,N,N,N,N,N,39088,41024,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38845,38781,38901,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,39852,64218,37570,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38833,N,N,N,N,N,36987,N,N,N,N,37886,38011, -N,38775,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64190,64835,37062,37028,37032,38057,N, -37033,N,N,N,N,35941,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38368,36989,N,N,N,N,N,N, -37477,N,N,N,N,N,N,N,N,N,N,N,N,N,64954,37828,N,N,N,N,N,N,N,N,65261,40363,41187, -N,38472,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40275,N,N,N,N,N,35497,N, -39877,N,38493,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38751,38495,38510,64349,N,N, -N,N,N,40369,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,65187,N,N,N,N,N,N,N,N,N,40370,N,N,38318,64675,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41122,N,N,38485,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,40276,N,N,37697,N,38317,37333,N,N,N,N,N,N,N,N,N,N,N,N,38778,65020, -36423,37885,37029,37036,N,N,N,N,N,N,N,N,38316,N,N,N,N,N,N,N,N,N,37038,65189,N, -N,N,N,N,40278,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38883,38370,N,N,N,N,N,37990, -N,N,38471,N,N,N,N,37304,N,N,N,N,40172,N,N,N,N,N,N,N,N,37037,N,38371,N,N,N,N,N, +34650,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,34632,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,34634,40556,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36850,36846,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,40151,N,N,N,N,N,N,N,N,N,N,N,N,40558,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35392,N, +N,N,N,N,N,N,N,N,N,36847,N,N,N,N,N,N,N,N,36852,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36853,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,38338,39018,N,38863,40677,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40572, +36929,N,N,N,N,N,N,40155,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37953,N,N,N,N, +40166,40368,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,40170,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40173,N,N,N,N,N,N,N,N,N,N,N,N, +40186,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,35682,35406,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40138,35430,N,N,N,N,N,N,N,N,N,N,40187,40188,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40190,N,N,N,N,N, +N,N,N,N,N,N,N,N,35411,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40165,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40256,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40257,N,N,N,N,N,N,N,N,N,N,N,N,36933,35699, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38858,N,40258,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,35425,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,35758,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +35538,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,35746,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40434, +40259,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40159,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,40260,N,N,N,N,N,N,N,N,N,N,36554,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36942,N,N,N,N,N,N,N,36531,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,40949,N,N,N,N,N,N,N,N,N,N,N,N,40261,36943,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,40263,N,N,N,35274,N,N,N,N,N,N,40117,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64510, +36958,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36963,36951,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36966,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,39872,N,N,N,N,N,N,N,N,N,N,N,64741,37218,N,N,N,N,N,N,N,N,N,N,36967,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36769,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,36770,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,40264,64211,N,N,N,N,N,N,36175,N,N,N,N,N,N,N,N,N,36957,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37049,N,N,N,N,N,N,N,N,N,N,N,N,N,36971, +35932,N,N,N,36969,65111,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,65109,36979,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +39919,40176,N,N,N,N,N,N,N,N,N,N,N,N,40267,N,N,N,N,N,N,N,N,N,N,N,N,N,65241,N,N, +N,65242,N,N,N,37344,36163,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37336,N,N,N,N,N,N,N, +N,N,N,38470,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37728, +N,64083,40147,N,N,N,N,N,N,N,N,N,N,N,N,40270,N,N,N,64320,N,N,N,36322,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37954,N,36950,N,N,39013,N,35948, +64074,N,N,40272,40274,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38319,38746,37705,38727, +41204,N,N,N,N,N,N,38776,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36815,N,N,N,64608,N,N,N,N, +N,N,N,N,35918,N,N,N,64598,N,N,N,N,N,N,N,N,N,N,N,N,N,37340,38497,37612,37725, +36574,38654,64847,38366,N,N,N,N,N,N,N,N,N,N,N,N,N,39088,41024,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38845,38781,38901, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39852,64218,37570,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38833,N,N,N,N,N,36987,N, +N,N,N,37886,38011,N,38775,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64190,64835,37062, +37028,37032,38057,N,37033,N,N,N,N,35941,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +38368,36989,N,N,N,N,N,N,37477,N,N,N,N,N,N,N,N,N,N,N,N,N,64954,37828,N,N,N,N,N, +N,N,N,65261,40363,41187,N,38472,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +40275,N,N,N,N,N,35497,N,39877,N,38493,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +38751,38495,38510,64349,N,N,N,N,N,40369,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65187,N,N,N,N,N,N,N,N,N,40370,N,N,38318,64675,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,34665,N,N,N,N,N,N,N,N, +41122,N,N,38485,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40276,N,N,37697,N,38317,37333,N,N, +N,N,N,N,N,N,N,N,N,N,38778,65020,36423,37885,37029,37036,N,N,N,N,N,N,N,N,38316, +N,N,N,N,N,N,N,N,N,37038,65189,N,N,N,N,N,40278,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,38883,38370,N,N,N,N,N,37990,N,N,38471,N,N,N,N,37304,N,N,N,N,40172,N,N,N,N, +N,N,N,N,37037,N,38371,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35663, +N,N,35555,N,N,N,N,35661,38378,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35663,N,N,35555,N,N,N,N,35661,38378,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35662,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36033,35821,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37337,N,N,41124,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38389,38388, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,40883,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65199,N,N,N,N, -N,65138,37498,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,65196,N,N,N,N,N,N,N,N,N,N,N,N,N,38387,40280,37746,N,N,37317,N,N,N,N, -N,N,N,38466,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37069,38398, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +35662,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36033, +35821,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,37337,N,N,41124,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,38389,38388,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40883,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,65199,N,N,N,N,N,65138,37498,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,65196,N,N,N,N,N,N,N,N,N,N,N, +N,N,38387,40280,36166,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37746,N,N,37317,N,N,N,N,N,N, +N,38466,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37069,38398, 37209,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40037,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38860,37070,N,N,N,N,N,N,40281,64757,65277,N,N, 40283,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, @@ -2168,70 +2203,72 @@ N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,40129,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,40296,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -37799,N,N,N,N,N,N,38516,41199,N,37201,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38593,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,35940,38518,40297,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64676, -N,N,N,N,N,N,N,N,N,N,N,N,40298,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37454,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40299,N,N,N,N,N,39873, -40300,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -35429,37213,N,N,N,N,N,N,N,N,40301,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +37799,N,N,N,N,N,N,38516,N,N,N,N,N,N,N,N,36093,41199,N,37201,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38593,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,34679,N,35940,38518,40297,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,64676,N,N,N,N,N,N,N,N,N,N,N,N,40298,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +37454,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,40299,N,N,N,N,N,39873,40300,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,35429,37213,N,N,N,N,N,N,N,N,40301,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37210,35906,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37210,35906,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40128,37226,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,40302,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,40614,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +40397,N,N,40303,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,40128,37226,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -40302,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40614, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40397,N,N,40303,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35259,40697,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38580,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,37234,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,35259,40697,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,38580,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37234,N, +40648,N,N,N,34673,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35669,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40648,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,35669,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40305,40306,N,N,N,N, -N,N,N,N,N,N,N,N,40652,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,40305,40306,N,N,N,N,N,N,N,N,N,N,N,N,40652,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37236,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40656,36956,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,37236,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,40656,36956,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36562,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,37288,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,37239,N,N,N,N,N,N,N,N,N,N,N,38591,N,N,N,N,N,38592,N,N,N,N, -36785,N,N,N,N,N,38583,35925,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,37240,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35262,37244,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,64375,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,36562,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37288,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37239,N,N,N,N,N,N,N,N,N,N,N, +38591,N,N,N,N,N,38592,N,N,N,N,36785,N,N,N,N,N,38583,35925,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37240,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35262, +37244,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64375,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,37237,37283,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37238,N,N,N, -N,N,N,N,N,38590,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,37241,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,38582, -37284,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37286,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37237,37283,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,37238,N,N,N,N,N,N,N,N,38590,36169,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37241,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,38582,37284,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +37286,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40309,N,N,N,N,N,N,N,N,N,N,N,36946,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,41029,N,37289,N,39082,N,N,N,35935,N,N,35754,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40157,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40311,34646,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,40309,N,N,N,N,N,N,N,N,N,N,N,36946,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -41029,N,37289,N,39082,N,N,N,35935,N,N,35754,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40157,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,40311,35136,40684,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,37802,38008,N,N,N,N,40314,35529,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,35659,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40940,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,35554,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,35136,40684,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,37802,38008,N,N,N,N,40314,35529,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35659,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40940,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +35554,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,40565,39028,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,39624,N,N,N,N,41031,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35779,N,N,N,N,N,N,N,N,N, -N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64584,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -64631,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -N,N,40018,36605,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -36776,N,N,N,N,N,N,N,N,N,38266,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, -36848, +N,N,40565,39028,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,39624,N,N,N,N,41031, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,35779,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,64584,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,64631,N,N,N,N,N,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,40018,36605,N,N,N,N, +N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36776,N,N,N,N,N,N,N,N,N, +38266,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,36848, }; static const struct unim_index big5hkscs_nonbmp_encmap[256] = { @@ -2249,84 +2286,84 @@ 253},{__big5hkscs_nonbmp_encmap+4292,119,150},{__big5hkscs_nonbmp_encmap+4324, 10,254},{__big5hkscs_nonbmp_encmap+4569,13,252},{__big5hkscs_nonbmp_encmap+ 4809,32,250},{__big5hkscs_nonbmp_encmap+5028,3,243},{__big5hkscs_nonbmp_encmap -+5269,45,75},{__big5hkscs_nonbmp_encmap+5300,68,194},{ -__big5hkscs_nonbmp_encmap+5427,42,172},{__big5hkscs_nonbmp_encmap+5558,70,249 -},{__big5hkscs_nonbmp_encmap+5738,28,213},{__big5hkscs_nonbmp_encmap+5924,15, -232},{__big5hkscs_nonbmp_encmap+6142,69,252},{__big5hkscs_nonbmp_encmap+6326, -42,195},{__big5hkscs_nonbmp_encmap+6480,8,124},{__big5hkscs_nonbmp_encmap+6597 -,33,250},{__big5hkscs_nonbmp_encmap+6815,101,237},{__big5hkscs_nonbmp_encmap+ -6952,19,190},{__big5hkscs_nonbmp_encmap+7124,27,246},{ -__big5hkscs_nonbmp_encmap+7344,18,205},{__big5hkscs_nonbmp_encmap+7532,3,247}, -{__big5hkscs_nonbmp_encmap+7777,38,147},{__big5hkscs_nonbmp_encmap+7887,102, -232},{__big5hkscs_nonbmp_encmap+8018,14,206},{__big5hkscs_nonbmp_encmap+8211, -38,201},{__big5hkscs_nonbmp_encmap+8375,7,238},{__big5hkscs_nonbmp_encmap+8607 -,13,239},{__big5hkscs_nonbmp_encmap+8834,116,227},{__big5hkscs_nonbmp_encmap+ -8946,51,218},{__big5hkscs_nonbmp_encmap+9114,3,249},{__big5hkscs_nonbmp_encmap -+9361,15,225},{__big5hkscs_nonbmp_encmap+9572,0,254},{ -__big5hkscs_nonbmp_encmap+9827,0,229},{__big5hkscs_nonbmp_encmap+10057,25,243 -},{__big5hkscs_nonbmp_encmap+10276,0,238},{__big5hkscs_nonbmp_encmap+10515,3, -215},{__big5hkscs_nonbmp_encmap+10728,58,58},{__big5hkscs_nonbmp_encmap+10729, -194,194},{__big5hkscs_nonbmp_encmap+10730,167,250},{__big5hkscs_nonbmp_encmap+ -10814,90,90},{__big5hkscs_nonbmp_encmap+10815,99,255},{ -__big5hkscs_nonbmp_encmap+10972,64,248},{__big5hkscs_nonbmp_encmap+11157,17, -252},{__big5hkscs_nonbmp_encmap+11393,53,240},{__big5hkscs_nonbmp_encmap+11581 -,17,225},{__big5hkscs_nonbmp_encmap+11790,4,252},{__big5hkscs_nonbmp_encmap+ -12039,27,250},{__big5hkscs_nonbmp_encmap+12263,13,248},{ -__big5hkscs_nonbmp_encmap+12499,4,214},{__big5hkscs_nonbmp_encmap+12710,5,200 -},{__big5hkscs_nonbmp_encmap+12906,24,212},{__big5hkscs_nonbmp_encmap+13095,6, -224},{__big5hkscs_nonbmp_encmap+13314,18,255},{__big5hkscs_nonbmp_encmap+13552 -,0,251},{__big5hkscs_nonbmp_encmap+13804,14,233},{__big5hkscs_nonbmp_encmap+ -14024,110,245},{__big5hkscs_nonbmp_encmap+14160,9,217},{ -__big5hkscs_nonbmp_encmap+14369,6,235},{__big5hkscs_nonbmp_encmap+14599,59,167 -},{__big5hkscs_nonbmp_encmap+14708,14,194},{__big5hkscs_nonbmp_encmap+14889, -44,157},{__big5hkscs_nonbmp_encmap+15003,43,231},{__big5hkscs_nonbmp_encmap+ -15192,32,216},{__big5hkscs_nonbmp_encmap+15377,14,19},{ -__big5hkscs_nonbmp_encmap+15383,25,110},{__big5hkscs_nonbmp_encmap+15469,49, -224},{__big5hkscs_nonbmp_encmap+15645,5,246},{__big5hkscs_nonbmp_encmap+15887, -6,225},{__big5hkscs_nonbmp_encmap+16107,87,225},{__big5hkscs_nonbmp_encmap+ -16246,3,204},{__big5hkscs_nonbmp_encmap+16448,149,233},{ -__big5hkscs_nonbmp_encmap+16533,116,232},{__big5hkscs_nonbmp_encmap+16650,1, -254},{__big5hkscs_nonbmp_encmap+16904,32,67},{__big5hkscs_nonbmp_encmap+16940, -14,216},{__big5hkscs_nonbmp_encmap+17143,26,226},{__big5hkscs_nonbmp_encmap+ -17344,41,165},{__big5hkscs_nonbmp_encmap+17469,2,221},{ -__big5hkscs_nonbmp_encmap+17689,88,208},{__big5hkscs_nonbmp_encmap+17810,53, -248},{__big5hkscs_nonbmp_encmap+18006,2,152},{__big5hkscs_nonbmp_encmap+18157, -18,191},{__big5hkscs_nonbmp_encmap+18331,18,252},{__big5hkscs_nonbmp_encmap+ -18566,22,204},{__big5hkscs_nonbmp_encmap+18749,28,199},{ -__big5hkscs_nonbmp_encmap+18921,14,250},{__big5hkscs_nonbmp_encmap+19158,45,82 -},{__big5hkscs_nonbmp_encmap+19196,5,247},{__big5hkscs_nonbmp_encmap+19439,33, -209},{__big5hkscs_nonbmp_encmap+19616,34,240},{__big5hkscs_nonbmp_encmap+19823 -,0,215},{__big5hkscs_nonbmp_encmap+20039,38,223},{__big5hkscs_nonbmp_encmap+ -20225,14,248},{__big5hkscs_nonbmp_encmap+20460,9,205},{ -__big5hkscs_nonbmp_encmap+20657,27,230},{__big5hkscs_nonbmp_encmap+20861,154, -154},{__big5hkscs_nonbmp_encmap+20862,34,134},{__big5hkscs_nonbmp_encmap+20963 -,116,254},{__big5hkscs_nonbmp_encmap+21102,7,148},{__big5hkscs_nonbmp_encmap+ -21244,15,204},{__big5hkscs_nonbmp_encmap+21434,88,200},{ -__big5hkscs_nonbmp_encmap+21547,36,253},{__big5hkscs_nonbmp_encmap+21765,10, -244},{__big5hkscs_nonbmp_encmap+22000,6,244},{__big5hkscs_nonbmp_encmap+22239, -18,18},{__big5hkscs_nonbmp_encmap+22240,47,220},{__big5hkscs_nonbmp_encmap+ -22414,77,79},{__big5hkscs_nonbmp_encmap+22417,249,249},{ -__big5hkscs_nonbmp_encmap+22418,2,244},{__big5hkscs_nonbmp_encmap+22661,46,188 -},{__big5hkscs_nonbmp_encmap+22804,7,226},{__big5hkscs_nonbmp_encmap+23024,6, -138},{__big5hkscs_nonbmp_encmap+23157,18,130},{__big5hkscs_nonbmp_encmap+23270 -,1,244},{__big5hkscs_nonbmp_encmap+23514,0,230},{__big5hkscs_nonbmp_encmap+ -23745,15,19},{__big5hkscs_nonbmp_encmap+23750,4,43},{__big5hkscs_nonbmp_encmap -+23790,51,252},{__big5hkscs_nonbmp_encmap+23992,15,252},{ -__big5hkscs_nonbmp_encmap+24230,12,255},{__big5hkscs_nonbmp_encmap+24474,3,210 -},{__big5hkscs_nonbmp_encmap+24682,52,185},{__big5hkscs_nonbmp_encmap+24816, -15,231},{__big5hkscs_nonbmp_encmap+25033,197,197},{__big5hkscs_nonbmp_encmap+ -25034,136,237},{__big5hkscs_nonbmp_encmap+25136,13,235},{0,0,0},{0,0,0},{ -__big5hkscs_nonbmp_encmap+25359,29,231},{__big5hkscs_nonbmp_encmap+25562,158, -244},{0,0,0},{__big5hkscs_nonbmp_encmap+25649,32,212},{ -__big5hkscs_nonbmp_encmap+25830,16,241},{__big5hkscs_nonbmp_encmap+26056,3,201 -},{__big5hkscs_nonbmp_encmap+26255,40,77},{__big5hkscs_nonbmp_encmap+26293,5, -213},{__big5hkscs_nonbmp_encmap+26502,115,173},{__big5hkscs_nonbmp_encmap+ -26561,62,246},{__big5hkscs_nonbmp_encmap+26746,6,248},{ -__big5hkscs_nonbmp_encmap+26989,35,222},{__big5hkscs_nonbmp_encmap+27177,20, -254},{__big5hkscs_nonbmp_encmap+27412,7,245},{__big5hkscs_nonbmp_encmap+27651, -32,255},{__big5hkscs_nonbmp_encmap+27875,169,169},{__big5hkscs_nonbmp_encmap+ -27876,52,91},{__big5hkscs_nonbmp_encmap+27916,198,203},{ -__big5hkscs_nonbmp_encmap+27922,1,169},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0 ++5269,45,99},{__big5hkscs_nonbmp_encmap+5324,68,194},{ +__big5hkscs_nonbmp_encmap+5451,42,172},{__big5hkscs_nonbmp_encmap+5582,70,249 +},{__big5hkscs_nonbmp_encmap+5762,28,213},{__big5hkscs_nonbmp_encmap+5948,15, +232},{__big5hkscs_nonbmp_encmap+6166,69,252},{__big5hkscs_nonbmp_encmap+6350, +42,195},{__big5hkscs_nonbmp_encmap+6504,8,124},{__big5hkscs_nonbmp_encmap+6621 +,33,250},{__big5hkscs_nonbmp_encmap+6839,101,237},{__big5hkscs_nonbmp_encmap+ +6976,19,190},{__big5hkscs_nonbmp_encmap+7148,27,246},{ +__big5hkscs_nonbmp_encmap+7368,18,205},{__big5hkscs_nonbmp_encmap+7556,3,247}, +{__big5hkscs_nonbmp_encmap+7801,38,147},{__big5hkscs_nonbmp_encmap+7911,102, +232},{__big5hkscs_nonbmp_encmap+8042,14,206},{__big5hkscs_nonbmp_encmap+8235, +38,201},{__big5hkscs_nonbmp_encmap+8399,7,238},{__big5hkscs_nonbmp_encmap+8631 +,13,239},{__big5hkscs_nonbmp_encmap+8858,116,227},{__big5hkscs_nonbmp_encmap+ +8970,51,218},{__big5hkscs_nonbmp_encmap+9138,3,249},{__big5hkscs_nonbmp_encmap ++9385,15,225},{__big5hkscs_nonbmp_encmap+9596,0,254},{ +__big5hkscs_nonbmp_encmap+9851,0,229},{__big5hkscs_nonbmp_encmap+10081,25,243 +},{__big5hkscs_nonbmp_encmap+10300,0,238},{__big5hkscs_nonbmp_encmap+10539,3, +215},{__big5hkscs_nonbmp_encmap+10752,58,58},{__big5hkscs_nonbmp_encmap+10753, +194,194},{__big5hkscs_nonbmp_encmap+10754,167,250},{__big5hkscs_nonbmp_encmap+ +10838,26,90},{__big5hkscs_nonbmp_encmap+10903,99,255},{ +__big5hkscs_nonbmp_encmap+11060,64,248},{__big5hkscs_nonbmp_encmap+11245,6,252 +},{__big5hkscs_nonbmp_encmap+11492,53,240},{__big5hkscs_nonbmp_encmap+11680, +17,236},{__big5hkscs_nonbmp_encmap+11900,4,252},{__big5hkscs_nonbmp_encmap+ +12149,27,250},{__big5hkscs_nonbmp_encmap+12373,13,248},{ +__big5hkscs_nonbmp_encmap+12609,4,214},{__big5hkscs_nonbmp_encmap+12820,5,200 +},{__big5hkscs_nonbmp_encmap+13016,24,212},{__big5hkscs_nonbmp_encmap+13205,6, +224},{__big5hkscs_nonbmp_encmap+13424,18,255},{__big5hkscs_nonbmp_encmap+13662 +,0,251},{__big5hkscs_nonbmp_encmap+13914,14,233},{__big5hkscs_nonbmp_encmap+ +14134,15,245},{__big5hkscs_nonbmp_encmap+14365,9,217},{ +__big5hkscs_nonbmp_encmap+14574,6,235},{__big5hkscs_nonbmp_encmap+14804,59,167 +},{__big5hkscs_nonbmp_encmap+14913,14,194},{__big5hkscs_nonbmp_encmap+15094, +44,157},{__big5hkscs_nonbmp_encmap+15208,43,231},{__big5hkscs_nonbmp_encmap+ +15397,32,216},{__big5hkscs_nonbmp_encmap+15582,14,19},{ +__big5hkscs_nonbmp_encmap+15588,25,154},{__big5hkscs_nonbmp_encmap+15718,49, +224},{__big5hkscs_nonbmp_encmap+15894,5,246},{__big5hkscs_nonbmp_encmap+16136, +6,225},{__big5hkscs_nonbmp_encmap+16356,87,225},{__big5hkscs_nonbmp_encmap+ +16495,3,204},{__big5hkscs_nonbmp_encmap+16697,84,233},{ +__big5hkscs_nonbmp_encmap+16847,116,232},{__big5hkscs_nonbmp_encmap+16964,1, +254},{__big5hkscs_nonbmp_encmap+17218,32,67},{__big5hkscs_nonbmp_encmap+17254, +14,216},{__big5hkscs_nonbmp_encmap+17457,26,226},{__big5hkscs_nonbmp_encmap+ +17658,41,165},{__big5hkscs_nonbmp_encmap+17783,2,221},{ +__big5hkscs_nonbmp_encmap+18003,88,208},{__big5hkscs_nonbmp_encmap+18124,53, +248},{__big5hkscs_nonbmp_encmap+18320,2,152},{__big5hkscs_nonbmp_encmap+18471, +18,191},{__big5hkscs_nonbmp_encmap+18645,18,252},{__big5hkscs_nonbmp_encmap+ +18880,22,204},{__big5hkscs_nonbmp_encmap+19063,28,199},{ +__big5hkscs_nonbmp_encmap+19235,14,250},{__big5hkscs_nonbmp_encmap+19472,45,82 +},{__big5hkscs_nonbmp_encmap+19510,5,247},{__big5hkscs_nonbmp_encmap+19753,33, +209},{__big5hkscs_nonbmp_encmap+19930,34,240},{__big5hkscs_nonbmp_encmap+20137 +,0,215},{__big5hkscs_nonbmp_encmap+20353,38,223},{__big5hkscs_nonbmp_encmap+ +20539,14,248},{__big5hkscs_nonbmp_encmap+20774,9,205},{ +__big5hkscs_nonbmp_encmap+20971,27,230},{__big5hkscs_nonbmp_encmap+21175,82, +255},{__big5hkscs_nonbmp_encmap+21349,34,134},{__big5hkscs_nonbmp_encmap+21450 +,116,254},{__big5hkscs_nonbmp_encmap+21589,7,148},{__big5hkscs_nonbmp_encmap+ +21731,15,204},{__big5hkscs_nonbmp_encmap+21921,88,200},{ +__big5hkscs_nonbmp_encmap+22034,36,253},{__big5hkscs_nonbmp_encmap+22252,10, +244},{__big5hkscs_nonbmp_encmap+22487,6,244},{__big5hkscs_nonbmp_encmap+22726, +18,197},{__big5hkscs_nonbmp_encmap+22906,47,220},{__big5hkscs_nonbmp_encmap+ +23080,77,79},{__big5hkscs_nonbmp_encmap+23083,46,249},{ +__big5hkscs_nonbmp_encmap+23287,2,244},{__big5hkscs_nonbmp_encmap+23530,46,188 +},{__big5hkscs_nonbmp_encmap+23673,7,226},{__big5hkscs_nonbmp_encmap+23893,6, +138},{__big5hkscs_nonbmp_encmap+24026,18,130},{__big5hkscs_nonbmp_encmap+24139 +,1,244},{__big5hkscs_nonbmp_encmap+24383,0,230},{__big5hkscs_nonbmp_encmap+ +24614,15,19},{__big5hkscs_nonbmp_encmap+24619,4,43},{__big5hkscs_nonbmp_encmap ++24659,51,252},{__big5hkscs_nonbmp_encmap+24861,15,252},{ +__big5hkscs_nonbmp_encmap+25099,12,255},{__big5hkscs_nonbmp_encmap+25343,3,210 +},{__big5hkscs_nonbmp_encmap+25551,52,185},{__big5hkscs_nonbmp_encmap+25685, +15,231},{__big5hkscs_nonbmp_encmap+25902,197,197},{__big5hkscs_nonbmp_encmap+ +25903,121,237},{__big5hkscs_nonbmp_encmap+26020,13,235},{0,0,0},{0,0,0},{ +__big5hkscs_nonbmp_encmap+26243,29,231},{__big5hkscs_nonbmp_encmap+26446,158, +244},{0,0,0},{__big5hkscs_nonbmp_encmap+26533,32,212},{ +__big5hkscs_nonbmp_encmap+26714,16,250},{__big5hkscs_nonbmp_encmap+26949,3,201 +},{__big5hkscs_nonbmp_encmap+27148,40,77},{__big5hkscs_nonbmp_encmap+27186,5, +213},{__big5hkscs_nonbmp_encmap+27395,115,173},{__big5hkscs_nonbmp_encmap+ +27454,62,246},{__big5hkscs_nonbmp_encmap+27639,6,248},{ +__big5hkscs_nonbmp_encmap+27882,35,222},{__big5hkscs_nonbmp_encmap+28070,20, +254},{__big5hkscs_nonbmp_encmap+28305,7,245},{__big5hkscs_nonbmp_encmap+28544, +32,255},{__big5hkscs_nonbmp_encmap+28768,81,169},{__big5hkscs_nonbmp_encmap+ +28857,52,91},{__big5hkscs_nonbmp_encmap+28897,198,203},{ +__big5hkscs_nonbmp_encmap+28903,1,169},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0 },{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0, 0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{ 0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0 @@ -2335,6 +2372,7 @@ 0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0 },{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0, 0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{ -__big5hkscs_nonbmp_encmap+28091,37,205},{__big5hkscs_nonbmp_encmap+28260,148, +__big5hkscs_nonbmp_encmap+29072,37,205},{__big5hkscs_nonbmp_encmap+29241,148, 212},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0}, }; + Modified: python/branches/py3k-ctypes-pep3118/Modules/cmathmodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/cmathmodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/cmathmodule.c Wed Apr 30 15:57:13 2008 @@ -3,31 +3,156 @@ /* much code borrowed from mathmodule.c */ #include "Python.h" +/* we need DBL_MAX, DBL_MIN, DBL_EPSILON, DBL_MANT_DIG and FLT_RADIX from + float.h. We assume that FLT_RADIX is either 2 or 16. */ +#include -#ifndef M_PI -#define M_PI (3.141592653589793239) +#if (FLT_RADIX != 2 && FLT_RADIX != 16) +#error "Modules/cmathmodule.c expects FLT_RADIX to be 2 or 16" #endif -/* First, the C functions that do the real work */ +#ifndef M_LN2 +#define M_LN2 (0.6931471805599453094) /* natural log of 2 */ +#endif + +#ifndef M_LN10 +#define M_LN10 (2.302585092994045684) /* natural log of 10 */ +#endif -/* constants */ -static Py_complex c_one = {1., 0.}; -static Py_complex c_half = {0.5, 0.}; -static Py_complex c_i = {0., 1.}; -static Py_complex c_halfi = {0., 0.5}; +/* + CM_LARGE_DOUBLE is used to avoid spurious overflow in the sqrt, log, + inverse trig and inverse hyperbolic trig functions. Its log is used in the + evaluation of exp, cos, cosh, sin, sinh, tan, and tanh to avoid unecessary + overflow. + */ + +#define CM_LARGE_DOUBLE (DBL_MAX/4.) +#define CM_SQRT_LARGE_DOUBLE (sqrt(CM_LARGE_DOUBLE)) +#define CM_LOG_LARGE_DOUBLE (log(CM_LARGE_DOUBLE)) +#define CM_SQRT_DBL_MIN (sqrt(DBL_MIN)) + +/* + CM_SCALE_UP is an odd integer chosen such that multiplication by + 2**CM_SCALE_UP is sufficient to turn a subnormal into a normal. + CM_SCALE_DOWN is (-(CM_SCALE_UP+1)/2). These scalings are used to compute + square roots accurately when the real and imaginary parts of the argument + are subnormal. +*/ + +#if FLT_RADIX==2 +#define CM_SCALE_UP (2*(DBL_MANT_DIG/2) + 1) +#elif FLT_RADIX==16 +#define CM_SCALE_UP (4*DBL_MANT_DIG+1) +#endif +#define CM_SCALE_DOWN (-(CM_SCALE_UP+1)/2) /* forward declarations */ -static Py_complex c_log(Py_complex); -static Py_complex c_prodi(Py_complex); +static Py_complex c_asinh(Py_complex); +static Py_complex c_atanh(Py_complex); +static Py_complex c_cosh(Py_complex); +static Py_complex c_sinh(Py_complex); static Py_complex c_sqrt(Py_complex); +static Py_complex c_tanh(Py_complex); static PyObject * math_error(void); +/* Code to deal with special values (infinities, NaNs, etc.). */ + +/* special_type takes a double and returns an integer code indicating + the type of the double as follows: +*/ + +enum special_types { + ST_NINF, /* 0, negative infinity */ + ST_NEG, /* 1, negative finite number (nonzero) */ + ST_NZERO, /* 2, -0. */ + ST_PZERO, /* 3, +0. */ + ST_POS, /* 4, positive finite number (nonzero) */ + ST_PINF, /* 5, positive infinity */ + ST_NAN, /* 6, Not a Number */ +}; + +static enum special_types +special_type(double d) +{ + if (Py_IS_FINITE(d)) { + if (d != 0) { + if (copysign(1., d) == 1.) + return ST_POS; + else + return ST_NEG; + } + else { + if (copysign(1., d) == 1.) + return ST_PZERO; + else + return ST_NZERO; + } + } + if (Py_IS_NAN(d)) + return ST_NAN; + if (copysign(1., d) == 1.) + return ST_PINF; + else + return ST_NINF; +} + +#define SPECIAL_VALUE(z, table) \ + if (!Py_IS_FINITE((z).real) || !Py_IS_FINITE((z).imag)) { \ + errno = 0; \ + return table[special_type((z).real)] \ + [special_type((z).imag)]; \ + } + +#define P Py_MATH_PI +#define P14 0.25*Py_MATH_PI +#define P12 0.5*Py_MATH_PI +#define P34 0.75*Py_MATH_PI +#define INF Py_HUGE_VAL +#define N Py_NAN +#define U -9.5426319407711027e33 /* unlikely value, used as placeholder */ + +/* First, the C functions that do the real work. Each of the c_* + functions computes and returns the C99 Annex G recommended result + and also sets errno as follows: errno = 0 if no floating-point + exception is associated with the result; errno = EDOM if C99 Annex + G recommends raising divide-by-zero or invalid for this result; and + errno = ERANGE where the overflow floating-point signal should be + raised. +*/ + +static Py_complex acos_special_values[7][7]; static Py_complex -c_acos(Py_complex x) +c_acos(Py_complex z) { - return c_neg(c_prodi(c_log(c_sum(x,c_prod(c_i, - c_sqrt(c_diff(c_one,c_prod(x,x)))))))); + Py_complex s1, s2, r; + + SPECIAL_VALUE(z, acos_special_values); + + if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { + /* avoid unnecessary overflow for large arguments */ + r.real = atan2(fabs(z.imag), z.real); + /* split into cases to make sure that the branch cut has the + correct continuity on systems with unsigned zeros */ + if (z.real < 0.) { + r.imag = -copysign(log(hypot(z.real/2., z.imag/2.)) + + M_LN2*2., z.imag); + } else { + r.imag = copysign(log(hypot(z.real/2., z.imag/2.)) + + M_LN2*2., -z.imag); + } + } else { + s1.real = 1.-z.real; + s1.imag = -z.imag; + s1 = c_sqrt(s1); + s2.real = 1.+z.real; + s2.imag = z.imag; + s2 = c_sqrt(s2); + r.real = 2.*atan2(s1.real, s2.real); + r.imag = asinh(s2.real*s1.imag - s2.imag*s1.real); + } + errno = 0; + return r; } PyDoc_STRVAR(c_acos_doc, @@ -36,14 +161,31 @@ "Return the arc cosine of x."); +static Py_complex acosh_special_values[7][7]; + static Py_complex -c_acosh(Py_complex x) +c_acosh(Py_complex z) { - Py_complex z; - z = c_sqrt(c_half); - z = c_log(c_prod(z, c_sum(c_sqrt(c_sum(x,c_one)), - c_sqrt(c_diff(x,c_one))))); - return c_sum(z, z); + Py_complex s1, s2, r; + + SPECIAL_VALUE(z, acosh_special_values); + + if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { + /* avoid unnecessary overflow for large arguments */ + r.real = log(hypot(z.real/2., z.imag/2.)) + M_LN2*2.; + r.imag = atan2(z.imag, z.real); + } else { + s1.real = z.real - 1.; + s1.imag = z.imag; + s1 = c_sqrt(s1); + s2.real = z.real + 1.; + s2.imag = z.imag; + s2 = c_sqrt(s2); + r.real = asinh(s1.real*s2.real + s1.imag*s2.imag); + r.imag = 2.*atan2(s1.imag, s2.real); + } + errno = 0; + return r; } PyDoc_STRVAR(c_acosh_doc, @@ -53,14 +195,16 @@ static Py_complex -c_asin(Py_complex x) +c_asin(Py_complex z) { - /* -i * log[(sqrt(1-x**2) + i*x] */ - const Py_complex squared = c_prod(x, x); - const Py_complex sqrt_1_minus_x_sq = c_sqrt(c_diff(c_one, squared)); - return c_neg(c_prodi(c_log( - c_sum(sqrt_1_minus_x_sq, c_prodi(x)) - ) ) ); + /* asin(z) = -i asinh(iz) */ + Py_complex s, r; + s.real = -z.imag; + s.imag = z.real; + s = c_asinh(s); + r.real = s.imag; + r.imag = -s.real; + return r; } PyDoc_STRVAR(c_asin_doc, @@ -69,14 +213,36 @@ "Return the arc sine of x."); +static Py_complex asinh_special_values[7][7]; + static Py_complex -c_asinh(Py_complex x) +c_asinh(Py_complex z) { - Py_complex z; - z = c_sqrt(c_half); - z = c_log(c_prod(z, c_sum(c_sqrt(c_sum(x, c_i)), - c_sqrt(c_diff(x, c_i))))); - return c_sum(z, z); + Py_complex s1, s2, r; + + SPECIAL_VALUE(z, asinh_special_values); + + if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { + if (z.imag >= 0.) { + r.real = copysign(log(hypot(z.real/2., z.imag/2.)) + + M_LN2*2., z.real); + } else { + r.real = -copysign(log(hypot(z.real/2., z.imag/2.)) + + M_LN2*2., -z.real); + } + r.imag = atan2(z.imag, fabs(z.real)); + } else { + s1.real = 1.+z.imag; + s1.imag = -z.real; + s1 = c_sqrt(s1); + s2.real = 1.-z.imag; + s2.imag = z.real; + s2 = c_sqrt(s2); + r.real = asinh(s1.real*s2.imag-s2.real*s1.imag); + r.imag = atan2(z.imag, s1.real*s2.real-s1.imag*s2.imag); + } + errno = 0; + return r; } PyDoc_STRVAR(c_asinh_doc, @@ -86,9 +252,46 @@ static Py_complex -c_atan(Py_complex x) +c_atan(Py_complex z) { - return c_prod(c_halfi,c_log(c_quot(c_sum(c_i,x),c_diff(c_i,x)))); + /* atan(z) = -i atanh(iz) */ + Py_complex s, r; + s.real = -z.imag; + s.imag = z.real; + s = c_atanh(s); + r.real = s.imag; + r.imag = -s.real; + return r; +} + +/* Windows screws up atan2 for inf and nan, and alpha Tru64 5.1 doesn't follow + C99 for atan2(0., 0.). */ +static double +c_atan2(Py_complex z) +{ + if (Py_IS_NAN(z.real) || Py_IS_NAN(z.imag)) + return Py_NAN; + if (Py_IS_INFINITY(z.imag)) { + if (Py_IS_INFINITY(z.real)) { + if (copysign(1., z.real) == 1.) + /* atan2(+-inf, +inf) == +-pi/4 */ + return copysign(0.25*Py_MATH_PI, z.imag); + else + /* atan2(+-inf, -inf) == +-pi*3/4 */ + return copysign(0.75*Py_MATH_PI, z.imag); + } + /* atan2(+-inf, x) == +-pi/2 for finite x */ + return copysign(0.5*Py_MATH_PI, z.imag); + } + if (Py_IS_INFINITY(z.real) || z.imag == 0.) { + if (copysign(1., z.real) == 1.) + /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */ + return copysign(0., z.imag); + else + /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */ + return copysign(Py_MATH_PI, z.imag); + } + return atan2(z.imag, z.real); } PyDoc_STRVAR(c_atan_doc, @@ -97,10 +300,53 @@ "Return the arc tangent of x."); +static Py_complex atanh_special_values[7][7]; + static Py_complex -c_atanh(Py_complex x) +c_atanh(Py_complex z) { - return c_prod(c_half,c_log(c_quot(c_sum(c_one,x),c_diff(c_one,x)))); + Py_complex r; + double ay, h; + + SPECIAL_VALUE(z, atanh_special_values); + + /* Reduce to case where z.real >= 0., using atanh(z) = -atanh(-z). */ + if (z.real < 0.) { + return c_neg(c_atanh(c_neg(z))); + } + + ay = fabs(z.imag); + if (z.real > CM_SQRT_LARGE_DOUBLE || ay > CM_SQRT_LARGE_DOUBLE) { + /* + if abs(z) is large then we use the approximation + atanh(z) ~ 1/z +/- i*pi/2 (+/- depending on the sign + of z.imag) + */ + h = hypot(z.real/2., z.imag/2.); /* safe from overflow */ + r.real = z.real/4./h/h; + /* the two negations in the next line cancel each other out + except when working with unsigned zeros: they're there to + ensure that the branch cut has the correct continuity on + systems that don't support signed zeros */ + r.imag = -copysign(Py_MATH_PI/2., -z.imag); + errno = 0; + } else if (z.real == 1. && ay < CM_SQRT_DBL_MIN) { + /* C99 standard says: atanh(1+/-0.) should be inf +/- 0i */ + if (ay == 0.) { + r.real = INF; + r.imag = z.imag; + errno = EDOM; + } else { + r.real = -log(sqrt(ay)/sqrt(hypot(ay, 2.))); + r.imag = copysign(atan2(2., -ay)/2, z.imag); + errno = 0; + } + } else { + r.real = log1p(4.*z.real/((1-z.real)*(1-z.real) + ay*ay))/4.; + r.imag = -atan2(-2.*z.imag, (1-z.real)*(1+z.real) - ay*ay)/2.; + errno = 0; + } + return r; } PyDoc_STRVAR(c_atanh_doc, @@ -110,11 +356,13 @@ static Py_complex -c_cos(Py_complex x) +c_cos(Py_complex z) { + /* cos(z) = cosh(iz) */ Py_complex r; - r.real = cos(x.real)*cosh(x.imag); - r.imag = -sin(x.real)*sinh(x.imag); + r.real = -z.imag; + r.imag = z.real; + r = c_cosh(r); return r; } @@ -124,12 +372,56 @@ "Return the cosine of x."); +/* cosh(infinity + i*y) needs to be dealt with specially */ +static Py_complex cosh_special_values[7][7]; + static Py_complex -c_cosh(Py_complex x) +c_cosh(Py_complex z) { Py_complex r; - r.real = cos(x.imag)*cosh(x.real); - r.imag = sin(x.imag)*sinh(x.real); + double x_minus_one; + + /* special treatment for cosh(+/-inf + iy) if y is not a NaN */ + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) && + (z.imag != 0.)) { + if (z.real > 0) { + r.real = copysign(INF, cos(z.imag)); + r.imag = copysign(INF, sin(z.imag)); + } + else { + r.real = copysign(INF, cos(z.imag)); + r.imag = -copysign(INF, sin(z.imag)); + } + } + else { + r = cosh_special_values[special_type(z.real)] + [special_type(z.imag)]; + } + /* need to set errno = EDOM if y is +/- infinity and x is not + a NaN */ + if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real)) + errno = EDOM; + else + errno = 0; + return r; + } + + if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { + /* deal correctly with cases where cosh(z.real) overflows but + cosh(z) does not. */ + x_minus_one = z.real - copysign(1., z.real); + r.real = cos(z.imag) * cosh(x_minus_one) * Py_MATH_E; + r.imag = sin(z.imag) * sinh(x_minus_one) * Py_MATH_E; + } else { + r.real = cos(z.imag) * cosh(z.real); + r.imag = sin(z.imag) * sinh(z.real); + } + /* detect overflow, and set errno accordingly */ + if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) + errno = ERANGE; + else + errno = 0; return r; } @@ -139,13 +431,57 @@ "Return the hyperbolic cosine of x."); +/* exp(infinity + i*y) and exp(-infinity + i*y) need special treatment for + finite y */ +static Py_complex exp_special_values[7][7]; + static Py_complex -c_exp(Py_complex x) +c_exp(Py_complex z) { Py_complex r; - double l = exp(x.real); - r.real = l*cos(x.imag); - r.imag = l*sin(x.imag); + double l; + + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) + && (z.imag != 0.)) { + if (z.real > 0) { + r.real = copysign(INF, cos(z.imag)); + r.imag = copysign(INF, sin(z.imag)); + } + else { + r.real = copysign(0., cos(z.imag)); + r.imag = copysign(0., sin(z.imag)); + } + } + else { + r = exp_special_values[special_type(z.real)] + [special_type(z.imag)]; + } + /* need to set errno = EDOM if y is +/- infinity and x is not + a NaN and not -infinity */ + if (Py_IS_INFINITY(z.imag) && + (Py_IS_FINITE(z.real) || + (Py_IS_INFINITY(z.real) && z.real > 0))) + errno = EDOM; + else + errno = 0; + return r; + } + + if (z.real > CM_LOG_LARGE_DOUBLE) { + l = exp(z.real-1.); + r.real = l*cos(z.imag)*Py_MATH_E; + r.imag = l*sin(z.imag)*Py_MATH_E; + } else { + l = exp(z.real); + r.real = l*cos(z.imag); + r.imag = l*sin(z.imag); + } + /* detect overflow, and set errno accordingly */ + if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) + errno = ERANGE; + else + errno = 0; return r; } @@ -155,24 +491,89 @@ "Return the exponential value e**x."); +static Py_complex log_special_values[7][7]; + static Py_complex -c_log(Py_complex x) +c_log(Py_complex z) { + /* + The usual formula for the real part is log(hypot(z.real, z.imag)). + There are four situations where this formula is potentially + problematic: + + (1) the absolute value of z is subnormal. Then hypot is subnormal, + so has fewer than the usual number of bits of accuracy, hence may + have large relative error. This then gives a large absolute error + in the log. This can be solved by rescaling z by a suitable power + of 2. + + (2) the absolute value of z is greater than DBL_MAX (e.g. when both + z.real and z.imag are within a factor of 1/sqrt(2) of DBL_MAX) + Again, rescaling solves this. + + (3) the absolute value of z is close to 1. In this case it's + difficult to achieve good accuracy, at least in part because a + change of 1ulp in the real or imaginary part of z can result in a + change of billions of ulps in the correctly rounded answer. + + (4) z = 0. The simplest thing to do here is to call the + floating-point log with an argument of 0, and let its behaviour + (returning -infinity, signaling a floating-point exception, setting + errno, or whatever) determine that of c_log. So the usual formula + is fine here. + + */ + Py_complex r; - double l = hypot(x.real,x.imag); - r.imag = atan2(x.imag, x.real); - r.real = log(l); + double ax, ay, am, an, h; + + SPECIAL_VALUE(z, log_special_values); + + ax = fabs(z.real); + ay = fabs(z.imag); + + if (ax > CM_LARGE_DOUBLE || ay > CM_LARGE_DOUBLE) { + r.real = log(hypot(ax/2., ay/2.)) + M_LN2; + } else if (ax < DBL_MIN && ay < DBL_MIN) { + if (ax > 0. || ay > 0.) { + /* catch cases where hypot(ax, ay) is subnormal */ + r.real = log(hypot(ldexp(ax, DBL_MANT_DIG), + ldexp(ay, DBL_MANT_DIG))) - DBL_MANT_DIG*M_LN2; + } + else { + /* log(+/-0. +/- 0i) */ + r.real = -INF; + r.imag = atan2(z.imag, z.real); + errno = EDOM; + return r; + } + } else { + h = hypot(ax, ay); + if (0.71 <= h && h <= 1.73) { + am = ax > ay ? ax : ay; /* max(ax, ay) */ + an = ax > ay ? ay : ax; /* min(ax, ay) */ + r.real = log1p((am-1)*(am+1)+an*an)/2.; + } else { + r.real = log(h); + } + } + r.imag = atan2(z.imag, z.real); + errno = 0; return r; } static Py_complex -c_log10(Py_complex x) +c_log10(Py_complex z) { Py_complex r; - double l = hypot(x.real,x.imag); - r.imag = atan2(x.imag, x.real)/log(10.); - r.real = log10(l); + int errno_save; + + r = c_log(z); + errno_save = errno; /* just in case the divisions affect errno */ + r.real = r.real / M_LN10; + r.imag = r.imag / M_LN10; + errno = errno_save; return r; } @@ -182,23 +583,16 @@ "Return the base-10 logarithm of x."); -/* internal function not available from Python */ -static Py_complex -c_prodi(Py_complex x) -{ - Py_complex r; - r.real = -x.imag; - r.imag = x.real; - return r; -} - - static Py_complex -c_sin(Py_complex x) +c_sin(Py_complex z) { - Py_complex r; - r.real = sin(x.real) * cosh(x.imag); - r.imag = cos(x.real) * sinh(x.imag); + /* sin(z) = -i sin(iz) */ + Py_complex s, r; + s.real = -z.imag; + s.imag = z.real; + s = c_sinh(s); + r.real = s.imag; + r.imag = -s.real; return r; } @@ -208,12 +602,55 @@ "Return the sine of x."); +/* sinh(infinity + i*y) needs to be dealt with specially */ +static Py_complex sinh_special_values[7][7]; + static Py_complex -c_sinh(Py_complex x) +c_sinh(Py_complex z) { Py_complex r; - r.real = cos(x.imag) * sinh(x.real); - r.imag = sin(x.imag) * cosh(x.real); + double x_minus_one; + + /* special treatment for sinh(+/-inf + iy) if y is finite and + nonzero */ + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) + && (z.imag != 0.)) { + if (z.real > 0) { + r.real = copysign(INF, cos(z.imag)); + r.imag = copysign(INF, sin(z.imag)); + } + else { + r.real = -copysign(INF, cos(z.imag)); + r.imag = copysign(INF, sin(z.imag)); + } + } + else { + r = sinh_special_values[special_type(z.real)] + [special_type(z.imag)]; + } + /* need to set errno = EDOM if y is +/- infinity and x is not + a NaN */ + if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real)) + errno = EDOM; + else + errno = 0; + return r; + } + + if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { + x_minus_one = z.real - copysign(1., z.real); + r.real = cos(z.imag) * sinh(x_minus_one) * Py_MATH_E; + r.imag = sin(z.imag) * cosh(x_minus_one) * Py_MATH_E; + } else { + r.real = cos(z.imag) * sinh(z.real); + r.imag = sin(z.imag) * cosh(z.real); + } + /* detect overflow, and set errno accordingly */ + if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) + errno = ERANGE; + else + errno = 0; return r; } @@ -223,29 +660,72 @@ "Return the hyperbolic sine of x."); +static Py_complex sqrt_special_values[7][7]; + static Py_complex -c_sqrt(Py_complex x) +c_sqrt(Py_complex z) { + /* + Method: use symmetries to reduce to the case when x = z.real and y + = z.imag are nonnegative. Then the real part of the result is + given by + + s = sqrt((x + hypot(x, y))/2) + + and the imaginary part is + + d = (y/2)/s + + If either x or y is very large then there's a risk of overflow in + computation of the expression x + hypot(x, y). We can avoid this + by rewriting the formula for s as: + + s = 2*sqrt(x/8 + hypot(x/8, y/8)) + + This costs us two extra multiplications/divisions, but avoids the + overhead of checking for x and y large. + + If both x and y are subnormal then hypot(x, y) may also be + subnormal, so will lack full precision. We solve this by rescaling + x and y by a sufficiently large power of 2 to ensure that x and y + are normal. + */ + + Py_complex r; double s,d; - if (x.real == 0. && x.imag == 0.) - r = x; - else { - s = sqrt(0.5*(fabs(x.real) + hypot(x.real,x.imag))); - d = 0.5*x.imag/s; - if (x.real > 0.) { - r.real = s; - r.imag = d; - } - else if (x.imag >= 0.) { - r.real = d; - r.imag = s; - } - else { - r.real = -d; - r.imag = -s; - } + double ax, ay; + + SPECIAL_VALUE(z, sqrt_special_values); + + if (z.real == 0. && z.imag == 0.) { + r.real = 0.; + r.imag = z.imag; + return r; + } + + ax = fabs(z.real); + ay = fabs(z.imag); + + if (ax < DBL_MIN && ay < DBL_MIN && (ax > 0. || ay > 0.)) { + /* here we catch cases where hypot(ax, ay) is subnormal */ + ax = ldexp(ax, CM_SCALE_UP); + s = ldexp(sqrt(ax + hypot(ax, ldexp(ay, CM_SCALE_UP))), + CM_SCALE_DOWN); + } else { + ax /= 8.; + s = 2.*sqrt(ax + hypot(ax, ay/8.)); } + d = ay/(2.*s); + + if (z.real >= 0.) { + r.real = s; + r.imag = copysign(d, z.imag); + } else { + r.real = d; + r.imag = copysign(s, z.imag); + } + errno = 0; return r; } @@ -256,23 +736,15 @@ static Py_complex -c_tan(Py_complex x) +c_tan(Py_complex z) { - Py_complex r; - double sr,cr,shi,chi; - double rs,is,rc,ic; - double d; - sr = sin(x.real); - cr = cos(x.real); - shi = sinh(x.imag); - chi = cosh(x.imag); - rs = sr * chi; - is = cr * shi; - rc = cr * chi; - ic = -sr * shi; - d = rc*rc + ic * ic; - r.real = (rs*rc + is*ic) / d; - r.imag = (is*rc - rs*ic) / d; + /* tan(z) = -i tanh(iz) */ + Py_complex s, r; + s.real = -z.imag; + s.imag = z.real; + s = c_tanh(s); + r.real = s.imag; + r.imag = -s.real; return r; } @@ -282,24 +754,70 @@ "Return the tangent of x."); +/* tanh(infinity + i*y) needs to be dealt with specially */ +static Py_complex tanh_special_values[7][7]; + static Py_complex -c_tanh(Py_complex x) +c_tanh(Py_complex z) { + /* Formula: + + tanh(x+iy) = (tanh(x)(1+tan(y)^2) + i tan(y)(1-tanh(x))^2) / + (1+tan(y)^2 tanh(x)^2) + + To avoid excessive roundoff error, 1-tanh(x)^2 is better computed + as 1/cosh(x)^2. When abs(x) is large, we approximate 1-tanh(x)^2 + by 4 exp(-2*x) instead, to avoid possible overflow in the + computation of cosh(x). + + */ + Py_complex r; - double si,ci,shr,chr; - double rs,is,rc,ic; - double d; - si = sin(x.imag); - ci = cos(x.imag); - shr = sinh(x.real); - chr = cosh(x.real); - rs = ci * shr; - is = si * chr; - rc = ci * chr; - ic = si * shr; - d = rc*rc + ic*ic; - r.real = (rs*rc + is*ic) / d; - r.imag = (is*rc - rs*ic) / d; + double tx, ty, cx, txty, denom; + + /* special treatment for tanh(+/-inf + iy) if y is finite and + nonzero */ + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) + && (z.imag != 0.)) { + if (z.real > 0) { + r.real = 1.0; + r.imag = copysign(0., + 2.*sin(z.imag)*cos(z.imag)); + } + else { + r.real = -1.0; + r.imag = copysign(0., + 2.*sin(z.imag)*cos(z.imag)); + } + } + else { + r = tanh_special_values[special_type(z.real)] + [special_type(z.imag)]; + } + /* need to set errno = EDOM if z.imag is +/-infinity and + z.real is finite */ + if (Py_IS_INFINITY(z.imag) && Py_IS_FINITE(z.real)) + errno = EDOM; + else + errno = 0; + return r; + } + + /* danger of overflow in 2.*z.imag !*/ + if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { + r.real = copysign(1., z.real); + r.imag = 4.*sin(z.imag)*cos(z.imag)*exp(-2.*fabs(z.real)); + } else { + tx = tanh(z.real); + ty = tan(z.imag); + cx = 1./cosh(z.real); + txty = tx*ty; + denom = 1. + txty*txty; + r.real = tx*(1.+ty*ty)/denom; + r.imag = ((ty/denom)*cx)*cx; + } + errno = 0; return r; } @@ -308,6 +826,7 @@ "\n" "Return the hyperbolic tangent of x."); + static PyObject * cmath_log(PyObject *self, PyObject *args) { @@ -325,7 +844,6 @@ PyFPE_END_PROTECT(x) if (errno != 0) return math_error(); - Py_ADJUST_ERANGE2(x.real, x.imag); return PyComplex_FromCComplex(x); } @@ -351,18 +869,24 @@ static PyObject * math_1(PyObject *args, Py_complex (*func)(Py_complex)) { - Py_complex x; + Py_complex x,r ; if (!PyArg_ParseTuple(args, "D", &x)) return NULL; errno = 0; - PyFPE_START_PROTECT("complex function", return 0) - x = (*func)(x); - PyFPE_END_PROTECT(x) - Py_ADJUST_ERANGE2(x.real, x.imag); - if (errno != 0) - return math_error(); - else - return PyComplex_FromCComplex(x); + PyFPE_START_PROTECT("complex function", return 0); + r = (*func)(x); + PyFPE_END_PROTECT(r); + if (errno == EDOM) { + PyErr_SetString(PyExc_ValueError, "math domain error"); + return NULL; + } + else if (errno == ERANGE) { + PyErr_SetString(PyExc_OverflowError, "math range error"); + return NULL; + } + else { + return PyComplex_FromCComplex(r); + } } #define FUNC1(stubname, func) \ @@ -386,6 +910,143 @@ FUNC1(cmath_tan, c_tan) FUNC1(cmath_tanh, c_tanh) +static PyObject * +cmath_phase(PyObject *self, PyObject *args) +{ + Py_complex z; + double phi; + if (!PyArg_ParseTuple(args, "D:phase", &z)) + return NULL; + errno = 0; + PyFPE_START_PROTECT("arg function", return 0) + phi = c_atan2(z); + PyFPE_END_PROTECT(r) + if (errno != 0) + return math_error(); + else + return PyFloat_FromDouble(phi); +} + +PyDoc_STRVAR(cmath_phase_doc, +"phase(z) -> float\n\n\ +Return argument, also known as the phase angle, of a complex."); + +static PyObject * +cmath_polar(PyObject *self, PyObject *args) +{ + Py_complex z; + double r, phi; + if (!PyArg_ParseTuple(args, "D:polar", &z)) + return NULL; + PyFPE_START_PROTECT("polar function", return 0) + phi = c_atan2(z); /* should not cause any exception */ + r = c_abs(z); /* sets errno to ERANGE on overflow; otherwise 0 */ + PyFPE_END_PROTECT(r) + if (errno != 0) + return math_error(); + else + return Py_BuildValue("dd", r, phi); +} + +PyDoc_STRVAR(cmath_polar_doc, +"polar(z) -> r: float, phi: float\n\n\ +Convert a complex from rectangular coordinates to polar coordinates. r is\n\ +the distance from 0 and phi the phase angle."); + +/* + rect() isn't covered by the C99 standard, but it's not too hard to + figure out 'spirit of C99' rules for special value handing: + + rect(x, t) should behave like exp(log(x) + it) for positive-signed x + rect(x, t) should behave like -exp(log(-x) + it) for negative-signed x + rect(nan, t) should behave like exp(nan + it), except that rect(nan, 0) + gives nan +- i0 with the sign of the imaginary part unspecified. + +*/ + +static Py_complex rect_special_values[7][7]; + +static PyObject * +cmath_rect(PyObject *self, PyObject *args) +{ + Py_complex z; + double r, phi; + if (!PyArg_ParseTuple(args, "dd:rect", &r, &phi)) + return NULL; + errno = 0; + PyFPE_START_PROTECT("rect function", return 0) + + /* deal with special values */ + if (!Py_IS_FINITE(r) || !Py_IS_FINITE(phi)) { + /* if r is +/-infinity and phi is finite but nonzero then + result is (+-INF +-INF i), but we need to compute cos(phi) + and sin(phi) to figure out the signs. */ + if (Py_IS_INFINITY(r) && (Py_IS_FINITE(phi) + && (phi != 0.))) { + if (r > 0) { + z.real = copysign(INF, cos(phi)); + z.imag = copysign(INF, sin(phi)); + } + else { + z.real = -copysign(INF, cos(phi)); + z.imag = -copysign(INF, sin(phi)); + } + } + else { + z = rect_special_values[special_type(r)] + [special_type(phi)]; + } + /* need to set errno = EDOM if r is a nonzero number and phi + is infinite */ + if (r != 0. && !Py_IS_NAN(r) && Py_IS_INFINITY(phi)) + errno = EDOM; + else + errno = 0; + } + else { + z.real = r * cos(phi); + z.imag = r * sin(phi); + errno = 0; + } + + PyFPE_END_PROTECT(z) + if (errno != 0) + return math_error(); + else + return PyComplex_FromCComplex(z); +} + +PyDoc_STRVAR(cmath_rect_doc, +"rect(r, phi) -> z: complex\n\n\ +Convert from polar coordinates to rectangular coordinates."); + +static PyObject * +cmath_isnan(PyObject *self, PyObject *args) +{ + Py_complex z; + if (!PyArg_ParseTuple(args, "D:isnan", &z)) + return NULL; + return PyBool_FromLong(Py_IS_NAN(z.real) || Py_IS_NAN(z.imag)); +} + +PyDoc_STRVAR(cmath_isnan_doc, +"isnan(z) -> bool\n\ +Checks if the real or imaginary part of z not a number (NaN)"); + +static PyObject * +cmath_isinf(PyObject *self, PyObject *args) +{ + Py_complex z; + if (!PyArg_ParseTuple(args, "D:isnan", &z)) + return NULL; + return PyBool_FromLong(Py_IS_INFINITY(z.real) || + Py_IS_INFINITY(z.imag)); +} + +PyDoc_STRVAR(cmath_isinf_doc, +"isinf(z) -> bool\n\ +Checks if the real or imaginary part of z is infinite."); + PyDoc_STRVAR(module_doc, "This module is always available. It provides access to mathematical\n" @@ -401,8 +1062,13 @@ {"cos", cmath_cos, METH_VARARGS, c_cos_doc}, {"cosh", cmath_cosh, METH_VARARGS, c_cosh_doc}, {"exp", cmath_exp, METH_VARARGS, c_exp_doc}, + {"isinf", cmath_isinf, METH_VARARGS, cmath_isinf_doc}, + {"isnan", cmath_isnan, METH_VARARGS, cmath_isnan_doc}, {"log", cmath_log, METH_VARARGS, cmath_log_doc}, {"log10", cmath_log10, METH_VARARGS, c_log10_doc}, + {"phase", cmath_phase, METH_VARARGS, cmath_phase_doc}, + {"polar", cmath_polar, METH_VARARGS, cmath_polar_doc}, + {"rect", cmath_rect, METH_VARARGS, cmath_rect_doc}, {"sin", cmath_sin, METH_VARARGS, c_sin_doc}, {"sinh", cmath_sinh, METH_VARARGS, c_sinh_doc}, {"sqrt", cmath_sqrt, METH_VARARGS, c_sqrt_doc}, @@ -421,6 +1087,121 @@ return; PyModule_AddObject(m, "pi", - PyFloat_FromDouble(atan(1.0) * 4.0)); - PyModule_AddObject(m, "e", PyFloat_FromDouble(exp(1.0))); + PyFloat_FromDouble(Py_MATH_PI)); + PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E)); + + /* initialize special value tables */ + +#define INIT_SPECIAL_VALUES(NAME, BODY) { Py_complex* p = (Py_complex*)NAME; BODY } +#define C(REAL, IMAG) p->real = REAL; p->imag = IMAG; ++p; + + INIT_SPECIAL_VALUES(acos_special_values, { + C(P34,INF) C(P,INF) C(P,INF) C(P,-INF) C(P,-INF) C(P34,-INF) C(N,INF) + C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N) + C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N) + C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N) + C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N) + C(P14,INF) C(0.,INF) C(0.,INF) C(0.,-INF) C(0.,-INF) C(P14,-INF) C(N,INF) + C(N,INF) C(N,N) C(N,N) C(N,N) C(N,N) C(N,-INF) C(N,N) + }) + + INIT_SPECIAL_VALUES(acosh_special_values, { + C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) + C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(asinh_special_values, { + C(-INF,-P14) C(-INF,-0.) C(-INF,-0.) C(-INF,0.) C(-INF,0.) C(-INF,P14) C(-INF,N) + C(-INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-INF,P12) C(N,N) + C(-INF,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) + C(INF,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(INF,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(atanh_special_values, { + C(-0.,-P12) C(-0.,-P12) C(-0.,-P12) C(-0.,P12) C(-0.,P12) C(-0.,P12) C(-0.,N) + C(-0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-0.,P12) C(N,N) + C(-0.,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-0.,P12) C(-0.,N) + C(0.,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,P12) C(0.,N) + C(0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(0.,P12) C(N,N) + C(0.,-P12) C(0.,-P12) C(0.,-P12) C(0.,P12) C(0.,P12) C(0.,P12) C(0.,N) + C(0.,-P12) C(N,N) C(N,N) C(N,N) C(N,N) C(0.,P12) C(N,N) + }) + + INIT_SPECIAL_VALUES(cosh_special_values, { + C(INF,N) C(U,U) C(INF,0.) C(INF,-0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(N,0.) C(U,U) C(1.,0.) C(1.,-0.) C(U,U) C(N,0.) C(N,0.) + C(N,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,0.) C(N,0.) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(exp_special_values, { + C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(log_special_values, { + C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(-INF,-P) C(-INF,P) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) + C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(sinh_special_values, { + C(INF,N) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(0.,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(0.,N) C(0.,N) + C(0.,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,N) C(0.,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(sqrt_special_values, { + C(INF,-INF) C(0.,-INF) C(0.,-INF) C(0.,INF) C(0.,INF) C(INF,INF) C(N,INF) + C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N) + C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N) + C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N) + C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N) + C(INF,-INF) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,INF) C(INF,N) + C(INF,-INF) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,INF) C(N,N) + }) + + INIT_SPECIAL_VALUES(tanh_special_values, { + C(-1.,0.) C(U,U) C(-1.,-0.) C(-1.,0.) C(U,U) C(-1.,0.) C(-1.,0.) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(1.,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(1.,0.) C(1.,0.) + C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(rect_special_values, { + C(INF,N) C(U,U) C(-INF,0.) C(-INF,-0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(0.,0.) C(U,U) C(-0.,0.) C(-0.,-0.) C(U,U) C(0.,0.) C(0.,0.) + C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) } Modified: python/branches/py3k-ctypes-pep3118/Modules/config.c.in ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/config.c.in (original) +++ python/branches/py3k-ctypes-pep3118/Modules/config.c.in Wed Apr 30 15:57:13 2008 @@ -28,7 +28,7 @@ extern void initimp(void); extern void initgc(void); extern void init_ast(void); -extern void init_types(void); +extern void _PyWarnings_Init(void); struct _inittab _PyImport_Inittab[] = { @@ -43,9 +43,6 @@ /* This lives in Python/Python-ast.c */ {"_ast", init_ast}, - /* This lives in Modules/_typesmodule.c */ - {"_types", init_types}, - /* These entries are here for sys.builtin_module_names */ {"__main__", NULL}, {"builtins", NULL}, @@ -54,6 +51,9 @@ /* This lives in gcmodule.c */ {"gc", initgc}, + /* This lives in _warnings.c */ + {"_warnings", _PyWarnings_Init}, + /* Sentinel */ {0, 0} }; Modified: python/branches/py3k-ctypes-pep3118/Modules/datetimemodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/datetimemodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/datetimemodule.c Wed Apr 30 15:57:13 2008 @@ -1170,10 +1170,24 @@ return NULL; } +static PyObject * +make_freplacement(PyObject *object) +{ + char freplacement[64]; + if (PyTime_Check(object)) + sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object)); + else if (PyDateTime_Check(object)) + sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object)); + else + sprintf(freplacement, "%06d", 0); + + return PyString_FromStringAndSize(freplacement, strlen(freplacement)); +} + /* I sure don't want to reproduce the strftime code from the time module, * so this imports the module and calls it. All the hair is due to - * giving special meanings to the %z and %Z format codes via a preprocessing - * step on the format string. + * giving special meanings to the %z, %Z and %f format codes via a + * preprocessing step on the format string. * tzinfoarg is the argument to pass to the object's tzinfo method, if * needed. */ @@ -1185,6 +1199,7 @@ PyObject *zreplacement = NULL; /* py string, replacement for %z */ PyObject *Zreplacement = NULL; /* py string, replacement for %Z */ + PyObject *freplacement = NULL; /* py string, replacement for %f */ const char *pin;/* pointer to next char in input format */ Py_ssize_t flen;/* length of input format */ @@ -1232,7 +1247,7 @@ } } - /* Scan the input format, looking for %z and %Z escapes, building + /* Scan the input format, looking for %z/%Z/%f escapes, building * a new format. Since computing the replacements for those codes * is expensive, don't unless they're actually used. */ @@ -1295,6 +1310,18 @@ &ntoappend); ntoappend = Py_SIZE(Zreplacement); } + else if (ch == 'f') { + /* format microseconds */ + if (freplacement == NULL) { + freplacement = make_freplacement(object); + if (freplacement == NULL) + goto Done; + } + assert(freplacement != NULL); + assert(PyString_Check(freplacement)); + ptoappend = PyString_AS_STRING(freplacement); + ntoappend = PyString_GET_SIZE(freplacement); + } else { /* percent followed by neither z nor Z */ ptoappend = pin - 2; @@ -1341,6 +1368,7 @@ Py_DECREF(time); } Done: + Py_XDECREF(freplacement); Py_XDECREF(zreplacement); Py_XDECREF(Zreplacement); Py_XDECREF(newfmt); @@ -3210,21 +3238,6 @@ return result; } -static PyObject * -time_format(PyDateTime_Time *self, PyObject *args) -{ - PyObject *format; - - if (!PyArg_ParseTuple(args, "U:__format__", &format)) - return NULL; - - /* if the format is zero length, return str(self) */ - if (PyUnicode_GetSize(format) == 0) - return PyObject_Str((PyObject *)self); - - return PyObject_CallMethod((PyObject *)self, "strftime", "O", format); -} - /* * Miscellaneous methods. */ @@ -3412,7 +3425,7 @@ {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS, PyDoc_STR("format -> strftime() style string.")}, - {"__format__", (PyCFunction)time_format, METH_VARARGS, + {"__format__", (PyCFunction)date_format, METH_VARARGS, PyDoc_STR("Formats self with strftime.")}, {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS, @@ -3815,28 +3828,47 @@ static PyObject * datetime_strptime(PyObject *cls, PyObject *args) { - PyObject *result = NULL, *obj, *module; + static PyObject *module = NULL; + PyObject *result = NULL, *obj, *st = NULL, *frac = NULL; const Py_UNICODE *string, *format; if (!PyArg_ParseTuple(args, "uu:strptime", &string, &format)) return NULL; - if ((module = PyImport_ImportModuleNoBlock("time")) == NULL) + if (module == NULL && + (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL) return NULL; - obj = PyObject_CallMethod(module, "strptime", "uu", string, format); - Py_DECREF(module); + /* _strptime._strptime returns a two-element tuple. The first + element is a time.struct_time object. The second is the + microseconds (which are not defined for time.struct_time). */ + obj = PyObject_CallMethod(module, "_strptime", "uu", string, format); if (obj != NULL) { - int i, good_timetuple = 1, overflow; - long int ia[6]; - if (PySequence_Check(obj) && PySequence_Size(obj) >= 6) - for (i=0; i < 6; i++) { - PyObject *p = PySequence_GetItem(obj, i); - if (p == NULL) { - Py_DECREF(obj); - return NULL; + int i, good_timetuple = 1; + long int ia[7]; + if (PySequence_Check(obj) && PySequence_Size(obj) == 2) { + st = PySequence_GetItem(obj, 0); + frac = PySequence_GetItem(obj, 1); + if (st == NULL || frac == NULL) + good_timetuple = 0; + /* copy y/m/d/h/m/s values out of the + time.struct_time */ + if (good_timetuple && + PySequence_Check(st) && + PySequence_Size(st) >= 6) { + for (i=0; i < 6; i++) { + PyObject *p = PySequence_GetItem(st, i); + if (p == NULL) { + good_timetuple = 0; + break; + } + if (PyLong_Check(p)) + ia[i] = PyLong_AsLong(p); + else + good_timetuple = 0; + Py_DECREF(p); } - if (PyLong_CheckExact(p)) { +/* if (PyLong_CheckExact(p)) { ia[i] = PyLong_AsLongAndOverflow(p, &overflow); if (overflow) good_timetuple = 0; @@ -3844,17 +3876,29 @@ else good_timetuple = 0; Py_DECREF(p); - } +*/ } + else + good_timetuple = 0; + /* follow that up with a little dose of microseconds */ + if (PyLong_Check(frac)) + ia[6] = PyLong_AsLong(frac); + else + good_timetuple = 0; + } else good_timetuple = 0; if (good_timetuple) - result = PyObject_CallFunction(cls, "iiiiii", - ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]); + result = PyObject_CallFunction(cls, "iiiiiii", + ia[0], ia[1], ia[2], + ia[3], ia[4], ia[5], + ia[6]); else PyErr_SetString(PyExc_ValueError, - "unexpected value from time.strptime"); - Py_DECREF(obj); + "unexpected value from _strptime._strptime"); } + Py_XDECREF(obj); + Py_XDECREF(st); + Py_XDECREF(frac); return result; } Modified: python/branches/py3k-ctypes-pep3118/Modules/dbmmodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/dbmmodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/dbmmodule.c Wed Apr 30 15:57:13 2008 @@ -344,6 +344,13 @@ 0, /*tp_as_number*/ &dbm_as_sequence, /*tp_as_sequence*/ &dbm_as_mapping, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_xxx4*/ }; /* ----------------------------------------------------------------- */ Deleted: python/branches/py3k-ctypes-pep3118/Modules/dlmodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/dlmodule.c Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,279 +0,0 @@ - -/* dl module */ - -#include "Python.h" - -#include - -#ifdef __VMS -#include -#endif - -#ifndef RTLD_LAZY -#define RTLD_LAZY 1 -#endif - -typedef void *PyUnivPtr; -typedef struct { - PyObject_HEAD - PyUnivPtr *dl_handle; -} dlobject; - -static PyTypeObject Dltype; - -static PyObject *Dlerror; - -static PyObject * -newdlobject(PyUnivPtr *handle) -{ - dlobject *xp; - xp = PyObject_New(dlobject, &Dltype); - if (xp == NULL) - return NULL; - xp->dl_handle = handle; - return (PyObject *)xp; -} - -static void -dl_dealloc(dlobject *xp) -{ - if (xp->dl_handle != NULL) - dlclose(xp->dl_handle); - PyObject_Del(xp); -} - -static PyObject * -dl_close(dlobject *xp) -{ - if (xp->dl_handle != NULL) { - dlclose(xp->dl_handle); - xp->dl_handle = NULL; - } - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -dl_sym(dlobject *xp, PyObject *args) -{ - char *name; - PyUnivPtr *func; - if (PyUnicode_Check(args)) { - name = PyUnicode_AsString(args); - } else { - PyErr_Format(PyExc_TypeError, "expected string, found %.200s", - Py_TYPE(args)->tp_name); - return NULL; - } - func = dlsym(xp->dl_handle, name); - if (func == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - return PyLong_FromLong((long)func); -} - -static PyObject * -dl_call(dlobject *xp, PyObject *args) -{ - PyObject *name; - long (*func)(long, long, long, long, long, - long, long, long, long, long); - long alist[10]; - long res; - Py_ssize_t i; - Py_ssize_t n = PyTuple_Size(args); - if (n < 1) { - PyErr_SetString(PyExc_TypeError, "at least a name is needed"); - return NULL; - } - name = PyTuple_GetItem(args, 0); - if (!PyUnicode_Check(name)) { - PyErr_SetString(PyExc_TypeError, - "function name must be a string"); - return NULL; - } - func = (long (*)(long, long, long, long, long, - long, long, long, long, long)) - dlsym(xp->dl_handle, PyUnicode_AsString(name)); - if (func == NULL) { - PyErr_SetString(PyExc_ValueError, dlerror()); - return NULL; - } - if (n-1 > 10) { - PyErr_SetString(PyExc_TypeError, - "too many arguments (max 10)"); - return NULL; - } - for (i = 1; i < n; i++) { - PyObject *v = PyTuple_GetItem(args, i); - if (PyLong_Check(v)) { - alist[i-1] = PyLong_AsLong(v); - if (alist[i-1] == -1 && PyErr_Occurred()) - return NULL; - } else if (PyUnicode_Check(v)) - alist[i-1] = (long)PyUnicode_AsString(v); - else if (v == Py_None) - alist[i-1] = (long) ((char *)NULL); - else { - PyErr_SetString(PyExc_TypeError, - "arguments must be int, string or None"); - return NULL; - } - } - for (; i <= 10; i++) - alist[i-1] = 0; - res = (*func)(alist[0], alist[1], alist[2], alist[3], alist[4], - alist[5], alist[6], alist[7], alist[8], alist[9]); - return PyLong_FromLong(res); -} - -static PyMethodDef dlobject_methods[] = { - {"call", (PyCFunction)dl_call, METH_VARARGS}, - {"sym", (PyCFunction)dl_sym, METH_O}, - {"close", (PyCFunction)dl_close, METH_NOARGS}, - {NULL, NULL} /* Sentinel */ -}; - -static PyObject * -dl_getattr(dlobject *xp, char *name) -{ - return Py_FindMethod(dlobject_methods, (PyObject *)xp, name); -} - - -static PyTypeObject Dltype = { - PyVarObject_HEAD_INIT(NULL, 0) - "dl.dl", /*tp_name*/ - sizeof(dlobject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)dl_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)dl_getattr,/*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ -}; - -static PyObject * -dl_open(PyObject *self, PyObject *args) -{ - char *name; - int mode; - PyUnivPtr *handle; - if (sizeof(int) != sizeof(long) || - sizeof(long) != sizeof(char *)) { - PyErr_SetString(PyExc_SystemError, - "module dl requires sizeof(int) == sizeof(long) == sizeof(char*)"); - return NULL; - } - - if (PyArg_ParseTuple(args, "z:open", &name)) - mode = RTLD_LAZY; - else { - PyErr_Clear(); - if (!PyArg_ParseTuple(args, "zi:open", &name, &mode)) - return NULL; -#ifndef RTLD_NOW - if (mode != RTLD_LAZY) { - PyErr_SetString(PyExc_ValueError, "mode must be 1"); - return NULL; - } -#endif - } - handle = dlopen(name, mode); - if (handle == NULL) { - PyErr_SetString(Dlerror, dlerror()); - return NULL; - } -#ifdef __VMS - /* Under OpenVMS dlopen doesn't do any check, just save the name - * for later use, so we have to check if the file is readable, - * the name can be a logical or a file from SYS$SHARE. - */ - if (access(name, R_OK)) { - char fname[strlen(name) + 20]; - strcpy(fname, "SYS$SHARE:"); - strcat(fname, name); - strcat(fname, ".EXE"); - if (access(fname, R_OK)) { - dlclose(handle); - PyErr_SetString(Dlerror, - "File not found or protection violation"); - return NULL; - } - } -#endif - return newdlobject(handle); -} - -static PyMethodDef dl_methods[] = { - {"open", dl_open, METH_VARARGS}, - {NULL, NULL} /* sentinel */ -}; - -/* From socketmodule.c - * Convenience routine to export an integer value. - * - * Errors are silently ignored, for better or for worse... - */ -static void -insint(PyObject *d, char *name, int value) -{ - PyObject *v = PyLong_FromLong((long) value); - if (!v || PyDict_SetItemString(d, name, v)) - PyErr_Clear(); - - Py_XDECREF(v); -} - -PyMODINIT_FUNC -initdl(void) -{ - PyObject *m, *d, *x; - - /* Initialize object type */ - Py_TYPE(&Dltype) = &PyType_Type; - - /* Create the module and add the functions */ - m = Py_InitModule("dl", dl_methods); - if (m == NULL) - return; - - /* Add some symbolic constants to the module */ - d = PyModule_GetDict(m); - Dlerror = x = PyErr_NewException("dl.error", NULL, NULL); - PyDict_SetItemString(d, "error", x); - x = PyLong_FromLong((long)RTLD_LAZY); - PyDict_SetItemString(d, "RTLD_LAZY", x); -#define INSINT(X) insint(d,#X,X) -#ifdef RTLD_NOW - INSINT(RTLD_NOW); -#endif -#ifdef RTLD_NOLOAD - INSINT(RTLD_NOLOAD); -#endif -#ifdef RTLD_GLOBAL - INSINT(RTLD_GLOBAL); -#endif -#ifdef RTLD_LOCAL - INSINT(RTLD_LOCAL); -#endif -#ifdef RTLD_PARENT - INSINT(RTLD_PARENT); -#endif -#ifdef RTLD_GROUP - INSINT(RTLD_GROUP); -#endif -#ifdef RTLD_WORLD - INSINT(RTLD_WORLD); -#endif -#ifdef RTLD_NODELETE - INSINT(RTLD_NODELETE); -#endif -} Modified: python/branches/py3k-ctypes-pep3118/Modules/fcntlmodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/fcntlmodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/fcntlmodule.c Wed Apr 30 15:57:13 2008 @@ -97,11 +97,20 @@ { #define IOCTL_BUFSZ 1024 int fd; - /* In PyArg_ParseTuple below, use the unsigned int 'I' format for - the signed int 'code' variable, because Python turns 0x8000000 - into a large positive number (PyLong, or PyInt on 64-bit - platforms,) whereas C expects it to be a negative int */ - int code; + /* In PyArg_ParseTuple below, we use the unsigned non-checked 'I' + format for the 'code' parameter because Python turns 0x8000000 + into either a large positive number (PyLong or PyInt on 64-bit + platforms) or a negative number on others (32-bit PyInt) + whereas the system expects it to be a 32bit bit field value + regardless of it being passed as an int or unsigned long on + various platforms. See the termios.TIOCSWINSZ constant across + platforms for an example of thise. + + If any of the 64bit platforms ever decide to use more than 32bits + in their unsigned long ioctl codes this will break and need + special casing based on the platform being built on. + */ + unsigned int code; int arg; int ret; char *str; Modified: python/branches/py3k-ctypes-pep3118/Modules/gcmodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/gcmodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/gcmodule.c Wed Apr 30 15:57:13 2008 @@ -19,6 +19,7 @@ */ #include "Python.h" +#include "frameobject.h" /* for PyFrame_ClearFreeList */ /* Get an object's GC head */ #define AS_GC(o) ((PyGC_Head *)(o)-1) @@ -687,6 +688,21 @@ } } +/* Clear all free lists + * All free lists are cleared during the collection of the highest generation. + * Allocated items in the free list may keep a pymalloc arena occupied. + * Clearing the free lists may give back memory to the OS earlier. + */ +static void +clear_freelists(void) +{ + (void)PyMethod_ClearFreeList(); + (void)PyFrame_ClearFreeList(); + (void)PyCFunction_ClearFreeList(); + (void)PyTuple_ClearFreeList(); + (void)PyUnicode_ClearFreeList(); +} + /* This is the main function. Read this to understand how the * collection process works. */ static Py_ssize_t @@ -839,6 +855,12 @@ */ (void)handle_finalizers(&finalizers, old); + /* Clear free list only during the collection of the higest + * generation */ + if (generation == NUM_GENERATIONS-1) { + clear_freelists(); + } + if (PyErr_Occurred()) { if (gc_str == NULL) gc_str = PyUnicode_FromString("garbage collection"); Modified: python/branches/py3k-ctypes-pep3118/Modules/gdbmmodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/gdbmmodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/gdbmmodule.c Wed Apr 30 15:57:13 2008 @@ -130,7 +130,7 @@ PyErr_SetObject(PyExc_KeyError, key); return NULL; } - v = PyBytes_FromStringAndSize(drec.dptr, drec.dsize); + v = PyString_FromStringAndSize(drec.dptr, drec.dsize); free(drec.dptr); return v; } @@ -220,7 +220,7 @@ key = gdbm_firstkey(dp->di_dbm); while (key.dptr) { - item = PyBytes_FromStringAndSize(key.dptr, key.dsize); + item = PyString_FromStringAndSize(key.dptr, key.dsize); if (item == NULL) { free(key.dptr); Py_DECREF(v); @@ -291,7 +291,7 @@ check_dbmobject_open(dp); key = gdbm_firstkey(dp->di_dbm); if (key.dptr) { - v = PyBytes_FromStringAndSize(key.dptr, key.dsize); + v = PyString_FromStringAndSize(key.dptr, key.dsize); free(key.dptr); return v; } @@ -323,7 +323,7 @@ check_dbmobject_open(dp); nextkey = gdbm_nextkey(dp->di_dbm, key); if (nextkey.dptr) { - v = PyBytes_FromStringAndSize(nextkey.dptr, nextkey.dsize); + v = PyString_FromStringAndSize(nextkey.dptr, nextkey.dsize); free(nextkey.dptr); return v; } @@ -407,7 +407,7 @@ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ - 0, /*tp_xxx4*/ + Py_TPFLAGS_DEFAULT, /*tp_xxx4*/ gdbm_object__doc__, /*tp_doc*/ }; Modified: python/branches/py3k-ctypes-pep3118/Modules/getpath.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/getpath.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/getpath.c Wed Apr 30 15:57:13 2008 @@ -122,19 +122,81 @@ #endif #ifndef LANDMARK -#define LANDMARK "os.py" +#define LANDMARK L"os.py" #endif -static char prefix[MAXPATHLEN+1]; -static char exec_prefix[MAXPATHLEN+1]; -static char progpath[MAXPATHLEN+1]; -static char *module_search_path = NULL; -static char lib_python[] = "lib/python" VERSION; +static wchar_t prefix[MAXPATHLEN+1]; +static wchar_t exec_prefix[MAXPATHLEN+1]; +static wchar_t progpath[MAXPATHLEN+1]; +static wchar_t *module_search_path = NULL; +static wchar_t lib_python[] = L"lib/python" VERSION; + +/* In principle, this should use HAVE__WSTAT, and _wstat + should be detected by autoconf. However, no current + POSIX system provides that function, so testing for + it is pointless. */ +#ifndef MS_WINDOWS +static int +_wstat(const wchar_t* path, struct stat *buf) +{ + char fname[PATH_MAX]; + size_t res = wcstombs(fname, path, sizeof(fname)); + if (res == (size_t)-1) { + errno = EINVAL; + return -1; + } + return stat(fname, buf); +} +#endif + +#ifndef MS_WINDOWS +static wchar_t* +_wgetcwd(wchar_t *buf, size_t size) +{ + char fname[PATH_MAX]; + if (getcwd(fname, PATH_MAX) == NULL) + return NULL; + if (mbstowcs(buf, fname, size) >= size) { + errno = ERANGE; + return NULL; + } + return buf; +} +#endif + +#ifdef HAVE_READLINK +int +_Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t bufsiz) +{ + char cbuf[PATH_MAX]; + char cpath[PATH_MAX]; + int res; + size_t r1 = wcstombs(cpath, path, PATH_MAX); + if (r1 == (size_t)-1 || r1 >= PATH_MAX) { + errno = EINVAL; + return -1; + } + res = (int)readlink(cpath, cbuf, PATH_MAX); + if (res == -1) + return -1; + if (res == PATH_MAX) { + errno = EINVAL; + return -1; + } + r1 = mbstowcs(buf, cbuf, bufsiz); + if (r1 == -1) { + errno = EINVAL; + return -1; + } + return (int)r1; + +} +#endif static void -reduce(char *dir) +reduce(wchar_t *dir) { - size_t i = strlen(dir); + size_t i = wcslen(dir); while (i > 0 && dir[i] != SEP) --i; dir[i] = '\0'; @@ -142,10 +204,10 @@ static int -isfile(char *filename) /* Is file, not directory */ +isfile(wchar_t *filename) /* Is file, not directory */ { struct stat buf; - if (stat(filename, &buf) != 0) + if (_wstat(filename, &buf) != 0) return 0; if (!S_ISREG(buf.st_mode)) return 0; @@ -154,14 +216,14 @@ static int -ismodule(char *filename) /* Is module -- check for .pyc/.pyo too */ +ismodule(wchar_t *filename) /* Is module -- check for .pyc/.pyo too */ { if (isfile(filename)) return 1; /* Check for the compiled version of prefix. */ - if (strlen(filename) < MAXPATHLEN) { - strcat(filename, Py_OptimizeFlag ? "o" : "c"); + if (wcslen(filename) < MAXPATHLEN) { + wcscat(filename, Py_OptimizeFlag ? L"o" : L"c"); if (isfile(filename)) return 1; } @@ -170,10 +232,10 @@ static int -isxfile(char *filename) /* Is executable file */ +isxfile(wchar_t *filename) /* Is executable file */ { struct stat buf; - if (stat(filename, &buf) != 0) + if (_wstat(filename, &buf) != 0) return 0; if (!S_ISREG(buf.st_mode)) return 0; @@ -184,10 +246,10 @@ static int -isdir(char *filename) /* Is directory */ +isdir(wchar_t *filename) /* Is directory */ { struct stat buf; - if (stat(filename, &buf) != 0) + if (_wstat(filename, &buf) != 0) return 0; if (!S_ISDIR(buf.st_mode)) return 0; @@ -205,34 +267,34 @@ stuff as fits will be appended. */ static void -joinpath(char *buffer, char *stuff) +joinpath(wchar_t *buffer, wchar_t *stuff) { size_t n, k; if (stuff[0] == SEP) n = 0; else { - n = strlen(buffer); + n = wcslen(buffer); if (n > 0 && buffer[n-1] != SEP && n < MAXPATHLEN) buffer[n++] = SEP; } if (n > MAXPATHLEN) Py_FatalError("buffer overflow in getpath.c's joinpath()"); - k = strlen(stuff); + k = wcslen(stuff); if (n + k > MAXPATHLEN) k = MAXPATHLEN - n; - strncpy(buffer+n, stuff, k); + wcsncpy(buffer+n, stuff, k); buffer[n+k] = '\0'; } /* copy_absolute requires that path be allocated at least MAXPATHLEN + 1 bytes and that p be no more than MAXPATHLEN bytes. */ static void -copy_absolute(char *path, char *p) +copy_absolute(wchar_t *path, wchar_t *p) { if (p[0] == SEP) - strcpy(path, p); + wcscpy(path, p); else { - getcwd(path, MAXPATHLEN); + _wgetcwd(path, MAXPATHLEN); if (p[0] == '.' && p[1] == SEP) p += 2; joinpath(path, p); @@ -241,46 +303,46 @@ /* absolutize() requires that path be allocated at least MAXPATHLEN+1 bytes. */ static void -absolutize(char *path) +absolutize(wchar_t *path) { - char buffer[MAXPATHLEN + 1]; + wchar_t buffer[MAXPATHLEN + 1]; if (path[0] == SEP) return; copy_absolute(buffer, path); - strcpy(path, buffer); + wcscpy(path, buffer); } /* search_for_prefix requires that argv0_path be no more than MAXPATHLEN bytes long. */ static int -search_for_prefix(char *argv0_path, char *home) +search_for_prefix(wchar_t *argv0_path, wchar_t *home) { size_t n; - char *vpath; + wchar_t *vpath; /* If PYTHONHOME is set, we believe it unconditionally */ if (home) { - char *delim; - strncpy(prefix, home, MAXPATHLEN); - delim = strchr(prefix, DELIM); + wchar_t *delim; + wcsncpy(prefix, home, MAXPATHLEN); + delim = wcschr(prefix, DELIM); if (delim) - *delim = '\0'; + *delim = L'\0'; joinpath(prefix, lib_python); joinpath(prefix, LANDMARK); return 1; } /* Check to see if argv[0] is in the build directory */ - strcpy(prefix, argv0_path); - joinpath(prefix, "Modules/Setup"); + wcscpy(prefix, argv0_path); + joinpath(prefix, L"Modules/Setup"); if (isfile(prefix)) { /* Check VPATH to see if argv0_path is in the build directory. */ - vpath = VPATH; - strcpy(prefix, argv0_path); + vpath = L"" VPATH; + wcscpy(prefix, argv0_path); joinpath(prefix, vpath); - joinpath(prefix, "Lib"); + joinpath(prefix, L"Lib"); joinpath(prefix, LANDMARK); if (ismodule(prefix)) return -1; @@ -289,17 +351,17 @@ /* Search from argv0_path, until root is found */ copy_absolute(prefix, argv0_path); do { - n = strlen(prefix); + n = wcslen(prefix); joinpath(prefix, lib_python); joinpath(prefix, LANDMARK); if (ismodule(prefix)) return 1; - prefix[n] = '\0'; + prefix[n] = L'\0'; reduce(prefix); } while (prefix[0]); /* Look at configure's PREFIX */ - strncpy(prefix, PREFIX, MAXPATHLEN); + wcsncpy(prefix, L"" PREFIX, MAXPATHLEN); joinpath(prefix, lib_python); joinpath(prefix, LANDMARK); if (ismodule(prefix)) @@ -314,26 +376,26 @@ MAXPATHLEN bytes long. */ static int -search_for_exec_prefix(char *argv0_path, char *home) +search_for_exec_prefix(wchar_t *argv0_path, wchar_t *home) { size_t n; /* If PYTHONHOME is set, we believe it unconditionally */ if (home) { - char *delim; - delim = strchr(home, DELIM); + wchar_t *delim; + delim = wcschr(home, DELIM); if (delim) - strncpy(exec_prefix, delim+1, MAXPATHLEN); + wcsncpy(exec_prefix, delim+1, MAXPATHLEN); else - strncpy(exec_prefix, home, MAXPATHLEN); + wcsncpy(exec_prefix, home, MAXPATHLEN); joinpath(exec_prefix, lib_python); - joinpath(exec_prefix, "lib-dynload"); + joinpath(exec_prefix, L"lib-dynload"); return 1; } /* Check to see if argv[0] is in the build directory */ - strcpy(exec_prefix, argv0_path); - joinpath(exec_prefix, "Modules/Setup"); + wcscpy(exec_prefix, argv0_path); + joinpath(exec_prefix, L"Modules/Setup"); if (isfile(exec_prefix)) { reduce(exec_prefix); return -1; @@ -342,19 +404,19 @@ /* Search from argv0_path, until root is found */ copy_absolute(exec_prefix, argv0_path); do { - n = strlen(exec_prefix); + n = wcslen(exec_prefix); joinpath(exec_prefix, lib_python); - joinpath(exec_prefix, "lib-dynload"); + joinpath(exec_prefix, L"lib-dynload"); if (isdir(exec_prefix)) return 1; - exec_prefix[n] = '\0'; + exec_prefix[n] = L'\0'; reduce(exec_prefix); } while (exec_prefix[0]); /* Look at configure's EXEC_PREFIX */ - strncpy(exec_prefix, EXEC_PREFIX, MAXPATHLEN); + wcsncpy(exec_prefix, L"" EXEC_PREFIX, MAXPATHLEN); joinpath(exec_prefix, lib_python); - joinpath(exec_prefix, "lib-dynload"); + joinpath(exec_prefix, L"lib-dynload"); if (isdir(exec_prefix)) return 1; @@ -366,22 +428,25 @@ static void calculate_path(void) { - extern char *Py_GetProgramName(void); + extern wchar_t *Py_GetProgramName(void); - static char delimiter[2] = {DELIM, '\0'}; - static char separator[2] = {SEP, '\0'}; - char *pythonpath = PYTHONPATH; - char *rtpypath = Py_GETENV("PYTHONPATH"); - char *home = Py_GetPythonHome(); - char *path = getenv("PATH"); - char *prog = Py_GetProgramName(); - char argv0_path[MAXPATHLEN+1]; - char zip_path[MAXPATHLEN+1]; + static wchar_t delimiter[2] = {DELIM, '\0'}; + static wchar_t separator[2] = {SEP, '\0'}; + wchar_t *pythonpath = L"" PYTHONPATH; + char *_rtpypath = Py_GETENV("PYTHONPATH"); /* XXX use wide version on Windows */ + wchar_t rtpypath[MAXPATHLEN+1]; + wchar_t *home = Py_GetPythonHome(); + char *_path = getenv("PATH"); + wchar_t wpath[MAXPATHLEN+1]; + wchar_t *path = NULL; + wchar_t *prog = Py_GetProgramName(); + wchar_t argv0_path[MAXPATHLEN+1]; + wchar_t zip_path[MAXPATHLEN+1]; int pfound, efound; /* 1 if found; -1 if found build directory */ - char *buf; + wchar_t *buf; size_t bufsz; size_t prefixsz; - char *defpath = pythonpath; + wchar_t *defpath = pythonpath; #ifdef WITH_NEXT_FRAMEWORK NSModule pythonModule; #endif @@ -393,13 +458,22 @@ #endif #endif + if (_path) { + size_t r = mbstowcs(wpath, _path, MAXPATHLEN+1); + path = wpath; + if (r == (size_t)-1 || r > MAXPATHLEN) { + /* Could not convert PATH, or it's too long. */ + path = NULL; + } + } + /* If there is no slash in the argv0 path, then we have to * assume python is on the user's $PATH, since there's no * other way to find a directory to start the search from. If * $PATH isn't exported, you lose. */ - if (strchr(prog, SEP)) - strncpy(progpath, prog, MAXPATHLEN); + if (wcschr(prog, SEP)) + wcsncpy(progpath, prog, MAXPATHLEN); #ifdef __APPLE__ /* On Mac OS X, if a script uses an interpreter of the form * "#!/opt/python2.3/bin/python", the kernel only passes "python" @@ -416,24 +490,24 @@ #endif /* __APPLE__ */ else if (path) { while (1) { - char *delim = strchr(path, DELIM); + wchar_t *delim = wcschr(path, DELIM); if (delim) { size_t len = delim - path; if (len > MAXPATHLEN) len = MAXPATHLEN; - strncpy(progpath, path, len); + wcsncpy(progpath, path, len); *(progpath + len) = '\0'; } else - strncpy(progpath, path, MAXPATHLEN); + wcsncpy(progpath, path, MAXPATHLEN); joinpath(progpath, prog); if (isxfile(progpath)) break; if (!delim) { - progpath[0] = '\0'; + progpath[0] = L'\0'; break; } path = delim + 1; @@ -443,7 +517,7 @@ progpath[0] = '\0'; if (progpath[0] != SEP) absolutize(progpath); - strncpy(argv0_path, progpath, MAXPATHLEN); + wcsncpy(argv0_path, progpath, MAXPATHLEN); argv0_path[MAXPATHLEN] = '\0'; #ifdef WITH_NEXT_FRAMEWORK @@ -454,7 +528,7 @@ */ pythonModule = NSModuleForSymbol(NSLookupAndBindSymbol("_Py_Initialize")); /* Use dylib functions to find out where the framework was loaded from */ - buf = (char *)NSLibraryNameForModule(pythonModule); + buf = (wchar_t *)NSLibraryNameForModule(pythonModule); if (buf != NULL) { /* We're in a framework. */ /* See if we might be in the build directory. The framework in the @@ -464,39 +538,39 @@ ** be running the interpreter in the build directory, so we use the ** build-directory-specific logic to find Lib and such. */ - strncpy(argv0_path, buf, MAXPATHLEN); + wcsncpy(argv0_path, buf, MAXPATHLEN); reduce(argv0_path); joinpath(argv0_path, lib_python); joinpath(argv0_path, LANDMARK); if (!ismodule(argv0_path)) { /* We are in the build directory so use the name of the executable - we know that the absolute path is passed */ - strncpy(argv0_path, prog, MAXPATHLEN); + wcsncpy(argv0_path, prog, MAXPATHLEN); } else { /* Use the location of the library as the progpath */ - strncpy(argv0_path, buf, MAXPATHLEN); + wcsncpy(argv0_path, buf, MAXPATHLEN); } } #endif #if HAVE_READLINK { - char tmpbuffer[MAXPATHLEN+1]; - int linklen = readlink(progpath, tmpbuffer, MAXPATHLEN); + wchar_t tmpbuffer[MAXPATHLEN+1]; + int linklen = _Py_wreadlink(progpath, tmpbuffer, MAXPATHLEN); while (linklen != -1) { /* It's not null terminated! */ tmpbuffer[linklen] = '\0'; if (tmpbuffer[0] == SEP) /* tmpbuffer should never be longer than MAXPATHLEN, but extra check does not hurt */ - strncpy(argv0_path, tmpbuffer, MAXPATHLEN); + wcsncpy(argv0_path, tmpbuffer, MAXPATHLEN); else { /* Interpret relative to progpath */ reduce(argv0_path); joinpath(argv0_path, tmpbuffer); } - linklen = readlink(argv0_path, tmpbuffer, MAXPATHLEN); + linklen = _Py_wreadlink(argv0_path, tmpbuffer, MAXPATHLEN); } } #endif /* HAVE_READLINK */ @@ -510,22 +584,22 @@ if (!Py_FrozenFlag) fprintf(stderr, "Could not find platform independent libraries \n"); - strncpy(prefix, PREFIX, MAXPATHLEN); + wcsncpy(prefix, L"" PREFIX, MAXPATHLEN); joinpath(prefix, lib_python); } else reduce(prefix); - strncpy(zip_path, prefix, MAXPATHLEN); - zip_path[MAXPATHLEN] = '\0'; + wcsncpy(zip_path, prefix, MAXPATHLEN); + zip_path[MAXPATHLEN] = L'\0'; if (pfound > 0) { /* Use the reduced prefix returned by Py_GetPrefix() */ reduce(zip_path); reduce(zip_path); } else - strncpy(zip_path, PREFIX, MAXPATHLEN); - joinpath(zip_path, "lib/python00.zip"); - bufsz = strlen(zip_path); /* Replace "00" with version */ + wcsncpy(zip_path, L"" PREFIX, MAXPATHLEN); + joinpath(zip_path, L"lib/python00.zip"); + bufsz = wcslen(zip_path); /* Replace "00" with version */ zip_path[bufsz - 6] = VERSION[0]; zip_path[bufsz - 5] = VERSION[2]; @@ -533,8 +607,8 @@ if (!Py_FrozenFlag) fprintf(stderr, "Could not find platform dependent libraries \n"); - strncpy(exec_prefix, EXEC_PREFIX, MAXPATHLEN); - joinpath(exec_prefix, "lib/lib-dynload"); + wcsncpy(exec_prefix, L"" EXEC_PREFIX, MAXPATHLEN); + joinpath(exec_prefix, L"lib/lib-dynload"); } /* If we found EXEC_PREFIX do *not* reduce it! (Yet.) */ @@ -546,13 +620,19 @@ */ bufsz = 0; - if (rtpypath) - bufsz += strlen(rtpypath) + 1; + if (_rtpypath) { + size_t s = mbstowcs(rtpypath, _rtpypath, sizeof(rtpypath)/sizeof(wchar_t)); + if (s == (size_t)-1 || s >=sizeof(rtpypath)) + /* XXX deal with errors more gracefully */ + _rtpypath = NULL; + if (_rtpypath) + bufsz += wcslen(rtpypath) + 1; + } - prefixsz = strlen(prefix) + 1; + prefixsz = wcslen(prefix) + 1; while (1) { - char *delim = strchr(defpath, DELIM); + wchar_t *delim = wcschr(defpath, DELIM); if (defpath[0] != SEP) /* Paths are relative to prefix */ @@ -561,65 +641,65 @@ if (delim) bufsz += delim - defpath + 1; else { - bufsz += strlen(defpath) + 1; + bufsz += wcslen(defpath) + 1; break; } defpath = delim + 1; } - bufsz += strlen(zip_path) + 1; - bufsz += strlen(exec_prefix) + 1; + bufsz += wcslen(zip_path) + 1; + bufsz += wcslen(exec_prefix) + 1; /* This is the only malloc call in this file */ - buf = (char *)PyMem_Malloc(bufsz); + buf = (wchar_t *)PyMem_Malloc(bufsz*sizeof(wchar_t)); if (buf == NULL) { /* We can't exit, so print a warning and limp along */ fprintf(stderr, "Not enough memory for dynamic PYTHONPATH.\n"); fprintf(stderr, "Using default static PYTHONPATH.\n"); - module_search_path = PYTHONPATH; + module_search_path = L"" PYTHONPATH; } else { /* Run-time value of $PYTHONPATH goes first */ - if (rtpypath) { - strcpy(buf, rtpypath); - strcat(buf, delimiter); + if (_rtpypath) { + wcscpy(buf, rtpypath); + wcscat(buf, delimiter); } else buf[0] = '\0'; /* Next is the default zip path */ - strcat(buf, zip_path); - strcat(buf, delimiter); + wcscat(buf, zip_path); + wcscat(buf, delimiter); /* Next goes merge of compile-time $PYTHONPATH with * dynamically located prefix. */ defpath = pythonpath; while (1) { - char *delim = strchr(defpath, DELIM); + wchar_t *delim = wcschr(defpath, DELIM); if (defpath[0] != SEP) { - strcat(buf, prefix); - strcat(buf, separator); + wcscat(buf, prefix); + wcscat(buf, separator); } if (delim) { size_t len = delim - defpath + 1; - size_t end = strlen(buf) + len; - strncat(buf, defpath, len); + size_t end = wcslen(buf) + len; + wcsncat(buf, defpath, len); *(buf + end) = '\0'; } else { - strcat(buf, defpath); + wcscat(buf, defpath); break; } defpath = delim + 1; } - strcat(buf, delimiter); + wcscat(buf, delimiter); /* Finally, on goes the directory for dynamic-load modules */ - strcat(buf, exec_prefix); + wcscat(buf, exec_prefix); /* And publish the results */ module_search_path = buf; @@ -636,26 +716,26 @@ /* The prefix is the root directory, but reduce() chopped * off the "/". */ if (!prefix[0]) - strcpy(prefix, separator); + wcscpy(prefix, separator); } else - strncpy(prefix, PREFIX, MAXPATHLEN); + wcsncpy(prefix, L"" PREFIX, MAXPATHLEN); if (efound > 0) { reduce(exec_prefix); reduce(exec_prefix); reduce(exec_prefix); if (!exec_prefix[0]) - strcpy(exec_prefix, separator); + wcscpy(exec_prefix, separator); } else - strncpy(exec_prefix, EXEC_PREFIX, MAXPATHLEN); + wcsncpy(exec_prefix, L"" EXEC_PREFIX, MAXPATHLEN); } /* External interface */ -char * +wchar_t * Py_GetPath(void) { if (!module_search_path) @@ -663,7 +743,7 @@ return module_search_path; } -char * +wchar_t * Py_GetPrefix(void) { if (!module_search_path) @@ -671,7 +751,7 @@ return prefix; } -char * +wchar_t * Py_GetExecPrefix(void) { if (!module_search_path) @@ -679,7 +759,7 @@ return exec_prefix; } -char * +wchar_t * Py_GetProgramFullPath(void) { if (!module_search_path) Modified: python/branches/py3k-ctypes-pep3118/Modules/itertoolsmodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/itertoolsmodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/itertoolsmodule.c Wed Apr 30 15:57:13 2008 @@ -198,7 +198,7 @@ { _grouperobject *igo; - igo = PyObject_New(_grouperobject, &_grouper_type); + igo = PyObject_GC_New(_grouperobject, &_grouper_type); if (igo == NULL) return NULL; igo->parent = (PyObject *)parent; @@ -206,15 +206,25 @@ igo->tgtkey = tgtkey; Py_INCREF(tgtkey); + PyObject_GC_Track(igo); return (PyObject *)igo; } static void _grouper_dealloc(_grouperobject *igo) { + PyObject_GC_UnTrack(igo); Py_DECREF(igo->parent); Py_DECREF(igo->tgtkey); - PyObject_Del(igo); + PyObject_GC_Del(igo); +} + +static int +_grouper_traverse(_grouperobject *igo, visitproc visit, void *arg) +{ + Py_VISIT(igo->parent); + Py_VISIT(igo->tgtkey); + return 0; } static PyObject * @@ -280,9 +290,9 @@ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ - 0, /* tp_traverse */ + (traverseproc)_grouper_traverse,/* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ @@ -299,7 +309,7 @@ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ - PyObject_Del, /* tp_free */ + PyObject_GC_Del, /* tp_free */ }; @@ -1418,117 +1428,136 @@ }; -/* imap object ************************************************************/ +/* chain object ************************************************************/ typedef struct { PyObject_HEAD - PyObject *iters; - PyObject *func; -} imapobject; + PyObject *source; /* Iterator over input iterables */ + PyObject *active; /* Currently running input iterator */ +} chainobject; -static PyTypeObject imap_type; +static PyTypeObject chain_type; -static PyObject * -imap_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +static PyObject * +chain_new_internal(PyTypeObject *type, PyObject *source) { - PyObject *it, *iters, *func; - imapobject *lz; - Py_ssize_t numargs, i; - - if (type == &imap_type && !_PyArg_NoKeywords("imap()", kwds)) - return NULL; + chainobject *lz; - numargs = PyTuple_Size(args); - if (numargs < 2) { - PyErr_SetString(PyExc_TypeError, - "imap() must have at least two arguments."); + lz = (chainobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(source); return NULL; } + + lz->source = source; + lz->active = NULL; + return (PyObject *)lz; +} - iters = PyTuple_New(numargs-1); - if (iters == NULL) +static PyObject * +chain_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + PyObject *source; + + if (type == &chain_type && !_PyArg_NoKeywords("chain()", kwds)) + return NULL; + + source = PyObject_GetIter(args); + if (source == NULL) return NULL; - for (i=1 ; itp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(iters); +static PyObject * +chain_new_from_iterable(PyTypeObject *type, PyObject *arg) +{ + PyObject *source; + + source = PyObject_GetIter(arg); + if (source == NULL) return NULL; - } - lz->iters = iters; - func = PyTuple_GET_ITEM(args, 0); - Py_INCREF(func); - lz->func = func; - return (PyObject *)lz; + return chain_new_internal(type, source); } static void -imap_dealloc(imapobject *lz) +chain_dealloc(chainobject *lz) { PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->iters); - Py_XDECREF(lz->func); + Py_XDECREF(lz->active); + Py_XDECREF(lz->source); Py_TYPE(lz)->tp_free(lz); } static int -imap_traverse(imapobject *lz, visitproc visit, void *arg) +chain_traverse(chainobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->iters); - Py_VISIT(lz->func); + Py_VISIT(lz->source); + Py_VISIT(lz->active); return 0; } static PyObject * -imap_next(imapobject *lz) +chain_next(chainobject *lz) { - PyObject *val; - PyObject *argtuple; - PyObject *result; - Py_ssize_t numargs, i; + PyObject *item; - numargs = PyTuple_Size(lz->iters); - argtuple = PyTuple_New(numargs); - if (argtuple == NULL) - return NULL; + if (lz->source == NULL) + return NULL; /* already stopped */ - for (i=0 ; iiters, i)); - if (val == NULL) { - Py_DECREF(argtuple); - return NULL; + if (lz->active == NULL) { + PyObject *iterable = PyIter_Next(lz->source); + if (iterable == NULL) { + Py_CLEAR(lz->source); + return NULL; /* no more input sources */ + } + lz->active = PyObject_GetIter(iterable); + Py_DECREF(iterable); + if (lz->active == NULL) { + Py_CLEAR(lz->source); + return NULL; /* input not iterable */ } - PyTuple_SET_ITEM(argtuple, i, val); } - result = PyObject_Call(lz->func, argtuple, NULL); - Py_DECREF(argtuple); - return result; + item = PyIter_Next(lz->active); + if (item != NULL) + return item; + if (PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_StopIteration)) + PyErr_Clear(); + else + return NULL; /* input raised an exception */ + } + Py_CLEAR(lz->active); + return chain_next(lz); /* recurse and use next active */ } -PyDoc_STRVAR(imap_doc, -"imap(func, *iterables) --> imap object\n\ +PyDoc_STRVAR(chain_doc, +"chain(*iterables) --> chain object\n\ \n\ -Make an iterator that computes the function using arguments from\n\ -each of the iterables. Stops when the shortest iterable is exhausted."); +Return a chain object whose .__next__() method returns elements from the\n\ +first iterable until it is exhausted, then elements from the next\n\ +iterable, until all of the iterables are exhausted."); + +PyDoc_STRVAR(chain_from_iterable_doc, +"chain.from_iterable(iterable) --> chain object\n\ +\n\ +Alternate chain() contructor taking a single iterable argument\n\ +that evaluates lazily."); -static PyTypeObject imap_type = { +static PyMethodDef chain_methods[] = { + {"from_iterable", (PyCFunction) chain_new_from_iterable, METH_O | METH_CLASS, + chain_from_iterable_doc}, + {NULL, NULL} /* sentinel */ +}; + +static PyTypeObject chain_type = { PyVarObject_HEAD_INIT(NULL, 0) - "itertools.imap", /* tp_name */ - sizeof(imapobject), /* tp_basicsize */ + "itertools.chain", /* tp_name */ + sizeof(chainobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ - (destructor)imap_dealloc, /* tp_dealloc */ + (destructor)chain_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ @@ -1545,14 +1574,14 @@ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ - imap_doc, /* tp_doc */ - (traverseproc)imap_traverse, /* tp_traverse */ + chain_doc, /* tp_doc */ + (traverseproc)chain_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ - (iternextfunc)imap_next, /* tp_iternext */ - 0, /* tp_methods */ + (iternextfunc)chain_next, /* tp_iternext */ + chain_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ @@ -1562,117 +1591,220 @@ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ - imap_new, /* tp_new */ + chain_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; -/* chain object ************************************************************/ +/* product object ************************************************************/ typedef struct { PyObject_HEAD - Py_ssize_t tuplesize; - Py_ssize_t iternum; /* which iterator is active */ - PyObject *ittuple; /* tuple of iterators */ -} chainobject; + PyObject *pools; /* tuple of pool tuples */ + Py_ssize_t *indices; /* one index per pool */ + PyObject *result; /* most recently returned result tuple */ + int stopped; /* set to 1 when the product iterator is exhausted */ +} productobject; -static PyTypeObject chain_type; +static PyTypeObject product_type; static PyObject * -chain_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +product_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - chainobject *lz; - Py_ssize_t tuplesize = PySequence_Length(args); + productobject *lz; + Py_ssize_t nargs, npools, repeat=1; + PyObject *pools = NULL; + Py_ssize_t *indices = NULL; Py_ssize_t i; - PyObject *ittuple; - - if (type == &chain_type && !_PyArg_NoKeywords("chain()", kwds)) - return NULL; - /* obtain iterators */ - assert(PyTuple_Check(args)); - ittuple = PyTuple_New(tuplesize); - if (ittuple == NULL) - return NULL; - for (i=0; i < tuplesize; ++i) { - PyObject *item = PyTuple_GET_ITEM(args, i); - PyObject *it = PyObject_GetIter(item); - if (it == NULL) { - if (PyErr_ExceptionMatches(PyExc_TypeError)) - PyErr_Format(PyExc_TypeError, - "chain argument #%zd must support iteration", - i+1); - Py_DECREF(ittuple); + if (kwds != NULL) { + char *kwlist[] = {"repeat", 0}; + PyObject *tmpargs = PyTuple_New(0); + if (tmpargs == NULL) + return NULL; + if (!PyArg_ParseTupleAndKeywords(tmpargs, kwds, "|n:product", kwlist, &repeat)) { + Py_DECREF(tmpargs); + return NULL; + } + Py_DECREF(tmpargs); + if (repeat < 0) { + PyErr_SetString(PyExc_ValueError, + "repeat argument cannot be negative"); return NULL; } - PyTuple_SET_ITEM(ittuple, i, it); } - /* create chainobject structure */ - lz = (chainobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(ittuple); - return NULL; + assert(PyTuple_Check(args)); + nargs = (repeat == 0) ? 0 : PyTuple_GET_SIZE(args); + npools = nargs * repeat; + + indices = PyMem_Malloc(npools * sizeof(Py_ssize_t)); + if (indices == NULL) { + PyErr_NoMemory(); + goto error; } - lz->ittuple = ittuple; - lz->iternum = 0; - lz->tuplesize = tuplesize; + pools = PyTuple_New(npools); + if (pools == NULL) + goto error; + + for (i=0; i < nargs ; ++i) { + PyObject *item = PyTuple_GET_ITEM(args, i); + PyObject *pool = PySequence_Tuple(item); + if (pool == NULL) + goto error; + PyTuple_SET_ITEM(pools, i, pool); + indices[i] = 0; + } + for ( ; i < npools; ++i) { + PyObject *pool = PyTuple_GET_ITEM(pools, i - nargs); + Py_INCREF(pool); + PyTuple_SET_ITEM(pools, i, pool); + indices[i] = 0; + } + + /* create productobject structure */ + lz = (productobject *)type->tp_alloc(type, 0); + if (lz == NULL) + goto error; + + lz->pools = pools; + lz->indices = indices; + lz->result = NULL; + lz->stopped = 0; return (PyObject *)lz; + +error: + if (indices != NULL) + PyMem_Free(indices); + Py_XDECREF(pools); + return NULL; } static void -chain_dealloc(chainobject *lz) +product_dealloc(productobject *lz) { PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->ittuple); + Py_XDECREF(lz->pools); + Py_XDECREF(lz->result); + PyMem_Free(lz->indices); Py_TYPE(lz)->tp_free(lz); } static int -chain_traverse(chainobject *lz, visitproc visit, void *arg) +product_traverse(productobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->ittuple); + Py_VISIT(lz->pools); + Py_VISIT(lz->result); return 0; } static PyObject * -chain_next(chainobject *lz) +product_next(productobject *lz) { - PyObject *it; - PyObject *item; + PyObject *pool; + PyObject *elem; + PyObject *oldelem; + PyObject *pools = lz->pools; + PyObject *result = lz->result; + Py_ssize_t npools = PyTuple_GET_SIZE(pools); + Py_ssize_t i; - while (lz->iternum < lz->tuplesize) { - it = PyTuple_GET_ITEM(lz->ittuple, lz->iternum); - item = PyIter_Next(it); - if (item != NULL) - return item; - if (PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - else - return NULL; + if (lz->stopped) + return NULL; + + if (result == NULL) { + /* On the first pass, return an initial tuple filled with the + first element from each pool. */ + result = PyTuple_New(npools); + if (result == NULL) + goto empty; + lz->result = result; + for (i=0; i < npools; i++) { + pool = PyTuple_GET_ITEM(pools, i); + if (PyTuple_GET_SIZE(pool) == 0) + goto empty; + elem = PyTuple_GET_ITEM(pool, 0); + Py_INCREF(elem); + PyTuple_SET_ITEM(result, i, elem); + } + } else { + Py_ssize_t *indices = lz->indices; + + /* Copy the previous result tuple or re-use it if available */ + if (Py_REFCNT(result) > 1) { + PyObject *old_result = result; + result = PyTuple_New(npools); + if (result == NULL) + goto empty; + lz->result = result; + for (i=0; i < npools; i++) { + elem = PyTuple_GET_ITEM(old_result, i); + Py_INCREF(elem); + PyTuple_SET_ITEM(result, i, elem); + } + Py_DECREF(old_result); } - lz->iternum++; + /* Now, we've got the only copy so we can update it in-place */ + assert (npools==0 || Py_REFCNT(result) == 1); + + /* Update the pool indices right-to-left. Only advance to the + next pool when the previous one rolls-over */ + for (i=npools-1 ; i >= 0 ; i--) { + pool = PyTuple_GET_ITEM(pools, i); + indices[i]++; + if (indices[i] == PyTuple_GET_SIZE(pool)) { + /* Roll-over and advance to next pool */ + indices[i] = 0; + elem = PyTuple_GET_ITEM(pool, 0); + Py_INCREF(elem); + oldelem = PyTuple_GET_ITEM(result, i); + PyTuple_SET_ITEM(result, i, elem); + Py_DECREF(oldelem); + } else { + /* No rollover. Just increment and stop here. */ + elem = PyTuple_GET_ITEM(pool, indices[i]); + Py_INCREF(elem); + oldelem = PyTuple_GET_ITEM(result, i); + PyTuple_SET_ITEM(result, i, elem); + Py_DECREF(oldelem); + break; + } + } + + /* If i is negative, then the indices have all rolled-over + and we're done. */ + if (i < 0) + goto empty; } + + Py_INCREF(result); + return result; + +empty: + lz->stopped = 1; return NULL; } -PyDoc_STRVAR(chain_doc, -"chain(*iterables) --> chain object\n\ +PyDoc_STRVAR(product_doc, +"product(*iterables) --> product object\n\ \n\ -Return a chain object whose .__next__() method returns elements from the\n\ -first iterable until it is exhausted, then elements from the next\n\ -iterable, until all of the iterables are exhausted."); +Cartesian product of input iterables. Equivalent to nested for-loops.\n\n\ +For example, product(A, B) returns the same as: ((x,y) for x in A for y in B).\n\ +The leftmost iterators are in the outermost for-loop, so the output tuples\n\ +cycle in a manner similar to an odometer (with the rightmost element changing\n\ +on every iteration).\n\n\ +product('ab', range(3)) --> ('a',0) ('a',1) ('a',2) ('b',0) ('b',1) ('b',2)\n\ +product((0,1), (0,1), (0,1)) --> (0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0) ..."); -static PyTypeObject chain_type = { +static PyTypeObject product_type = { PyVarObject_HEAD_INIT(NULL, 0) - "itertools.chain", /* tp_name */ - sizeof(chainobject), /* tp_basicsize */ + "itertools.product", /* tp_name */ + sizeof(productobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ - (destructor)chain_dealloc, /* tp_dealloc */ + (destructor)product_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ @@ -1689,13 +1821,13 @@ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ - chain_doc, /* tp_doc */ - (traverseproc)chain_traverse, /* tp_traverse */ + product_doc, /* tp_doc */ + (traverseproc)product_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ - (iternextfunc)chain_next, /* tp_iternext */ + (iternextfunc)product_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ @@ -1706,116 +1838,474 @@ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ - chain_new, /* tp_new */ + product_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; -/* ifilter object ************************************************************/ +/* combinations object ************************************************************/ typedef struct { PyObject_HEAD - PyObject *func; - PyObject *it; -} ifilterobject; + PyObject *pool; /* input converted to a tuple */ + Py_ssize_t *indices; /* one index per result element */ + PyObject *result; /* most recently returned result tuple */ + Py_ssize_t r; /* size of result tuple */ + int stopped; /* set to 1 when the combinations iterator is exhausted */ +} combinationsobject; + +static PyTypeObject combinations_type; + +static PyObject * +combinations_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + combinationsobject *co; + Py_ssize_t n; + Py_ssize_t r; + PyObject *pool = NULL; + PyObject *iterable = NULL; + Py_ssize_t *indices = NULL; + Py_ssize_t i; + static char *kwargs[] = {"iterable", "r", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations", kwargs, + &iterable, &r)) + return NULL; + + pool = PySequence_Tuple(iterable); + if (pool == NULL) + goto error; + n = PyTuple_GET_SIZE(pool); + if (r < 0) { + PyErr_SetString(PyExc_ValueError, "r must be non-negative"); + goto error; + } + if (r > n) { + PyErr_SetString(PyExc_ValueError, "r cannot be bigger than the iterable"); + goto error; + } + + indices = PyMem_Malloc(r * sizeof(Py_ssize_t)); + if (indices == NULL) { + PyErr_NoMemory(); + goto error; + } + + for (i=0 ; itp_alloc(type, 0); + if (co == NULL) + goto error; -static PyTypeObject ifilter_type; + co->pool = pool; + co->indices = indices; + co->result = NULL; + co->r = r; + co->stopped = 0; + + return (PyObject *)co; + +error: + if (indices != NULL) + PyMem_Free(indices); + Py_XDECREF(pool); + return NULL; +} + +static void +combinations_dealloc(combinationsobject *co) +{ + PyObject_GC_UnTrack(co); + Py_XDECREF(co->pool); + Py_XDECREF(co->result); + PyMem_Free(co->indices); + Py_TYPE(co)->tp_free(co); +} + +static int +combinations_traverse(combinationsobject *co, visitproc visit, void *arg) +{ + Py_VISIT(co->pool); + Py_VISIT(co->result); + return 0; +} static PyObject * -ifilter_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +combinations_next(combinationsobject *co) { - PyObject *func, *seq; - PyObject *it; - ifilterobject *lz; + PyObject *elem; + PyObject *oldelem; + PyObject *pool = co->pool; + Py_ssize_t *indices = co->indices; + PyObject *result = co->result; + Py_ssize_t n = PyTuple_GET_SIZE(pool); + Py_ssize_t r = co->r; + Py_ssize_t i, j, index; - if (type == &ifilter_type && !_PyArg_NoKeywords("ifilter()", kwds)) + if (co->stopped) return NULL; - if (!PyArg_UnpackTuple(args, "ifilter", 2, 2, &func, &seq)) - return NULL; + if (result == NULL) { + /* On the first pass, initialize result tuple using the indices */ + result = PyTuple_New(r); + if (result == NULL) + goto empty; + co->result = result; + for (i=0; i 1) { + PyObject *old_result = result; + result = PyTuple_New(r); + if (result == NULL) + goto empty; + co->result = result; + for (i=0; i= 0 && indices[i] == i+n-r ; i--) + ; + + /* If i is negative, then the indices are all at + their maximum value and we're done. */ + if (i < 0) + goto empty; + + /* Increment the current index which we know is not at its + maximum. Then move back to the right setting each index + to its lowest possible value (one higher than the index + to its left -- this maintains the sort order invariant). */ + indices[i]++; + for (j=i+1 ; jtp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(it); +empty: + co->stopped = 1; + return NULL; +} + +PyDoc_STRVAR(combinations_doc, +"combinations(iterables) --> combinations object\n\ +\n\ +Return successive r-length combinations of elements in the iterable.\n\n\ +combinations(range(4), 3) --> (0,1,2), (0,1,3), (0,2,3), (1,2,3)"); + +static PyTypeObject combinations_type = { + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.combinations", /* tp_name */ + sizeof(combinationsobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)combinations_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + combinations_doc, /* tp_doc */ + (traverseproc)combinations_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)combinations_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + combinations_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ +}; + + +/* permutations object ************************************************************ + +def permutations(iterable, r=None): + 'permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)' + pool = tuple(iterable) + n = len(pool) + r = n if r is None else r + indices = range(n) + cycles = range(n-r+1, n+1)[::-1] + yield tuple(pool[i] for i in indices[:r]) + while n: + for i in reversed(range(r)): + cycles[i] -= 1 + if cycles[i] == 0: + indices[i:] = indices[i+1:] + indices[i:i+1] + cycles[i] = n - i + else: + j = cycles[i] + indices[i], indices[-j] = indices[-j], indices[i] + yield tuple(pool[i] for i in indices[:r]) + break + else: + return +*/ + +typedef struct { + PyObject_HEAD + PyObject *pool; /* input converted to a tuple */ + Py_ssize_t *indices; /* one index per element in the pool */ + Py_ssize_t *cycles; /* one rollover counter per element in the result */ + PyObject *result; /* most recently returned result tuple */ + Py_ssize_t r; /* size of result tuple */ + int stopped; /* set to 1 when the permutations iterator is exhausted */ +} permutationsobject; + +static PyTypeObject permutations_type; + +static PyObject * +permutations_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + permutationsobject *po; + Py_ssize_t n; + Py_ssize_t r; + PyObject *robj = Py_None; + PyObject *pool = NULL; + PyObject *iterable = NULL; + Py_ssize_t *indices = NULL; + Py_ssize_t *cycles = NULL; + Py_ssize_t i; + static char *kwargs[] = {"iterable", "r", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:permutations", kwargs, + &iterable, &robj)) return NULL; - } - Py_INCREF(func); - lz->func = func; - lz->it = it; - return (PyObject *)lz; + pool = PySequence_Tuple(iterable); + if (pool == NULL) + goto error; + n = PyTuple_GET_SIZE(pool); + + r = n; + if (robj != Py_None) { + if (!PyLong_Check(robj)) { + PyErr_SetString(PyExc_TypeError, "Expected int as r"); + goto error; + } + r = PyLong_AsSsize_t(robj); + if (r == -1 && PyErr_Occurred()) + goto error; + } + if (r < 0) { + PyErr_SetString(PyExc_ValueError, "r must be non-negative"); + goto error; + } + if (r > n) { + PyErr_SetString(PyExc_ValueError, "r cannot be bigger than the iterable"); + goto error; + } + + indices = PyMem_Malloc(n * sizeof(Py_ssize_t)); + cycles = PyMem_Malloc(r * sizeof(Py_ssize_t)); + if (indices == NULL || cycles == NULL) { + PyErr_NoMemory(); + goto error; + } + + for (i=0 ; itp_alloc(type, 0); + if (po == NULL) + goto error; + + po->pool = pool; + po->indices = indices; + po->cycles = cycles; + po->result = NULL; + po->r = r; + po->stopped = 0; + + return (PyObject *)po; + +error: + if (indices != NULL) + PyMem_Free(indices); + if (cycles != NULL) + PyMem_Free(cycles); + Py_XDECREF(pool); + return NULL; } static void -ifilter_dealloc(ifilterobject *lz) +permutations_dealloc(permutationsobject *po) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->func); - Py_XDECREF(lz->it); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(po); + Py_XDECREF(po->pool); + Py_XDECREF(po->result); + PyMem_Free(po->indices); + PyMem_Free(po->cycles); + Py_TYPE(po)->tp_free(po); } static int -ifilter_traverse(ifilterobject *lz, visitproc visit, void *arg) +permutations_traverse(permutationsobject *po, visitproc visit, void *arg) { - Py_VISIT(lz->it); - Py_VISIT(lz->func); + Py_VISIT(po->pool); + Py_VISIT(po->result); return 0; } static PyObject * -ifilter_next(ifilterobject *lz) +permutations_next(permutationsobject *po) { - PyObject *item; - PyObject *it = lz->it; - long ok; - PyObject *(*iternext)(PyObject *); + PyObject *elem; + PyObject *oldelem; + PyObject *pool = po->pool; + Py_ssize_t *indices = po->indices; + Py_ssize_t *cycles = po->cycles; + PyObject *result = po->result; + Py_ssize_t n = PyTuple_GET_SIZE(pool); + Py_ssize_t r = po->r; + Py_ssize_t i, j, k, index; - assert(PyIter_Check(it)); - iternext = *Py_TYPE(it)->tp_iternext; - for (;;) { - item = iternext(it); - if (item == NULL) - return NULL; + if (po->stopped) + return NULL; - if (lz->func == Py_None) { - ok = PyObject_IsTrue(item); - } else { - PyObject *good; - good = PyObject_CallFunctionObjArgs(lz->func, - item, NULL); - if (good == NULL) { - Py_DECREF(item); - return NULL; + if (result == NULL) { + /* On the first pass, initialize result tuple using the indices */ + result = PyTuple_New(r); + if (result == NULL) + goto empty; + po->result = result; + for (i=0; i 1) { + PyObject *old_result = result; + result = PyTuple_New(r); + if (result == NULL) + goto empty; + po->result = result; + for (i=0; i=0 ; i--) { + cycles[i] -= 1; + if (cycles[i] == 0) { + /* rotatation: indices[i:] = indices[i+1:] + indices[i:i+1] */ + index = indices[i]; + for (j=i ; jstopped = 1; + return NULL; } -PyDoc_STRVAR(ifilter_doc, -"ifilter(function or None, sequence) --> ifilter object\n\ +PyDoc_STRVAR(permutations_doc, +"permutations(iterables[, r]) --> permutations object\n\ \n\ -Return those items of sequence for which function(item) is true.\n\ -If function is None, return the items that are true."); +Return successive r-length permutations of elements in the iterable.\n\n\ +permutations(range(4), 3) --> (0,1,2), (0,1,3), (0,2,3), (1,2,3)"); -static PyTypeObject ifilter_type = { +static PyTypeObject permutations_type = { PyVarObject_HEAD_INIT(NULL, 0) - "itertools.ifilter", /* tp_name */ - sizeof(ifilterobject), /* tp_basicsize */ + "itertools.permutations", /* tp_name */ + sizeof(permutationsobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ - (destructor)ifilter_dealloc, /* tp_dealloc */ + (destructor)permutations_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ @@ -1832,13 +2322,13 @@ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ - ifilter_doc, /* tp_doc */ - (traverseproc)ifilter_traverse, /* tp_traverse */ + permutations_doc, /* tp_doc */ + (traverseproc)permutations_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ - (iternextfunc)ifilter_next, /* tp_iternext */ + (iternextfunc)permutations_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ @@ -1849,33 +2339,33 @@ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ - ifilter_new, /* tp_new */ + permutations_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; -/* ifilterfalse object ************************************************************/ +/* filterfalse object ************************************************************/ typedef struct { PyObject_HEAD PyObject *func; PyObject *it; -} ifilterfalseobject; +} filterfalseobject; -static PyTypeObject ifilterfalse_type; +static PyTypeObject filterfalse_type; static PyObject * -ifilterfalse_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +filterfalse_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *func, *seq; PyObject *it; - ifilterfalseobject *lz; + filterfalseobject *lz; - if (type == &ifilterfalse_type && - !_PyArg_NoKeywords("ifilterfalse()", kwds)) + if (type == &filterfalse_type && + !_PyArg_NoKeywords("filterfalse()", kwds)) return NULL; - if (!PyArg_UnpackTuple(args, "ifilterfalse", 2, 2, &func, &seq)) + if (!PyArg_UnpackTuple(args, "filterfalse", 2, 2, &func, &seq)) return NULL; /* Get iterator. */ @@ -1883,8 +2373,8 @@ if (it == NULL) return NULL; - /* create ifilterfalseobject structure */ - lz = (ifilterfalseobject *)type->tp_alloc(type, 0); + /* create filterfalseobject structure */ + lz = (filterfalseobject *)type->tp_alloc(type, 0); if (lz == NULL) { Py_DECREF(it); return NULL; @@ -1897,7 +2387,7 @@ } static void -ifilterfalse_dealloc(ifilterfalseobject *lz) +filterfalse_dealloc(filterfalseobject *lz) { PyObject_GC_UnTrack(lz); Py_XDECREF(lz->func); @@ -1906,7 +2396,7 @@ } static int -ifilterfalse_traverse(ifilterfalseobject *lz, visitproc visit, void *arg) +filterfalse_traverse(filterfalseobject *lz, visitproc visit, void *arg) { Py_VISIT(lz->it); Py_VISIT(lz->func); @@ -1914,7 +2404,7 @@ } static PyObject * -ifilterfalse_next(ifilterfalseobject *lz) +filterfalse_next(filterfalseobject *lz) { PyObject *item; PyObject *it = lz->it; @@ -1928,7 +2418,7 @@ if (item == NULL) return NULL; - if (lz->func == Py_None) { + if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) { ok = PyObject_IsTrue(item); } else { PyObject *good; @@ -1947,19 +2437,19 @@ } } -PyDoc_STRVAR(ifilterfalse_doc, -"ifilterfalse(function or None, sequence) --> ifilterfalse object\n\ +PyDoc_STRVAR(filterfalse_doc, +"filterfalse(function or None, sequence) --> filterfalse object\n\ \n\ Return those items of sequence for which function(item) is false.\n\ If function is None, return the items that are false."); -static PyTypeObject ifilterfalse_type = { +static PyTypeObject filterfalse_type = { PyVarObject_HEAD_INIT(NULL, 0) - "itertools.ifilterfalse", /* tp_name */ - sizeof(ifilterfalseobject), /* tp_basicsize */ + "itertools.filterfalse", /* tp_name */ + sizeof(filterfalseobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ - (destructor)ifilterfalse_dealloc, /* tp_dealloc */ + (destructor)filterfalse_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ @@ -1976,13 +2466,13 @@ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ - ifilterfalse_doc, /* tp_doc */ - (traverseproc)ifilterfalse_traverse, /* tp_traverse */ + filterfalse_doc, /* tp_doc */ + (traverseproc)filterfalse_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ - (iternextfunc)ifilterfalse_next, /* tp_iternext */ + (iternextfunc)filterfalse_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ @@ -1993,7 +2483,7 @@ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ - ifilterfalse_new, /* tp_new */ + filterfalse_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; @@ -2147,193 +2637,6 @@ }; -/* izip object ************************************************************/ - -#include "Python.h" - -typedef struct { - PyObject_HEAD - Py_ssize_t tuplesize; - PyObject *ittuple; /* tuple of iterators */ - PyObject *result; -} izipobject; - -static PyTypeObject izip_type; - -static PyObject * -izip_new(PyTypeObject *type, PyObject *args, PyObject *kwds) -{ - izipobject *lz; - Py_ssize_t i; - PyObject *ittuple; /* tuple of iterators */ - PyObject *result; - Py_ssize_t tuplesize = PySequence_Length(args); - - if (type == &izip_type && !_PyArg_NoKeywords("izip()", kwds)) - return NULL; - - /* args must be a tuple */ - assert(PyTuple_Check(args)); - - /* obtain iterators */ - ittuple = PyTuple_New(tuplesize); - if (ittuple == NULL) - return NULL; - for (i=0; i < tuplesize; ++i) { - PyObject *item = PyTuple_GET_ITEM(args, i); - PyObject *it = PyObject_GetIter(item); - if (it == NULL) { - if (PyErr_ExceptionMatches(PyExc_TypeError)) - PyErr_Format(PyExc_TypeError, - "izip argument #%zd must support iteration", - i+1); - Py_DECREF(ittuple); - return NULL; - } - PyTuple_SET_ITEM(ittuple, i, it); - } - - /* create a result holder */ - result = PyTuple_New(tuplesize); - if (result == NULL) { - Py_DECREF(ittuple); - return NULL; - } - for (i=0 ; i < tuplesize ; i++) { - Py_INCREF(Py_None); - PyTuple_SET_ITEM(result, i, Py_None); - } - - /* create izipobject structure */ - lz = (izipobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(ittuple); - Py_DECREF(result); - return NULL; - } - lz->ittuple = ittuple; - lz->tuplesize = tuplesize; - lz->result = result; - - return (PyObject *)lz; -} - -static void -izip_dealloc(izipobject *lz) -{ - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->ittuple); - Py_XDECREF(lz->result); - Py_TYPE(lz)->tp_free(lz); -} - -static int -izip_traverse(izipobject *lz, visitproc visit, void *arg) -{ - Py_VISIT(lz->ittuple); - Py_VISIT(lz->result); - return 0; -} - -static PyObject * -izip_next(izipobject *lz) -{ - Py_ssize_t i; - Py_ssize_t tuplesize = lz->tuplesize; - PyObject *result = lz->result; - PyObject *it; - PyObject *item; - PyObject *olditem; - - if (tuplesize == 0) - return NULL; - if (Py_REFCNT(result) == 1) { - Py_INCREF(result); - for (i=0 ; i < tuplesize ; i++) { - it = PyTuple_GET_ITEM(lz->ittuple, i); - assert(PyIter_Check(it)); - item = (*Py_TYPE(it)->tp_iternext)(it); - if (item == NULL) { - Py_DECREF(result); - return NULL; - } - olditem = PyTuple_GET_ITEM(result, i); - PyTuple_SET_ITEM(result, i, item); - Py_DECREF(olditem); - } - } else { - result = PyTuple_New(tuplesize); - if (result == NULL) - return NULL; - for (i=0 ; i < tuplesize ; i++) { - it = PyTuple_GET_ITEM(lz->ittuple, i); - assert(PyIter_Check(it)); - item = (*Py_TYPE(it)->tp_iternext)(it); - if (item == NULL) { - Py_DECREF(result); - return NULL; - } - PyTuple_SET_ITEM(result, i, item); - } - } - return result; -} - -PyDoc_STRVAR(izip_doc, -"izip(iter1 [,iter2 [...]]) --> izip object\n\ -\n\ -Return a izip object whose .__next__() method returns a tuple where\n\ -the i-th element comes from the i-th iterable argument. The .__next__()\n\ -method continues until the shortest iterable in the argument sequence\n\ -is exhausted and then it raises StopIteration. Works like the zip()\n\ -function but consumes less memory by returning an iterator instead of\n\ -a list."); - -static PyTypeObject izip_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.izip", /* tp_name */ - sizeof(izipobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)izip_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - izip_doc, /* tp_doc */ - (traverseproc)izip_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)izip_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - izip_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ -}; - - /* repeat object ************************************************************/ typedef struct { @@ -2470,7 +2773,7 @@ PyObject_GC_Del, /* tp_free */ }; -/* iziplongest object ************************************************************/ +/* ziplongest object ************************************************************/ #include "Python.h" @@ -2481,14 +2784,14 @@ PyObject *ittuple; /* tuple of iterators */ PyObject *result; PyObject *fillvalue; -} iziplongestobject; +} ziplongestobject; -static PyTypeObject iziplongest_type; +static PyTypeObject ziplongest_type; static PyObject * -izip_longest_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +zip_longest_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - iziplongestobject *lz; + ziplongestobject *lz; Py_ssize_t i; PyObject *ittuple; /* tuple of iterators */ PyObject *result; @@ -2499,7 +2802,7 @@ fillvalue = PyDict_GetItemString(kwds, "fillvalue"); if (fillvalue == NULL || PyDict_Size(kwds) > 1) { PyErr_SetString(PyExc_TypeError, - "izip_longest() got an unexpected keyword argument"); + "zip_longest() got an unexpected keyword argument"); return NULL; } } @@ -2517,7 +2820,7 @@ if (it == NULL) { if (PyErr_ExceptionMatches(PyExc_TypeError)) PyErr_Format(PyExc_TypeError, - "izip_longest argument #%zd must support iteration", + "zip_longest argument #%zd must support iteration", i+1); Py_DECREF(ittuple); return NULL; @@ -2536,8 +2839,8 @@ PyTuple_SET_ITEM(result, i, Py_None); } - /* create iziplongestobject structure */ - lz = (iziplongestobject *)type->tp_alloc(type, 0); + /* create ziplongestobject structure */ + lz = (ziplongestobject *)type->tp_alloc(type, 0); if (lz == NULL) { Py_DECREF(ittuple); Py_DECREF(result); @@ -2553,7 +2856,7 @@ } static void -izip_longest_dealloc(iziplongestobject *lz) +zip_longest_dealloc(ziplongestobject *lz) { PyObject_GC_UnTrack(lz); Py_XDECREF(lz->ittuple); @@ -2563,7 +2866,7 @@ } static int -izip_longest_traverse(iziplongestobject *lz, visitproc visit, void *arg) +zip_longest_traverse(ziplongestobject *lz, visitproc visit, void *arg) { Py_VISIT(lz->ittuple); Py_VISIT(lz->result); @@ -2572,7 +2875,7 @@ } static PyObject * -izip_longest_next(iziplongestobject *lz) +zip_longest_next(ziplongestobject *lz) { Py_ssize_t i; Py_ssize_t tuplesize = lz->tuplesize; @@ -2643,10 +2946,10 @@ return result; } -PyDoc_STRVAR(izip_longest_doc, -"izip_longest(iter1 [,iter2 [...]], [fillvalue=None]) --> izip_longest object\n\ +PyDoc_STRVAR(zip_longest_doc, +"zip_longest(iter1 [,iter2 [...]], [fillvalue=None]) --> zip_longest object\n\ \n\ -Return an izip_longest object whose .__next__() method returns a tuple where\n\ +Return an zip_longest object whose .__next__() method returns a tuple where\n\ the i-th element comes from the i-th iterable argument. The .__next__()\n\ method continues until the longest iterable in the argument sequence\n\ is exhausted and then it raises StopIteration. When the shorter iterables\n\ @@ -2654,13 +2957,13 @@ defaults to None or can be specified by a keyword argument.\n\ "); -static PyTypeObject iziplongest_type = { +static PyTypeObject ziplongest_type = { PyVarObject_HEAD_INIT(NULL, 0) - "itertools.izip_longest", /* tp_name */ - sizeof(iziplongestobject), /* tp_basicsize */ + "itertools.zip_longest", /* tp_name */ + sizeof(ziplongestobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ - (destructor)izip_longest_dealloc, /* tp_dealloc */ + (destructor)zip_longest_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ @@ -2677,13 +2980,13 @@ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ - izip_longest_doc, /* tp_doc */ - (traverseproc)izip_longest_traverse, /* tp_traverse */ + zip_longest_doc, /* tp_doc */ + (traverseproc)zip_longest_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ - (iternextfunc)izip_longest_next, /* tp_iternext */ + (iternextfunc)zip_longest_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ @@ -2694,7 +2997,7 @@ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ - izip_longest_new, /* tp_new */ + zip_longest_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; @@ -2709,13 +3012,10 @@ repeat(elem [,n]) --> elem, elem, elem, ... endlessly or up to n times\n\ \n\ Iterators terminating on the shortest input sequence:\n\ -izip(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... \n\ -izip_longest(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... \n\ -ifilter(pred, seq) --> elements of seq where pred(elem) is True\n\ -ifilterfalse(pred, seq) --> elements of seq where pred(elem) is False\n\ +zip_longest(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... \n\ +filterfalse(pred, seq) --> elements of seq where pred(elem) is False\n\ islice(seq, [start,] stop [, step]) --> elements from\n\ seq[start:stop:step]\n\ -imap(fun, p, q, ...) --> fun(p0, q0), fun(p1, q1), ...\n\ starmap(fun, seq) --> fun(*seq[0]), fun(*seq[1]), ...\n\ tee(it, n=2) --> (it1, it2 , ... itn) splits one iterator into n\n\ chain(p, q, ...) --> p0, p1, ... plast, q0, q1, ... \n\ @@ -2737,18 +3037,18 @@ PyObject *m; char *name; PyTypeObject *typelist[] = { + &combinations_type, &cycle_type, &dropwhile_type, &takewhile_type, &islice_type, &starmap_type, - &imap_type, &chain_type, - &ifilter_type, - &ifilterfalse_type, + &filterfalse_type, &count_type, - &izip_type, - &iziplongest_type, + &ziplongest_type, + &permutations_type, + &product_type, &repeat_type, &groupby_type, NULL Modified: python/branches/py3k-ctypes-pep3118/Modules/main.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/main.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/main.c Wed Apr 30 15:57:13 2008 @@ -12,6 +12,7 @@ #include #ifdef HAVE_FCNTL_H #include +#define PATH_MAX MAXPATHLEN #endif #endif @@ -40,17 +41,17 @@ #endif /* For Py_GetArgcArgv(); set by main() */ -static char **orig_argv; +static wchar_t **orig_argv; static int orig_argc; /* command line options */ -#define BASE_OPTS "bBc:dEhim:OStuvVW:xX?" +#define BASE_OPTS L"bBc:dEhiJm:OStuvVW:xX?" #define PROGRAM_OPTS BASE_OPTS /* Short usage message (with %s for argv0) */ static char *usage_line = -"usage: %s [option] ... [-c cmd | -m mod | file | -] [arg] ...\n"; +"usage: %ls [option] ... [-c cmd | -m mod | file | -] [arg] ...\n"; /* Long usage message, split into parts < 512 bytes */ static char *usage_1 = "\ @@ -96,9 +97,30 @@ PYTHONCASEOK : ignore case in 'import' statements (Windows).\n\ "; +#ifndef MS_WINDOWS +static FILE* +_wfopen(const wchar_t *path, const wchar_t *mode) +{ + char cpath[PATH_MAX]; + char cmode[10]; + size_t r; + r = wcstombs(cpath, path, PATH_MAX); + if (r == (size_t)-1 || r >= PATH_MAX) { + errno = EINVAL; + return NULL; + } + r = wcstombs(cmode, mode, 10); + if (r == (size_t)-1 || r >= 10) { + errno = EINVAL; + return NULL; + } + return fopen(cpath, cmode); +} +#endif + static int -usage(int exitcode, char* program) +usage(int exitcode, wchar_t* program) { FILE *f = exitcode ? stderr : stdout; @@ -187,11 +209,11 @@ return 0; } -static int RunMainFromImporter(char *filename) +static int RunMainFromImporter(wchar_t *filename) { PyObject *argv0 = NULL, *importer = NULL; - if ((argv0 = PyUnicode_DecodeFSDefault(filename)) && + if ((argv0 = PyUnicode_FromWideChar(filename,wcslen(filename))) && (importer = PyImport_GetImporter(argv0)) && (importer->ob_type != &PyNullImporter_Type)) { @@ -249,12 +271,12 @@ /* Main program */ int -Py_Main(int argc, char **argv) +Py_Main(int argc, wchar_t **argv) { int c; int sts; char *command = NULL; - char *filename = NULL; + wchar_t *filename = NULL; char *module = NULL; FILE *fp = stdin; char *p; @@ -275,14 +297,19 @@ while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) { if (c == 'c') { + size_t r1 = wcslen(_PyOS_optarg) + 2; + size_t r2; /* -c is the last option; following arguments that look like options are left for the command to interpret. */ - command = (char *)malloc(strlen(_PyOS_optarg) + 2); + command = (char *)malloc(r1); if (command == NULL) Py_FatalError( "not enough memory to copy -c argument"); - strcpy(command, _PyOS_optarg); + r2 = wcstombs(command, _PyOS_optarg, r1); + if (r2 > r1-2) + Py_FatalError( + "not enough memory to copy -c argument"); strcat(command, "\n"); break; } @@ -291,11 +318,16 @@ /* -m is the last option; following arguments that look like options are left for the module to interpret. */ - module = (char *)malloc(strlen(_PyOS_optarg) + 2); + size_t r1 = wcslen(_PyOS_optarg) + 1; + size_t r2; + module = (char *)malloc(r1); if (module == NULL) Py_FatalError( "not enough memory to copy -m argument"); - strcpy(module, _PyOS_optarg); + r2 = wcstombs(module, _PyOS_optarg, r1); + if (r2 >= r1) + Py_FatalError( + "not enough memory to copy -m argument"); break; } @@ -313,6 +345,8 @@ Py_InteractiveFlag++; break; + /* case 'J': reserved for Jython */ + case 'O': Py_OptimizeFlag++; break; @@ -346,6 +380,8 @@ skipfirstline = 1; break; + /* case 'X': reserved for implementation-specific arguments */ + case 'h': case '?': help++; @@ -355,7 +391,7 @@ version++; break; - case 'W': + case 'W': PySys_AddWarnOption(_PyOS_optarg); break; @@ -384,7 +420,7 @@ unbuffered = 1; if (command == NULL && module == NULL && _PyOS_optind < argc && - strcmp(argv[_PyOS_optind], "-") != 0) + wcscmp(argv[_PyOS_optind], L"-") != 0) { #ifdef __VMS filename = decc$translate_vms(argv[_PyOS_optind]); @@ -462,14 +498,14 @@ if (command != NULL) { /* Backup _PyOS_optind and force sys.argv[0] = '-c' */ _PyOS_optind--; - argv[_PyOS_optind] = "-c"; + argv[_PyOS_optind] = L"-c"; } if (module != NULL) { /* Backup _PyOS_optind and force sys.argv[0] = '-c' so that PySys_SetArgv correctly sets sys.path[0] to ''*/ _PyOS_optind--; - argv[_PyOS_optind] = "-c"; + argv[_PyOS_optind] = L"-c"; } PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind); @@ -506,14 +542,10 @@ } if (sts==-1 && filename!=NULL) { - if ((fp = fopen(filename, "r")) == NULL) { -#ifdef HAVE_STRERROR - fprintf(stderr, "%s: can't open file '%s': [Errno %d] %s\n", + if ((fp = _wfopen(filename, L"r")) == NULL) { + fprintf(stderr, "%ls: can't open file '%ls': [Errno %d] %s\n", argv[0], filename, errno, strerror(errno)); -#else - fprintf(stderr, "%s: can't open file '%s': Errno %d\n", - argv[0], filename, errno); -#endif + return 2; } else if (skipfirstline) { @@ -532,7 +564,7 @@ struct stat sb; if (fstat(fileno(fp), &sb) == 0 && S_ISDIR(sb.st_mode)) { - fprintf(stderr, "%s: '%s' is a directory, cannot continue\n", argv[0], filename); + fprintf(stderr, "%ls: '%ls' is a directory, cannot continue\n", argv[0], filename); fclose(fp); return 1; } @@ -540,9 +572,17 @@ } if (sts==-1) { + char cfilename[PATH_MAX]; + char *p_cfilename = ""; + if (filename) { + size_t r = wcstombs(cfilename, filename, PATH_MAX); + p_cfilename = cfilename; + if (r == (size_t)-1 || r >= PATH_MAX) + p_cfilename = ""; + } sts = PyRun_AnyFileExFlags( fp, - filename == NULL ? "" : filename, + p_cfilename, filename != NULL, &cf) != 0; } @@ -593,7 +633,7 @@ This is rare, but it is needed by the secureware extension. */ void -Py_GetArgcArgv(int *argc, char ***argv) +Py_GetArgcArgv(int *argc, wchar_t ***argv) { *argc = orig_argc; *argv = orig_argv; Modified: python/branches/py3k-ctypes-pep3118/Modules/mathmodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/mathmodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/mathmodule.c Wed Apr 30 15:57:13 2008 @@ -1,17 +1,60 @@ /* Math module -- standard C math library functions, pi and e */ +/* Here are some comments from Tim Peters, extracted from the + discussion attached to http://bugs.python.org/issue1640. They + describe the general aims of the math module with respect to + special values, IEEE-754 floating-point exceptions, and Python + exceptions. + +These are the "spirit of 754" rules: + +1. If the mathematical result is a real number, but of magnitude too +large to approximate by a machine float, overflow is signaled and the +result is an infinity (with the appropriate sign). + +2. If the mathematical result is a real number, but of magnitude too +small to approximate by a machine float, underflow is signaled and the +result is a zero (with the appropriate sign). + +3. At a singularity (a value x such that the limit of f(y) as y +approaches x exists and is an infinity), "divide by zero" is signaled +and the result is an infinity (with the appropriate sign). This is +complicated a little by that the left-side and right-side limits may +not be the same; e.g., 1/x approaches +inf or -inf as x approaches 0 +from the positive or negative directions. In that specific case, the +sign of the zero determines the result of 1/0. + +4. At a point where a function has no defined result in the extended +reals (i.e., the reals plus an infinity or two), invalid operation is +signaled and a NaN is returned. + +And these are what Python has historically /tried/ to do (but not +always successfully, as platform libm behavior varies a lot): + +For #1, raise OverflowError. + +For #2, return a zero (with the appropriate sign if that happens by +accident ;-)). + +For #3 and #4, raise ValueError. It may have made sense to raise +Python's ZeroDivisionError in #3, but historically that's only been +raised for division by zero and mod by zero. + +*/ + +/* + In general, on an IEEE-754 platform the aim is to follow the C99 + standard, including Annex 'F', whenever possible. Where the + standard recommends raising the 'divide-by-zero' or 'invalid' + floating-point exceptions, Python should raise a ValueError. Where + the standard recommends raising 'overflow', Python should raise an + OverflowError. In all other circumstances a value should be + returned. + */ + #include "Python.h" #include "longintrepr.h" /* just for SHIFT */ -#ifndef _MSC_VER -#ifndef __STDC__ -extern double fmod (double, double); -extern double frexp (double, int *); -extern double ldexp (double, int); -extern double modf (double, double *); -#endif /* __STDC__ */ -#endif /* _MSC_VER */ - #ifdef _OSF_SOURCE /* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */ extern double copysign(double, double); @@ -52,41 +95,147 @@ return result; } +/* + wrapper for atan2 that deals directly with special cases before + delegating to the platform libm for the remaining cases. This + is necessary to get consistent behaviour across platforms. + Windows, FreeBSD and alpha Tru64 are amongst platforms that don't + always follow C99. +*/ + +static double +m_atan2(double y, double x) +{ + if (Py_IS_NAN(x) || Py_IS_NAN(y)) + return Py_NAN; + if (Py_IS_INFINITY(y)) { + if (Py_IS_INFINITY(x)) { + if (copysign(1., x) == 1.) + /* atan2(+-inf, +inf) == +-pi/4 */ + return copysign(0.25*Py_MATH_PI, y); + else + /* atan2(+-inf, -inf) == +-pi*3/4 */ + return copysign(0.75*Py_MATH_PI, y); + } + /* atan2(+-inf, x) == +-pi/2 for finite x */ + return copysign(0.5*Py_MATH_PI, y); + } + if (Py_IS_INFINITY(x) || y == 0.) { + if (copysign(1., x) == 1.) + /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */ + return copysign(0., y); + else + /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */ + return copysign(Py_MATH_PI, y); + } + return atan2(y, x); +} + +/* + math_1 is used to wrap a libm function f that takes a double + arguments and returns a double. + + The error reporting follows these rules, which are designed to do + the right thing on C89/C99 platforms and IEEE 754/non IEEE 754 + platforms. + + - a NaN result from non-NaN inputs causes ValueError to be raised + - an infinite result from finite inputs causes OverflowError to be + raised if can_overflow is 1, or raises ValueError if can_overflow + is 0. + - if the result is finite and errno == EDOM then ValueError is + raised + - if the result is finite and nonzero and errno == ERANGE then + OverflowError is raised + + The last rule is used to catch overflow on platforms which follow + C89 but for which HUGE_VAL is not an infinity. + + For the majority of one-argument functions these rules are enough + to ensure that Python's functions behave as specified in 'Annex F' + of the C99 standard, with the 'invalid' and 'divide-by-zero' + floating-point exceptions mapping to Python's ValueError and the + 'overflow' floating-point exception mapping to OverflowError. + math_1 only works for functions that don't have singularities *and* + the possibility of overflow; fortunately, that covers everything we + care about right now. +*/ + static PyObject * math_1_to_whatever(PyObject *arg, double (*func) (double), - PyObject *(*from_double_func) (double)) + PyObject *(*from_double_func) (double), + int can_overflow) { - double x = PyFloat_AsDouble(arg); + double x, r; + x = PyFloat_AsDouble(arg); if (x == -1.0 && PyErr_Occurred()) return NULL; errno = 0; - PyFPE_START_PROTECT("in math_1", return 0) - x = (*func)(x); - PyFPE_END_PROTECT(x) - Py_SET_ERRNO_ON_MATH_ERROR(x); - if (errno && is_error(x)) + PyFPE_START_PROTECT("in math_1", return 0); + r = (*func)(x); + PyFPE_END_PROTECT(r); + if (Py_IS_NAN(r)) { + if (!Py_IS_NAN(x)) + errno = EDOM; + else + errno = 0; + } + else if (Py_IS_INFINITY(r)) { + if (Py_IS_FINITE(x)) + errno = can_overflow ? ERANGE : EDOM; + else + errno = 0; + } + if (errno && is_error(r)) return NULL; else - return (*from_double_func)(x); + return (*from_double_func)(r); } +/* + math_2 is used to wrap a libm function f that takes two double + arguments and returns a double. + + The error reporting follows these rules, which are designed to do + the right thing on C89/C99 platforms and IEEE 754/non IEEE 754 + platforms. + + - a NaN result from non-NaN inputs causes ValueError to be raised + - an infinite result from finite inputs causes OverflowError to be + raised. + - if the result is finite and errno == EDOM then ValueError is + raised + - if the result is finite and nonzero and errno == ERANGE then + OverflowError is raised + + The last rule is used to catch overflow on platforms which follow + C89 but for which HUGE_VAL is not an infinity. + + For most two-argument functions (copysign, fmod, hypot, atan2) + these rules are enough to ensure that Python's functions behave as + specified in 'Annex F' of the C99 standard, with the 'invalid' and + 'divide-by-zero' floating-point exceptions mapping to Python's + ValueError and the 'overflow' floating-point exception mapping to + OverflowError. +*/ + static PyObject * -math_1(PyObject *arg, double (*func) (double)) +math_1(PyObject *arg, double (*func) (double), int can_overflow) { - return math_1_to_whatever(arg, func, PyFloat_FromDouble); + return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow); } static PyObject * -math_1_to_int(PyObject *arg, double (*func) (double)) +math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow) { - return math_1_to_whatever(arg, func, PyLong_FromDouble); + return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow); } static PyObject * math_2(PyObject *args, double (*func) (double, double), char *funcname) { PyObject *ox, *oy; - double x, y; + double x, y, r; if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy)) return NULL; x = PyFloat_AsDouble(ox); @@ -94,19 +243,30 @@ if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) return NULL; errno = 0; - PyFPE_START_PROTECT("in math_2", return 0) - x = (*func)(x, y); - PyFPE_END_PROTECT(x) - Py_SET_ERRNO_ON_MATH_ERROR(x); - if (errno && is_error(x)) + PyFPE_START_PROTECT("in math_2", return 0); + r = (*func)(x, y); + PyFPE_END_PROTECT(r); + if (Py_IS_NAN(r)) { + if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) + errno = EDOM; + else + errno = 0; + } + else if (Py_IS_INFINITY(r)) { + if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) + errno = ERANGE; + else + errno = 0; + } + if (errno && is_error(r)) return NULL; else - return PyFloat_FromDouble(x); + return PyFloat_FromDouble(r); } -#define FUNC1(funcname, func, docstring) \ +#define FUNC1(funcname, func, can_overflow, docstring) \ static PyObject * math_##funcname(PyObject *self, PyObject *args) { \ - return math_1(args, func); \ + return math_1(args, func, can_overflow); \ }\ PyDoc_STRVAR(math_##funcname##_doc, docstring); @@ -116,29 +276,35 @@ }\ PyDoc_STRVAR(math_##funcname##_doc, docstring); -FUNC1(acos, acos, +FUNC1(acos, acos, 0, "acos(x)\n\nReturn the arc cosine (measured in radians) of x.") -FUNC1(asin, asin, +FUNC1(acosh, acosh, 0, + "acosh(x)\n\nReturn the hyperbolic arc cosine (measured in radians) of x.") +FUNC1(asin, asin, 0, "asin(x)\n\nReturn the arc sine (measured in radians) of x.") -FUNC1(atan, atan, +FUNC1(asinh, asinh, 0, + "asinh(x)\n\nReturn the hyperbolic arc sine (measured in radians) of x.") +FUNC1(atan, atan, 0, "atan(x)\n\nReturn the arc tangent (measured in radians) of x.") -FUNC2(atan2, atan2, +FUNC2(atan2, m_atan2, "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n" "Unlike atan(y/x), the signs of both x and y are considered.") +FUNC1(atanh, atanh, 0, + "atanh(x)\n\nReturn the hyperbolic arc tangent (measured in radians) of x.") static PyObject * math_ceil(PyObject *self, PyObject *number) { static PyObject *ceil_str = NULL; PyObject *method; if (ceil_str == NULL) { - ceil_str = PyUnicode_FromString("__ceil__"); + ceil_str = PyUnicode_InternFromString("__ceil__"); if (ceil_str == NULL) return NULL; } method = _PyType_Lookup(Py_TYPE(number), ceil_str); if (method == NULL) - return math_1_to_int(number, ceil); + return math_1_to_int(number, ceil, 0); else return PyObject_CallFunction(method, "O", number); } @@ -147,23 +313,15 @@ "ceil(x)\n\nReturn the ceiling of x as an int.\n" "This is the smallest integral value >= x."); -FUNC1(cos, cos, +FUNC2(copysign, copysign, + "copysign(x,y)\n\nReturn x with the sign of y.") +FUNC1(cos, cos, 0, "cos(x)\n\nReturn the cosine of x (measured in radians).") -FUNC1(cosh, cosh, +FUNC1(cosh, cosh, 1, "cosh(x)\n\nReturn the hyperbolic cosine of x.") - -#ifdef MS_WINDOWS -# define copysign _copysign -# define HAVE_COPYSIGN 1 -#endif -#ifdef HAVE_COPYSIGN -FUNC2(copysign, copysign, - "copysign(x,y)\n\nReturn x with the sign of y."); -#endif - -FUNC1(exp, exp, +FUNC1(exp, exp, 1, "exp(x)\n\nReturn e raised to the power of x.") -FUNC1(fabs, fabs, +FUNC1(fabs, fabs, 0, "fabs(x)\n\nReturn the absolute value of the float x.") static PyObject * math_floor(PyObject *self, PyObject *number) { @@ -171,14 +329,14 @@ PyObject *method; if (floor_str == NULL) { - floor_str = PyUnicode_FromString("__floor__"); + floor_str = PyUnicode_InternFromString("__floor__"); if (floor_str == NULL) return NULL; } method = _PyType_Lookup(Py_TYPE(number), floor_str); if (method == NULL) - return math_1_to_int(number, floor); + return math_1_to_int(number, floor, 0); else return PyObject_CallFunction(method, "O", number); } @@ -187,38 +345,70 @@ "floor(x)\n\nReturn the floor of x as an int.\n" "This is the largest integral value <= x."); -FUNC2(fmod, fmod, - "fmod(x,y)\n\nReturn fmod(x, y), according to platform C." - " x % y may differ.") -FUNC2(hypot, hypot, - "hypot(x,y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).") -FUNC2(pow, pow, - "pow(x,y)\n\nReturn x**y (x to the power of y).") -FUNC1(sin, sin, +FUNC1(log1p, log1p, 1, + "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n\ + The result is computed in a way which is accurate for x near zero.") +FUNC1(sin, sin, 0, "sin(x)\n\nReturn the sine of x (measured in radians).") -FUNC1(sinh, sinh, +FUNC1(sinh, sinh, 1, "sinh(x)\n\nReturn the hyperbolic sine of x.") -FUNC1(sqrt, sqrt, +FUNC1(sqrt, sqrt, 0, "sqrt(x)\n\nReturn the square root of x.") -FUNC1(tan, tan, +FUNC1(tan, tan, 0, "tan(x)\n\nReturn the tangent of x (measured in radians).") -FUNC1(tanh, tanh, +FUNC1(tanh, tanh, 0, "tanh(x)\n\nReturn the hyperbolic tangent of x.") static PyObject * +math_trunc(PyObject *self, PyObject *number) +{ + static PyObject *trunc_str = NULL; + PyObject *trunc; + + if (Py_TYPE(number)->tp_dict == NULL) { + if (PyType_Ready(Py_TYPE(number)) < 0) + return NULL; + } + + if (trunc_str == NULL) { + trunc_str = PyUnicode_InternFromString("__trunc__"); + if (trunc_str == NULL) + return NULL; + } + + trunc = _PyType_Lookup(Py_TYPE(number), trunc_str); + if (trunc == NULL) { + PyErr_Format(PyExc_TypeError, + "type %.100s doesn't define __trunc__ method", + Py_TYPE(number)->tp_name); + return NULL; + } + return PyObject_CallFunctionObjArgs(trunc, number, NULL); +} + +PyDoc_STRVAR(math_trunc_doc, +"trunc(x:Real) -> Integral\n" +"\n" +"Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method."); + +static PyObject * math_frexp(PyObject *self, PyObject *arg) { int i; double x = PyFloat_AsDouble(arg); if (x == -1.0 && PyErr_Occurred()) return NULL; - errno = 0; - x = frexp(x, &i); - Py_SET_ERRNO_ON_MATH_ERROR(x); - if (errno && is_error(x)) - return NULL; - else - return Py_BuildValue("(di)", x, i); + /* deal with special cases directly, to sidestep platform + differences */ + if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) { + i = 0; + } + else { + PyFPE_START_PROTECT("in math_frexp", return 0); + x = frexp(x, &i); + PyFPE_END_PROTECT(x); + } + return Py_BuildValue("(di)", x, i); } PyDoc_STRVAR(math_frexp_doc, @@ -231,19 +421,24 @@ static PyObject * math_ldexp(PyObject *self, PyObject *args) { - double x; + double x, r; int exp; if (! PyArg_ParseTuple(args, "di:ldexp", &x, &exp)) return NULL; errno = 0; - PyFPE_START_PROTECT("ldexp", return 0) - x = ldexp(x, exp); - PyFPE_END_PROTECT(x) - Py_SET_ERRNO_ON_MATH_ERROR(x); - if (errno && is_error(x)) + PyFPE_START_PROTECT("in math_ldexp", return 0) + r = ldexp(x, exp); + PyFPE_END_PROTECT(r) + if (Py_IS_FINITE(x) && Py_IS_INFINITY(r)) + errno = ERANGE; + /* Windows MSVC8 sets errno = EDOM on ldexp(NaN, i); + we unset it to avoid raising a ValueError here. */ + if (errno == EDOM) + errno = 0; + if (errno && is_error(r)) return NULL; else - return PyFloat_FromDouble(x); + return PyFloat_FromDouble(r); } PyDoc_STRVAR(math_ldexp_doc, @@ -255,13 +450,20 @@ double y, x = PyFloat_AsDouble(arg); if (x == -1.0 && PyErr_Occurred()) return NULL; + /* some platforms don't do the right thing for NaNs and + infinities, so we take care of special cases directly. */ + if (!Py_IS_FINITE(x)) { + if (Py_IS_INFINITY(x)) + return Py_BuildValue("(dd)", copysign(0., x), x); + else if (Py_IS_NAN(x)) + return Py_BuildValue("(dd)", x, x); + } + errno = 0; + PyFPE_START_PROTECT("in math_modf", return 0); x = modf(x, &y); - Py_SET_ERRNO_ON_MATH_ERROR(x); - if (errno && is_error(x)) - return NULL; - else - return Py_BuildValue("(dd)", x, y); + PyFPE_END_PROTECT(x); + return Py_BuildValue("(dd)", x, y); } PyDoc_STRVAR(math_modf_doc, @@ -291,16 +493,16 @@ "math domain error"); return NULL; } - /* Value is ~= x * 2**(e*SHIFT), so the log ~= - log(x) + log(2) * e * SHIFT. - CAUTION: e*SHIFT may overflow using int arithmetic, + /* Value is ~= x * 2**(e*PyLong_SHIFT), so the log ~= + log(x) + log(2) * e * PyLong_SHIFT. + CAUTION: e*PyLong_SHIFT may overflow using int arithmetic, so force use of double. */ x = func(x) + (e * (double)PyLong_SHIFT) * func(2.0); return PyFloat_FromDouble(x); } /* Else let libm handle it by itself. */ - return math_1(arg, func); + return math_1(arg, func, 0); } static PyObject * @@ -343,6 +545,167 @@ PyDoc_STRVAR(math_log10_doc, "log10(x) -> the base 10 logarithm of x."); +static PyObject * +math_fmod(PyObject *self, PyObject *args) +{ + PyObject *ox, *oy; + double r, x, y; + if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy)) + return NULL; + x = PyFloat_AsDouble(ox); + y = PyFloat_AsDouble(oy); + if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) + return NULL; + /* fmod(x, +/-Inf) returns x for finite x. */ + if (Py_IS_INFINITY(y) && Py_IS_FINITE(x)) + return PyFloat_FromDouble(x); + errno = 0; + PyFPE_START_PROTECT("in math_fmod", return 0); + r = fmod(x, y); + PyFPE_END_PROTECT(r); + if (Py_IS_NAN(r)) { + if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) + errno = EDOM; + else + errno = 0; + } + if (errno && is_error(r)) + return NULL; + else + return PyFloat_FromDouble(r); +} + +PyDoc_STRVAR(math_fmod_doc, +"fmod(x,y)\n\nReturn fmod(x, y), according to platform C." +" x % y may differ."); + +static PyObject * +math_hypot(PyObject *self, PyObject *args) +{ + PyObject *ox, *oy; + double r, x, y; + if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy)) + return NULL; + x = PyFloat_AsDouble(ox); + y = PyFloat_AsDouble(oy); + if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) + return NULL; + /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */ + if (Py_IS_INFINITY(x)) + return PyFloat_FromDouble(fabs(x)); + if (Py_IS_INFINITY(y)) + return PyFloat_FromDouble(fabs(y)); + errno = 0; + PyFPE_START_PROTECT("in math_hypot", return 0); + r = hypot(x, y); + PyFPE_END_PROTECT(r); + if (Py_IS_NAN(r)) { + if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) + errno = EDOM; + else + errno = 0; + } + else if (Py_IS_INFINITY(r)) { + if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) + errno = ERANGE; + else + errno = 0; + } + if (errno && is_error(r)) + return NULL; + else + return PyFloat_FromDouble(r); +} + +PyDoc_STRVAR(math_hypot_doc, +"hypot(x,y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y)."); + +/* pow can't use math_2, but needs its own wrapper: the problem is + that an infinite result can arise either as a result of overflow + (in which case OverflowError should be raised) or as a result of + e.g. 0.**-5. (for which ValueError needs to be raised.) +*/ + +static PyObject * +math_pow(PyObject *self, PyObject *args) +{ + PyObject *ox, *oy; + double r, x, y; + int odd_y; + + if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy)) + return NULL; + x = PyFloat_AsDouble(ox); + y = PyFloat_AsDouble(oy); + if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) + return NULL; + + /* deal directly with IEEE specials, to cope with problems on various + platforms whose semantics don't exactly match C99 */ + if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) { + errno = 0; + if (Py_IS_NAN(x)) + r = y == 0. ? 1. : x; /* NaN**0 = 1 */ + else if (Py_IS_NAN(y)) + r = x == 1. ? 1. : y; /* 1**NaN = 1 */ + else if (Py_IS_INFINITY(x)) { + odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0; + if (y > 0.) + r = odd_y ? x : fabs(x); + else if (y == 0.) + r = 1.; + else /* y < 0. */ + r = odd_y ? copysign(0., x) : 0.; + } + else if (Py_IS_INFINITY(y)) { + if (fabs(x) == 1.0) + r = 1.; + else if (y > 0. && fabs(x) > 1.0) + r = y; + else if (y < 0. && fabs(x) < 1.0) { + r = -y; /* result is +inf */ + if (x == 0.) /* 0**-inf: divide-by-zero */ + errno = EDOM; + } + else + r = 0.; + } + } + else { + /* let libm handle finite**finite */ + errno = 0; + PyFPE_START_PROTECT("in math_pow", return 0); + r = pow(x, y); + PyFPE_END_PROTECT(r); + /* a NaN result should arise only from (-ve)**(finite + non-integer); in this case we want to raise ValueError. */ + if (!Py_IS_FINITE(r)) { + if (Py_IS_NAN(r)) { + errno = EDOM; + } + /* + an infinite result here arises either from: + (A) (+/-0.)**negative (-> divide-by-zero) + (B) overflow of x**y with x and y finite + */ + else if (Py_IS_INFINITY(r)) { + if (x == 0.) + errno = EDOM; + else + errno = ERANGE; + } + } + } + + if (errno && is_error(r)) + return NULL; + else + return PyFloat_FromDouble(r); +} + +PyDoc_STRVAR(math_pow_doc, +"pow(x,y)\n\nReturn x**y (x to the power of y)."); + static const double degToRad = Py_MATH_PI / 180.0; static const double radToDeg = 180.0 / Py_MATH_PI; @@ -396,16 +759,16 @@ "isinf(x) -> bool\n\ Checks if float x is infinite (positive or negative)"); - static PyMethodDef math_methods[] = { {"acos", math_acos, METH_O, math_acos_doc}, + {"acosh", math_acosh, METH_O, math_acosh_doc}, {"asin", math_asin, METH_O, math_asin_doc}, + {"asinh", math_asinh, METH_O, math_asinh_doc}, {"atan", math_atan, METH_O, math_atan_doc}, {"atan2", math_atan2, METH_VARARGS, math_atan2_doc}, + {"atanh", math_atanh, METH_O, math_atanh_doc}, {"ceil", math_ceil, METH_O, math_ceil_doc}, -#ifdef HAVE_COPYSIGN {"copysign", math_copysign, METH_VARARGS, math_copysign_doc}, -#endif {"cos", math_cos, METH_O, math_cos_doc}, {"cosh", math_cosh, METH_O, math_cosh_doc}, {"degrees", math_degrees, METH_O, math_degrees_doc}, @@ -419,6 +782,7 @@ {"isnan", math_isnan, METH_O, math_isnan_doc}, {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc}, {"log", math_log, METH_VARARGS, math_log_doc}, + {"log1p", math_log1p, METH_O, math_log1p_doc}, {"log10", math_log10, METH_O, math_log10_doc}, {"modf", math_modf, METH_O, math_modf_doc}, {"pow", math_pow, METH_VARARGS, math_pow_doc}, @@ -428,6 +792,7 @@ {"sqrt", math_sqrt, METH_O, math_sqrt_doc}, {"tan", math_tan, METH_O, math_tan_doc}, {"tanh", math_tanh, METH_O, math_tanh_doc}, + {"trunc", math_trunc, METH_O, math_trunc_doc}, {NULL, NULL} /* sentinel */ }; @@ -439,27 +804,15 @@ PyMODINIT_FUNC initmath(void) { - PyObject *m, *d, *v; + PyObject *m; m = Py_InitModule3("math", math_methods, module_doc); if (m == NULL) goto finally; - d = PyModule_GetDict(m); - if (d == NULL) - goto finally; - if (!(v = PyFloat_FromDouble(Py_MATH_PI))) - goto finally; - if (PyDict_SetItemString(d, "pi", v) < 0) - goto finally; - Py_DECREF(v); - - if (!(v = PyFloat_FromDouble(Py_MATH_E))) - goto finally; - if (PyDict_SetItemString(d, "e", v) < 0) - goto finally; - Py_DECREF(v); + PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI)); + PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E)); - finally: + finally: return; } Modified: python/branches/py3k-ctypes-pep3118/Modules/mmapmodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/mmapmodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/mmapmodule.c Wed Apr 30 15:57:13 2008 @@ -259,8 +259,8 @@ int reverse) { Py_ssize_t start = self->pos; - Py_ssize_t end = self->size; - char *needle; + Py_ssize_t end = self->size; + const char *needle; Py_ssize_t len; CHECK_VALID(NULL); @@ -268,8 +268,8 @@ &needle, &len, &start, &end)) { return NULL; } else { - char *p; - char sign = reverse ? -1 : 1; + const char *p, *start_p, *end_p; + int sign = reverse ? -1 : 1; if (start < 0) start += self->size; @@ -285,11 +285,11 @@ else if ((size_t)end > self->size) end = self->size; - start += (Py_ssize_t)self->data; - end += (Py_ssize_t)self->data; + start_p = self->data + start; + end_p = self->data + end; - for (p = (char *)(reverse ? end - len : start); - p >= (char *)start && p + len <= (char *)end; p+=sign) { + for (p = (reverse ? end_p - len : start_p); + (p >= start_p) && (p + len <= end_p); p += sign) { Py_ssize_t i; for (i = 0; i < len && needle[i] == p[i]; ++i) /* nothing */; @@ -543,23 +543,21 @@ if ((size_t)(offset + size) > self->size) { PyErr_SetString(PyExc_ValueError, "flush values out of range"); return NULL; - } else { + } #ifdef MS_WINDOWS - return PyLong_FromLong((long) - FlushViewOfFile(self->data+offset, size)); -#endif /* MS_WINDOWS */ -#ifdef UNIX - /* XXX semantics of return value? */ - /* XXX flags for msync? */ - if (-1 == msync(self->data + offset, size, - MS_SYNC)) - { - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } - return PyLong_FromLong(0); -#endif /* UNIX */ + return PyLong_FromLong((long) FlushViewOfFile(self->data+offset, size)); +#elif defined(UNIX) + /* XXX semantics of return value? */ + /* XXX flags for msync? */ + if (-1 == msync(self->data + offset, size, MS_SYNC)) { + PyErr_SetFromErrno(mmap_module_error); + return NULL; } + return PyLong_FromLong(0); +#else + PyErr_SetString(PyExc_ValueError, "flush not supported on this system"); + return NULL; +#endif } static PyObject * @@ -1045,6 +1043,10 @@ "mmap invalid access parameter."); } + if (prot == PROT_READ) { + access = ACCESS_READ; + } + #ifdef HAVE_FSTAT # ifdef __VMS /* on OpenVMS we must ensure that all bytes are written to the file */ @@ -1324,7 +1326,10 @@ dict = PyModule_GetDict(module); if (!dict) return; - mmap_module_error = PyExc_EnvironmentError; + mmap_module_error = PyErr_NewException("mmap.error", + PyExc_EnvironmentError , NULL); + if (mmap_module_error == NULL) + return; PyDict_SetItemString(dict, "error", mmap_module_error); PyDict_SetItemString(dict, "mmap", (PyObject*) &mmap_object_type); #ifdef PROT_EXEC Modified: python/branches/py3k-ctypes-pep3118/Modules/operator.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/operator.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/operator.c Wed Apr 30 15:57:13 2008 @@ -160,47 +160,6 @@ return result; } -static PyObject* -op_getslice(PyObject *s, PyObject *a) -{ - PyObject *a1; - Py_ssize_t a2, a3; - - if (!PyArg_ParseTuple(a, "Onn:getslice", &a1, &a2, &a3)) - return NULL; - return PySequence_GetSlice(a1, a2, a3); -} - -static PyObject* -op_setslice(PyObject *s, PyObject *a) -{ - PyObject *a1, *a4; - Py_ssize_t a2, a3; - - if (!PyArg_ParseTuple(a, "OnnO:setslice", &a1, &a2, &a3, &a4)) - return NULL; - - if (-1 == PySequence_SetSlice(a1, a2, a3, a4)) - return NULL; - - Py_RETURN_NONE; -} - -static PyObject* -op_delslice(PyObject *s, PyObject *a) -{ - PyObject *a1; - Py_ssize_t a2, a3; - - if (!PyArg_ParseTuple(a, "Onn:delslice", &a1, &a2, &a3)) - return NULL; - - if (-1 == PySequence_DelSlice(a1, a2, a3)) - return NULL; - - Py_RETURN_NONE; -} - #undef spam1 #undef spam2 #undef spam1o @@ -276,12 +235,6 @@ "delitem(a, b) -- Same as del a[b].") spam2(pow,__pow__, "pow(a, b) -- Same as a ** b.") spam2(ipow,__ipow__, "ipow(a, b) -- Same as a **= b.") -spam2(getslice,__getslice__, - "getslice(a, b, c) -- Same as a[b:c].") -spam2(setslice,__setslice__, -"setslice(a, b, c, d) -- Same as a[b:c] = d.") -spam2(delslice,__delslice__, -"delslice(a, b, c) -- Same as del a[b:c].") spam2(lt,__lt__, "lt(a, b) -- Same as anattrs == 1) - return PyObject_GetAttr(obj, ag->attr); + return dotted_getattr(obj, ag->attr); assert(PyTuple_Check(ag->attr)); assert(PyTuple_GET_SIZE(ag->attr) == nattrs); @@ -506,7 +494,7 @@ for (i=0 ; i < nattrs ; i++) { PyObject *attr, *val; attr = PyTuple_GET_ITEM(ag->attr, i); - val = PyObject_GetAttr(obj, attr); + val = dotted_getattr(obj, attr); if (val == NULL) { Py_DECREF(result); return NULL; @@ -521,7 +509,9 @@ \n\ Return a callable object that fetches the given attribute(s) from its operand.\n\ After, f=attrgetter('name'), the call f(r) returns r.name.\n\ -After, g=attrgetter('name', 'date'), the call g(r) returns (r.name, r.date)."); +After, g=attrgetter('name', 'date'), the call g(r) returns (r.name, r.date).\n\ +After, h=attrgetter('name.first', 'name.last'), the call h(r) returns\n\ +(r.name.first, r.name.last)."); static PyTypeObject attrgetter_type = { PyVarObject_HEAD_INIT(NULL, 0) @@ -565,6 +555,139 @@ attrgetter_new, /* tp_new */ 0, /* tp_free */ }; + + +/* methodcaller object **********************************************************/ + +typedef struct { + PyObject_HEAD + PyObject *name; + PyObject *args; + PyObject *kwds; +} methodcallerobject; + +static PyTypeObject methodcaller_type; + +static PyObject * +methodcaller_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + methodcallerobject *mc; + PyObject *name, *newargs; + + if (PyTuple_GET_SIZE(args) < 1) { + PyErr_SetString(PyExc_TypeError, "methodcaller needs at least " + "one argument, the method name"); + return NULL; + } + + /* create methodcallerobject structure */ + mc = PyObject_GC_New(methodcallerobject, &methodcaller_type); + if (mc == NULL) + return NULL; + + newargs = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args)); + if (newargs == NULL) { + Py_DECREF(mc); + return NULL; + } + mc->args = newargs; + + name = PyTuple_GET_ITEM(args, 0); + Py_INCREF(name); + mc->name = name; + + Py_XINCREF(kwds); + mc->kwds = kwds; + + PyObject_GC_Track(mc); + return (PyObject *)mc; +} + +static void +methodcaller_dealloc(methodcallerobject *mc) +{ + PyObject_GC_UnTrack(mc); + Py_XDECREF(mc->name); + Py_XDECREF(mc->args); + Py_XDECREF(mc->kwds); + PyObject_GC_Del(mc); +} + +static int +methodcaller_traverse(methodcallerobject *mc, visitproc visit, void *arg) +{ + Py_VISIT(mc->args); + Py_VISIT(mc->kwds); + return 0; +} + +static PyObject * +methodcaller_call(methodcallerobject *mc, PyObject *args, PyObject *kw) +{ + PyObject *method, *obj, *result; + + if (!PyArg_UnpackTuple(args, "methodcaller", 1, 1, &obj)) + return NULL; + method = PyObject_GetAttr(obj, mc->name); + if (method == NULL) + return NULL; + result = PyObject_Call(method, mc->args, mc->kwds); + Py_DECREF(method); + return result; +} + +PyDoc_STRVAR(methodcaller_doc, +"methodcaller(name, ...) --> methodcaller object\n\ +\n\ +Return a callable object that calls the given method on its operand.\n\ +After, f = methodcaller('name'), the call f(r) returns r.name().\n\ +After, g = methodcaller('name', 'date', foo=1), the call g(r) returns\n\ +r.name('date', foo=1)."); + +static PyTypeObject methodcaller_type = { + PyVarObject_HEAD_INIT(NULL, 0) + "operator.methodcaller", /* tp_name */ + sizeof(methodcallerobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)methodcaller_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + (ternaryfunc)methodcaller_call, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ + methodcaller_doc, /* tp_doc */ + (traverseproc)methodcaller_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + methodcaller_new, /* tp_new */ + 0, /* tp_free */ +}; + + /* Initialization function for the module (*must* be called initoperator) */ PyMODINIT_FUNC @@ -587,4 +710,9 @@ return; Py_INCREF(&attrgetter_type); PyModule_AddObject(m, "attrgetter", (PyObject *)&attrgetter_type); + + if (PyType_Ready(&methodcaller_type) < 0) + return; + Py_INCREF(&methodcaller_type); + PyModule_AddObject(m, "methodcaller", (PyObject *)&methodcaller_type); } Modified: python/branches/py3k-ctypes-pep3118/Modules/posixmodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/posixmodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/posixmodule.c Wed Apr 30 15:57:13 2008 @@ -1906,9 +1906,9 @@ posix_chown(PyObject *self, PyObject *args) { char *path = NULL; - int uid, gid; + long uid, gid; int res; - if (!PyArg_ParseTuple(args, "etii:chown", + if (!PyArg_ParseTuple(args, "etll:chown", Py_FileSystemDefaultEncoding, &path, &uid, &gid)) return NULL; @@ -3579,9 +3579,9 @@ Py_BEGIN_ALLOW_THREADS #if defined(PYCC_GCC) - spawnval = spawnve(mode, path, argvlist, envlist); + spawnval = spawnvpe(mode, path, argvlist, envlist); #else - spawnval = _spawnve(mode, path, argvlist, envlist); + spawnval = _spawnvpe(mode, path, argvlist, envlist); #endif Py_END_ALLOW_THREADS @@ -3616,11 +3616,11 @@ static PyObject * posix_fork1(PyObject *self, PyObject *noargs) { - int pid = fork1(); + pid_t pid = fork1(); if (pid == -1) return posix_error(); PyOS_AfterFork(); - return PyLong_FromLong((long)pid); + return PyLong_FromLong(pid); } #endif @@ -3634,12 +3634,12 @@ static PyObject * posix_fork(PyObject *self, PyObject *noargs) { - int pid = fork(); + pid_t pid = fork(); if (pid == -1) return posix_error(); if (pid == 0) PyOS_AfterFork(); - return PyLong_FromLong((long)pid); + return PyLong_FromLong(pid); } #endif @@ -3741,14 +3741,15 @@ static PyObject * posix_forkpty(PyObject *self, PyObject *noargs) { - int master_fd = -1, pid; + int master_fd = -1; + pid_t pid; pid = forkpty(&master_fd, NULL, NULL, NULL); if (pid == -1) return posix_error(); if (pid == 0) PyOS_AfterFork(); - return Py_BuildValue("(ii)", pid, master_fd); + return Py_BuildValue("(li)", pid, master_fd); } #endif @@ -3963,7 +3964,8 @@ static PyObject * posix_kill(PyObject *self, PyObject *args) { - int pid, sig; + pid_t pid; + int sig; if (!PyArg_ParseTuple(args, "ii:kill", &pid, &sig)) return NULL; #if defined(PYOS_OS2) && !defined(PYCC_GCC) @@ -4208,7 +4210,7 @@ #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4) static PyObject * -wait_helper(int pid, int status, struct rusage *ru) +wait_helper(pid_t pid, int status, struct rusage *ru) { PyObject *result; static PyObject *struct_rusage; @@ -4274,7 +4276,8 @@ static PyObject * posix_wait3(PyObject *self, PyObject *args) { - int pid, options; + pid_t pid; + int options; struct rusage ru; WAIT_TYPE status; WAIT_STATUS_INT(status) = 0; @@ -4298,7 +4301,8 @@ static PyObject * posix_wait4(PyObject *self, PyObject *args) { - int pid, options; + pid_t pid; + int options; struct rusage ru; WAIT_TYPE status; WAIT_STATUS_INT(status) = 0; @@ -4322,7 +4326,8 @@ static PyObject * posix_waitpid(PyObject *self, PyObject *args) { - int pid, options; + pid_t pid; + int options; WAIT_TYPE status; WAIT_STATUS_INT(status) = 0; @@ -4371,7 +4376,7 @@ static PyObject * posix_wait(PyObject *self, PyObject *noargs) { - int pid; + pid_t pid; WAIT_TYPE status; WAIT_STATUS_INT(status) = 0; @@ -4541,10 +4546,10 @@ */ return Py_BuildValue( "ddddd", - (double)(kernel.dwHighDateTime*429.4967296 + - kernel.dwLowDateTime*1e-7), (double)(user.dwHighDateTime*429.4967296 + user.dwLowDateTime*1e-7), + (double)(kernel.dwHighDateTime*429.4967296 + + kernel.dwLowDateTime*1e-7), (double)0, (double)0, (double)0); @@ -4566,7 +4571,8 @@ static PyObject * posix_getsid(PyObject *self, PyObject *args) { - int pid, sid; + pid_t pid; + int sid; if (!PyArg_ParseTuple(args, "i:getsid", &pid)) return NULL; sid = getsid(pid); @@ -4600,7 +4606,8 @@ static PyObject * posix_setpgid(PyObject *self, PyObject *args) { - int pid, pgrp; + pid_t pid; + int pgrp; if (!PyArg_ParseTuple(args, "ii:setpgid", &pid, &pgrp)) return NULL; if (setpgid(pid, pgrp) < 0) @@ -4619,7 +4626,8 @@ static PyObject * posix_tcgetpgrp(PyObject *self, PyObject *args) { - int fd, pgid; + int fd; + pid_t pgid; if (!PyArg_ParseTuple(args, "i:tcgetpgrp", &fd)) return NULL; pgid = tcgetpgrp(fd); @@ -5231,7 +5239,6 @@ } #endif /* unsetenv */ -#ifdef HAVE_STRERROR PyDoc_STRVAR(posix_strerror__doc__, "strerror(code) -> string\n\n\ Translate an error code to a message string."); @@ -5251,7 +5258,6 @@ } return PyUnicode_FromString(message); } -#endif /* strerror */ #ifdef HAVE_SYS_WAIT_H @@ -5533,7 +5539,6 @@ size_t hi = tablesize; int cmp; const char *confname; - Py_ssize_t namelen; if (!PyUnicode_Check(arg)) { PyErr_SetString(PyExc_TypeError, "configuration names must be strings or integers"); @@ -5542,7 +5547,6 @@ confname = PyUnicode_AsString(arg); if (confname == NULL) return 0; - namelen = strlen(confname); while (lo < hi) { mid = (lo + hi) / 2; cmp = strcmp(confname, table[mid].name); @@ -6969,9 +6973,7 @@ #ifdef HAVE_UNSETENV {"unsetenv", posix_unsetenv, METH_VARARGS, posix_unsetenv__doc__}, #endif -#ifdef HAVE_STRERROR {"strerror", posix_strerror, METH_VARARGS, posix_strerror__doc__}, -#endif #ifdef HAVE_FCHDIR {"fchdir", posix_fchdir, METH_O, posix_fchdir__doc__}, #endif Modified: python/branches/py3k-ctypes-pep3118/Modules/python.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/python.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/python.c Wed Apr 30 15:57:13 2008 @@ -1,14 +1,27 @@ /* Minimal main program -- everything is loaded from the library */ #include "Python.h" +#include #ifdef __FreeBSD__ #include #endif +#ifdef MS_WINDOWS +int +wmain(int argc, wchar_t **argv) +{ + return Py_Main(argc, argv); +} +#else int main(int argc, char **argv) { + wchar_t **argv_copy = PyMem_Malloc(sizeof(wchar_t*)*argc); + /* We need a second copies, as Python might modify the first one. */ + wchar_t **argv_copy2 = PyMem_Malloc(sizeof(wchar_t*)*argc); + int i, res; + char *oldloc; /* 754 requires that FP exceptions run in "no stop" mode by default, * and until C vendors implement C99's ways to control FP exceptions, * Python requires non-stop mode. Alas, some platforms enable FP @@ -20,5 +33,33 @@ m = fpgetmask(); fpsetmask(m & ~FP_X_OFL); #endif - return Py_Main(argc, argv); + if (!argv_copy || !argv_copy2) { + fprintf(stderr, "out of memory"); + return 1; + } + oldloc = setlocale(LC_ALL, NULL); + setlocale(LC_ALL, ""); + for (i = 0; i < argc; i++) { + size_t argsize = mbstowcs(NULL, argv[i], 0); + if (argsize == (size_t)-1) { + fprintf(stderr, "Could not convert argument %d to string", i); + return 1; + } + argv_copy[i] = PyMem_Malloc((argsize+1)*sizeof(wchar_t)); + argv_copy2[i] = argv_copy[i]; + if (!argv_copy[i]) { + fprintf(stderr, "out of memory"); + return 1; + } + mbstowcs(argv_copy[i], argv[i], argsize+1); + } + setlocale(LC_ALL, oldloc); + res = Py_Main(argc, argv_copy); + for (i = 0; i < argc; i++) { + PyMem_Free(argv_copy2[i]); + } + PyMem_Free(argv_copy); + PyMem_Free(argv_copy2); + return res; } +#endif Modified: python/branches/py3k-ctypes-pep3118/Modules/selectmodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/selectmodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/selectmodule.c Wed Apr 30 15:57:13 2008 @@ -5,6 +5,7 @@ */ #include "Python.h" +#include #ifdef __APPLE__ /* Perform runtime testing for a broken poll on OSX to make it easier @@ -53,7 +54,6 @@ # endif #endif - static PyObject *SelectError; /* list of Python objects and their file descriptor */ @@ -238,7 +238,7 @@ seconds = (long)timeout; timeout = timeout - (double)seconds; tv.tv_sec = seconds; - tv.tv_usec = (long)(timeout*1000000.0); + tv.tv_usec = (long)(timeout * 1E6); tvp = &tv; } @@ -402,11 +402,59 @@ return NULL; self->ufd_uptodate = 0; - + Py_INCREF(Py_None); return Py_None; } +PyDoc_STRVAR(poll_modify_doc, +"modify(fd, eventmask) -> None\n\n\ +Modify an already registered file descriptor.\n\ +fd -- either an integer, or an object with a fileno() method returning an\n\ + int.\n\ +events -- an optional bitmask describing the type of events to check for"); + +static PyObject * +poll_modify(pollObject *self, PyObject *args) +{ + PyObject *o, *key, *value; + int fd, events; + int err; + + if (!PyArg_ParseTuple(args, "Oi:modify", &o, &events)) { + return NULL; + } + + fd = PyObject_AsFileDescriptor(o); + if (fd == -1) return NULL; + + /* Modify registered fd */ + key = PyLong_FromLong(fd); + if (key == NULL) + return NULL; + if (PyDict_GetItem(self->dict, key) == NULL) { + errno = ENOENT; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + value = PyLong_FromLong(events); + if (value == NULL) { + Py_DECREF(key); + return NULL; + } + err = PyDict_SetItem(self->dict, key, value); + Py_DECREF(key); + Py_DECREF(value); + if (err < 0) + return NULL; + + self->ufd_uptodate = 0; + + Py_INCREF(Py_None); + return Py_None; +} + + PyDoc_STRVAR(poll_unregister_doc, "unregister(fd) -> None\n\n\ Remove a file descriptor being tracked by the polling object."); @@ -480,9 +528,9 @@ return NULL; /* call poll() */ - Py_BEGIN_ALLOW_THREADS; + Py_BEGIN_ALLOW_THREADS poll_result = poll(self->ufds, self->ufd_len, timeout); - Py_END_ALLOW_THREADS; + Py_END_ALLOW_THREADS if (poll_result < 0) { PyErr_SetFromErrno(SelectError); @@ -540,7 +588,9 @@ static PyMethodDef poll_methods[] = { {"register", (PyCFunction)poll_register, METH_VARARGS, poll_register_doc}, - {"unregister", (PyCFunction)poll_unregister, + {"modify", (PyCFunction)poll_modify, + METH_VARARGS, poll_modify_doc}, + {"unregister", (PyCFunction)poll_unregister, METH_O, poll_unregister_doc}, {"poll", (PyCFunction)poll_poll, METH_VARARGS, poll_poll_doc}, @@ -643,6 +693,1004 @@ #endif /* HAVE_POLL */ +#ifdef HAVE_EPOLL +/* ************************************************************************** + * epoll interface for Linux 2.6 + * + * Written by Christian Heimes + * Inspired by Twisted's _epoll.pyx and select.poll() + */ + +#ifdef HAVE_SYS_EPOLL_H +#include +#endif + +typedef struct { + PyObject_HEAD + SOCKET epfd; /* epoll control file descriptor */ +} pyEpoll_Object; + +static PyTypeObject pyEpoll_Type; +#define pyepoll_CHECK(op) (PyObject_TypeCheck((op), &pyEpoll_Type)) + +static PyObject * +pyepoll_err_closed(void) +{ + PyErr_SetString(PyExc_ValueError, "I/O operation on closed epoll fd"); + return NULL; +} + +static int +pyepoll_internal_close(pyEpoll_Object *self) +{ + int save_errno = 0; + if (self->epfd >= 0) { + int epfd = self->epfd; + self->epfd = -1; + Py_BEGIN_ALLOW_THREADS + if (close(epfd) < 0) + save_errno = errno; + Py_END_ALLOW_THREADS + } + return save_errno; +} + +static PyObject * +newPyEpoll_Object(PyTypeObject *type, int sizehint, SOCKET fd) +{ + pyEpoll_Object *self; + + if (sizehint == -1) { + sizehint = FD_SETSIZE-1; + } + else if (sizehint < 1) { + PyErr_Format(PyExc_ValueError, + "sizehint must be greater zero, got %d", + sizehint); + return NULL; + } + + assert(type != NULL && type->tp_alloc != NULL); + self = (pyEpoll_Object *) type->tp_alloc(type, 0); + if (self == NULL) + return NULL; + + if (fd == -1) { + Py_BEGIN_ALLOW_THREADS + self->epfd = epoll_create(sizehint); + Py_END_ALLOW_THREADS + } + else { + self->epfd = fd; + } + if (self->epfd < 0) { + Py_DECREF(self); + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + return (PyObject *)self; +} + + +static PyObject * +pyepoll_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + int sizehint = -1; + static char *kwlist[] = {"sizehint", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:epoll", kwlist, + &sizehint)) + return NULL; + + return newPyEpoll_Object(type, sizehint, -1); +} + + +static void +pyepoll_dealloc(pyEpoll_Object *self) +{ + (void)pyepoll_internal_close(self); + Py_TYPE(self)->tp_free(self); +} + +static PyObject* +pyepoll_close(pyEpoll_Object *self) +{ + errno = pyepoll_internal_close(self); + if (errno < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + Py_RETURN_NONE; +} + +PyDoc_STRVAR(pyepoll_close_doc, +"close() -> None\n\ +\n\ +Close the epoll control file descriptor. Further operations on the epoll\n\ +object will raise an exception."); + +static PyObject* +pyepoll_get_closed(pyEpoll_Object *self) +{ + if (self->epfd < 0) + Py_RETURN_TRUE; + else + Py_RETURN_FALSE; +} + +static PyObject* +pyepoll_fileno(pyEpoll_Object *self) +{ + if (self->epfd < 0) + return pyepoll_err_closed(); + return PyLong_FromLong(self->epfd); +} + +PyDoc_STRVAR(pyepoll_fileno_doc, +"fileno() -> int\n\ +\n\ +Return the epoll control file descriptor."); + +static PyObject* +pyepoll_fromfd(PyObject *cls, PyObject *args) +{ + SOCKET fd; + + if (!PyArg_ParseTuple(args, "i:fromfd", &fd)) + return NULL; + + return newPyEpoll_Object((PyTypeObject*)cls, -1, fd); +} + +PyDoc_STRVAR(pyepoll_fromfd_doc, +"fromfd(fd) -> epoll\n\ +\n\ +Create an epoll object from a given control fd."); + +static PyObject * +pyepoll_internal_ctl(int epfd, int op, PyObject *pfd, unsigned int events) +{ + struct epoll_event ev; + int result; + int fd; + + if (epfd < 0) + return pyepoll_err_closed(); + + fd = PyObject_AsFileDescriptor(pfd); + if (fd == -1) { + return NULL; + } + + switch(op) { + case EPOLL_CTL_ADD: + case EPOLL_CTL_MOD: + ev.events = events; + ev.data.fd = fd; + Py_BEGIN_ALLOW_THREADS + result = epoll_ctl(epfd, op, fd, &ev); + Py_END_ALLOW_THREADS + break; + case EPOLL_CTL_DEL: + /* In kernel versions before 2.6.9, the EPOLL_CTL_DEL + * operation required a non-NULL pointer in event, even + * though this argument is ignored. */ + Py_BEGIN_ALLOW_THREADS + result = epoll_ctl(epfd, op, fd, &ev); + if (errno == EBADF) { + /* fd already closed */ + result = 0; + errno = 0; + } + Py_END_ALLOW_THREADS + break; + default: + result = -1; + errno = EINVAL; + } + + if (result < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + Py_RETURN_NONE; +} + +static PyObject * +pyepoll_register(pyEpoll_Object *self, PyObject *args, PyObject *kwds) +{ + PyObject *pfd; + unsigned int events = EPOLLIN | EPOLLOUT | EPOLLPRI; + static char *kwlist[] = {"fd", "eventmask", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|I:register", kwlist, + &pfd, &events)) { + return NULL; + } + + return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_ADD, pfd, events); +} + +PyDoc_STRVAR(pyepoll_register_doc, +"register(fd[, eventmask]) -> bool\n\ +\n\ +Registers a new fd or modifies an already registered fd. register() returns\n\ +True if a new fd was registered or False if the event mask for fd was modified.\n\ +fd is the target file descriptor of the operation.\n\ +events is a bit set composed of the various EPOLL constants; the default\n\ +is EPOLL_IN | EPOLL_OUT | EPOLL_PRI.\n\ +\n\ +The epoll interface supports all file descriptors that support poll."); + +static PyObject * +pyepoll_modify(pyEpoll_Object *self, PyObject *args, PyObject *kwds) +{ + PyObject *pfd; + unsigned int events; + static char *kwlist[] = {"fd", "eventmask", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OI:modify", kwlist, + &pfd, &events)) { + return NULL; + } + + return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_MOD, pfd, events); +} + +PyDoc_STRVAR(pyepoll_modify_doc, +"modify(fd, eventmask) -> None\n\ +\n\ +fd is the target file descriptor of the operation\n\ +events is a bit set composed of the various EPOLL constants"); + +static PyObject * +pyepoll_unregister(pyEpoll_Object *self, PyObject *args, PyObject *kwds) +{ + PyObject *pfd; + static char *kwlist[] = {"fd", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:unregister", kwlist, + &pfd)) { + return NULL; + } + + return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_DEL, pfd, 0); +} + +PyDoc_STRVAR(pyepoll_unregister_doc, +"unregister(fd) -> None\n\ +\n\ +fd is the target file descriptor of the operation."); + +static PyObject * +pyepoll_poll(pyEpoll_Object *self, PyObject *args, PyObject *kwds) +{ + double dtimeout = -1.; + int timeout; + int maxevents = -1; + int nfds, i; + PyObject *elist = NULL, *etuple = NULL; + struct epoll_event *evs = NULL; + static char *kwlist[] = {"timeout", "maxevents", NULL}; + + if (self->epfd < 0) + return pyepoll_err_closed(); + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|di:poll", kwlist, + &dtimeout, &maxevents)) { + return NULL; + } + + if (dtimeout < 0) { + timeout = -1; + } + else if (dtimeout * 1000.0 > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "timeout is too large"); + return NULL; + } + else { + timeout = (int)(dtimeout * 1000.0); + } + + if (maxevents == -1) { + maxevents = FD_SETSIZE-1; + } + else if (maxevents < 1) { + PyErr_Format(PyExc_ValueError, + "maxevents must be greater than 0, got %d", + maxevents); + return NULL; + } + + evs = PyMem_New(struct epoll_event, maxevents); + if (evs == NULL) { + Py_DECREF(self); + PyErr_NoMemory(); + return NULL; + } + + Py_BEGIN_ALLOW_THREADS + nfds = epoll_wait(self->epfd, evs, maxevents, timeout); + Py_END_ALLOW_THREADS + if (nfds < 0) { + PyErr_SetFromErrno(PyExc_IOError); + goto error; + } + + elist = PyList_New(nfds); + if (elist == NULL) { + goto error; + } + + for (i = 0; i < nfds; i++) { + etuple = Py_BuildValue("iI", evs[i].data.fd, evs[i].events); + if (etuple == NULL) { + Py_CLEAR(elist); + goto error; + } + PyList_SET_ITEM(elist, i, etuple); + } + + error: + PyMem_Free(evs); + return elist; +} + +PyDoc_STRVAR(pyepoll_poll_doc, +"poll([timeout=-1[, maxevents=-1]]) -> [(fd, events), (...)]\n\ +\n\ +Wait for events on the epoll file descriptor for a maximum time of timeout\n\ +in seconds (as float). -1 makes poll wait indefinitely.\n\ +Up to maxevents are returned to the caller."); + +static PyMethodDef pyepoll_methods[] = { + {"fromfd", (PyCFunction)pyepoll_fromfd, + METH_VARARGS | METH_CLASS, pyepoll_fromfd_doc}, + {"close", (PyCFunction)pyepoll_close, METH_NOARGS, + pyepoll_close_doc}, + {"fileno", (PyCFunction)pyepoll_fileno, METH_NOARGS, + pyepoll_fileno_doc}, + {"modify", (PyCFunction)pyepoll_modify, + METH_VARARGS | METH_KEYWORDS, pyepoll_modify_doc}, + {"register", (PyCFunction)pyepoll_register, + METH_VARARGS | METH_KEYWORDS, pyepoll_register_doc}, + {"unregister", (PyCFunction)pyepoll_unregister, + METH_VARARGS | METH_KEYWORDS, pyepoll_unregister_doc}, + {"poll", (PyCFunction)pyepoll_poll, + METH_VARARGS | METH_KEYWORDS, pyepoll_poll_doc}, + {NULL, NULL}, +}; + +static PyGetSetDef pyepoll_getsetlist[] = { + {"closed", (getter)pyepoll_get_closed, NULL, + "True if the epoll handler is closed"}, + {0}, +}; + +PyDoc_STRVAR(pyepoll_doc, +"select.epoll([sizehint=-1])\n\ +\n\ +Returns an epolling object\n\ +\n\ +sizehint must be a positive integer or -1 for the default size. The\n\ +sizehint is used to optimize internal data structures. It doesn't limit\n\ +the maximum number of monitored events."); + +static PyTypeObject pyEpoll_Type = { + PyVarObject_HEAD_INIT(NULL, 0) + "select.epoll", /* tp_name */ + sizeof(pyEpoll_Object), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)pyepoll_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + pyepoll_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + pyepoll_methods, /* tp_methods */ + 0, /* tp_members */ + pyepoll_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + pyepoll_new, /* tp_new */ + 0, /* tp_free */ +}; + +#endif /* HAVE_EPOLL */ + +#ifdef HAVE_KQUEUE +/* ************************************************************************** + * kqueue interface for BSD + * + * Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#ifdef HAVE_SYS_EVENT_H +#include +#endif + +PyDoc_STRVAR(kqueue_event_doc, +"kevent(ident, filter=KQ_FILTER_READ, flags=KQ_ADD, fflags=0, data=0, udata=0)\n\ +\n\ +This object is the equivalent of the struct kevent for the C API.\n\ +\n\ +See the kqueue manpage for more detailed information about the meaning\n\ +of the arguments.\n\ +\n\ +One minor note: while you might hope that udata could store a\n\ +reference to a python object, it cannot, because it is impossible to\n\ +keep a proper reference count of the object once it's passed into the\n\ +kernel. Therefore, I have restricted it to only storing an integer. I\n\ +recommend ignoring it and simply using the 'ident' field to key off\n\ +of. You could also set up a dictionary on the python side to store a\n\ +udata->object mapping."); + +typedef struct { + PyObject_HEAD + struct kevent e; +} kqueue_event_Object; + +static PyTypeObject kqueue_event_Type; + +#define kqueue_event_Check(op) (PyObject_TypeCheck((op), &kqueue_event_Type)) + +typedef struct { + PyObject_HEAD + SOCKET kqfd; /* kqueue control fd */ +} kqueue_queue_Object; + +static PyTypeObject kqueue_queue_Type; + +#define kqueue_queue_Check(op) (PyObject_TypeCheck((op), &kqueue_queue_Type)) + +/* Unfortunately, we can't store python objects in udata, because + * kevents in the kernel can be removed without warning, which would + * forever lose the refcount on the object stored with it. + */ + +#define KQ_OFF(x) offsetof(kqueue_event_Object, x) +static struct PyMemberDef kqueue_event_members[] = { + {"ident", T_UINT, KQ_OFF(e.ident)}, + {"filter", T_SHORT, KQ_OFF(e.filter)}, + {"flags", T_USHORT, KQ_OFF(e.flags)}, + {"fflags", T_UINT, KQ_OFF(e.fflags)}, + {"data", T_INT, KQ_OFF(e.data)}, + {"udata", T_INT, KQ_OFF(e.udata)}, + {NULL} /* Sentinel */ +}; +#undef KQ_OFF + +static PyObject * +kqueue_event_repr(kqueue_event_Object *s) +{ + char buf[1024]; + PyOS_snprintf( + buf, sizeof(buf), + "", + (unsigned long)(s->e.ident), s->e.filter, s->e.flags, + s->e.fflags, (long)(s->e.data), s->e.udata); + return PyString_FromString(buf); +} + +static int +kqueue_event_init(kqueue_event_Object *self, PyObject *args, PyObject *kwds) +{ + PyObject *pfd; + static char *kwlist[] = {"ident", "filter", "flags", "fflags", + "data", "udata", NULL}; + + EV_SET(&(self->e), 0, EVFILT_READ, EV_ADD, 0, 0, 0); /* defaults */ + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|hhiii:kevent", kwlist, + &pfd, &(self->e.filter), &(self->e.flags), + &(self->e.fflags), &(self->e.data), &(self->e.udata))) { + return -1; + } + + self->e.ident = PyObject_AsFileDescriptor(pfd); + if (self->e.ident == -1) { + return -1; + } + return 0; +} + +static PyObject * +kqueue_event_richcompare(kqueue_event_Object *s, kqueue_event_Object *o, + int op) +{ + int result = 0; + + if (!kqueue_event_Check(o)) { + if (op == Py_EQ || op == Py_NE) { + PyObject *res = op == Py_EQ ? Py_False : Py_True; + Py_INCREF(res); + return res; + } + PyErr_Format(PyExc_TypeError, + "can't compare %.200s to %.200s", + Py_TYPE(s)->tp_name, Py_TYPE(o)->tp_name); + return NULL; + } + if (((result = s->e.ident - o->e.ident) == 0) && + ((result = s->e.filter - o->e.filter) == 0) && + ((result = s->e.flags - o->e.flags) == 0) && + ((result = s->e.fflags - o->e.fflags) == 0) && + ((result = s->e.data - o->e.data) == 0) && + ((result = s->e.udata - o->e.udata) == 0) + ) { + result = 0; + } + + switch (op) { + case Py_EQ: + result = (result == 0); + break; + case Py_NE: + result = (result != 0); + break; + case Py_LE: + result = (result <= 0); + break; + case Py_GE: + result = (result >= 0); + break; + case Py_LT: + result = (result < 0); + break; + case Py_GT: + result = (result > 0); + break; + } + return PyBool_FromLong(result); +} + +static PyTypeObject kqueue_event_Type = { + PyVarObject_HEAD_INIT(NULL, 0) + "select.kevent", /* tp_name */ + sizeof(kqueue_event_Object), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + (reprfunc)kqueue_event_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + kqueue_event_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + (richcmpfunc)kqueue_event_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + kqueue_event_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)kqueue_event_init, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ +}; + +static PyObject * +kqueue_queue_err_closed(void) +{ + PyErr_SetString(PyExc_ValueError, "I/O operation on closed kqueue fd"); + return NULL; +} + +static int +kqueue_queue_internal_close(kqueue_queue_Object *self) +{ + int save_errno = 0; + if (self->kqfd >= 0) { + int kqfd = self->kqfd; + self->kqfd = -1; + Py_BEGIN_ALLOW_THREADS + if (close(kqfd) < 0) + save_errno = errno; + Py_END_ALLOW_THREADS + } + return save_errno; +} + +static PyObject * +newKqueue_Object(PyTypeObject *type, SOCKET fd) +{ + kqueue_queue_Object *self; + assert(type != NULL && type->tp_alloc != NULL); + self = (kqueue_queue_Object *) type->tp_alloc(type, 0); + if (self == NULL) { + return NULL; + } + + if (fd == -1) { + Py_BEGIN_ALLOW_THREADS + self->kqfd = kqueue(); + Py_END_ALLOW_THREADS + } + else { + self->kqfd = fd; + } + if (self->kqfd < 0) { + Py_DECREF(self); + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + return (PyObject *)self; +} + +static PyObject * +kqueue_queue_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + + if ((args != NULL && PyObject_Size(args)) || + (kwds != NULL && PyObject_Size(kwds))) { + PyErr_SetString(PyExc_ValueError, + "select.kqueue doesn't accept arguments"); + return NULL; + } + + return newKqueue_Object(type, -1); +} + +static void +kqueue_queue_dealloc(kqueue_queue_Object *self) +{ + kqueue_queue_internal_close(self); + Py_TYPE(self)->tp_free(self); +} + +static PyObject* +kqueue_queue_close(kqueue_queue_Object *self) +{ + errno = kqueue_queue_internal_close(self); + if (errno < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + Py_RETURN_NONE; +} + +PyDoc_STRVAR(kqueue_queue_close_doc, +"close() -> None\n\ +\n\ +Close the kqueue control file descriptor. Further operations on the kqueue\n\ +object will raise an exception."); + +static PyObject* +kqueue_queue_get_closed(kqueue_queue_Object *self) +{ + if (self->kqfd < 0) + Py_RETURN_TRUE; + else + Py_RETURN_FALSE; +} + +static PyObject* +kqueue_queue_fileno(kqueue_queue_Object *self) +{ + if (self->kqfd < 0) + return kqueue_queue_err_closed(); + return PyLong_FromLong(self->kqfd); +} + +PyDoc_STRVAR(kqueue_queue_fileno_doc, +"fileno() -> int\n\ +\n\ +Return the kqueue control file descriptor."); + +static PyObject* +kqueue_queue_fromfd(PyObject *cls, PyObject *args) +{ + SOCKET fd; + + if (!PyArg_ParseTuple(args, "i:fromfd", &fd)) + return NULL; + + return newKqueue_Object((PyTypeObject*)cls, fd); +} + +PyDoc_STRVAR(kqueue_queue_fromfd_doc, +"fromfd(fd) -> kqueue\n\ +\n\ +Create a kqueue object from a given control fd."); + +static PyObject * +kqueue_queue_control(kqueue_queue_Object *self, PyObject *args) +{ + int nevents = 0; + int gotevents = 0; + int nchanges = 0; + int i = 0; + PyObject *otimeout = NULL; + PyObject *ch = NULL; + PyObject *it = NULL, *ei = NULL; + PyObject *result = NULL; + struct kevent *evl = NULL; + struct kevent *chl = NULL; + struct timespec timeoutspec; + struct timespec *ptimeoutspec; + + if (self->kqfd < 0) + return kqueue_queue_err_closed(); + + if (!PyArg_ParseTuple(args, "Oi|O:control", &ch, &nevents, &otimeout)) + return NULL; + + if (nevents < 0) { + PyErr_Format(PyExc_ValueError, + "Length of eventlist must be 0 or positive, got %d", + nchanges); + return NULL; + } + + if (ch != NULL && ch != Py_None) { + it = PyObject_GetIter(ch); + if (it == NULL) { + PyErr_SetString(PyExc_TypeError, + "changelist is not iterable"); + return NULL; + } + nchanges = PyObject_Size(ch); + if (nchanges < 0) { + return NULL; + } + } + + if (otimeout == Py_None || otimeout == NULL) { + ptimeoutspec = NULL; + } + else if (PyNumber_Check(otimeout)) { + double timeout; + long seconds; + + timeout = PyFloat_AsDouble(otimeout); + if (timeout == -1 && PyErr_Occurred()) + return NULL; + if (timeout > (double)LONG_MAX) { + PyErr_SetString(PyExc_OverflowError, + "timeout period too long"); + return NULL; + } + if (timeout < 0) { + PyErr_SetString(PyExc_ValueError, + "timeout must be positive or None"); + return NULL; + } + + seconds = (long)timeout; + timeout = timeout - (double)seconds; + timeoutspec.tv_sec = seconds; + timeoutspec.tv_nsec = (long)(timeout * 1E9); + ptimeoutspec = &timeoutspec; + } + else { + PyErr_Format(PyExc_TypeError, + "timeout argument must be an number " + "or None, got %.200s", + Py_TYPE(otimeout)->tp_name); + return NULL; + } + + if (nchanges) { + chl = PyMem_New(struct kevent, nchanges); + if (chl == NULL) { + PyErr_NoMemory(); + return NULL; + } + while ((ei = PyIter_Next(it)) != NULL) { + if (!kqueue_event_Check(ei)) { + Py_DECREF(ei); + PyErr_SetString(PyExc_TypeError, + "changelist must be an iterable of " + "select.kevent objects"); + goto error; + } else { + chl[i] = ((kqueue_event_Object *)ei)->e; + } + Py_DECREF(ei); + } + } + Py_CLEAR(it); + + /* event list */ + if (nevents) { + evl = PyMem_New(struct kevent, nevents); + if (evl == NULL) { + PyErr_NoMemory(); + return NULL; + } + } + + Py_BEGIN_ALLOW_THREADS + gotevents = kevent(self->kqfd, chl, nchanges, + evl, nevents, ptimeoutspec); + Py_END_ALLOW_THREADS + + if (gotevents == -1) { + PyErr_SetFromErrno(PyExc_OSError); + goto error; + } + + result = PyList_New(gotevents); + if (result == NULL) { + goto error; + } + + for (i=0; i < gotevents; i++) { + kqueue_event_Object *ch; + + ch = PyObject_New(kqueue_event_Object, &kqueue_event_Type); + if (ch == NULL) { + goto error; + } + ch->e = evl[i]; + PyList_SET_ITEM(result, i, (PyObject *)ch); + } + PyMem_Free(chl); + PyMem_Free(evl); + return result; + + error: + PyMem_Free(chl); + PyMem_Free(evl); + Py_XDECREF(result); + Py_XDECREF(it); + return NULL; +} + +PyDoc_STRVAR(kqueue_queue_control_doc, +"control(changelist, max_events=0[, timeout=None]) -> eventlist\n\ +\n\ +Calls the kernel kevent function.\n\ +- changelist must be a list of kevent objects describing the changes\n\ + to be made to the kernel's watch list or None.\n\ +- max_events lets you specify the maximum number of events that the\n\ + kernel will return.\n\ +- timeout is the maximum time to wait in seconds, or else None,\n\ + to wait forever. timeout accepts floats for smaller timeouts, too."); + + +static PyMethodDef kqueue_queue_methods[] = { + {"fromfd", (PyCFunction)kqueue_queue_fromfd, + METH_VARARGS | METH_CLASS, kqueue_queue_fromfd_doc}, + {"close", (PyCFunction)kqueue_queue_close, METH_NOARGS, + kqueue_queue_close_doc}, + {"fileno", (PyCFunction)kqueue_queue_fileno, METH_NOARGS, + kqueue_queue_fileno_doc}, + {"control", (PyCFunction)kqueue_queue_control, + METH_VARARGS , kqueue_queue_control_doc}, + {NULL, NULL}, +}; + +static PyGetSetDef kqueue_queue_getsetlist[] = { + {"closed", (getter)kqueue_queue_get_closed, NULL, + "True if the kqueue handler is closed"}, + {0}, +}; + +PyDoc_STRVAR(kqueue_queue_doc, +"Kqueue syscall wrapper.\n\ +\n\ +For example, to start watching a socket for input:\n\ +>>> kq = kqueue()\n\ +>>> sock = socket()\n\ +>>> sock.connect((host, port))\n\ +>>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_ADD)], 0)\n\ +\n\ +To wait one second for it to become writeable:\n\ +>>> kq.control(None, 1, 1000)\n\ +\n\ +To stop listening:\n\ +>>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_DELETE)], 0)"); + +static PyTypeObject kqueue_queue_Type = { + PyVarObject_HEAD_INIT(NULL, 0) + "select.kqueue", /* tp_name */ + sizeof(kqueue_queue_Object), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)kqueue_queue_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + kqueue_queue_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + kqueue_queue_methods, /* tp_methods */ + 0, /* tp_members */ + kqueue_queue_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + kqueue_queue_new, /* tp_new */ + 0, /* tp_free */ +}; + +#endif /* HAVE_KQUEUE */ +/* ************************************************************************ */ + PyDoc_STRVAR(select_doc, "select(rlist, wlist, xlist[, timeout]) -> (rlist, wlist, xlist)\n\ \n\ @@ -664,14 +1712,15 @@ that are ready.\n\ \n\ *** IMPORTANT NOTICE ***\n\ -On Windows and OpenVMS, only sockets are supported; on Unix, all file descriptors."); +On Windows and OpenVMS, only sockets are supported; on Unix, all file\n\ +descriptors can be used."); static PyMethodDef select_methods[] = { - {"select", select_select, METH_VARARGS, select_doc}, -#if defined(HAVE_POLL) - {"poll", select_poll, METH_NOARGS, poll_doc}, + {"select", select_select, METH_VARARGS, select_doc}, +#ifdef HAVE_POLL + {"poll", select_poll, METH_NOARGS, poll_doc}, #endif /* HAVE_POLL */ - {0, 0}, /* sentinel */ + {0, 0}, /* sentinel */ }; PyDoc_STRVAR(module_doc, @@ -691,8 +1740,8 @@ SelectError = PyErr_NewException("select.error", NULL, NULL); Py_INCREF(SelectError); PyModule_AddObject(m, "error", SelectError); -#if defined(HAVE_POLL) +#if defined(HAVE_POLL) #ifdef __APPLE__ if (select_have_broken_poll()) { if (PyObject_DelAttrString(m, "poll") == -1) { @@ -727,4 +1776,103 @@ #endif } #endif /* HAVE_POLL */ + +#ifdef HAVE_EPOLL + Py_TYPE(&pyEpoll_Type) = &PyType_Type; + if (PyType_Ready(&pyEpoll_Type) < 0) + return; + + Py_INCREF(&pyEpoll_Type); + PyModule_AddObject(m, "epoll", (PyObject *) &pyEpoll_Type); + + PyModule_AddIntConstant(m, "EPOLLIN", EPOLLIN); + PyModule_AddIntConstant(m, "EPOLLOUT", EPOLLOUT); + PyModule_AddIntConstant(m, "EPOLLPRI", EPOLLPRI); + PyModule_AddIntConstant(m, "EPOLLERR", EPOLLERR); + PyModule_AddIntConstant(m, "EPOLLHUP", EPOLLHUP); + PyModule_AddIntConstant(m, "EPOLLET", EPOLLET); +#ifdef EPOLLONESHOT + /* Kernel 2.6.2+ */ + PyModule_AddIntConstant(m, "EPOLLONESHOT", EPOLLONESHOT); +#endif + /* PyModule_AddIntConstant(m, "EPOLL_RDHUP", EPOLLRDHUP); */ + PyModule_AddIntConstant(m, "EPOLLRDNORM", EPOLLRDNORM); + PyModule_AddIntConstant(m, "EPOLLRDBAND", EPOLLRDBAND); + PyModule_AddIntConstant(m, "EPOLLWRNORM", EPOLLWRNORM); + PyModule_AddIntConstant(m, "EPOLLWRBAND", EPOLLWRBAND); + PyModule_AddIntConstant(m, "EPOLLMSG", EPOLLMSG); +#endif /* HAVE_EPOLL */ + +#ifdef HAVE_KQUEUE + kqueue_event_Type.tp_new = PyType_GenericNew; + Py_TYPE(&kqueue_event_Type) = &PyType_Type; + if(PyType_Ready(&kqueue_event_Type) < 0) + return; + + Py_INCREF(&kqueue_event_Type); + PyModule_AddObject(m, "kevent", (PyObject *)&kqueue_event_Type); + + Py_TYPE(&kqueue_queue_Type) = &PyType_Type; + if(PyType_Ready(&kqueue_queue_Type) < 0) + return; + Py_INCREF(&kqueue_queue_Type); + PyModule_AddObject(m, "kqueue", (PyObject *)&kqueue_queue_Type); + + /* event filters */ + PyModule_AddIntConstant(m, "KQ_FILTER_READ", EVFILT_READ); + PyModule_AddIntConstant(m, "KQ_FILTER_WRITE", EVFILT_WRITE); + PyModule_AddIntConstant(m, "KQ_FILTER_AIO", EVFILT_AIO); + PyModule_AddIntConstant(m, "KQ_FILTER_VNODE", EVFILT_VNODE); + PyModule_AddIntConstant(m, "KQ_FILTER_PROC", EVFILT_PROC); +#ifdef EVFILT_NETDEV + PyModule_AddIntConstant(m, "KQ_FILTER_NETDEV", EVFILT_NETDEV); +#endif + PyModule_AddIntConstant(m, "KQ_FILTER_SIGNAL", EVFILT_SIGNAL); + PyModule_AddIntConstant(m, "KQ_FILTER_TIMER", EVFILT_TIMER); + + /* event flags */ + PyModule_AddIntConstant(m, "KQ_EV_ADD", EV_ADD); + PyModule_AddIntConstant(m, "KQ_EV_DELETE", EV_DELETE); + PyModule_AddIntConstant(m, "KQ_EV_ENABLE", EV_ENABLE); + PyModule_AddIntConstant(m, "KQ_EV_DISABLE", EV_DISABLE); + PyModule_AddIntConstant(m, "KQ_EV_ONESHOT", EV_ONESHOT); + PyModule_AddIntConstant(m, "KQ_EV_CLEAR", EV_CLEAR); + + PyModule_AddIntConstant(m, "KQ_EV_SYSFLAGS", EV_SYSFLAGS); + PyModule_AddIntConstant(m, "KQ_EV_FLAG1", EV_FLAG1); + + PyModule_AddIntConstant(m, "KQ_EV_EOF", EV_EOF); + PyModule_AddIntConstant(m, "KQ_EV_ERROR", EV_ERROR); + + /* READ WRITE filter flag */ + PyModule_AddIntConstant(m, "KQ_NOTE_LOWAT", NOTE_LOWAT); + + /* VNODE filter flags */ + PyModule_AddIntConstant(m, "KQ_NOTE_DELETE", NOTE_DELETE); + PyModule_AddIntConstant(m, "KQ_NOTE_WRITE", NOTE_WRITE); + PyModule_AddIntConstant(m, "KQ_NOTE_EXTEND", NOTE_EXTEND); + PyModule_AddIntConstant(m, "KQ_NOTE_ATTRIB", NOTE_ATTRIB); + PyModule_AddIntConstant(m, "KQ_NOTE_LINK", NOTE_LINK); + PyModule_AddIntConstant(m, "KQ_NOTE_RENAME", NOTE_RENAME); + PyModule_AddIntConstant(m, "KQ_NOTE_REVOKE", NOTE_REVOKE); + + /* PROC filter flags */ + PyModule_AddIntConstant(m, "KQ_NOTE_EXIT", NOTE_EXIT); + PyModule_AddIntConstant(m, "KQ_NOTE_FORK", NOTE_FORK); + PyModule_AddIntConstant(m, "KQ_NOTE_EXEC", NOTE_EXEC); + PyModule_AddIntConstant(m, "KQ_NOTE_PCTRLMASK", NOTE_PCTRLMASK); + PyModule_AddIntConstant(m, "KQ_NOTE_PDATAMASK", NOTE_PDATAMASK); + + PyModule_AddIntConstant(m, "KQ_NOTE_TRACK", NOTE_TRACK); + PyModule_AddIntConstant(m, "KQ_NOTE_CHILD", NOTE_CHILD); + PyModule_AddIntConstant(m, "KQ_NOTE_TRACKERR", NOTE_TRACKERR); + + /* NETDEV filter flags */ +#ifdef EVFILT_NETDEV + PyModule_AddIntConstant(m, "KQ_NOTE_LINKUP", NOTE_LINKUP); + PyModule_AddIntConstant(m, "KQ_NOTE_LINKDOWN", NOTE_LINKDOWN); + PyModule_AddIntConstant(m, "KQ_NOTE_LINKINV", NOTE_LINKINV); +#endif + +#endif /* HAVE_KQUEUE */ } Modified: python/branches/py3k-ctypes-pep3118/Modules/signalmodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/signalmodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/signalmodule.c Wed Apr 30 15:57:13 2008 @@ -13,6 +13,9 @@ #include #include +#ifdef HAVE_SYS_TIME_H +#include +#endif #ifndef SIG_ERR #define SIG_ERR ((PyOS_sighandler_t)(-1)) @@ -93,6 +96,49 @@ static PyOS_sighandler_t old_siginthandler = SIG_DFL; +#ifdef HAVE_GETITIMER +static PyObject *ItimerError; + +/* auxiliary functions for setitimer/getitimer */ +static void +timeval_from_double(double d, struct timeval *tv) +{ + tv->tv_sec = floor(d); + tv->tv_usec = fmod(d, 1.0) * 1000000.0; +} + +static inline double +double_from_timeval(struct timeval *tv) +{ + return tv->tv_sec + (double)(tv->tv_usec / 1000000.0); +} + +static PyObject * +itimer_retval(struct itimerval *iv) +{ + PyObject *r, *v; + + r = PyTuple_New(2); + if (r == NULL) + return NULL; + + if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_value)))) { + Py_DECREF(r); + return NULL; + } + + PyTuple_SET_ITEM(r, 0, v); + + if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_interval)))) { + Py_DECREF(r); + return NULL; + } + + PyTuple_SET_ITEM(r, 1, v); + + return r; +} +#endif static PyObject * signal_default_int_handler(PyObject *self, PyObject *args) @@ -272,6 +318,36 @@ None -- if an unknown handler is in effect\n\ anything else -- the callable Python object used as a handler"); +#ifdef HAVE_SIGINTERRUPT +PyDoc_STRVAR(siginterrupt_doc, +"siginterrupt(sig, flag) -> None\n\ +change system call restart behaviour: if flag is False, system calls\n\ +will be restarted when interrupted by signal sig, else system calls\n\ +will be interrupted."); + +static PyObject * +signal_siginterrupt(PyObject *self, PyObject *args) +{ + int sig_num; + int flag; + + if (!PyArg_ParseTuple(args, "ii:siginterrupt", &sig_num, &flag)) + return NULL; + if (sig_num < 1 || sig_num >= NSIG) { + PyErr_SetString(PyExc_ValueError, + "signal number out of range"); + return NULL; + } + if (siginterrupt(sig_num, flag)<0) { + PyErr_SetFromErrno(PyExc_RuntimeError); + return NULL; + } + + Py_INCREF(Py_None); + return Py_None; +} + +#endif static PyObject * signal_set_wakeup_fd(PyObject *self, PyObject *args) @@ -317,14 +393,83 @@ } +#ifdef HAVE_SETITIMER +static PyObject * +signal_setitimer(PyObject *self, PyObject *args) +{ + double first; + double interval = 0; + int which; + struct itimerval new, old; + + if(!PyArg_ParseTuple(args, "id|d:setitimer", &which, &first, &interval)) + return NULL; + + timeval_from_double(first, &new.it_value); + timeval_from_double(interval, &new.it_interval); + /* Let OS check "which" value */ + if (setitimer(which, &new, &old) != 0) { + PyErr_SetFromErrno(ItimerError); + return NULL; + } + + return itimer_retval(&old); +} + +PyDoc_STRVAR(setitimer_doc, +"setitimer(which, seconds[, interval])\n\ +\n\ +Sets given itimer (one of ITIMER_REAL, ITIMER_VIRTUAL\n\ +or ITIMER_PROF) to fire after value seconds and after\n\ +that every interval seconds.\n\ +The itimer can be cleared by setting seconds to zero.\n\ +\n\ +Returns old values as a tuple: (delay, interval)."); +#endif + + +#ifdef HAVE_GETITIMER +static PyObject * +signal_getitimer(PyObject *self, PyObject *args) +{ + int which; + struct itimerval old; + + if (!PyArg_ParseTuple(args, "i:getitimer", &which)) + return NULL; + + if (getitimer(which, &old) != 0) { + PyErr_SetFromErrno(ItimerError); + return NULL; + } + + return itimer_retval(&old); +} + +PyDoc_STRVAR(getitimer_doc, +"getitimer(which)\n\ +\n\ +Returns current value of given itimer."); +#endif + + /* List of functions defined in the module */ static PyMethodDef signal_methods[] = { #ifdef HAVE_ALARM {"alarm", signal_alarm, METH_VARARGS, alarm_doc}, #endif +#ifdef HAVE_SETITIMER + {"setitimer", signal_setitimer, METH_VARARGS, setitimer_doc}, +#endif +#ifdef HAVE_GETITIMER + {"getitimer", signal_getitimer, METH_VARARGS, getitimer_doc}, +#endif {"signal", signal_signal, METH_VARARGS, signal_doc}, {"getsignal", signal_getsignal, METH_VARARGS, getsignal_doc}, {"set_wakeup_fd", signal_set_wakeup_fd, METH_VARARGS, set_wakeup_fd_doc}, +#ifdef HAVE_SIGINTERRUPT + {"siginterrupt", signal_siginterrupt, METH_VARARGS, siginterrupt_doc}, +#endif #ifdef HAVE_PAUSE {"pause", (PyCFunction)signal_pause, METH_NOARGS,pause_doc}, @@ -341,19 +486,32 @@ Functions:\n\ \n\ alarm() -- cause SIGALRM after a specified time [Unix only]\n\ +setitimer() -- cause a signal (described below) after a specified\n\ + float time and the timer may restart then [Unix only]\n\ +getitimer() -- get current value of timer [Unix only]\n\ signal() -- set the action for a given signal\n\ getsignal() -- get the signal action for a given signal\n\ pause() -- wait until a signal arrives [Unix only]\n\ default_int_handler() -- default SIGINT handler\n\ \n\ -Constants:\n\ -\n\ +signal constants:\n\ SIG_DFL -- used to refer to the system default handler\n\ SIG_IGN -- used to ignore the signal\n\ NSIG -- number of defined signals\n\ -\n\ SIGINT, SIGTERM, etc. -- signal numbers\n\ \n\ +itimer constants:\n\ +ITIMER_REAL -- decrements in real time, and delivers SIGALRM upon\n\ + expiration\n\ +ITIMER_VIRTUAL -- decrements only when the process is executing,\n\ + and delivers SIGVTALRM upon expiration\n\ +ITIMER_PROF -- decrements both when the process is executing and\n\ + when the system is executing on behalf of the process.\n\ + Coupled with ITIMER_VIRTUAL, this timer is usually\n\ + used to profile the time spent by the application\n\ + in user and kernel space. SIGPROF is delivered upon\n\ + expiration.\n\ +\n\n\ *** IMPORTANT NOTICE ***\n\ A signal handler function is called with two arguments:\n\ the first is the signal number, the second is the interrupted stack frame."); @@ -606,6 +764,29 @@ PyDict_SetItemString(d, "SIGINFO", x); Py_XDECREF(x); #endif + +#ifdef ITIMER_REAL + x = PyLong_FromLong(ITIMER_REAL); + PyDict_SetItemString(d, "ITIMER_REAL", x); + Py_DECREF(x); +#endif +#ifdef ITIMER_VIRTUAL + x = PyLong_FromLong(ITIMER_VIRTUAL); + PyDict_SetItemString(d, "ITIMER_VIRTUAL", x); + Py_DECREF(x); +#endif +#ifdef ITIMER_PROF + x = PyLong_FromLong(ITIMER_PROF); + PyDict_SetItemString(d, "ITIMER_PROF", x); + Py_DECREF(x); +#endif + +#if defined (HAVE_SETITIMER) || defined (HAVE_GETITIMER) + ItimerError = PyErr_NewException("signal.ItimerError", + PyExc_IOError, NULL); + PyDict_SetItemString(d, "ItimerError", ItimerError); +#endif + if (!PyErr_Occurred()) return; Modified: python/branches/py3k-ctypes-pep3118/Modules/socketmodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/socketmodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/socketmodule.c Wed Apr 30 15:57:13 2008 @@ -2922,15 +2922,10 @@ } if (h->h_addrtype != af) { -#ifdef HAVE_STRERROR /* Let's get real error message to return */ PyErr_SetString(socket_error, (char *)strerror(EAFNOSUPPORT)); -#else - PyErr_SetString( - socket_error, - "Address family not supported by protocol family"); -#endif + return NULL; } Modified: python/branches/py3k-ctypes-pep3118/Modules/syslogmodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/syslogmodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/syslogmodule.c Wed Apr 30 15:57:13 2008 @@ -100,9 +100,10 @@ message = PyUnicode_AsString(message_object); if (message == NULL) return NULL; + Py_BEGIN_ALLOW_THREADS; syslog(priority, "%s", message); - Py_INCREF(Py_None); - return Py_None; + Py_END_ALLOW_THREADS; + Py_RETURN_NONE; } static PyObject * Modified: python/branches/py3k-ctypes-pep3118/Modules/timemodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/timemodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/timemodule.c Wed Apr 30 15:57:13 2008 @@ -561,7 +561,7 @@ if (!strptime_module) return NULL; - strptime_result = PyObject_CallMethod(strptime_module, "strptime", "O", args); + strptime_result = PyObject_CallMethod(strptime_module, "_strptime_time", "O", args); Py_DECREF(strptime_module); return strptime_result; } @@ -661,7 +661,7 @@ #endif /* HAVE_MKTIME */ #ifdef HAVE_WORKING_TZSET -void inittimezone(PyObject *module); +static void inittimezone(PyObject *module); static PyObject * time_tzset(PyObject *self, PyObject *unused) @@ -697,11 +697,12 @@ should not be relied on."); #endif /* HAVE_WORKING_TZSET */ -void inittimezone(PyObject *m) { +static void +inittimezone(PyObject *m) { /* This code moved from inittime wholesale to allow calling it from time_tzset. In the future, some parts of it can be moved back (for platforms that don't HAVE_WORKING_TZSET, when we know what they - are), and the extranious calls to tzset(3) should be removed. + are), and the extraneous calls to tzset(3) should be removed. I haven't done this yet, as I don't want to change this code as little as possible when introducing the time.tzset and time.tzsetwall methods. This should simply be a method of doing the following once, Modified: python/branches/py3k-ctypes-pep3118/Modules/zlibmodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Modules/zlibmodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Modules/zlibmodule.c Wed Apr 30 15:57:13 2008 @@ -794,6 +794,10 @@ if (!PyArg_ParseTuple(args, "|i:flush", &length)) return NULL; + if (length <= 0) { + PyErr_SetString(PyExc_ValueError, "length must be greater than zero"); + return NULL; + } if (!(retval = PyBytes_FromStringAndSize(NULL, length))) return NULL; @@ -915,14 +919,14 @@ static PyObject * PyZlib_adler32(PyObject *self, PyObject *args) { - uLong adler32val = adler32(0L, Z_NULL, 0); + unsigned int adler32val = 1; /* adler32(0L, Z_NULL, 0) */ Byte *buf; int len; - if (!PyArg_ParseTuple(args, "s#|k:adler32", &buf, &len, &adler32val)) + if (!PyArg_ParseTuple(args, "s#|I:adler32", &buf, &len, &adler32val)) return NULL; adler32val = adler32(adler32val, buf, len); - return PyLong_FromLong(adler32val); + return PyLong_FromUnsignedLong(adler32val & 0xffffffffU); } PyDoc_STRVAR(crc32__doc__, @@ -934,13 +938,14 @@ static PyObject * PyZlib_crc32(PyObject *self, PyObject *args) { - uLong crc32val = crc32(0L, Z_NULL, 0); + unsigned int crc32val = 0; /* crc32(0L, Z_NULL, 0) */ Byte *buf; - int len; - if (!PyArg_ParseTuple(args, "s#|k:crc32", &buf, &len, &crc32val)) + int len, signed_val; + + if (!PyArg_ParseTuple(args, "s#|I:crc32", &buf, &len, &crc32val)) return NULL; - crc32val = crc32(crc32val, buf, len); - return PyLong_FromLong(crc32val); + signed_val = crc32(crc32val, buf, len); + return PyLong_FromUnsignedLong(signed_val & 0xffffffffU); } Modified: python/branches/py3k-ctypes-pep3118/Objects/abstract.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/abstract.c (original) +++ python/branches/py3k-ctypes-pep3118/Objects/abstract.c Wed Apr 30 15:57:13 2008 @@ -673,7 +673,7 @@ { if (view == NULL) return 0; if (((flags & PyBUF_LOCK) == PyBUF_LOCK) && - readonly >= 0) { + readonly != 0) { PyErr_SetString(PyExc_BufferError, "Cannot lock this object."); return -1; @@ -704,6 +704,57 @@ return 0; } +PyObject * +PyObject_Format(PyObject *obj, PyObject *format_spec) +{ + static PyObject * str__format__ = NULL; + PyObject *meth; + PyObject *empty = NULL; + PyObject *result = NULL; + + /* Initialize cached value */ + if (str__format__ == NULL) { + /* Initialize static variable needed by _PyType_Lookup */ + str__format__ = PyUnicode_FromString("__format__"); + if (str__format__ == NULL) + goto done; + } + + /* If no format_spec is provided, use an empty string */ + if (format_spec == NULL) { + empty = PyUnicode_FromUnicode(NULL, 0); + format_spec = empty; + } + + /* Make sure the type is initialized. float gets initialized late */ + if (Py_TYPE(obj)->tp_dict == NULL) + if (PyType_Ready(Py_TYPE(obj)) < 0) + goto done; + + /* Find the (unbound!) __format__ method (a borrowed reference) */ + meth = _PyType_Lookup(Py_TYPE(obj), str__format__); + if (meth == NULL) { + PyErr_Format(PyExc_TypeError, + "Type %.100s doesn't define __format__", + Py_TYPE(obj)->tp_name); + goto done; + } + + /* And call it, binding it to the value */ + result = PyObject_CallFunctionObjArgs(meth, obj, format_spec, NULL); + + if (result && !PyUnicode_Check(result)) { + PyErr_SetString(PyExc_TypeError, + "__format__ method did not return string"); + Py_DECREF(result); + result = NULL; + goto done; + } + +done: + Py_XDECREF(empty); + return result; +} /* Operations on numbers */ int @@ -1242,6 +1293,40 @@ } +PyObject * +_PyNumber_ConvertIntegralToInt(PyObject *integral, const char* error_format) +{ + static PyObject *int_name = NULL; + if (int_name == NULL) { + int_name = PyUnicode_InternFromString("__int__"); + if (int_name == NULL) + return NULL; + } + + if (integral && !PyLong_Check(integral)) { + /* Don't go through tp_as_number->nb_int to avoid + hitting the classic class fallback to __trunc__. */ + PyObject *int_func = PyObject_GetAttr(integral, int_name); + if (int_func == NULL) { + PyErr_Clear(); /* Raise a different error. */ + goto non_integral_error; + } + Py_DECREF(integral); + integral = PyEval_CallObject(int_func, NULL); + Py_DECREF(int_func); + if (integral && !PyLong_Check(integral)) { + goto non_integral_error; + } + } + return integral; + +non_integral_error: + PyErr_Format(PyExc_TypeError, error_format, Py_TYPE(integral)->tp_name); + Py_DECREF(integral); + return NULL; +} + + /* Add a check for embedded NULL-bytes in the argument. */ static PyObject * long_from_string(const char *s, Py_ssize_t len) @@ -1265,9 +1350,17 @@ PyNumber_Long(PyObject *o) { PyNumberMethods *m; + static PyObject *trunc_name = NULL; + PyObject *trunc_func; const char *buffer; Py_ssize_t buffer_len; + if (trunc_name == NULL) { + trunc_name = PyUnicode_InternFromString("__trunc__"); + if (trunc_name == NULL) + return NULL; + } + if (o == NULL) return null_error(); if (PyLong_CheckExact(o)) { @@ -1287,6 +1380,7 @@ return res; } if (m && m->nb_long) { /* This should include subclasses of long */ + /* Classic classes always take this branch. */ PyObject *res = m->nb_long(o); if (res && !PyLong_Check(res)) { PyErr_Format(PyExc_TypeError, @@ -1299,6 +1393,27 @@ } if (PyLong_Check(o)) /* A long subclass without nb_long */ return _PyLong_Copy((PyLongObject *)o); + trunc_func = PyObject_GetAttr(o, trunc_name); + if (trunc_func) { + PyObject *truncated = PyEval_CallObject(trunc_func, NULL); + PyObject *int_instance; + Py_DECREF(trunc_func); + /* __trunc__ is specified to return an Integral type, + but long() needs to return a long. */ + int_instance = _PyNumber_ConvertIntegralToInt( + truncated, + "__trunc__ returned non-Integral (type %.200s)"); + return int_instance; + } + PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */ + + if (PyString_Check(o)) + /* need to do extra error checking that PyLong_FromString() + * doesn't do. In particular long('9.5') must raise an + * exception, not truncate the float. + */ + return long_from_string(PyString_AS_STRING(o), + PyString_GET_SIZE(o)); if (PyUnicode_Check(o)) /* The above check is done in PyLong_FromUnicode(). */ return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o), @@ -1341,13 +1456,19 @@ PyObject * PyNumber_ToBase(PyObject *n, int base) { - PyObject *res; + PyObject *res = NULL; PyObject *index = PyNumber_Index(n); if (!index) return NULL; - assert(PyLong_Check(index)); - res = _PyLong_Format(index, base); + if (PyLong_Check(index)) + res = _PyLong_Format(index, base); + else + /* It should not be possible to get here, as + PyNumber_Index already has a check for the same + condition */ + PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not " + "int or long"); Py_DECREF(index); return res; } @@ -2333,7 +2454,7 @@ PyObject *bases; if (__bases__ == NULL) { - __bases__ = PyUnicode_FromString("__bases__"); + __bases__ = PyUnicode_InternFromString("__bases__"); if (__bases__ == NULL) return NULL; } @@ -2413,7 +2534,7 @@ int retval = 0; if (__class__ == NULL) { - __class__ = PyUnicode_FromString("__class__"); + __class__ = PyUnicode_InternFromString("__class__"); if (__class__ == NULL) return -1; } @@ -2476,11 +2597,21 @@ int PyObject_IsInstance(PyObject *inst, PyObject *cls) { - PyObject *t, *v, *tb; + static PyObject *name = NULL; PyObject *checker; - PyErr_Fetch(&t, &v, &tb); - checker = PyObject_GetAttrString(cls, "__instancecheck__"); - PyErr_Restore(t, v, tb); + + /* Quick test for an exact match */ + if (Py_TYPE(inst) == (PyTypeObject *)cls) + return 1; + + if (name == NULL) { + name = PyUnicode_InternFromString("__instancecheck__"); + if (name == NULL) + return -1; + } + checker = PyObject_GetAttr(cls, name); + if (checker == NULL && PyErr_Occurred()) + PyErr_Clear(); if (checker != NULL) { PyObject *res; int ok = -1; @@ -2547,10 +2678,17 @@ int PyObject_IsSubclass(PyObject *derived, PyObject *cls) { + static PyObject *name = NULL; PyObject *t, *v, *tb; PyObject *checker; PyErr_Fetch(&t, &v, &tb); - checker = PyObject_GetAttrString(cls, "__subclasscheck__"); + + if (name == NULL) { + name = PyUnicode_InternFromString("__subclasscheck__"); + if (name == NULL) + return -1; + } + checker = PyObject_GetAttr(cls, name); PyErr_Restore(t, v, tb); if (checker != NULL) { PyObject *res; Modified: python/branches/py3k-ctypes-pep3118/Objects/bytesobject.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/bytesobject.c (original) +++ python/branches/py3k-ctypes-pep3118/Objects/bytesobject.c Wed Apr 30 15:57:13 2008 @@ -52,27 +52,27 @@ static int bytes_getbuffer(PyBytesObject *obj, Py_buffer *view, int flags) { - int ret; - void *ptr; - if (view == NULL) { - obj->ob_exports++; - return 0; - } - if (obj->ob_bytes == NULL) - ptr = ""; - else - ptr = obj->ob_bytes; - ret = PyBuffer_FillInfo(view, ptr, Py_SIZE(obj), 0, flags); - if (ret >= 0) { - obj->ob_exports++; - } - return ret; + int ret; + void *ptr; + if (view == NULL) { + obj->ob_exports++; + return 0; + } + if (obj->ob_bytes == NULL) + ptr = ""; + else + ptr = obj->ob_bytes; + ret = PyBuffer_FillInfo(view, ptr, Py_SIZE(obj), 0, flags); + if (ret >= 0) { + obj->ob_exports++; + } + return ret; } static void bytes_releasebuffer(PyBytesObject *obj, Py_buffer *view) { - obj->ob_exports--; + obj->ob_exports--; } static Py_ssize_t @@ -108,7 +108,11 @@ PyBytesObject *new; Py_ssize_t alloc; - assert(size >= 0); + if (size < 0) { + PyErr_SetString(PyExc_SystemError, + "Negative size passed to PyBytes_FromStringAndSize"); + return NULL; + } new = PyObject_New(PyBytesObject, &PyBytes_Type); if (new == NULL) @@ -2388,16 +2392,16 @@ for (i = j = len - 1; i >= 0; ) { /* find a token */ - while (i >= 0 && Py_UNICODE_ISSPACE(s[i])) + while (i >= 0 && ISSPACE(s[i])) i--; j = i; - while (i >= 0 && !Py_UNICODE_ISSPACE(s[i])) + while (i >= 0 && !ISSPACE(s[i])) i--; if (j > i) { if (maxcount-- <= 0) break; SPLIT_ADD(s, i + 1, j + 1); - while (i >= 0 && Py_UNICODE_ISSPACE(s[i])) + while (i >= 0 && ISSPACE(s[i])) i--; j = i; } @@ -2581,7 +2585,7 @@ static PyObject * bytes_extend(PyBytesObject *self, PyObject *arg) { - PyObject *it, *item, *tmp, *res; + PyObject *it, *item, *bytes_obj; Py_ssize_t buf_size = 0, len = 0; int value; char *buf; @@ -2601,36 +2605,46 @@ /* Try to determine the length of the argument. 32 is abitrary. */ buf_size = _PyObject_LengthHint(arg, 32); - buf = (char *)PyMem_Malloc(buf_size * sizeof(char)); - if (buf == NULL) - return PyErr_NoMemory(); + bytes_obj = PyBytes_FromStringAndSize(NULL, buf_size); + if (bytes_obj == NULL) + return NULL; + buf = PyBytes_AS_STRING(bytes_obj); while ((item = PyIter_Next(it)) != NULL) { if (! _getbytevalue(item, &value)) { Py_DECREF(item); Py_DECREF(it); + Py_DECREF(bytes_obj); return NULL; } buf[len++] = value; Py_DECREF(item); + if (len >= buf_size) { buf_size = len + (len >> 1) + 1; - buf = (char *)PyMem_Realloc(buf, buf_size * sizeof(char)); - if (buf == NULL) { + if (PyBytes_Resize((PyObject *)bytes_obj, buf_size) < 0) { Py_DECREF(it); - return PyErr_NoMemory(); + Py_DECREF(bytes_obj); + return NULL; } + /* Recompute the `buf' pointer, since the resizing operation may + have invalidated it. */ + buf = PyBytes_AS_STRING(bytes_obj); } } Py_DECREF(it); - /* XXX: Is possible to avoid a full copy of the buffer? */ - tmp = PyBytes_FromStringAndSize(buf, len); - res = bytes_extend(self, tmp); - Py_DECREF(tmp); - PyMem_Free(buf); + /* Resize down to exact size. */ + if (PyBytes_Resize((PyObject *)bytes_obj, len) < 0) { + Py_DECREF(bytes_obj); + return NULL; + } - return res; + if (bytes_setslice(self, Py_SIZE(self), Py_SIZE(self), bytes_obj) == -1) + return NULL; + Py_DECREF(bytes_obj); + + Py_RETURN_NONE; } PyDoc_STRVAR(pop__doc__, Modified: python/branches/py3k-ctypes-pep3118/Objects/cellobject.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/cellobject.c (original) +++ python/branches/py3k-ctypes-pep3118/Objects/cellobject.c Wed Apr 30 15:57:13 2008 @@ -31,13 +31,15 @@ int PyCell_Set(PyObject *op, PyObject *obj) { + PyObject* oldobj; if (!PyCell_Check(op)) { PyErr_BadInternalCall(); return -1; } - Py_XDECREF(((PyCellObject*)op)->ob_ref); + oldobj = PyCell_GET(op); Py_XINCREF(obj); PyCell_SET(op, obj); + Py_XDECREF(oldobj); return 0; } @@ -49,6 +51,18 @@ PyObject_GC_Del(op); } +static int +cell_compare(PyCellObject *a, PyCellObject *b) +{ + if (a->ob_ref == NULL) { + if (b->ob_ref == NULL) + return 0; + return -1; + } else if (b->ob_ref == NULL) + return 1; + return PyObject_Compare(a->ob_ref, b->ob_ref); +} + static PyObject * cell_repr(PyCellObject *op) { @@ -100,7 +114,7 @@ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ - 0, /* tp_compare */ + (cmpfunc)cell_compare, /* tp_compare */ (reprfunc)cell_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ Modified: python/branches/py3k-ctypes-pep3118/Objects/classobject.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/classobject.c (original) +++ python/branches/py3k-ctypes-pep3118/Objects/classobject.c Wed Apr 30 15:57:13 2008 @@ -5,6 +5,15 @@ #define TP_DESCR_GET(t) ((t)->tp_descr_get) +/* Free list for method objects to safe malloc/free overhead + * The im_self element is used to chain the elements. + */ +static PyMethodObject *free_list; +static int numfree = 0; +#ifndef PyMethod_MAXFREELIST +#define PyMethod_MAXFREELIST 256 +#endif + PyObject * PyMethod_Function(PyObject *im) { @@ -30,8 +39,6 @@ function. */ -static PyMethodObject *free_list; - PyObject * PyMethod_New(PyObject *func, PyObject *self) { @@ -48,6 +55,7 @@ if (im != NULL) { free_list = (PyMethodObject *)(im->im_self); PyObject_INIT(im, &PyMethod_Type); + numfree--; } else { im = PyObject_GC_New(PyMethodObject, &PyMethod_Type); @@ -165,8 +173,14 @@ PyObject_ClearWeakRefs((PyObject *)im); Py_DECREF(im->im_func); Py_XDECREF(im->im_self); - im->im_self = (PyObject *)free_list; - free_list = im; + if (numfree < PyMethod_MAXFREELIST) { + im->im_self = (PyObject *)free_list; + free_list = im; + numfree++; + } + else { + PyObject_GC_Del(im); + } } static PyObject * @@ -368,14 +382,25 @@ /* Clear out the free list */ -void -PyMethod_Fini(void) +int +PyMethod_ClearFreeList(void) { + int freelist_size = numfree; + while (free_list) { PyMethodObject *im = free_list; free_list = (PyMethodObject *)(im->im_self); PyObject_GC_Del(im); + numfree--; } + assert(numfree == 0); + return freelist_size; +} + +void +PyMethod_Fini(void) +{ + (void)PyMethod_ClearFreeList(); } /* ------------------------------------------------------------------------ Modified: python/branches/py3k-ctypes-pep3118/Objects/codeobject.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/codeobject.c (original) +++ python/branches/py3k-ctypes-pep3118/Objects/codeobject.c Wed Apr 30 15:57:13 2008 @@ -179,8 +179,9 @@ } PyDoc_STRVAR(code_doc, -"code(argcount, nlocals, stacksize, flags, codestring, constants, names,\n\ - varnames, filename, name, firstlineno, lnotab[, freevars[, cellvars]])\n\ +"code(argcount, kwonlyargcount nlocals, stacksize, flags, codestring,\n\ + constants, names, varnames, filename, name, firstlineno,\n\ + lnotab[, freevars[, cellvars]])\n\ \n\ Create a code object. Not for the faint of heart."); Modified: python/branches/py3k-ctypes-pep3118/Objects/complexobject.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/complexobject.c (original) +++ python/branches/py3k-ctypes-pep3118/Objects/complexobject.c Wed Apr 30 15:57:13 2008 @@ -8,6 +8,10 @@ #include "Python.h" #include "structmember.h" +#ifdef HAVE_IEEEFP_H +#include +#endif + #ifndef WITHOUT_COMPLEX /* Precisions used by repr() and str(), respectively. @@ -183,6 +187,38 @@ } +double +c_abs(Py_complex z) +{ + /* sets errno = ERANGE on overflow; otherwise errno = 0 */ + double result; + + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + /* C99 rules: if either the real or the imaginary part is an + infinity, return infinity, even if the other part is a + NaN. */ + if (Py_IS_INFINITY(z.real)) { + result = fabs(z.real); + errno = 0; + return result; + } + if (Py_IS_INFINITY(z.imag)) { + result = fabs(z.imag); + errno = 0; + return result; + } + /* either the real or imaginary part is a NaN, + and neither is infinite. Result should be NaN. */ + return Py_NAN; + } + result = hypot(z.real, z.imag); + if (!Py_IS_FINITE(result)) + errno = ERANGE; + else + errno = 0; + return result; +} + static PyObject * complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval) { @@ -265,13 +301,14 @@ /* return -1 on failure */ cv.real = -1.; cv.imag = 0.; - + + if (complex_str == NULL) { + if (!(complex_str = PyUnicode_FromString("__complex__"))) + return cv; + } + { PyObject *complexfunc; - if (!complex_str) { - if (!(complex_str = PyUnicode_FromString("__complex__"))) - return cv; - } complexfunc = _PyType_Lookup(op->ob_type, complex_str); /* complexfunc is a borrowed reference */ if (complexfunc) { @@ -313,16 +350,48 @@ { char format[32]; if (v->cval.real == 0.) { - PyOS_snprintf(format, sizeof(format), "%%.%ig", precision); - PyOS_ascii_formatd(buf, bufsz - 1, format, v->cval.imag); - strncat(buf, "j", 1); + if (!Py_IS_FINITE(v->cval.imag)) { + if (Py_IS_NAN(v->cval.imag)) + strncpy(buf, "nan*j", 6); + else if (copysign(1, v->cval.imag) == 1) + strncpy(buf, "inf*j", 6); + else + strncpy(buf, "-inf*j", 7); + } + else { + PyOS_snprintf(format, sizeof(format), "%%.%ig", precision); + PyOS_ascii_formatd(buf, bufsz - 1, format, v->cval.imag); + strncat(buf, "j", 1); + } } else { char re[64], im[64]; /* Format imaginary part with sign, real part without */ - PyOS_snprintf(format, sizeof(format), "%%.%ig", precision); - PyOS_ascii_formatd(re, sizeof(re), format, v->cval.real); - PyOS_snprintf(format, sizeof(format), "%%+.%ig", precision); - PyOS_ascii_formatd(im, sizeof(im), format, v->cval.imag); + if (!Py_IS_FINITE(v->cval.real)) { + if (Py_IS_NAN(v->cval.real)) + strncpy(re, "nan", 4); + /* else if (copysign(1, v->cval.real) == 1) */ + else if (v->cval.real > 0) + strncpy(re, "inf", 4); + else + strncpy(re, "-inf", 5); + } + else { + PyOS_snprintf(format, sizeof(format), "%%.%ig", precision); + PyOS_ascii_formatd(re, sizeof(re), format, v->cval.real); + } + if (!Py_IS_FINITE(v->cval.imag)) { + if (Py_IS_NAN(v->cval.imag)) + strncpy(im, "+nan*", 6); + /* else if (copysign(1, v->cval.imag) == 1) */ + else if (v->cval.imag > 0) + strncpy(im, "+inf*", 6); + else + strncpy(im, "-inf*", 6); + } + else { + PyOS_snprintf(format, sizeof(format), "%%+.%ig", precision); + PyOS_ascii_formatd(im, sizeof(im), format, v->cval.imag); + } PyOS_snprintf(buf, bufsz, "(%s%sj)", re, im); } } @@ -540,9 +609,16 @@ complex_abs(PyComplexObject *v) { double result; + PyFPE_START_PROTECT("complex_abs", return 0) - result = hypot(v->cval.real,v->cval.imag); + result = c_abs(v->cval); PyFPE_END_PROTECT(result) + + if (errno == ERANGE) { + PyErr_SetString(PyExc_OverflowError, + "absolute value too large"); + return NULL; + } return PyFloat_FromDouble(result); } @@ -620,9 +696,29 @@ return Py_BuildValue("(D)", &v->cval); } +#if 0 +static PyObject * +complex_is_finite(PyObject *self) +{ + Py_complex c; + c = ((PyComplexObject *)self)->cval; + return PyBool_FromLong((long)(Py_IS_FINITE(c.real) && + Py_IS_FINITE(c.imag))); +} + +PyDoc_STRVAR(complex_is_finite_doc, +"complex.is_finite() -> bool\n" +"\n" +"Returns True if the real and the imaginary part is finite."); +#endif + static PyMethodDef complex_methods[] = { {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS, complex_conjugate_doc}, +#if 0 + {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS, + complex_is_finite_doc}, +#endif {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS}, {NULL, NULL} /* sentinel */ }; Modified: python/branches/py3k-ctypes-pep3118/Objects/descrobject.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/descrobject.c (original) +++ python/branches/py3k-ctypes-pep3118/Objects/descrobject.c Wed Apr 30 15:57:13 2008 @@ -168,7 +168,7 @@ int *pres) { assert(obj != NULL); - if (!PyObject_IsInstance(obj, (PyObject *)(descr->d_type))) { + if (!PyObject_TypeCheck(obj, descr->d_type)) { PyErr_Format(PyExc_TypeError, "descriptor '%V' for '%.100s' objects " "doesn't apply to '%.100s' object", @@ -1083,7 +1083,7 @@ PyDoc_STRVAR(getter_doc, "Descriptor to change the getter on a property."); -PyObject * +static PyObject * property_getter(PyObject *self, PyObject *getter) { return property_copy(self, getter, NULL, NULL, NULL); @@ -1093,7 +1093,7 @@ PyDoc_STRVAR(setter_doc, "Descriptor to change the setter on a property."); -PyObject * +static PyObject * property_setter(PyObject *self, PyObject *setter) { return property_copy(self, NULL, setter, NULL, NULL); @@ -1103,7 +1103,7 @@ PyDoc_STRVAR(deleter_doc, "Descriptor to change the deleter on a property."); -PyObject * +static PyObject * property_deleter(PyObject *self, PyObject *deleter) { return property_copy(self, NULL, NULL, deleter, NULL); Modified: python/branches/py3k-ctypes-pep3118/Objects/dictobject.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/dictobject.c (original) +++ python/branches/py3k-ctypes-pep3118/Objects/dictobject.c Wed Apr 30 15:57:13 2008 @@ -163,6 +163,24 @@ } #endif +/* Debug statistic to compare allocations with reuse through the free list */ +#undef SHOW_ALLOC_COUNT +#ifdef SHOW_ALLOC_COUNT +static size_t count_alloc = 0; +static size_t count_reuse = 0; + +static void +show_alloc(void) +{ + fprintf(stderr, "Dict allocations: %" PY_FORMAT_SIZE_T "d\n", + count_alloc); + fprintf(stderr, "Dict reuse through freelist: %" PY_FORMAT_SIZE_T + "d\n", count_reuse); + fprintf(stderr, "%.2f%% reuse rate\n\n", + (100.0*count_reuse/(count_alloc+count_reuse))); +} +#endif + /* Initialization macros. There are two ways to create a dict: PyDict_New() is the main C API function, and the tp_new slot maps to dict_new(). In the latter case we @@ -184,9 +202,23 @@ } while(0) /* Dictionary reuse scheme to save calls to malloc, free, and memset */ -#define MAXFREEDICTS 80 -static PyDictObject *free_dicts[MAXFREEDICTS]; -static int num_free_dicts = 0; +#ifndef PyDict_MAXFREELIST +#define PyDict_MAXFREELIST 80 +#endif +static PyDictObject *free_list[PyDict_MAXFREELIST]; +static int numfree = 0; + +void +PyDict_Fini(void) +{ + PyDictObject *op; + + while (numfree) { + op = free_list[--numfree]; + assert(PyDict_CheckExact(op)); + PyObject_GC_Del(op); + } +} PyObject * PyDict_New(void) @@ -199,9 +231,12 @@ #ifdef SHOW_CONVERSION_COUNTS Py_AtExit(show_counts); #endif +#ifdef SHOW_ALLOC_COUNT + Py_AtExit(show_alloc); +#endif } - if (num_free_dicts) { - mp = free_dicts[--num_free_dicts]; + if (numfree) { + mp = free_list[--numfree]; assert (mp != NULL); assert (Py_TYPE(mp) == &PyDict_Type); _Py_NewReference((PyObject *)mp); @@ -211,11 +246,17 @@ assert (mp->ma_used == 0); assert (mp->ma_table == mp->ma_smalltable); assert (mp->ma_mask == PyDict_MINSIZE - 1); +#ifdef SHOW_ALLOC_COUNT + count_reuse++; +#endif } else { mp = PyObject_GC_New(PyDictObject, &PyDict_Type); if (mp == NULL) return NULL; EMPTY_TO_MINSIZE(mp); +#ifdef SHOW_ALLOC_COUNT + count_alloc++; +#endif } mp->ma_lookup = lookdict_unicode; #ifdef SHOW_CONVERSION_COUNTS @@ -897,8 +938,8 @@ } if (mp->ma_table != mp->ma_smalltable) PyMem_DEL(mp->ma_table); - if (num_free_dicts < MAXFREEDICTS && Py_TYPE(mp) == &PyDict_Type) - free_dicts[num_free_dicts++] = mp; + if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type) + free_list[numfree++] = mp; else Py_TYPE(mp)->tp_free((PyObject *)mp); Py_TRASHCAN_SAFE_END(mp) @@ -1379,7 +1420,7 @@ return -1; } mp = (PyDictObject*)a; - if (PyDict_CheckExact(b)) { + if (PyDict_Check(b)) { other = (PyDictObject*)b; if (other == mp || other->ma_used == 0) /* a.update(a) or a.update({}); nothing to do */ Deleted: python/branches/py3k-ctypes-pep3118/Objects/doubledigits.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/doubledigits.c Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,601 +0,0 @@ -/* Free-format floating point printer - * - * Based on "Floating-Point Printer Sample Code", by Robert G. Burger, - * http://www.cs.indiana.edu/~burger/fp/index.html - */ - -#include "Python.h" - -#if defined(__alpha) || defined(__i386) || defined(_M_IX86) || defined(_M_X64) || defined(_M_IA64) -#define LITTLE_ENDIAN_IEEE_DOUBLE -#elif !(defined(__ppc__) || defined(sparc) || defined(__sgi) || defined(_IBMR2) || defined(hpux)) -#error unknown machine type -#endif - -#if defined(_M_IX86) -#define UNSIGNED64 unsigned __int64 -#elif defined(__alpha) -#define UNSIGNED64 unsigned long -#else -#define UNSIGNED64 unsigned long long -#endif - -#ifndef U32 -#define U32 unsigned int -#endif - -/* exponent stored + 1024, hidden bit to left of decimal point */ -#define bias 1023 -#define bitstoright 52 -#define m1mask 0xf -#define hidden_bit 0x100000 -#ifdef LITTLE_ENDIAN_IEEE_DOUBLE -struct dblflt { - unsigned int m4: 16; - unsigned int m3: 16; - unsigned int m2: 16; - unsigned int m1: 4; - unsigned int e: 11; - unsigned int s: 1; -}; -#else -/* Big Endian IEEE Double Floats */ -struct dblflt { - unsigned int s: 1; - unsigned int e: 11; - unsigned int m1: 4; - unsigned int m2: 16; - unsigned int m3: 16; - unsigned int m4: 16; -}; -#endif -#define float_radix 2.147483648e9 - - -typedef UNSIGNED64 Bigit; -#define BIGSIZE 24 -#define MIN_E -1074 -#define MAX_FIVE 325 -#define B_P1 ((Bigit)1 << 52) - -typedef struct { - int l; - Bigit d[BIGSIZE]; -} Bignum; - -static Bignum R, S, MP, MM, five[MAX_FIVE]; -static Bignum S2, S3, S4, S5, S6, S7, S8, S9; -static int ruf, k, s_n, use_mp, qr_shift, sl, slr; - -static void mul10(Bignum *x); -static void big_short_mul(Bignum *x, Bigit y, Bignum *z); -/* -static void print_big(Bignum *x); -*/ -static int estimate(int n); -static void one_shift_left(int y, Bignum *z); -static void short_shift_left(Bigit x, int y, Bignum *z); -static void big_shift_left(Bignum *x, int y, Bignum *z); -static int big_comp(Bignum *x, Bignum *y); -static int sub_big(Bignum *x, Bignum *y, Bignum *z); -static void add_big(Bignum *x, Bignum *y, Bignum *z); -static int add_cmp(void); -static int qr(void); - -/*static int _PyFloat_Digits(char *buf, double v, int *signum);*/ -/*static void _PyFloat_DigitsInit(void);*/ - -#define ADD(x, y, z, k) {\ - Bigit x_add, z_add;\ - x_add = (x);\ - if ((k))\ - z_add = x_add + (y) + 1, (k) = (z_add <= x_add);\ - else\ - z_add = x_add + (y), (k) = (z_add < x_add);\ - (z) = z_add;\ -} - -#define SUB(x, y, z, b) {\ - Bigit x_sub, y_sub;\ - x_sub = (x); y_sub = (y);\ - if ((b))\ - (z) = x_sub - y_sub - 1, b = (y_sub >= x_sub);\ - else\ - (z) = x_sub - y_sub, b = (y_sub > x_sub);\ -} - -#define MUL(x, y, z, k) {\ - Bigit x_mul, low, high;\ - x_mul = (x);\ - low = (x_mul & 0xffffffff) * (y) + (k);\ - high = (x_mul >> 32) * (y) + (low >> 32);\ - (k) = high >> 32;\ - (z) = (low & 0xffffffff) | (high << 32);\ -} - -#define SLL(x, y, z, k) {\ - Bigit x_sll = (x);\ - (z) = (x_sll << (y)) | (k);\ - (k) = x_sll >> (64 - (y));\ -} - -static void -mul10(Bignum *x) -{ - int i, l; - Bigit *p, k; - - l = x->l; - for (i = l, p = &x->d[0], k = 0; i >= 0; i--) - MUL(*p, 10, *p++, k); - if (k != 0) - *p = k, x->l = l+1; -} - -static void -big_short_mul(Bignum *x, Bigit y, Bignum *z) -{ - int i, xl, zl; - Bigit *xp, *zp, k; - U32 high, low; - - xl = x->l; - xp = &x->d[0]; - zl = xl; - zp = &z->d[0]; - high = y >> 32; - low = y & 0xffffffff; - for (i = xl, k = 0; i >= 0; i--, xp++, zp++) { - Bigit xlow, xhigh, z0, t, c, z1; - xlow = *xp & 0xffffffff; - xhigh = *xp >> 32; - z0 = (xlow * low) + k; /* Cout is (z0 < k) */ - t = xhigh * low; - z1 = (xlow * high) + t; - c = (z1 < t); - t = z0 >> 32; - z1 += t; - c += (z1 < t); - *zp = (z1 << 32) | (z0 & 0xffffffff); - k = (xhigh * high) + (c << 32) + (z1 >> 32) + (z0 < k); - } - if (k != 0) - *zp = k, zl++; - z->l = zl; -} - -/* -static void -print_big(Bignum *x) -{ - int i; - Bigit *p; - - printf("#x"); - i = x->l; - p = &x->d[i]; - for (p = &x->d[i]; i >= 0; i--) { - Bigit b = *p--; - printf("%08x%08x", (int)(b >> 32), (int)(b & 0xffffffff)); - } -} -*/ - -static int -estimate(int n) -{ - if (n < 0) - return (int)(n*0.3010299956639812); - else - return 1+(int)(n*0.3010299956639811); -} - -static void -one_shift_left(int y, Bignum *z) -{ - int n, m, i; - Bigit *zp; - - n = y / 64; - m = y % 64; - zp = &z->d[0]; - for (i = n; i > 0; i--) *zp++ = 0; - *zp = (Bigit)1 << m; - z->l = n; -} - -static void -short_shift_left(Bigit x, int y, Bignum *z) -{ - int n, m, i, zl; - Bigit *zp; - - n = y / 64; - m = y % 64; - zl = n; - zp = &(z->d[0]); - for (i = n; i > 0; i--) *zp++ = 0; - if (m == 0) - *zp = x; - else { - Bigit high = x >> (64 - m); - *zp = x << m; - if (high != 0) - *++zp = high, zl++; - } - z->l = zl; -} - -static void -big_shift_left(Bignum *x, int y, Bignum *z) -{ - int n, m, i, xl, zl; - Bigit *xp, *zp, k; - - n = y / 64; - m = y % 64; - xl = x->l; - xp = &(x->d[0]); - zl = xl + n; - zp = &(z->d[0]); - for (i = n; i > 0; i--) *zp++ = 0; - if (m == 0) - for (i = xl; i >= 0; i--) *zp++ = *xp++; - else { - for (i = xl, k = 0; i >= 0; i--) - SLL(*xp++, m, *zp++, k); - if (k != 0) - *zp = k, zl++; - } - z->l = zl; -} - - -static int -big_comp(Bignum *x, Bignum *y) -{ - int i, xl, yl; - Bigit *xp, *yp; - - xl = x->l; - yl = y->l; - if (xl > yl) return 1; - if (xl < yl) return -1; - xp = &x->d[xl]; - yp = &y->d[xl]; - for (i = xl; i >= 0; i--, xp--, yp--) { - Bigit a = *xp; - Bigit b = *yp; - - if (a > b) return 1; - else if (a < b) return -1; - } - return 0; -} - -static int -sub_big(Bignum *x, Bignum *y, Bignum *z) -{ - int xl, yl, zl, b, i; - Bigit *xp, *yp, *zp; - - xl = x->l; - yl = y->l; - if (yl > xl) return 1; - xp = &x->d[0]; - yp = &y->d[0]; - zp = &z->d[0]; - - for (i = yl, b = 0; i >= 0; i--) - SUB(*xp++, *yp++, *zp++, b); - for (i = xl-yl; b && i > 0; i--) { - Bigit x_sub; - x_sub = *xp++; - *zp++ = x_sub - 1; - b = (x_sub == 0); - } - for (; i > 0; i--) *zp++ = *xp++; - if (b) return 1; - zl = xl; - while (*--zp == 0) zl--; - z->l = zl; - return 0; -} - -static void -add_big(Bignum *x, Bignum *y, Bignum *z) -{ - int xl, yl, k, i; - Bigit *xp, *yp, *zp; - - xl = x->l; - yl = y->l; - if (yl > xl) { - int tl; - Bignum *tn; - tl = xl; xl = yl; yl = tl; - tn = x; x = y; y = tn; - } - - xp = &x->d[0]; - yp = &y->d[0]; - zp = &z->d[0]; - - for (i = yl, k = 0; i >= 0; i--) - ADD(*xp++, *yp++, *zp++, k); - for (i = xl-yl; k && i > 0; i--) { - Bigit z_add; - z_add = *xp++ + 1; - k = (z_add == 0); - *zp++ = z_add; - } - for (; i > 0; i--) *zp++ = *xp++; - if (k) - *zp = 1, z->l = xl+1; - else - z->l = xl; -} - -static int -add_cmp() -{ - int rl, ml, sl, suml; - static Bignum sum; - - rl = R.l; - ml = (use_mp ? MP.l : MM.l); - sl = S.l; - - suml = rl >= ml ? rl : ml; - if ((sl > suml+1) || ((sl == suml+1) && (S.d[sl] > 1))) return -1; - if (sl < suml) return 1; - - add_big(&R, (use_mp ? &MP : &MM), &sum); - return big_comp(&sum, &S); -} - -static int -qr() -{ - if (big_comp(&R, &S5) < 0) - if (big_comp(&R, &S2) < 0) - if (big_comp(&R, &S) < 0) - return 0; - else { - sub_big(&R, &S, &R); - return 1; - } - else if (big_comp(&R, &S3) < 0) { - sub_big(&R, &S2, &R); - return 2; - } - else if (big_comp(&R, &S4) < 0) { - sub_big(&R, &S3, &R); - return 3; - } - else { - sub_big(&R, &S4, &R); - return 4; - } - else if (big_comp(&R, &S7) < 0) - if (big_comp(&R, &S6) < 0) { - sub_big(&R, &S5, &R); - return 5; - } - else { - sub_big(&R, &S6, &R); - return 6; - } - else if (big_comp(&R, &S9) < 0) - if (big_comp(&R, &S8) < 0) { - sub_big(&R, &S7, &R); - return 7; - } - else { - sub_big(&R, &S8, &R); - return 8; - } - else { - sub_big(&R, &S9, &R); - return 9; - } -} - -#define OUTDIG(d) { *buf++ = (d) + '0'; *buf = 0; return k; } - -int -_PyFloat_Digits(char *buf, double v, int *signum) -{ - struct dblflt *x; - int sign, e, f_n, m_n, i, d, tc1, tc2; - Bigit f; - - /* decompose float into sign, mantissa & exponent */ - x = (struct dblflt *)&v; - sign = x->s; - e = x->e; - f = (Bigit)(x->m1 << 16 | x->m2) << 32 | (U32)(x->m3 << 16 | x->m4); - if (e != 0) { - e = e - bias - bitstoright; - f |= (Bigit)hidden_bit << 32; - } - else if (f != 0) - /* denormalized */ - e = 1 - bias - bitstoright; - - *signum = sign; - if (f == 0) { - *buf++ = '0'; - *buf = 0; - return 0; - } - - ruf = !(f & 1); /* ruf = (even? f) */ - - /* Compute the scaling factor estimate, k */ - if (e > MIN_E) - k = estimate(e+52); - else { - int n; - Bigit y; - - for (n = e+52, y = (Bigit)1 << 52; f < y; n--) y >>= 1; - k = estimate(n); - } - - if (e >= 0) - if (f != B_P1) - use_mp = 0, f_n = e+1, s_n = 1, m_n = e; - else - use_mp = 1, f_n = e+2, s_n = 2, m_n = e; - else - if ((e == MIN_E) || (f != B_P1)) - use_mp = 0, f_n = 1, s_n = 1-e, m_n = 0; - else - use_mp = 1, f_n = 2, s_n = 2-e, m_n = 0; - - /* Scale it! */ - if (k == 0) { - short_shift_left(f, f_n, &R); - one_shift_left(s_n, &S); - one_shift_left(m_n, &MM); - if (use_mp) one_shift_left(m_n+1, &MP); - qr_shift = 1; - } - else if (k > 0) { - s_n += k; - if (m_n >= s_n) - f_n -= s_n, m_n -= s_n, s_n = 0; - else - f_n -= m_n, s_n -= m_n, m_n = 0; - short_shift_left(f, f_n, &R); - big_shift_left(&five[k-1], s_n, &S); - one_shift_left(m_n, &MM); - if (use_mp) one_shift_left(m_n+1, &MP); - qr_shift = 0; - } - else { - Bignum *power = &five[-k-1]; - - s_n += k; - big_short_mul(power, f, &S); - big_shift_left(&S, f_n, &R); - one_shift_left(s_n, &S); - big_shift_left(power, m_n, &MM); - if (use_mp) big_shift_left(power, m_n+1, &MP); - qr_shift = 1; - } - - /* fixup */ - if (add_cmp() <= -ruf) { - k--; - mul10(&R); - mul10(&MM); - if (use_mp) mul10(&MP); - } - - /* - printf("\nk = %d\n", k); - printf("R = "); print_big(&R); - printf("\nS = "); print_big(&S); - printf("\nM- = "); print_big(&MM); - if (use_mp) printf("\nM+ = "), print_big(&MP); - putchar('\n'); - fflush(0); - */ - - if (qr_shift) { - sl = s_n / 64; - slr = s_n % 64; - } - else { - big_shift_left(&S, 1, &S2); - add_big(&S2, &S, &S3); - big_shift_left(&S2, 1, &S4); - add_big(&S4, &S, &S5); - add_big(&S4, &S2, &S6); - add_big(&S4, &S3, &S7); - big_shift_left(&S4, 1, &S8); - add_big(&S8, &S, &S9); - } - -again: - if (qr_shift) { /* Take advantage of the fact that S = (ash 1 s_n) */ - if (R.l < sl) - d = 0; - else if (R.l == sl) { - Bigit *p; - - p = &R.d[sl]; - d = *p >> slr; - *p &= ((Bigit)1 << slr) - 1; - for (i = sl; (i > 0) && (*p == 0); i--) p--; - R.l = i; - } - else { - Bigit *p; - - p = &R.d[sl+1]; - d = *p << (64 - slr) | *(p-1) >> slr; - p--; - *p &= ((Bigit)1 << slr) - 1; - for (i = sl; (i > 0) && (*p == 0); i--) p--; - R.l = i; - } - } - else /* We need to do quotient-remainder */ - d = qr(); - - tc1 = big_comp(&R, &MM) < ruf; - tc2 = add_cmp() > -ruf; - if (!tc1) - if (!tc2) { - mul10(&R); - mul10(&MM); - if (use_mp) mul10(&MP); - *buf++ = d + '0'; - goto again; - } - else - OUTDIG(d+1) - else - if (!tc2) - OUTDIG(d) - else { - big_shift_left(&R, 1, &MM); - if (big_comp(&MM, &S) == -1) - OUTDIG(d) - else - OUTDIG(d+1) - } -} - -void -_PyFloat_DigitsInit() -{ - int n, i, l; - Bignum *b; - Bigit *xp, *zp, k; - - five[0].l = l = 0; - five[0].d[0] = 5; - for (n = MAX_FIVE-1, b = &five[0]; n > 0; n--) { - xp = &b->d[0]; - b++; - zp = &b->d[0]; - for (i = l, k = 0; i >= 0; i--) - MUL(*xp++, 5, *zp++, k); - if (k != 0) - *zp = k, l++; - b->l = l; - } - - /* - for (n = 1, b = &five[0]; n <= MAX_FIVE; n++) { - big_shift_left(b++, n, &R); - print_big(&R); - putchar('\n'); - } - fflush(0); - */ -} Modified: python/branches/py3k-ctypes-pep3118/Objects/floatobject.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/floatobject.c (original) +++ python/branches/py3k-ctypes-pep3118/Objects/floatobject.c Wed Apr 30 15:57:13 2008 @@ -12,11 +12,11 @@ #include #include -#if !defined(__STDC__) -extern double fmod(double, double); -extern double pow(double, double); +#ifdef HAVE_IEEEFP_H +#include #endif + #ifdef _OSF_SOURCE /* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */ extern int finite(double); @@ -106,15 +106,9 @@ PyObject * PyFloat_GetInfo(void) { - static PyObject* floatinfo; + PyObject* floatinfo; int pos = 0; - if (floatinfo != NULL) { - Py_INCREF(floatinfo); - return floatinfo; - } - PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc); - floatinfo = PyStructSequence_New(&FloatInfoType); if (floatinfo == NULL) { return NULL; @@ -143,8 +137,6 @@ Py_CLEAR(floatinfo); return NULL; } - - Py_INCREF(floatinfo); return floatinfo; } @@ -228,11 +220,11 @@ p++; } if (PyOS_strnicmp(p, "inf", 4) == 0) { - return PyFloat_FromDouble(sign * Py_HUGE_VAL); + Py_RETURN_INF(sign); } #ifdef Py_NAN if(PyOS_strnicmp(p, "nan", 4) == 0) { - return PyFloat_FromDouble(Py_NAN); + Py_RETURN_NAN; } #endif PyOS_snprintf(buffer, sizeof(buffer), @@ -382,110 +374,6 @@ format_double(buf, buflen, PyFloat_AS_DOUBLE(v), precision); } -#ifdef Py_BROKEN_REPR -/* The following function is based on Tcl_PrintDouble, - * from tclUtil.c. - */ - -#define is_infinite(d) ( (d) > DBL_MAX || (d) < -DBL_MAX ) -#define is_nan(d) ((d) != (d)) - -static void -format_double_repr(char *dst, double value) -{ - char *p, c; - int exp; - int signum; - char buffer[30]; - - /* - * Handle NaN. - */ - - if (is_nan(value)) { - strcpy(dst, "nan"); - return; - } - - /* - * Handle infinities. - */ - - if (is_infinite(value)) { - if (value < 0) { - strcpy(dst, "-inf"); - } else { - strcpy(dst, "inf"); - } - return; - } - - /* - * Ordinary (normal and denormal) values. - */ - - exp = _PyFloat_Digits(buffer, value, &signum)+1; - if (signum) { - *dst++ = '-'; - } - p = buffer; - if (exp < -3 || exp > 17) { - /* - * E format for numbers < 1e-3 or >= 1e17. - */ - - *dst++ = *p++; - c = *p; - if (c != '\0') { - *dst++ = '.'; - while (c != '\0') { - *dst++ = c; - c = *++p; - } - } - sprintf(dst, "e%+d", exp-1); - } else { - /* - * F format for others. - */ - - if (exp <= 0) { - *dst++ = '0'; - } - c = *p; - while (exp-- > 0) { - if (c != '\0') { - *dst++ = c; - c = *++p; - } else { - *dst++ = '0'; - } - } - *dst++ = '.'; - if (c == '\0') { - *dst++ = '0'; - } else { - while (++exp < 0) { - *dst++ = '0'; - } - while (c != '\0') { - *dst++ = c; - c = *++p; - } - } - *dst++ = '\0'; - } -} - -static void -format_float_repr(char *buf, PyFloatObject *v) -{ - assert(PyFloat_Check(v)); - format_double_repr(buf, PyFloat_AS_DOUBLE(v)); -} - -#endif /* Py_BROKEN_REPR */ - /* Macro and helper that convert PyObject obj to a C double and store the value in dbl. If conversion to double raises an exception, obj is set to NULL, and the function invoking this macro returns NULL. If @@ -538,13 +426,8 @@ static PyObject * float_repr(PyFloatObject *v) { -#ifdef Py_BROKEN_REPR - char buf[30]; - format_float_repr(buf, v); -#else char buf[100]; format_float(buf, sizeof(buf), v, PREC_REPR); -#endif return PyUnicode_FromString(buf); } @@ -808,10 +691,13 @@ double a,b; CONVERT_TO_DOUBLE(v, a); CONVERT_TO_DOUBLE(w, b); +#ifdef Py_NAN if (b == 0.0) { - PyErr_SetString(PyExc_ZeroDivisionError, "float division"); + PyErr_SetString(PyExc_ZeroDivisionError, + "float division"); return NULL; } +#endif PyFPE_START_PROTECT("divide", return 0) a = a / b; PyFPE_END_PROTECT(a) @@ -823,12 +709,15 @@ { double vx, wx; double mod; - CONVERT_TO_DOUBLE(v, vx); - CONVERT_TO_DOUBLE(w, wx); + CONVERT_TO_DOUBLE(v, vx); + CONVERT_TO_DOUBLE(w, wx); +#ifdef Py_NAN if (wx == 0.0) { - PyErr_SetString(PyExc_ZeroDivisionError, "float modulo"); + PyErr_SetString(PyExc_ZeroDivisionError, + "float modulo"); return NULL; } +#endif PyFPE_START_PROTECT("modulo", return 0) mod = fmod(vx, wx); /* note: checking mod*wx < 0 is incorrect -- underflows to @@ -932,6 +821,9 @@ } return PyFloat_FromDouble(0.0); } + if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */ + return PyFloat_FromDouble(1.0); + } if (iv < 0.0) { /* Whether this is an error is a mess, and bumps into libm * bugs so we have to figure it out ourselves. @@ -999,6 +891,57 @@ } static PyObject * +float_is_integer(PyObject *v) +{ + double x = PyFloat_AsDouble(v); + PyObject *o; + + if (x == -1.0 && PyErr_Occurred()) + return NULL; + if (!Py_IS_FINITE(x)) + Py_RETURN_FALSE; + PyFPE_START_PROTECT("is_integer", return NULL) + o = (floor(x) == x) ? Py_True : Py_False; + PyFPE_END_PROTECT(x) + if (errno != 0) { + PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError : + PyExc_ValueError); + return NULL; + } + Py_INCREF(o); + return o; +} + +#if 0 +static PyObject * +float_is_inf(PyObject *v) +{ + double x = PyFloat_AsDouble(v); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)Py_IS_INFINITY(x)); +} + +static PyObject * +float_is_nan(PyObject *v) +{ + double x = PyFloat_AsDouble(v); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)Py_IS_NAN(x)); +} + +static PyObject * +float_is_finite(PyObject *v) +{ + double x = PyFloat_AsDouble(v); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)Py_IS_FINITE(x)); +} +#endif + +static PyObject * float_trunc(PyObject *v) { double x = PyFloat_AsDouble(v); @@ -1073,6 +1016,104 @@ return v; } +static PyObject * +float_as_integer_ratio(PyObject *v, PyObject *unused) +{ + double self; + double float_part; + int exponent; + int i; + + PyObject *prev; + PyObject *py_exponent = NULL; + PyObject *numerator = NULL; + PyObject *denominator = NULL; + PyObject *result_pair = NULL; + PyNumberMethods *long_methods = PyLong_Type.tp_as_number; + +#define INPLACE_UPDATE(obj, call) \ + prev = obj; \ + obj = call; \ + Py_DECREF(prev); \ + + CONVERT_TO_DOUBLE(v, self); + + if (Py_IS_INFINITY(self)) { + PyErr_SetString(PyExc_OverflowError, + "Cannot pass infinity to float.as_integer_ratio."); + return NULL; + } +#ifdef Py_NAN + if (Py_IS_NAN(self)) { + PyErr_SetString(PyExc_ValueError, + "Cannot pass nan to float.as_integer_ratio."); + return NULL; + } +#endif + + PyFPE_START_PROTECT("as_integer_ratio", goto error); + float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */ + PyFPE_END_PROTECT(float_part); + + for (i=0; i<300 && float_part != floor(float_part) ; i++) { + float_part *= 2.0; + exponent--; + } + /* self == float_part * 2**exponent exactly and float_part is integral. + If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part + to be truncated by PyLong_FromDouble(). */ + + numerator = PyLong_FromDouble(float_part); + if (numerator == NULL) goto error; + + /* fold in 2**exponent */ + denominator = PyLong_FromLong(1); + py_exponent = PyLong_FromLong(labs((long)exponent)); + if (py_exponent == NULL) goto error; + INPLACE_UPDATE(py_exponent, + long_methods->nb_lshift(denominator, py_exponent)); + if (py_exponent == NULL) goto error; + if (exponent > 0) { + INPLACE_UPDATE(numerator, + long_methods->nb_multiply(numerator, py_exponent)); + if (numerator == NULL) goto error; + } + else { + Py_DECREF(denominator); + denominator = py_exponent; + py_exponent = NULL; + } + + /* Returns ints instead of longs where possible */ + INPLACE_UPDATE(numerator, PyNumber_Int(numerator)); + if (numerator == NULL) goto error; + INPLACE_UPDATE(denominator, PyNumber_Int(denominator)); + if (denominator == NULL) goto error; + + result_pair = PyTuple_Pack(2, numerator, denominator); + +#undef INPLACE_UPDATE +error: + Py_XDECREF(py_exponent); + Py_XDECREF(denominator); + Py_XDECREF(numerator); + return result_pair; +} + +PyDoc_STRVAR(float_as_integer_ratio_doc, +"float.as_integer_ratio() -> (int, int)\n" +"\n" +"Returns a pair of integers, whose ratio is exactly equal to the original\n" +"float and with a positive denominator.\n" +"Raises OverflowError on infinities and a ValueError on nans.\n" +"\n" +">>> (10.0).as_integer_ratio()\n" +"(10, 1)\n" +">>> (0.0).as_integer_ratio()\n" +"(0, 1)\n" +">>> (-.25).as_integer_ratio()\n" +"(-1, 4)"); + static PyObject * float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds); @@ -1274,13 +1315,25 @@ static PyMethodDef float_methods[] = { - {"conjugate", (PyCFunction)float_float, METH_NOARGS, + {"conjugate", (PyCFunction)float_float, METH_NOARGS, "Returns self, the complex conjugate of any float."}, {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS, "Returns the Integral closest to x between 0 and x."}, {"__round__", (PyCFunction)float_round, METH_VARARGS, "Returns the Integral closest to x, rounding half toward even.\n" "When an argument is passed, works like built-in round(x, ndigits)."}, + {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS, + float_as_integer_ratio_doc}, + {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS, + "Returns True if the float is an integer."}, +#if 0 + {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS, + "Returns True if the float is positive or negative infinite."}, + {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS, + "Returns True if the float is finite, neither infinite nor NaN."}, + {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS, + "Returns True if the float is not a number (NaN)."}, +#endif {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS}, {"__getformat__", (PyCFunction)float_getformat, METH_O|METH_CLASS, float_getformat_doc}, @@ -1438,24 +1491,21 @@ double_format = detected_double_format; float_format = detected_float_format; -#ifdef Py_BROKEN_REPR - /* Initialize floating point repr */ - _PyFloat_DigitsInit(); -#endif + /* Init float info */ + if (FloatInfoType.tp_name == 0) + PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc); } void -PyFloat_Fini(void) +PyFloat_CompactFreeList(size_t *pbc, size_t *pbf, size_t *bsum) { PyFloatObject *p; PyFloatBlock *list, *next; unsigned i; - int bc, bf; /* block count, number of freed blocks */ - int frem, fsum; /* remaining unfreed floats per block, total */ + size_t bc = 0, bf = 0; /* block count, number of freed blocks */ + size_t fsum = 0; /* total unfreed ints */ + int frem; /* remaining unfreed ints per block */ - bc = 0; - bf = 0; - fsum = 0; list = block_list; block_list = NULL; free_list = NULL; @@ -1490,6 +1540,22 @@ fsum += frem; list = next; } + *pbc = bc; + *pbf = bf; + *bsum = fsum; +} + +void +PyFloat_Fini(void) +{ + PyFloatObject *p; + PyFloatBlock *list; + unsigned i; + size_t bc, bf; /* block count, number of freed blocks */ + size_t fsum; /* total unfreed floats per block */ + + PyFloat_CompactFreeList(&bc, &bf, &fsum); + if (!Py_VerboseFlag) return; fprintf(stderr, "# cleanup floats"); @@ -1498,7 +1564,9 @@ } else { fprintf(stderr, - ": %d unfreed float%s in %d out of %d block%s\n", + ": %" PY_FORMAT_SIZE_T "d unfreed float%s in %" + PY_FORMAT_SIZE_T "d out of %" + PY_FORMAT_SIZE_T "d block%s\n", fsum, fsum == 1 ? "" : "s", bc - bf, bc, bc == 1 ? "" : "s"); } @@ -1528,9 +1596,6 @@ /*---------------------------------------------------------------------------- * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h. - * - * TODO: On platforms that use the standard IEEE-754 single and double - * formats natively, these routines could simply copy the bytes. */ int _PyFloat_Pack4(double x, unsigned char *p, int le) @@ -1610,28 +1675,31 @@ /* Done */ return 0; - Overflow: - PyErr_SetString(PyExc_OverflowError, - "float too large to pack with f format"); - return -1; } else { float y = (float)x; const char *s = (char*)&y; int i, incr = 1; + if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x)) + goto Overflow; + if ((float_format == ieee_little_endian_format && !le) || (float_format == ieee_big_endian_format && le)) { p += 3; incr = -1; } - + for (i = 0; i < 4; i++) { *p = *s++; p += incr; } return 0; } + Overflow: + PyErr_SetString(PyExc_OverflowError, + "float too large to pack with f format"); + return -1; } int Modified: python/branches/py3k-ctypes-pep3118/Objects/frameobject.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/frameobject.c (original) +++ python/branches/py3k-ctypes-pep3118/Objects/frameobject.c Wed Apr 30 15:57:13 2008 @@ -401,14 +401,15 @@ call depth of more than 20 or 30 is probably already exceptional unless the program contains run-away recursion. I hope. - Later, MAXFREELIST was added to bound the # of frames saved on + Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on free_list. Else programs creating lots of cyclic trash involving frames could provoke free_list into growing without bound. */ static PyFrameObject *free_list = NULL; static int numfree = 0; /* number of frames currently in free_list */ -#define MAXFREELIST 200 /* max value for numfree */ +/* max value for numfree */ +#define PyFrame_MAXFREELIST 200 static void frame_dealloc(PyFrameObject *f) @@ -441,7 +442,7 @@ co = f->f_code; if (co->co_zombieframe == NULL) co->co_zombieframe = f; - else if (numfree < MAXFREELIST) { + else if (numfree < PyFrame_MAXFREELIST) { ++numfree; f->f_back = free_list; free_list = f; @@ -896,10 +897,11 @@ } /* Clear out the free list */ - -void -PyFrame_Fini(void) +int +PyFrame_ClearFreeList(void) { + int freelist_size = numfree; + while (free_list != NULL) { PyFrameObject *f = free_list; free_list = free_list->f_back; @@ -907,6 +909,13 @@ --numfree; } assert(numfree == 0); + return freelist_size; +} + +void +PyFrame_Fini(void) +{ + (void)PyFrame_ClearFreeList(); Py_XDECREF(builtin_object); builtin_object = NULL; } Modified: python/branches/py3k-ctypes-pep3118/Objects/genobject.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/genobject.c (original) +++ python/branches/py3k-ctypes-pep3118/Objects/genobject.c Wed Apr 30 15:57:13 2008 @@ -11,6 +11,7 @@ gen_traverse(PyGenObject *gen, visitproc visit, void *arg) { Py_VISIT((PyObject *)gen->gi_frame); + Py_VISIT(gen->gi_code); return 0; } @@ -35,6 +36,7 @@ _PyObject_GC_UNTRACK(self); Py_CLEAR(gen->gi_frame); + Py_CLEAR(gen->gi_code); PyObject_GC_Del(gen); } @@ -283,6 +285,7 @@ static PyMemberDef gen_memberlist[] = { {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY}, {"gi_running", T_INT, offsetof(PyGenObject, gi_running), READONLY}, + {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY}, {NULL} /* Sentinel */ }; @@ -353,6 +356,8 @@ return NULL; } gen->gi_frame = f; + Py_INCREF(f->f_code); + gen->gi_code = (PyObject *)(f->f_code); gen->gi_running = 0; gen->gi_weakreflist = NULL; _PyObject_GC_TRACK(gen); Modified: python/branches/py3k-ctypes-pep3118/Objects/iterobject.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/iterobject.c (original) +++ python/branches/py3k-ctypes-pep3118/Objects/iterobject.c Wed Apr 30 15:57:13 2008 @@ -230,172 +230,3 @@ }; -/*********************** Zip Iterator **************************/ -/* Largely copied from itertools.c by Brian Holmes */ - -typedef struct zipiterobject_t { - PyObject_HEAD - PyTupleObject *it_tuple; /* Set to NULL when iterator is exhausted */ - Py_ssize_t resultsize; - PyTupleObject *result; /* Reusable tuple for optimization */ -} zipiterobject; - - /* Forward */ - -PyObject * -_PyZip_CreateIter(PyObject* args) -{ - Py_ssize_t i; - Py_ssize_t tuplesize; - PyObject* ziptuple; - PyObject* result; - struct zipiterobject_t* zipiter; - - assert(PyTuple_Check(args)); - - if (Py_TYPE(&PyZipIter_Type) == NULL) { - if (PyType_Ready(&PyZipIter_Type) < 0) - return NULL; - } - - tuplesize = PySequence_Length((PyObject*) args); - - ziptuple = PyTuple_New(tuplesize); - if (ziptuple == NULL) - return NULL; - - for (i = 0; i < tuplesize; i++) { - PyObject *o = PyTuple_GET_ITEM(args, i); - PyObject *it = PyObject_GetIter(o); - if (it == NULL) { - /* XXX Should we do this? - if (PyErr_ExceptionMatches(PyExc_TypeError)) - PyErr_Format(PyExc_TypeError, - "zip argument #%zd must support iteration", - I+1); - */ - Py_DECREF(ziptuple); - return NULL; - } - PyTuple_SET_ITEM(ziptuple, i, it); - } - - /* create a reusable result holder */ - result = PyTuple_New(tuplesize); - if (result == NULL) { - Py_DECREF(ziptuple); - return NULL; - } - for (i = 0; i < tuplesize; i++) { - Py_INCREF(Py_None); - PyTuple_SET_ITEM(result, i, Py_None); - } - - zipiter = PyObject_GC_New(zipiterobject, &PyZipIter_Type); - if (zipiter == NULL) { - Py_DECREF(ziptuple); - Py_DECREF(result); - return NULL; - } - - zipiter->result = (PyTupleObject*) result; - zipiter->resultsize = tuplesize; - zipiter->it_tuple = (PyTupleObject *) ziptuple; - _PyObject_GC_TRACK(zipiter); - return (PyObject *)zipiter; -} - -static void -zipiter_dealloc(zipiterobject *it) -{ - _PyObject_GC_UNTRACK(it); - Py_XDECREF(it->it_tuple); - Py_XDECREF(it->result); - PyObject_GC_Del(it); -} - -static int -zipiter_traverse(zipiterobject *it, visitproc visit, void *arg) -{ - Py_VISIT(it->it_tuple); - Py_VISIT(it->result); - return 0; -} - -static PyObject * -zipiter_next(zipiterobject *zit) -{ - Py_ssize_t i; - Py_ssize_t tuplesize = zit->resultsize; - PyObject *result = (PyObject*) zit->result; - PyObject *olditem; - - if (tuplesize == 0) - return NULL; - - if (result->ob_refcnt == 1) { - Py_INCREF(result); - for (i = 0; i < tuplesize; i++) { - PyObject *it = PyTuple_GET_ITEM(zit->it_tuple, i); - PyObject *item; - assert(PyIter_Check(it)); - item = (*it->ob_type->tp_iternext)(it); - if (item == NULL) { - Py_DECREF(result); - return NULL; - } - olditem = PyTuple_GET_ITEM(result, i); - PyTuple_SET_ITEM(result, i, item); - Py_DECREF(olditem); - } - } else { - result = PyTuple_New(tuplesize); - if (result == NULL) - return NULL; - for (i = 0; i < tuplesize; i++) { - PyObject *it = PyTuple_GET_ITEM(zit->it_tuple, i); - PyObject *item; - assert(PyIter_Check(it)); - item = (*it->ob_type->tp_iternext)(it); - if (item == NULL) { - Py_DECREF(result); - return NULL; - } - PyTuple_SET_ITEM(result, i, item); - } - } - return result; -} - -PyTypeObject PyZipIter_Type = { - PyVarObject_HEAD_INIT(0, 0) - "zip_iterator", /* tp_name */ - sizeof(zipiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)zipiter_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ - 0, /* tp_doc */ - (traverseproc)zipiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weakzipoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)zipiter_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ -}; Modified: python/branches/py3k-ctypes-pep3118/Objects/listobject.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/listobject.c (original) +++ python/branches/py3k-ctypes-pep3118/Objects/listobject.c Wed Apr 30 15:57:13 2008 @@ -63,19 +63,38 @@ return 0; } +/* Debug statistic to compare allocations with reuse through the free list */ +#undef SHOW_ALLOC_COUNT +#ifdef SHOW_ALLOC_COUNT +static size_t count_alloc = 0; +static size_t count_reuse = 0; + +static void +show_alloc(void) +{ + fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n", + count_alloc); + fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T + "d\n", count_reuse); + fprintf(stderr, "%.2f%% reuse rate\n\n", + (100.0*count_reuse/(count_alloc+count_reuse))); +} +#endif + /* Empty list reuse scheme to save calls to malloc and free */ -#define MAXFREELISTS 80 -static PyListObject *free_lists[MAXFREELISTS]; -static int num_free_lists = 0; +#ifndef PyList_MAXFREELIST +#define PyList_MAXFREELIST 80 +#endif +static PyListObject *free_list[PyList_MAXFREELIST]; +static int numfree = 0; void PyList_Fini(void) { PyListObject *op; - while (num_free_lists) { - num_free_lists--; - op = free_lists[num_free_lists]; + while (numfree) { + op = free_list[--numfree]; assert(PyList_CheckExact(op)); PyObject_GC_Del(op); } @@ -86,6 +105,13 @@ { PyListObject *op; size_t nbytes; +#ifdef SHOW_ALLOC_COUNT + static int initialized = 0; + if (!initialized) { + Py_AtExit(show_alloc); + initialized = 1; + } +#endif if (size < 0) { PyErr_BadInternalCall(); @@ -95,14 +121,20 @@ /* Check for overflow */ if (nbytes / sizeof(PyObject *) != (size_t)size) return PyErr_NoMemory(); - if (num_free_lists) { - num_free_lists--; - op = free_lists[num_free_lists]; + if (numfree) { + numfree--; + op = free_list[numfree]; _Py_NewReference((PyObject *)op); +#ifdef SHOW_ALLOC_COUNT + count_reuse++; +#endif } else { op = PyObject_GC_New(PyListObject, &PyList_Type); if (op == NULL) return NULL; +#ifdef SHOW_ALLOC_COUNT + count_alloc++; +#endif } if (size <= 0) op->ob_item = NULL; @@ -265,8 +297,8 @@ } PyMem_FREE(op->ob_item); } - if (num_free_lists < MAXFREELISTS && PyList_CheckExact(op)) - free_lists[num_free_lists++] = op; + if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op)) + free_list[numfree++] = op; else Py_TYPE(op)->tp_free((PyObject *)op); Py_TRASHCAN_SAFE_END(op) @@ -466,7 +498,7 @@ if (n && size/n != Py_SIZE(a)) return PyErr_NoMemory(); if (size == 0) - return PyList_New(0); + return PyList_New(0); np = (PyListObject *) PyList_New(size); if (np == NULL) return NULL; @@ -633,11 +665,11 @@ list_inplace_repeat(PyListObject *self, Py_ssize_t n) { PyObject **items; - Py_ssize_t size, i, j, p, newsize; + Py_ssize_t size, i, j, p; size = PyList_GET_SIZE(self); - if (size == 0) { + if (size == 0 || n == 1) { Py_INCREF(self); return (PyObject *)self; } @@ -648,10 +680,11 @@ return (PyObject *)self; } - newsize = size * n; - if (newsize/n != size) + if (size > PY_SSIZE_T_MAX / n) { return PyErr_NoMemory(); - if (list_resize(self, newsize) == -1) + } + + if (list_resize(self, size*n) == -1) return NULL; p = size; @@ -887,64 +920,17 @@ * pieces to this algorithm; read listsort.txt for overviews and details. */ -/* Comparison function. Takes care of calling a user-supplied - * comparison function (any callable Python object), which must not be - * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool - * with Py_LT if you know it's NULL). +/* Comparison function: PyObject_RichCompareBool with Py_LT. * Returns -1 on error, 1 if x < y, 0 if x >= y. */ -static int -islt(PyObject *x, PyObject *y, PyObject *compare) -{ - PyObject *res; - PyObject *args; - Py_ssize_t i; - assert(compare != NULL); - /* Call the user's comparison function and translate the 3-way - * result into true or false (or error). - */ - args = PyTuple_New(2); - if (args == NULL) - return -1; - Py_INCREF(x); - Py_INCREF(y); - PyTuple_SET_ITEM(args, 0, x); - PyTuple_SET_ITEM(args, 1, y); - res = PyObject_Call(compare, args, NULL); - Py_DECREF(args); - if (res == NULL) - return -1; - if (!PyLong_CheckExact(res)) { - PyErr_Format(PyExc_TypeError, - "comparison function must return int, not %.200s", - res->ob_type->tp_name); - Py_DECREF(res); - return -1; - } - i = PyLong_AsLong(res); - Py_DECREF(res); - if (i == -1 && PyErr_Occurred()) { - /* Overflow in long conversion. */ - return -1; - } - return i < 0; -} - -/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls - * islt. This avoids a layer of function call in the usual case, and - * sorting does many comparisons. - * Returns -1 on error, 1 if x < y, 0 if x >= y. - */ -#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \ - PyObject_RichCompareBool(X, Y, Py_LT) : \ - islt(X, Y, COMPARE)) +#define ISLT(X, Y) (PyObject_RichCompareBool(X, Y, Py_LT)) /* Compare X to Y via "<". Goto "fail" if the comparison raises an error. Else "k" is set to true iff X. X and Y are PyObject*s. */ -#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \ +#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \ if (k) /* binarysort is the best method for sorting small arrays: it does @@ -959,8 +945,7 @@ the input (nothing is lost or duplicated). */ static int -binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare) - /* compare -- comparison function object, or NULL for default */ +binarysort(PyObject **lo, PyObject **hi, PyObject **start) { register Py_ssize_t k; register PyObject **l, **p, **r; @@ -1025,7 +1010,7 @@ Returns -1 in case of error. */ static Py_ssize_t -count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending) +count_run(PyObject **lo, PyObject **hi, int *descending) { Py_ssize_t k; Py_ssize_t n; @@ -1080,7 +1065,7 @@ Returns -1 on error. See listsort.txt for info on the method. */ static Py_ssize_t -gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare) +gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint) { Py_ssize_t ofs; Py_ssize_t lastofs; @@ -1171,7 +1156,7 @@ written as one routine with yet another "left or right?" flag. */ static Py_ssize_t -gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare) +gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint) { Py_ssize_t ofs; Py_ssize_t lastofs; @@ -1272,9 +1257,6 @@ }; typedef struct s_MergeState { - /* The user-supplied comparison function. or NULL if none given. */ - PyObject *compare; - /* This controls when we get *into* galloping mode. It's initialized * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for * random data, and lower for highly structured data. @@ -1305,10 +1287,9 @@ /* Conceptually a MergeState's constructor. */ static void -merge_init(MergeState *ms, PyObject *compare) +merge_init(MergeState *ms) { assert(ms != NULL); - ms->compare = compare; ms->a = ms->temparray; ms->alloced = MERGESTATE_TEMP_SIZE; ms->n = 0; @@ -1365,7 +1346,6 @@ PyObject **pb, Py_ssize_t nb) { Py_ssize_t k; - PyObject *compare; PyObject **dest; int result = -1; /* guilty until proved innocent */ Py_ssize_t min_gallop; @@ -1385,7 +1365,6 @@ goto CopyB; min_gallop = ms->min_gallop; - compare = ms->compare; for (;;) { Py_ssize_t acount = 0; /* # of times A won in a row */ Py_ssize_t bcount = 0; /* # of times B won in a row */ @@ -1395,7 +1374,7 @@ */ for (;;) { assert(na > 1 && nb > 0); - k = ISLT(*pb, *pa, compare); + k = ISLT(*pb, *pa); if (k) { if (k < 0) goto Fail; @@ -1430,7 +1409,7 @@ assert(na > 1 && nb > 0); min_gallop -= min_gallop > 1; ms->min_gallop = min_gallop; - k = gallop_right(*pb, pa, na, 0, compare); + k = gallop_right(*pb, pa, na, 0); acount = k; if (k) { if (k < 0) @@ -1453,7 +1432,7 @@ if (nb == 0) goto Succeed; - k = gallop_left(*pa, pb, nb, 0, compare); + k = gallop_left(*pa, pb, nb, 0); bcount = k; if (k) { if (k < 0) @@ -1497,7 +1476,6 @@ merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb) { Py_ssize_t k; - PyObject *compare; PyObject **dest; int result = -1; /* guilty until proved innocent */ PyObject **basea; @@ -1522,7 +1500,6 @@ goto CopyA; min_gallop = ms->min_gallop; - compare = ms->compare; for (;;) { Py_ssize_t acount = 0; /* # of times A won in a row */ Py_ssize_t bcount = 0; /* # of times B won in a row */ @@ -1532,7 +1509,7 @@ */ for (;;) { assert(na > 0 && nb > 1); - k = ISLT(*pb, *pa, compare); + k = ISLT(*pb, *pa); if (k) { if (k < 0) goto Fail; @@ -1567,7 +1544,7 @@ assert(na > 0 && nb > 1); min_gallop -= min_gallop > 1; ms->min_gallop = min_gallop; - k = gallop_right(*pb, basea, na, na-1, compare); + k = gallop_right(*pb, basea, na, na-1); if (k < 0) goto Fail; k = na - k; @@ -1585,7 +1562,7 @@ if (nb == 1) goto CopyA; - k = gallop_left(*pa, baseb, nb, nb-1, compare); + k = gallop_left(*pa, baseb, nb, nb-1); if (k < 0) goto Fail; k = nb - k; @@ -1637,7 +1614,6 @@ PyObject **pa, **pb; Py_ssize_t na, nb; Py_ssize_t k; - PyObject *compare; assert(ms != NULL); assert(ms->n >= 2); @@ -1663,8 +1639,7 @@ /* Where does b start in a? Elements in a before that can be * ignored (already in place). */ - compare = ms->compare; - k = gallop_right(*pb, pa, na, 0, compare); + k = gallop_right(*pb, pa, na, 0); if (k < 0) return -1; pa += k; @@ -1675,7 +1650,7 @@ /* Where does a end in b? Elements in b after that can be * ignored (already in place). */ - nb = gallop_left(pa[na-1], pb, nb, nb-1, compare); + nb = gallop_left(pa[na-1], pb, nb, nb-1); if (nb <= 0) return nb; @@ -1770,8 +1745,8 @@ pattern. Holds a key which is used for comparisons and the original record which is returned during the undecorate phase. By exposing only the key during comparisons, the underlying sort stability characteristics are left - unchanged. Also, if a custom comparison function is used, it will only see - the key instead of a full record. */ + unchanged. Also, the comparison function will only see the key instead of + a full record. */ typedef struct { PyObject_HEAD @@ -1865,104 +1840,6 @@ return value; } -/* Wrapper for user specified cmp functions in combination with a - specified key function. Makes sure the cmp function is presented - with the actual key instead of the sortwrapper */ - -typedef struct { - PyObject_HEAD - PyObject *func; -} cmpwrapperobject; - -static void -cmpwrapper_dealloc(cmpwrapperobject *co) -{ - Py_XDECREF(co->func); - PyObject_Del(co); -} - -static PyObject * -cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds) -{ - PyObject *x, *y, *xx, *yy; - - if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y)) - return NULL; - if (!PyObject_TypeCheck(x, &PySortWrapper_Type) || - !PyObject_TypeCheck(y, &PySortWrapper_Type)) { - PyErr_SetString(PyExc_TypeError, - "expected a sortwrapperobject"); - return NULL; - } - xx = ((sortwrapperobject *)x)->key; - yy = ((sortwrapperobject *)y)->key; - return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL); -} - -PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys."); - -PyTypeObject PyCmpWrapper_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "cmpwrapper", /* tp_name */ - sizeof(cmpwrapperobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)cmpwrapper_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - (ternaryfunc)cmpwrapper_call, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - cmpwrapper_doc, /* tp_doc */ -}; - -static PyObject * -build_cmpwrapper(PyObject *cmpfunc) -{ - cmpwrapperobject *co; - - co = PyObject_New(cmpwrapperobject, &PyCmpWrapper_Type); - if (co == NULL) - return NULL; - Py_INCREF(cmpfunc); - co->func = cmpfunc; - return (PyObject *)co; -} - -static int -is_default_cmp(PyObject *cmpfunc) -{ - PyCFunctionObject *f; - const char *module; - if (cmpfunc == NULL || cmpfunc == Py_None) - return 1; - if (!PyCFunction_Check(cmpfunc)) - return 0; - f = (PyCFunctionObject *)cmpfunc; - if (f->m_self != NULL) - return 0; - if (!PyUnicode_Check(f->m_module)) - return 0; - module = PyUnicode_AsString(f->m_module); - if (module == NULL) - return 0; - if (strcmp(module, "builtins") != 0) - return 0; - if (strcmp(f->m_ml->ml_name, "cmp") != 0) - return 0; - return 1; -} - /* An adaptive, stable, natural mergesort. See listsort.txt. * Returns Py_None on success, NULL on error. Even in case of error, the * list will be some permutation of its input state (nothing is lost or @@ -1978,31 +1855,27 @@ Py_ssize_t saved_ob_size, saved_allocated; PyObject **saved_ob_item; PyObject **final_ob_item; - PyObject *compare = NULL; PyObject *result = NULL; /* guilty until proved innocent */ int reverse = 0; PyObject *keyfunc = NULL; Py_ssize_t i; PyObject *key, *value, *kvpair; - static char *kwlist[] = {"cmp", "key", "reverse", 0}; + static char *kwlist[] = {"key", "reverse", 0}; assert(self != NULL); assert (PyList_Check(self)); if (args != NULL) { - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort", - kwlist, &compare, &keyfunc, &reverse)) + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:sort", + kwlist, &keyfunc, &reverse)) + return NULL; + if (Py_SIZE(args) > 0) { + PyErr_SetString(PyExc_TypeError, + "must use keyword argument for key function"); return NULL; + } } - if (is_default_cmp(compare)) - compare = NULL; if (keyfunc == Py_None) keyfunc = NULL; - if (compare != NULL && keyfunc != NULL) { - compare = build_cmpwrapper(compare); - if (compare == NULL) - return NULL; - } else - Py_XINCREF(compare); /* The list is temporarily made empty, so that mutations performed * by comparison functions can't affect the slice of memory we're @@ -2042,7 +1915,7 @@ if (reverse && saved_ob_size > 1) reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size); - merge_init(&ms, compare); + merge_init(&ms); nremaining = saved_ob_size; if (nremaining < 2) @@ -2059,7 +1932,7 @@ Py_ssize_t n; /* Identify next run. */ - n = count_run(lo, hi, compare, &descending); + n = count_run(lo, hi, &descending); if (n < 0) goto fail; if (descending) @@ -2068,7 +1941,7 @@ if (n < minrun) { const Py_ssize_t force = nremaining <= minrun ? nremaining : minrun; - if (binarysort(lo, lo + force, lo + n, compare) < 0) + if (binarysort(lo, lo + force, lo + n) < 0) goto fail; n = force; } @@ -2130,7 +2003,6 @@ } PyMem_FREE(final_ob_item); } - Py_XDECREF(compare); Py_XINCREF(result); return result; } @@ -2399,7 +2271,7 @@ PyDoc_STRVAR(reverse_doc, "L.reverse() -- reverse *IN PLACE*"); PyDoc_STRVAR(sort_doc, -"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\ +"L.sort(key=None, reverse=False) -- stable sort *IN PLACE*;\n\ cmp(x, y) -> -1, 0, 1"); static PyObject *list_subscript(PyListObject*, PyObject*); Modified: python/branches/py3k-ctypes-pep3118/Objects/longobject.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/longobject.c (original) +++ python/branches/py3k-ctypes-pep3118/Objects/longobject.c Wed Apr 30 15:57:13 2008 @@ -160,6 +160,7 @@ PyLong_FromLong(long ival) { PyLongObject *v; + unsigned long abs_ival; unsigned long t; /* unsigned so >> doesn't propagate sign bit */ int ndigits = 0; int sign = 1; @@ -167,9 +168,15 @@ CHECK_SMALL_INT(ival); if (ival < 0) { - ival = -ival; + /* if LONG_MIN == -LONG_MAX-1 (true on most platforms) then + ANSI C says that the result of -ival is undefined when ival + == LONG_MIN. Hence the following workaround. */ + abs_ival = (unsigned long)(-1-ival) + 1; sign = -1; } + else { + abs_ival = (unsigned long)ival; + } /* Fast path for single-digits ints */ if (!(ival>>PyLong_SHIFT)) { @@ -193,7 +200,7 @@ } /* Larger numbers: loop to determine number of digits */ - t = (unsigned long)ival; + t = abs_ival; while (t) { ++ndigits; t >>= PyLong_SHIFT; @@ -202,7 +209,7 @@ if (v != NULL) { digit *p = v->ob_digit; Py_SIZE(v) = ndigits*sign; - t = (unsigned long)ival; + t = abs_ival; while (t) { *p++ = (digit)(t & PyLong_MASK); t >>= PyLong_SHIFT; @@ -1033,21 +1040,27 @@ PyLong_FromLongLong(PY_LONG_LONG ival) { PyLongObject *v; + unsigned PY_LONG_LONG abs_ival; unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */ int ndigits = 0; int negative = 0; CHECK_SMALL_INT(ival); if (ival < 0) { - ival = -ival; + /* avoid signed overflow on negation; see comments + in PyLong_FromLong above. */ + abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1; negative = 1; } + else { + abs_ival = (unsigned PY_LONG_LONG)ival; + } /* Count the number of Python digits. We used to pick 5 ("big enough for anything"), but that's a waste of time and space given that 5*15 = 75 bits are rarely needed. */ - t = (unsigned PY_LONG_LONG)ival; + t = abs_ival; while (t) { ++ndigits; t >>= PyLong_SHIFT; @@ -1056,7 +1069,7 @@ if (v != NULL) { digit *p = v->ob_digit; Py_SIZE(v) = negative ? -ndigits : ndigits; - t = (unsigned PY_LONG_LONG)ival; + t = abs_ival; while (t) { *p++ = (digit)(t & PyLong_MASK); t >>= PyLong_SHIFT; @@ -1099,13 +1112,39 @@ PyObject * PyLong_FromSsize_t(Py_ssize_t ival) { - Py_ssize_t bytes = ival; - int one = 1; - if (ival < PyLong_BASE) - return PyLong_FromLong(ival); - return _PyLong_FromByteArray( - (unsigned char *)&bytes, - SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1); + PyLongObject *v; + size_t abs_ival; + size_t t; /* unsigned so >> doesn't propagate sign bit */ + int ndigits = 0; + int negative = 0; + + CHECK_SMALL_INT(ival); + if (ival < 0) { + /* avoid signed overflow when ival = SIZE_T_MIN */ + abs_ival = (size_t)(-1-ival)+1; + negative = 1; + } + else { + abs_ival = (size_t)ival; + } + + /* Count the number of Python digits. */ + t = abs_ival; + while (t) { + ++ndigits; + t >>= PyLong_SHIFT; + } + v = _PyLong_New(ndigits); + if (v != NULL) { + digit *p = v->ob_digit; + Py_SIZE(v) = negative ? -ndigits : ndigits; + t = abs_ival; + while (t) { + *p++ = (digit)(t & PyLong_MASK); + t >>= PyLong_SHIFT; + } + } + return (PyObject *)v; } /* Create a new long int object from a C size_t. */ @@ -1113,13 +1152,28 @@ PyObject * PyLong_FromSize_t(size_t ival) { - size_t bytes = ival; - int one = 1; + PyLongObject *v; + size_t t; + int ndigits = 0; + if (ival < PyLong_BASE) return PyLong_FromLong(ival); - return _PyLong_FromByteArray( - (unsigned char *)&bytes, - SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0); + /* Count the number of Python digits. */ + t = ival; + while (t) { + ++ndigits; + t >>= PyLong_SHIFT; + } + v = _PyLong_New(ndigits); + if (v != NULL) { + digit *p = v->ob_digit; + Py_SIZE(v) = ndigits; + while (ival) { + *p++ = (digit)(ival & PyLong_MASK); + ival >>= PyLong_SHIFT; + } + } + return (PyObject *)v; } /* Get a C PY_LONG_LONG int from a long int object. @@ -3570,9 +3624,21 @@ #undef UNDEF_NDIGITS } +#if 0 +static PyObject * +long_is_finite(PyObject *v) +{ + Py_RETURN_TRUE; +} +#endif + static PyMethodDef long_methods[] = { {"conjugate", (PyCFunction)long_long, METH_NOARGS, "Returns self, the complex conjugate of any int."}, +#if 0 + {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS, + "Returns always True."}, +#endif {"__trunc__", (PyCFunction)long_long, METH_NOARGS, "Truncating an Integral returns itself."}, {"__floor__", (PyCFunction)long_long, METH_NOARGS, @@ -3705,17 +3771,32 @@ _PyLong_Init(void) { #if NSMALLNEGINTS + NSMALLPOSINTS > 0 - int ival; + int ival, size; PyLongObject *v = small_ints; - for (ival = -NSMALLNEGINTS; ival < 0; ival++, v++) { - PyObject_INIT(v, &PyLong_Type); - Py_SIZE(v) = -1; - v->ob_digit[0] = -ival; - } - for (; ival < NSMALLPOSINTS; ival++, v++) { - PyObject_INIT(v, &PyLong_Type); - Py_SIZE(v) = ival ? 1 : 0; - v->ob_digit[0] = ival; + + for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) { + size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1); + if (Py_TYPE(v) == &PyLong_Type) { + /* The element is already initialized, most likely + * the Python interpreter was initialized before. + */ + Py_ssize_t refcnt; + PyObject* op = (PyObject*)v; + + refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op); + _Py_NewReference(op); + /* _Py_NewReference sets the ref count to 1 but + * the ref count might be larger. Set the refcnt + * to the original refcnt + 1 */ + Py_REFCNT(op) = refcnt + 1; + assert(Py_SIZE(op) == size); + assert(v->ob_digit[0] == abs(ival)); + } + else { + PyObject_INIT(v, &PyLong_Type); + } + Py_SIZE(v) = size; + v->ob_digit[0] = abs(ival); } #endif return 1; @@ -3724,19 +3805,15 @@ void PyLong_Fini(void) { -#if 0 - int i; - /* This is currently not needed; the small integers - are statically allocated */ + /* Integers are currently statically allocated. Py_DECREF is not + needed, but Python must forget about the reference or multiple + reinitializations will fail. */ #if NSMALLNEGINTS + NSMALLPOSINTS > 0 - PyIntObject **q; - - i = NSMALLNEGINTS + NSMALLPOSINTS; - q = small_ints; - while (--i >= 0) { - Py_XDECREF(*q); - *q++ = NULL; - } -#endif + int i; + PyLongObject *v = small_ints; + for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) { + _Py_DEC_REFTOTAL; + _Py_ForgetReference((PyObject*)v); + } #endif } Modified: python/branches/py3k-ctypes-pep3118/Objects/methodobject.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/methodobject.c (original) +++ python/branches/py3k-ctypes-pep3118/Objects/methodobject.c Wed Apr 30 15:57:13 2008 @@ -4,7 +4,14 @@ #include "Python.h" #include "structmember.h" +/* Free list for method objects to safe malloc/free overhead + * The m_self element is used to chain the objects. + */ static PyCFunctionObject *free_list = NULL; +static int numfree = 0; +#ifndef PyCFunction_MAXFREELIST +#define PyCFunction_MAXFREELIST 256 +#endif PyObject * PyCFunction_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module) @@ -14,6 +21,7 @@ if (op != NULL) { free_list = (PyCFunctionObject *)(op->m_self); PyObject_INIT(op, &PyCFunction_Type); + numfree--; } else { op = PyObject_GC_New(PyCFunctionObject, &PyCFunction_Type); @@ -116,8 +124,14 @@ _PyObject_GC_UNTRACK(m); Py_XDECREF(m->m_self); Py_XDECREF(m->m_module); - m->m_self = (PyObject *)free_list; - free_list = m; + if (numfree < PyCFunction_MAXFREELIST) { + m->m_self = (PyObject *)free_list; + free_list = m; + numfree++; + } + else { + PyObject_GC_Del(m); + } } static PyObject * @@ -305,21 +319,32 @@ /* Clear out the free list */ -void -PyCFunction_Fini(void) +int +PyCFunction_ClearFreeList(void) { + int freelist_size = numfree; + while (free_list) { PyCFunctionObject *v = free_list; free_list = (PyCFunctionObject *)(v->m_self); PyObject_GC_Del(v); + numfree--; } + assert(numfree == 0); + return freelist_size; +} + +void +PyCFunction_Fini(void) +{ + (void)PyCFunction_ClearFreeList(); } /* PyCFunction_New() is now just a macro that calls PyCFunction_NewEx(), but it's part of the API so we need to keep a function around that existing C extensions can call. */ - + #undef PyCFunction_New PyAPI_FUNC(PyObject *) PyCFunction_New(PyMethodDef *, PyObject *); Modified: python/branches/py3k-ctypes-pep3118/Objects/rangeobject.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/rangeobject.c (original) +++ python/branches/py3k-ctypes-pep3118/Objects/rangeobject.c Wed Apr 30 15:57:13 2008 @@ -216,11 +216,11 @@ if (!PyErr_Occurred()) PyErr_SetString(PyExc_IndexError, "range object index out of range"); - return NULL; - } + return NULL; + } /* XXX(nnorwitz): optimize for short ints. */ - rem = PyLong_FromSsize_t(i % len); + rem = PyLong_FromSsize_t(i); if (!rem) return NULL; incr = PyNumber_Multiply(rem, r->step); Modified: python/branches/py3k-ctypes-pep3118/Objects/setobject.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/setobject.c (original) +++ python/branches/py3k-ctypes-pep3118/Objects/setobject.c Wed Apr 30 15:57:13 2008 @@ -52,9 +52,11 @@ } while(0) /* Reuse scheme to save calls to malloc, free, and memset */ -#define MAXFREESETS 80 -static PySetObject *free_sets[MAXFREESETS]; -static int num_free_sets = 0; +#ifndef PySet_MAXFREELIST +#define PySet_MAXFREELIST 80 +#endif +static PySetObject *free_list[PySet_MAXFREELIST]; +static int numfree = 0; /* @@ -561,8 +563,8 @@ } if (so->table != so->smalltable) PyMem_DEL(so->table); - if (num_free_sets < MAXFREESETS && PyAnySet_CheckExact(so)) - free_sets[num_free_sets++] = so; + if (numfree < PySet_MAXFREELIST && PyAnySet_CheckExact(so)) + free_list[numfree++] = so; else Py_TYPE(so)->tp_free(so); Py_TRASHCAN_SAFE_END(so) @@ -904,7 +906,7 @@ { PyObject *key, *it; - if (PyAnySet_CheckExact(other)) + if (PyAnySet_Check(other)) return set_merge(so, other); if (PyDict_CheckExact(other)) { @@ -975,9 +977,9 @@ } /* create PySetObject structure */ - if (num_free_sets && + if (numfree && (type == &PySet_Type || type == &PyFrozenSet_Type)) { - so = free_sets[--num_free_sets]; + so = free_list[--numfree]; assert (so != NULL && PyAnySet_CheckExact(so)); Py_TYPE(so) = type; _Py_NewReference((PyObject *)so); @@ -1045,9 +1047,9 @@ { PySetObject *so; - while (num_free_sets) { - num_free_sets--; - so = free_sets[num_free_sets]; + while (numfree) { + numfree--; + so = free_list[numfree]; PyObject_GC_Del(so); } Py_CLEAR(dummy); @@ -1199,7 +1201,7 @@ if (result == NULL) return NULL; - if (PyAnySet_CheckExact(other)) { + if (PyAnySet_Check(other)) { Py_ssize_t pos = 0; setentry *entry; @@ -1390,7 +1392,7 @@ if ((PyObject *)so == other) return set_clear_internal(so); - if (PyAnySet_CheckExact(other)) { + if (PyAnySet_Check(other)) { setentry *entry; Py_ssize_t pos = 0; @@ -1439,7 +1441,7 @@ setentry *entry; Py_ssize_t pos = 0; - if (!PyAnySet_CheckExact(other) && !PyDict_CheckExact(other)) { + if (!PyAnySet_Check(other) && !PyDict_CheckExact(other)) { result = set_copy(so); if (result == NULL) return NULL; @@ -1546,7 +1548,7 @@ Py_RETURN_NONE; } - if (PyAnySet_CheckExact(other)) { + if (PyAnySet_Check(other)) { Py_INCREF(other); otherset = (PySetObject *)other; } else { @@ -1629,7 +1631,7 @@ setentry *entry; Py_ssize_t pos = 0; - if (!PyAnySet_CheckExact(other)) { + if (!PyAnySet_Check(other)) { PyObject *tmp, *result; tmp = make_new_set(&PySet_Type, other); if (tmp == NULL) @@ -1658,7 +1660,7 @@ { PyObject *tmp, *result; - if (!PyAnySet_CheckExact(other)) { + if (!PyAnySet_Check(other)) { tmp = make_new_set(&PySet_Type, other); if (tmp == NULL) return NULL; @@ -2127,17 +2129,7 @@ PyObject * PyFrozenSet_New(PyObject *iterable) { - PyObject *args, *result; - - if (iterable == NULL) - args = PyTuple_New(0); - else - args = PyTuple_Pack(1, iterable); - if (args == NULL) - return NULL; - result = frozenset_new(&PyFrozenSet_Type, args, NULL); - Py_DECREF(args); - return result; + return make_new_set(&PyFrozenSet_Type, iterable); } Py_ssize_t @@ -2153,7 +2145,7 @@ int PySet_Clear(PyObject *set) { - if (!PyType_IsSubtype(Py_TYPE(set), &PySet_Type)) { + if (!PySet_Check(set)) { PyErr_BadInternalCall(); return -1; } @@ -2173,7 +2165,7 @@ int PySet_Discard(PyObject *set, PyObject *key) { - if (!PyType_IsSubtype(Py_TYPE(set), &PySet_Type)) { + if (!PySet_Check(set)) { PyErr_BadInternalCall(); return -1; } @@ -2181,28 +2173,14 @@ } int -PySet_Add(PyObject *set, PyObject *key) -{ - if (!PyType_IsSubtype(Py_TYPE(set), &PySet_Type)) { - PyErr_BadInternalCall(); - return -1; - } - return set_add_key((PySetObject *)set, key); -} - -int -_PySet_Next(PyObject *set, Py_ssize_t *pos, PyObject **key) +PySet_Add(PyObject *anyset, PyObject *key) { - setentry *entry_ptr; - - if (!PyAnySet_Check(set)) { + if (!PySet_Check(anyset) && + (!PyFrozenSet_Check(anyset) || Py_REFCNT(anyset) != 1)) { PyErr_BadInternalCall(); return -1; } - if (set_next((PySetObject *)set, pos, &entry_ptr) == 0) - return 0; - *key = entry_ptr->key; - return 1; + return set_add_key((PySetObject *)anyset, key); } int @@ -2224,7 +2202,7 @@ PyObject * PySet_Pop(PyObject *set) { - if (!PyType_IsSubtype(Py_TYPE(set), &PySet_Type)) { + if (!PySet_Check(set)) { PyErr_BadInternalCall(); return NULL; } @@ -2234,7 +2212,7 @@ int _PySet_Update(PyObject *set, PyObject *iterable) { - if (!PyType_IsSubtype(Py_TYPE(set), &PySet_Type)) { + if (!PySet_Check(set)) { PyErr_BadInternalCall(); return -1; } @@ -2261,6 +2239,7 @@ Py_ssize_t i; PyObject *elem=NULL, *dup=NULL, *t, *f, *dup2, *x; PyObject *ob = (PyObject *)so; + long hash; /* Verify preconditions and exercise type/size checks */ assert(PyAnySet_Check(ob)); @@ -2301,11 +2280,15 @@ f = PyFrozenSet_New(dup); assertRaises(PySet_Clear(f) == -1, PyExc_SystemError); assertRaises(_PySet_Update(f, dup) == -1, PyExc_SystemError); + assert(PySet_Add(f, elem) == 0); + Py_INCREF(f); + assertRaises(PySet_Add(f, elem) == -1, PyExc_SystemError); + Py_DECREF(f); Py_DECREF(f); /* Exercise direct iteration */ i = 0, count = 0; - while (_PySet_Next((PyObject *)dup, &i, &x)) { + while (_PySet_NextEntry((PyObject *)dup, &i, &x, &hash)) { s = PyUnicode_AsString(x); assert(s && (s[0] == 'a' || s[0] == 'b' || s[0] == 'c')); count++; @@ -2330,7 +2313,6 @@ f = PyFrozenSet_New(dup); assert(PySet_Size(f) == 3); assert(PyFrozenSet_CheckExact(f)); - assertRaises(PySet_Add(f, elem) == -1, PyExc_SystemError); assertRaises(PySet_Discard(f, elem) == -1, PyExc_SystemError); assertRaises(PySet_Pop(f) == NULL, PyExc_SystemError); Py_DECREF(f); Modified: python/branches/py3k-ctypes-pep3118/Objects/stringlib/formatter.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/stringlib/formatter.h (original) +++ python/branches/py3k-ctypes-pep3118/Objects/stringlib/formatter.h Wed Apr 30 15:57:13 2008 @@ -130,16 +130,16 @@ } else if (end-ptr >= 1 && is_alignment_token(ptr[0])) { format->align = ptr[0]; - ptr++; + ++ptr; } /* Parse the various sign options */ if (end-ptr >= 1 && is_sign_element(ptr[0])) { format->sign = ptr[0]; - ptr++; + ++ptr; #if ALLOW_PARENS_FOR_SIGN if (end-ptr >= 1 && ptr[0] == ')') { - ptr++; + ++ptr; } #endif } @@ -150,7 +150,7 @@ if (format->align == '\0') { format->align = '='; } - ptr++; + ++ptr; } /* XXX add error checking */ @@ -165,7 +165,7 @@ /* Parse field precision */ if (end-ptr && ptr[0] == '.') { - ptr++; + ++ptr; /* XXX add error checking */ specified_width = get_integer(&ptr, end, &format->precision); @@ -189,13 +189,13 @@ if (end-ptr == 1) { format->type = ptr[0]; - ptr++; + ++ptr; } return 1; } - +#if defined FORMAT_FLOAT || defined FORMAT_LONG /************************************************************************/ /*********** common routines for numeric formatting *********************/ /************************************************************************/ @@ -288,7 +288,8 @@ else { /* determine which of left, space, or right padding is needed */ - Py_ssize_t padding = format->width - (r->n_lsign + n_digits + r->n_rsign); + Py_ssize_t padding = format->width - + (r->n_lsign + n_digits + r->n_rsign); if (format->align == '<') r->n_rpadding = padding; else if (format->align == '>') @@ -338,6 +339,7 @@ } return p_digits; } +#endif /* FORMAT_FLOAT || FORMAT_LONG */ /************************************************************************/ /*********** string formatting ******************************************/ @@ -434,18 +436,23 @@ /*********** long formatting ********************************************/ /************************************************************************/ +#if defined FORMAT_LONG || defined FORMAT_INT +typedef PyObject* +(*IntOrLongToString)(PyObject *value, int base); + static PyObject * -format_long_internal(PyObject *value, const InternalFormatSpec *format) +format_int_or_long_internal(PyObject *value, const InternalFormatSpec *format, + IntOrLongToString tostring) { PyObject *result = NULL; - int total_leading_chars_to_skip = 0; /* also includes sign, if - present */ + PyObject *tmp = NULL; + STRINGLIB_CHAR *pnumeric_chars; + STRINGLIB_CHAR numeric_char; STRINGLIB_CHAR sign = '\0'; STRINGLIB_CHAR *p; Py_ssize_t n_digits; /* count of digits need from the computed string */ - Py_ssize_t len; - Py_ssize_t tmp; + Py_ssize_t n_leading_chars; NumberFieldWidths spec; long x; @@ -469,6 +476,7 @@ /* taken from unicodeobject.c formatchar() */ /* Integer input truncated to a character */ +/* XXX: won't work for int */ x = PyLong_AsLong(value); if (x == -1 && PyErr_Occurred()) goto done; @@ -487,151 +495,121 @@ goto done; } #endif - result = STRINGLIB_NEW(NULL, 1); - if (result == NULL) - goto done; - p = STRINGLIB_STR(result); - p[0] = (Py_UNICODE) x; - n_digits = len = 1; + numeric_char = (STRINGLIB_CHAR)x; + pnumeric_chars = &numeric_char; + n_digits = 1; } else { int base; - int format_leading_chars_to_skip; /* characters added by - PyNumber_ToBase that we - want to skip over. - instead of using them, - we'll compute our - own. */ - /* compute the base and how many characters will be added by + int leading_chars_to_skip; /* Number of characters added by + PyNumber_ToBase that we want to + skip over. */ + + /* Compute the base and how many characters will be added by PyNumber_ToBase */ switch (format->type) { case 'b': base = 2; - format_leading_chars_to_skip = 2; /* 0b */ + leading_chars_to_skip = 2; /* 0b */ break; case 'o': base = 8; - format_leading_chars_to_skip = 2; /* 0o */ + leading_chars_to_skip = 2; /* 0o */ break; case 'x': case 'X': base = 16; - format_leading_chars_to_skip = 2; /* 0x */ + leading_chars_to_skip = 2; /* 0x */ break; default: /* shouldn't be needed, but stops a compiler warning */ case 'd': base = 10; - format_leading_chars_to_skip = 0; + leading_chars_to_skip = 0; break; } - /* do the hard part, converting to a string in a given base */ - result = PyNumber_ToBase(value, base); - if (result == NULL) + /* Do the hard part, converting to a string in a given base */ + tmp = tostring(value, base); + if (tmp == NULL) goto done; - n_digits = STRINGLIB_LEN(result); - len = n_digits; - p = STRINGLIB_STR(result); - - /* if X, convert to uppercase */ - if (format->type == 'X') - for (tmp = 0; tmp < len; tmp++) - p[tmp] = STRINGLIB_TOUPPER(p[tmp]); + pnumeric_chars = STRINGLIB_STR(tmp); + n_digits = STRINGLIB_LEN(tmp); + + /* Remember not to modify what pnumeric_chars points to. it + might be interned. Only modify it after we copy it into a + newly allocated output buffer. */ - /* is a sign character present in the output? if so, remember it + /* Is a sign character present in the output? If so, remember it and skip it */ - sign = p[0]; + sign = pnumeric_chars[0]; if (sign == '-') { - total_leading_chars_to_skip += 1; - n_digits--; + ++leading_chars_to_skip; } - /* skip over the leading digits (0x, 0b, etc.) */ - assert(n_digits >= format_leading_chars_to_skip + 1); - n_digits -= format_leading_chars_to_skip; - total_leading_chars_to_skip += format_leading_chars_to_skip; + /* Skip over the leading chars (0x, 0b, etc.) */ + n_digits -= leading_chars_to_skip; + pnumeric_chars += leading_chars_to_skip; } + /* Calculate the widths of the various leading and trailing parts */ calc_number_widths(&spec, sign, n_digits, format); - /* if the buffer is getting bigger, realloc it. if it's getting - smaller, don't realloc because we need to move the results - around first. realloc after we've done that */ - - if (spec.n_total > len) { - if (STRINGLIB_RESIZE(&result, spec.n_total) < 0) - goto done; - /* recalc, because string might have moved */ - p = STRINGLIB_STR(result); - } - - /* copy the characters into position first, since we're going to - overwrite some of that space */ - /* we need to move if the number of left padding in the output is - different from the number of characters we need to skip */ - if ((spec.n_lpadding + spec.n_lsign + spec.n_spadding) != - total_leading_chars_to_skip) { - memmove(p + (spec.n_lpadding + spec.n_lsign + spec.n_spadding), - p + total_leading_chars_to_skip, - n_digits * sizeof(STRINGLIB_CHAR)); + /* Allocate a new string to hold the result */ + result = STRINGLIB_NEW(NULL, spec.n_total); + if (!result) + goto done; + p = STRINGLIB_STR(result); + + /* Fill in the digit parts */ + n_leading_chars = spec.n_lpadding + spec.n_lsign + spec.n_spadding; + memmove(p + n_leading_chars, + pnumeric_chars, + n_digits * sizeof(STRINGLIB_CHAR)); + + /* if X, convert to uppercase */ + if (format->type == 'X') { + Py_ssize_t t; + for (t = 0; t < n_digits; ++t) + p[t + n_leading_chars] = STRINGLIB_TOUPPER(p[t + n_leading_chars]); } - /* now fill in the non-digit parts */ + /* Fill in the non-digit parts */ fill_number(p, &spec, n_digits, format->fill_char == '\0' ? ' ' : format->fill_char); - /* if we're getting smaller, realloc now */ - if (spec.n_total < len) { - if (STRINGLIB_RESIZE(&result, spec.n_total) < 0) - goto done; - } - done: + Py_XDECREF(tmp); return result; } - +#endif /* defined FORMAT_LONG || defined FORMAT_INT */ /************************************************************************/ /*********** float formatting *******************************************/ /************************************************************************/ +#ifdef FORMAT_FLOAT +#if STRINGLIB_IS_UNICODE /* taken from unicodeobject.c */ static Py_ssize_t strtounicode(Py_UNICODE *buffer, const char *charbuffer) { register Py_ssize_t i; Py_ssize_t len = strlen(charbuffer); - for (i = len - 1; i >= 0; i--) + for (i = len - 1; i >= 0; --i) buffer[i] = (Py_UNICODE) charbuffer[i]; return len; } - -/* the callback function to call to do the actual float formatting. - it matches the definition of PyOS_ascii_formatd */ -typedef char* -(*DoubleSnprintfFunction)(char *buffer, size_t buf_len, - const char *format, double d); - -/* just a wrapper to make PyOS_snprintf look like DoubleSnprintfFunction */ -static char* -snprintf_double(char *buffer, size_t buf_len, const char *format, double d) -{ - PyOS_snprintf(buffer, buf_len, format, d); - return NULL; -} +#endif /* see FORMATBUFLEN in unicodeobject.c */ #define FLOAT_FORMATBUFLEN 120 /* much of this is taken from unicodeobject.c */ -/* use type instead of format->type, so that it can be overridden by - format_number() */ static PyObject * -_format_float(STRINGLIB_CHAR type, PyObject *value, - const InternalFormatSpec *format, - DoubleSnprintfFunction snprintf) +format_float_internal(PyObject *value, + const InternalFormatSpec *format) { /* fmt = '%.' + `prec` + `type` + '%%' worst case length = 2 + 10 (len of INT_MAX) + 1 + 2 = 15 (use 20)*/ @@ -663,6 +641,7 @@ char* trailing = ""; STRINGLIB_CHAR *p; NumberFieldWidths spec; + STRINGLIB_CHAR type = format->type; #if STRINGLIB_IS_UNICODE Py_UNICODE unicodebuf[FLOAT_FORMATBUFLEN]; @@ -694,10 +673,11 @@ /* cast "type", because if we're in unicode we need to pass a 8-bit char. this is safe, because we've restricted what "type" can be */ - PyOS_snprintf(fmt, sizeof(fmt), "%%.%" PY_FORMAT_SIZE_T "d%c", precision, (char)type); + PyOS_snprintf(fmt, sizeof(fmt), "%%.%" PY_FORMAT_SIZE_T "d%c", precision, + (char)type); - /* call the passed in function to do the actual formatting */ - snprintf(charbuf, sizeof(charbuf), fmt, x); + /* do the actual formatting */ + PyOS_ascii_formatd(charbuf, sizeof(charbuf), fmt, x); /* adding trailing to fmt with PyOS_snprintf doesn't work, not sure why. we'll just concatentate it here, no harm done. we @@ -723,8 +703,8 @@ and skip it */ sign = p[0]; if (sign == '-') { - p++; - n_digits--; + ++p; + --n_digits; } calc_number_widths(&spec, sign, n_digits, format); @@ -739,37 +719,51 @@ format->fill_char == '\0' ? ' ' : format->fill_char); /* fill in the digit parts */ - memmove(STRINGLIB_STR(result) + (spec.n_lpadding + spec.n_lsign + spec.n_spadding), + memmove(STRINGLIB_STR(result) + + (spec.n_lpadding + spec.n_lsign + spec.n_spadding), p, n_digits * sizeof(STRINGLIB_CHAR)); done: return result; } - -static PyObject * -format_float_internal(PyObject *value, const InternalFormatSpec *format) -{ - if (format->type == 'n') - return _format_float('f', value, format, snprintf_double); - else - return _format_float(format->type, value, format, PyOS_ascii_formatd); -} +#endif /* FORMAT_FLOAT */ /************************************************************************/ /*********** built in formatters ****************************************/ /************************************************************************/ - +#ifdef FORMAT_STRING PyObject * FORMAT_STRING(PyObject* value, PyObject* args) { PyObject *format_spec; - PyObject *tmp = NULL; PyObject *result = NULL; +#if PY_VERSION_HEX < 0x03000000 + PyObject *tmp = NULL; +#endif InternalFormatSpec format; - if (!PyArg_ParseTuple(args, STRINGLIB_PARSE_CODE ":__format__", &format_spec)) + /* If 2.x, we accept either str or unicode, and try to convert it + to the right type. In 3.x, we insist on only unicode */ +#if PY_VERSION_HEX >= 0x03000000 + if (!PyArg_ParseTuple(args, STRINGLIB_PARSE_CODE ":__format__", + &format_spec)) goto done; +#else + /* If 2.x, convert format_spec to the same type as value */ + /* This is to allow things like u''.format('') */ + if (!PyArg_ParseTuple(args, "O:__format__", &format_spec)) + goto done; + if (!(PyString_Check(format_spec) || PyUnicode_Check(format_spec))) { + PyErr_Format(PyExc_TypeError, "__format__ arg must be str " + "or unicode, not %s", Py_TYPE(format_spec)->tp_name); + goto done; + } + tmp = STRINGLIB_TOSTR(format_spec); + if (tmp == NULL) + goto done; + format_spec = tmp; +#endif /* check for the special case of zero length format spec, make it equivalent to str(value) */ @@ -778,6 +772,7 @@ goto done; } + /* parse the format_spec */ if (!parse_internal_render_format_spec(format_spec, &format, 's')) goto done; @@ -788,58 +783,43 @@ /* no type conversion needed, already a string. do the formatting */ result = format_string_internal(value, &format); break; -#if 0 - case 'b': - case 'c': - case 'd': - case 'o': - case 'x': - case 'X': - /* convert to integer */ - /* XXX: make a stringlib function to do this when backporting, - since FromUnicode differs from FromString */ - tmp = PyLong_FromUnicode(STRINGLIB_STR(value), STRINGLIB_LEN(value), 0); - if (tmp == NULL) - goto done; - result = format_long_internal(tmp, &format); - break; - - case 'e': - case 'E': - case 'f': - case 'F': - case 'g': - case 'G': - case 'n': - case '%': - /* convert to float */ - tmp = PyFloat_FromString(value); - if (tmp == NULL) - goto done; - result = format_float_internal(tmp, &format); - break; -#endif default: /* unknown */ - PyErr_Format(PyExc_ValueError, "Unknown conversion type %c", - format.type); + #if STRINGLIB_IS_UNICODE + /* If STRINGLIB_CHAR is Py_UNICODE, %c might be out-of-range, + hence the two cases. If it is char, gcc complains that the + condition below is always true, hence the ifdef. */ + if (format.type > 32 && format.type <128) + #endif + PyErr_Format(PyExc_ValueError, "Unknown conversion type %c", + (char)format.type); + #if STRINGLIB_IS_UNICODE + else + PyErr_Format(PyExc_ValueError, "Unknown conversion type '\\x%x'", + (unsigned int)format.type); + #endif goto done; } done: +#if PY_VERSION_HEX < 0x03000000 Py_XDECREF(tmp); +#endif return result; } +#endif /* FORMAT_STRING */ -PyObject * -FORMAT_LONG(PyObject* value, PyObject* args) +#if defined FORMAT_LONG || defined FORMAT_INT +static PyObject* +format_int_or_long(PyObject* value, PyObject* args, IntOrLongToString tostring) { PyObject *format_spec; PyObject *result = NULL; PyObject *tmp = NULL; InternalFormatSpec format; - if (!PyArg_ParseTuple(args, STRINGLIB_PARSE_CODE ":__format__", &format_spec)) + if (!PyArg_ParseTuple(args, STRINGLIB_PARSE_CODE ":__format__", + &format_spec)) goto done; /* check for the special case of zero length format spec, make @@ -855,23 +835,15 @@ /* type conversion? */ switch (format.type) { -#if 0 - case 's': - /* convert to string/unicode */ - tmp = STRINGLIB_TOSTR(value); - if (tmp == NULL) - goto done; - result = format_string_internal(tmp, &format); - break; -#endif case 'b': case 'c': case 'd': case 'o': case 'x': case 'X': - /* no type conversion needed, already an int. do the formatting */ - result = format_long_internal(value, &format); + /* no type conversion needed, already an int (or long). do + the formatting */ + result = format_int_or_long_internal(value, &format, tostring); break; case 'e': @@ -900,13 +872,57 @@ Py_XDECREF(tmp); return result; } +#endif /* FORMAT_LONG || defined FORMAT_INT */ + +#ifdef FORMAT_LONG +/* Need to define long_format as a function that will convert a long + to a string. In 3.0, _PyLong_Format has the correct signature. In + 2.x, we need to fudge a few parameters */ +#if PY_VERSION_HEX >= 0x03000000 +#define long_format _PyLong_Format +#else +static PyObject* +long_format(PyObject* value, int base) +{ + /* Convert to base, don't add trailing 'L', and use the new octal + format. We already know this is a long object */ + assert(PyLong_Check(value)); + /* convert to base, don't add 'L', and use the new octal format */ + return _PyLong_Format(value, base, 0, 1); +} +#endif + +PyObject * +FORMAT_LONG(PyObject* value, PyObject* args) +{ + return format_int_or_long(value, args, long_format); +} +#endif /* FORMAT_LONG */ + +#ifdef FORMAT_INT +/* this is only used for 2.x, not 3.0 */ +static PyObject* +int_format(PyObject* value, int base) +{ + /* Convert to base, and use the new octal format. We already + know this is an int object */ + assert(PyInt_Check(value)); + return _PyInt_Format((PyIntObject*)value, base, 1); +} PyObject * +FORMAT_INT(PyObject* value, PyObject* args) +{ + return format_int_or_long(value, args, int_format); +} +#endif /* FORMAT_INT */ + +#ifdef FORMAT_FLOAT +PyObject * FORMAT_FLOAT(PyObject *value, PyObject *args) { PyObject *format_spec; PyObject *result = NULL; - PyObject *tmp = NULL; InternalFormatSpec format; if (!PyArg_ParseTuple(args, STRINGLIB_PARSE_CODE ":__format__", &format_spec)) @@ -920,33 +936,16 @@ } /* parse the format_spec */ - if (!parse_internal_render_format_spec(format_spec, &format, 'g')) + if (!parse_internal_render_format_spec(format_spec, &format, '\0')) goto done; /* type conversion? */ switch (format.type) { -#if 0 - case 's': - /* convert to string/unicode */ - tmp = STRINGLIB_TOSTR(value); - if (tmp == NULL) - goto done; - result = format_string_internal(tmp, &format); - break; -#endif - case 'b': - case 'c': - case 'd': - case 'o': - case 'x': - case 'X': - /* convert to integer */ - tmp = PyNumber_Long(value); - if (tmp == NULL) - goto done; - result = format_long_internal(tmp, &format); - break; - + case '\0': + /* 'Z' means like 'g', but with at least one decimal. See + PyOS_ascii_formatd */ + format.type = 'Z'; + /* Deliberate fall through to the next case statement */ case 'e': case 'E': case 'f': @@ -967,6 +966,6 @@ } done: - Py_XDECREF(tmp); return result; } +#endif /* FORMAT_FLOAT */ Modified: python/branches/py3k-ctypes-pep3118/Objects/stringlib/string_format.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/stringlib/string_format.h (original) +++ python/branches/py3k-ctypes-pep3118/Objects/stringlib/string_format.h Wed Apr 30 15:57:13 2008 @@ -6,6 +6,11 @@ */ +/* Defines for Python 2.6 compatability */ +#if PY_VERSION_HEX < 0x03000000 +#define PyLong_FromSsize_t _PyLong_FromSsize_t +#endif + /* Defines for more efficiently reallocating the string buffer */ #define INITIAL_SIZE_INCREMENT 100 #define SIZE_MULTIPLIER 2 @@ -470,81 +475,44 @@ field object and field specification string generated by get_field_and_spec, and renders the field into the output string. - format() does the actual calling of the objects __format__ method. + render_field calls fieldobj.__format__(format_spec) method, and + appends to the output. */ - - -/* returns fieldobj.__format__(format_spec) */ -static PyObject * -format(PyObject *fieldobj, SubString *format_spec) +static int +render_field(PyObject *fieldobj, SubString *format_spec, OutputString *output) { - static PyObject *format_str = NULL; - PyObject *meth; - PyObject *spec = NULL; + int ok = 0; PyObject *result = NULL; - /* Initialize cached value */ - if (format_str == NULL) { - /* Initialize static variable needed by _PyType_Lookup */ - format_str = PyUnicode_FromString("__format__"); - if (format_str == NULL) - return NULL; - } - - /* Make sure the type is initialized. float gets initialized late */ - if (Py_TYPE(fieldobj)->tp_dict == NULL) - if (PyType_Ready(Py_TYPE(fieldobj)) < 0) - return NULL; - /* we need to create an object out of the pointers we have */ - spec = SubString_new_object_or_empty(format_spec); - if (spec == NULL) - goto done; - - /* Find the (unbound!) __format__ method (a borrowed reference) */ - meth = _PyType_Lookup(Py_TYPE(fieldobj), format_str); - if (meth == NULL) { - PyErr_Format(PyExc_TypeError, - "Type %.100s doesn't define __format__", - Py_TYPE(fieldobj)->tp_name); + PyObject *format_spec_object = SubString_new_object_or_empty(format_spec); + if (format_spec_object == NULL) goto done; - } - /* And call it, binding it to the value */ - result = PyObject_CallFunctionObjArgs(meth, fieldobj, spec, NULL); + result = PyObject_Format(fieldobj, format_spec_object); if (result == NULL) goto done; - if (!STRINGLIB_CHECK(result)) { - PyErr_SetString(PyExc_TypeError, - "__format__ method did not return " - STRINGLIB_TYPE_NAME); - Py_DECREF(result); - result = NULL; - goto done; +#if PY_VERSION_HEX >= 0x03000000 + assert(PyUnicode_Check(result)); +#else + assert(PyString_Check(result) || PyUnicode_Check(result)); + + /* Convert result to our type. We could be str, and result could + be unicode */ + { + PyObject *tmp = STRINGLIB_TOSTR(result); + if (tmp == NULL) + goto done; + Py_DECREF(result); + result = tmp; } - -done: - Py_XDECREF(spec); - return result; -} - -/* - render_field calls fieldobj.__format__(format_spec) method, and - appends to the output. -*/ -static int -render_field(PyObject *fieldobj, SubString *format_spec, OutputString *output) -{ - int ok = 0; - PyObject *result = format(fieldobj, format_spec); - - if (result == NULL) - goto done; +#endif ok = output_data(output, STRINGLIB_STR(result), STRINGLIB_LEN(result)); done: + Py_DECREF(format_spec_object); Py_XDECREF(result); return ok; } @@ -770,11 +738,19 @@ case 'r': return PyObject_Repr(obj); case 's': - return PyObject_Str(obj); + return STRINGLIB_TOSTR(obj); default: - PyErr_Format(PyExc_ValueError, - "Unknown converion specifier %c", - conversion); + if (conversion > 32 && conversion < 127) { + /* It's the ASCII subrange; casting to char is safe + (assuming the execution character set is an ASCII + superset). */ + PyErr_Format(PyExc_ValueError, + "Unknown conversion specifier %c", + (char)conversion); + } else + PyErr_Format(PyExc_ValueError, + "Unknown conversion specifier \\x%x", + (unsigned int)conversion); return NULL; } } @@ -845,7 +821,7 @@ } /* - do_markup is the top-level loop for the format() function. It + do_markup is the top-level loop for the format() method. It searches through the format string for escapes to markup codes, and calls other functions to move non-markup text to the output, and to perform the markup to the output. @@ -958,7 +934,7 @@ typedef struct { PyObject_HEAD - PyUnicodeObject *str; + STRINGLIB_OBJECT *str; MarkupIterator it_markup; } formatteriterobject; @@ -984,7 +960,7 @@ SubString literal; SubString field_name; SubString format_spec; - Py_UNICODE conversion; + STRINGLIB_CHAR conversion; int format_spec_needs_expanding; int result = MarkupIterator_next(&it->it_markup, &literal, &field_name, &format_spec, &conversion, @@ -1028,7 +1004,7 @@ Py_INCREF(conversion_str); } else - conversion_str = PyUnicode_FromUnicode(&conversion, 1); + conversion_str = STRINGLIB_NEW(&conversion, 1); if (conversion_str == NULL) goto done; @@ -1047,7 +1023,7 @@ {NULL, NULL} /* sentinel */ }; -PyTypeObject PyFormatterIter_Type = { +static PyTypeObject PyFormatterIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "formatteriterator", /* tp_name */ sizeof(formatteriterobject), /* tp_basicsize */ @@ -1085,7 +1061,7 @@ describing the parsed elements. It's a wrapper around stringlib/string_format.h's MarkupIterator */ static PyObject * -formatter_parser(PyUnicodeObject *self) +formatter_parser(STRINGLIB_OBJECT *self) { formatteriterobject *it; @@ -1099,8 +1075,8 @@ /* initialize the contained MarkupIterator */ MarkupIterator_init(&it->it_markup, - PyUnicode_AS_UNICODE(self), - PyUnicode_GET_SIZE(self)); + STRINGLIB_STR(self), + STRINGLIB_LEN(self)); return (PyObject *)it; } @@ -1118,7 +1094,7 @@ typedef struct { PyObject_HEAD - PyUnicodeObject *str; + STRINGLIB_OBJECT *str; FieldNameIterator it_field; } fieldnameiterobject; @@ -1220,7 +1196,7 @@ field_name_split. The iterator it returns is a FieldNameIterator */ static PyObject * -formatter_field_name_split(PyUnicodeObject *self) +formatter_field_name_split(STRINGLIB_OBJECT *self) { SubString first; Py_ssize_t first_idx; Modified: python/branches/py3k-ctypes-pep3118/Objects/stringlib/stringdefs.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/stringlib/stringdefs.h (original) +++ python/branches/py3k-ctypes-pep3118/Objects/stringlib/stringdefs.h Wed Apr 30 15:57:13 2008 @@ -6,12 +6,15 @@ compiled as unicode. */ #define STRINGLIB_IS_UNICODE 0 +#define STRINGLIB_OBJECT PyStringObject #define STRINGLIB_CHAR char #define STRINGLIB_TYPE_NAME "string" #define STRINGLIB_PARSE_CODE "S" -#define STRINGLIB_EMPTY string_empty +#define STRINGLIB_EMPTY nullstring #define STRINGLIB_ISDECIMAL(x) ((x >= '0') && (x <= '9')) #define STRINGLIB_TODECIMAL(x) (STRINGLIB_ISDECIMAL(x) ? (x - '0') : -1) +#define STRINGLIB_TOUPPER toupper +#define STRINGLIB_TOLOWER tolower #define STRINGLIB_FILL memset #define STRINGLIB_STR PyString_AS_STRING #define STRINGLIB_LEN PyString_GET_SIZE Modified: python/branches/py3k-ctypes-pep3118/Objects/stringlib/unicodedefs.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/stringlib/unicodedefs.h (original) +++ python/branches/py3k-ctypes-pep3118/Objects/stringlib/unicodedefs.h Wed Apr 30 15:57:13 2008 @@ -6,6 +6,7 @@ compiled as unicode. */ #define STRINGLIB_IS_UNICODE 1 +#define STRINGLIB_OBJECT PyUnicodeObject #define STRINGLIB_CHAR Py_UNICODE #define STRINGLIB_TYPE_NAME "unicode" #define STRINGLIB_PARSE_CODE "U" @@ -20,7 +21,12 @@ #define STRINGLIB_NEW PyUnicode_FromUnicode #define STRINGLIB_RESIZE PyUnicode_Resize #define STRINGLIB_CHECK PyUnicode_Check + +#if PY_VERSION_HEX < 0x03000000 +#define STRINGLIB_TOSTR PyObject_Unicode +#else #define STRINGLIB_TOSTR PyObject_Str +#endif #define STRINGLIB_WANT_CONTAINS_OBJ 1 Modified: python/branches/py3k-ctypes-pep3118/Objects/stringobject.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/stringobject.c (original) +++ python/branches/py3k-ctypes-pep3118/Objects/stringobject.c Wed Apr 30 15:57:13 2008 @@ -64,7 +64,11 @@ PyString_FromStringAndSize(const char *str, Py_ssize_t size) { register PyStringObject *op; - assert(size >= 0); + if (size < 0) { + PyErr_SetString(PyExc_SystemError, + "Negative size passed to PyString_FromStringAndSize"); + return NULL; + } if (size == 0 && (op = nullstring) != NULL) { #ifdef COUNT_ALLOCS null_strings++; @@ -2772,7 +2776,7 @@ } buf[j++] = (top << 4) + bot; } - if (_PyString_Resize(&newstring, j) < 0) + if (j != byteslen && _PyString_Resize(&newstring, j) < 0) goto error; return newstring; @@ -2788,7 +2792,7 @@ return Py_BuildValue("(s#)", v->ob_sval, Py_SIZE(v)); } - + static PyMethodDef string_methods[] = { {"__getnewargs__", (PyCFunction)string_getnewargs, METH_NOARGS}, Modified: python/branches/py3k-ctypes-pep3118/Objects/tupleobject.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/tupleobject.c (original) +++ python/branches/py3k-ctypes-pep3118/Objects/tupleobject.c Wed Apr 30 15:57:13 2008 @@ -4,19 +4,19 @@ #include "Python.h" /* Speed optimization to avoid frequent malloc/free of small tuples */ -#ifndef MAXSAVESIZE -#define MAXSAVESIZE 20 /* Largest tuple to save on free list */ +#ifndef PyTuple_MAXSAVESIZE +#define PyTuple_MAXSAVESIZE 20 /* Largest tuple to save on free list */ #endif -#ifndef MAXSAVEDTUPLES -#define MAXSAVEDTUPLES 2000 /* Maximum number of tuples of each size to save */ +#ifndef PyTuple_MAXFREELIST +#define PyTuple_MAXFREELIST 2000 /* Maximum number of tuples of each size to save */ #endif -#if MAXSAVESIZE > 0 -/* Entries 1 up to MAXSAVESIZE are free lists, entry 0 is the empty +#if PyTuple_MAXSAVESIZE > 0 +/* Entries 1 up to PyTuple_MAXSAVESIZE are free lists, entry 0 is the empty tuple () of which at most one instance will be allocated. */ -static PyTupleObject *free_tuples[MAXSAVESIZE]; -static int num_free_tuples[MAXSAVESIZE]; +static PyTupleObject *free_list[PyTuple_MAXSAVESIZE]; +static int numfree[PyTuple_MAXSAVESIZE]; #endif #ifdef COUNT_ALLOCS int fast_tuple_allocs; @@ -32,18 +32,18 @@ PyErr_BadInternalCall(); return NULL; } -#if MAXSAVESIZE > 0 - if (size == 0 && free_tuples[0]) { - op = free_tuples[0]; +#if PyTuple_MAXSAVESIZE > 0 + if (size == 0 && free_list[0]) { + op = free_list[0]; Py_INCREF(op); #ifdef COUNT_ALLOCS tuple_zero_allocs++; #endif return (PyObject *) op; } - if (size < MAXSAVESIZE && (op = free_tuples[size]) != NULL) { - free_tuples[size] = (PyTupleObject *) op->ob_item[0]; - num_free_tuples[size]--; + if (size < PyTuple_MAXSAVESIZE && (op = free_list[size]) != NULL) { + free_list[size] = (PyTupleObject *) op->ob_item[0]; + numfree[size]--; #ifdef COUNT_ALLOCS fast_tuple_allocs++; #endif @@ -71,10 +71,10 @@ } for (i=0; i < size; i++) op->ob_item[i] = NULL; -#if MAXSAVESIZE > 0 +#if PyTuple_MAXSAVESIZE > 0 if (size == 0) { - free_tuples[0] = op; - ++num_free_tuples[0]; + free_list[0] = op; + ++numfree[0]; Py_INCREF(op); /* extra INCREF so that this is never freed */ } #endif @@ -167,14 +167,14 @@ i = len; while (--i >= 0) Py_XDECREF(op->ob_item[i]); -#if MAXSAVESIZE > 0 - if (len < MAXSAVESIZE && - num_free_tuples[len] < MAXSAVEDTUPLES && +#if PyTuple_MAXSAVESIZE > 0 + if (len < PyTuple_MAXSAVESIZE && + numfree[len] < PyTuple_MAXFREELIST && Py_TYPE(op) == &PyTuple_Type) { - op->ob_item[0] = (PyObject *) free_tuples[len]; - num_free_tuples[len]++; - free_tuples[len] = op; + op->ob_item[0] = (PyObject *) free_list[len]; + numfree[len]++; + free_list[len] = op; goto done; /* return */ } #endif @@ -430,6 +430,53 @@ return (PyObject *) np; } +static PyObject * +tupleindex(PyTupleObject *self, PyObject *args) +{ + Py_ssize_t i, start=0, stop=Py_SIZE(self); + PyObject *v; + + if (!PyArg_ParseTuple(args, "O|O&O&:index", &v, + _PyEval_SliceIndex, &start, + _PyEval_SliceIndex, &stop)) + return NULL; + if (start < 0) { + start += Py_SIZE(self); + if (start < 0) + start = 0; + } + if (stop < 0) { + stop += Py_SIZE(self); + if (stop < 0) + stop = 0; + } + for (i = start; i < stop && i < Py_SIZE(self); i++) { + int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); + if (cmp > 0) + return PyLong_FromSsize_t(i); + else if (cmp < 0) + return NULL; + } + PyErr_SetString(PyExc_ValueError, "tuple.index(x): x not in list"); + return NULL; +} + +static PyObject * +tuplecount(PyTupleObject *self, PyObject *v) +{ + Py_ssize_t count = 0; + Py_ssize_t i; + + for (i = 0; i < Py_SIZE(self); i++) { + int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); + if (cmp > 0) + count++; + else if (cmp < 0) + return NULL; + } + return PyLong_FromSsize_t(count); +} + static int tupletraverse(PyTupleObject *o, visitproc visit, void *arg) { @@ -636,8 +683,15 @@ } +PyDoc_STRVAR(index_doc, +"T.index(value, [start, [stop]]) -> integer -- return first index of value"); +PyDoc_STRVAR(count_doc, +"T.count(value) -> integer -- return number of occurrences of value"); + static PyMethodDef tuple_methods[] = { {"__getnewargs__", (PyCFunction)tuple_getnewargs, METH_NOARGS}, + {"index", (PyCFunction)tupleindex, METH_VARARGS, index_doc}, + {"count", (PyCFunction)tuplecount, METH_O, count_doc}, {NULL, NULL} /* sentinel */ }; @@ -753,19 +807,18 @@ return 0; } -void -PyTuple_Fini(void) +int +PyTuple_ClearFreeList(void) { -#if MAXSAVESIZE > 0 + int freelist_size = 0; +#if PyTuple_MAXSAVESIZE > 0 int i; - - Py_XDECREF(free_tuples[0]); - free_tuples[0] = NULL; - - for (i = 1; i < MAXSAVESIZE; i++) { + for (i = 1; i < PyTuple_MAXSAVESIZE; i++) { PyTupleObject *p, *q; - p = free_tuples[i]; - free_tuples[i] = NULL; + p = free_list[i]; + freelist_size += numfree[i]; + free_list[i] = NULL; + numfree[i] = 0; while (p) { q = p; p = (PyTupleObject *)(p->ob_item[0]); @@ -773,6 +826,20 @@ } } #endif + return freelist_size; +} + +void +PyTuple_Fini(void) +{ +#if PyTuple_MAXSAVESIZE > 0 + /* empty tuples are used all over the place and applications may + * rely on the fact that an empty tuple is a singleton. */ + Py_XDECREF(free_list[0]); + free_list[0] = NULL; + + (void)PyTuple_ClearFreeList(); +#endif } /*********************** Tuple Iterator **************************/ Modified: python/branches/py3k-ctypes-pep3118/Objects/typeobject.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/typeobject.c (original) +++ python/branches/py3k-ctypes-pep3118/Objects/typeobject.c Wed Apr 30 15:57:13 2008 @@ -33,6 +33,24 @@ static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP]; static unsigned int next_version_tag = 0; +static void type_modified(PyTypeObject *); + +unsigned int +PyType_ClearCache(void) +{ + Py_ssize_t i; + unsigned int cur_version_tag = next_version_tag - 1; + + for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) { + method_cache[i].version = 0; + Py_CLEAR(method_cache[i].name); + method_cache[i].value = NULL; + } + next_version_tag = 0; + /* mark all version tags as invalid */ + type_modified(&PyBaseObject_Type); + return cur_version_tag; +} static void type_modified(PyTypeObject *type) @@ -59,7 +77,7 @@ PyObject *raw, *ref; Py_ssize_t i, n; - if(!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) + if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) return; raw = type->tp_subclasses; @@ -95,7 +113,7 @@ Py_ssize_t i, n; int clear = 0; - if(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG)) + if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG)) return; n = PyTuple_GET_SIZE(bases); @@ -301,6 +319,40 @@ } static PyObject * +type_abstractmethods(PyTypeObject *type, void *context) +{ + PyObject *mod = PyDict_GetItemString(type->tp_dict, + "__abstractmethods__"); + if (!mod) { + PyErr_Format(PyExc_AttributeError, "__abstractmethods__"); + return NULL; + } + Py_XINCREF(mod); + return mod; +} + +static int +type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context) +{ + /* __abstractmethods__ should only be set once on a type, in + abc.ABCMeta.__new__, so this function doesn't do anything + special to update subclasses. + */ + int res = PyDict_SetItemString(type->tp_dict, + "__abstractmethods__", value); + if (res == 0) { + type_modified(type); + if (value && PyObject_IsTrue(value)) { + type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT; + } + else { + type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT; + } + } + return res; +} + +static PyObject * type_get_bases(PyTypeObject *type, void *context) { Py_INCREF(type->tp_bases); @@ -537,6 +589,8 @@ {"__name__", (getter)type_name, (setter)type_set_name, NULL}, {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL}, {"__module__", (getter)type_module, (setter)type_set_module, NULL}, + {"__abstractmethods__", (getter)type_abstractmethods, + (setter)type_set_abstractmethods, NULL}, {"__dict__", (getter)type_dict, NULL, NULL}, {"__doc__", (getter)type_get_doc, NULL, NULL}, {0} @@ -546,7 +600,6 @@ type_repr(PyTypeObject *type) { PyObject *mod, *name, *rtn; - char *kind; mod = type_module(type, NULL); if (mod == NULL) @@ -559,15 +612,10 @@ if (name == NULL) return NULL; - if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) - kind = "class"; - else - kind = "type"; - if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins")) - rtn = PyUnicode_FromFormat("<%s '%U.%U'>", kind, mod, name); + rtn = PyUnicode_FromFormat("", mod, name); else - rtn = PyUnicode_FromFormat("<%s '%s'>", kind, type->tp_name); + rtn = PyUnicode_FromFormat("", type->tp_name); Py_XDECREF(mod); Py_DECREF(name); @@ -1342,8 +1390,8 @@ PyObject *bases, *result; PyObject *to_merge, *bases_aslist; - if(type->tp_dict == NULL) { - if(PyType_Ready(type) < 0) + if (type->tp_dict == NULL) { + if (PyType_Ready(type) < 0) return NULL; } @@ -2204,7 +2252,7 @@ unsigned int h; if (MCACHE_CACHEABLE_NAME(name) && - PyType_HasFeature(type,Py_TPFLAGS_VALID_VERSION_TAG)) { + PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) { /* fast path */ h = MCACHE_HASH_METHOD(type, name); if (method_cache[h].version == type->tp_version_tag && @@ -2620,6 +2668,52 @@ } if (err < 0) return NULL; + + if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) { + static PyObject *comma = NULL; + PyObject *abstract_methods = NULL; + PyObject *builtins; + PyObject *sorted; + PyObject *sorted_methods = NULL; + PyObject *joined = NULL; + + /* Compute ", ".join(sorted(type.__abstractmethods__)) + into joined. */ + abstract_methods = type_abstractmethods(type, NULL); + if (abstract_methods == NULL) + goto error; + builtins = PyEval_GetBuiltins(); + if (builtins == NULL) + goto error; + sorted = PyDict_GetItemString(builtins, "sorted"); + if (sorted == NULL) + goto error; + sorted_methods = PyObject_CallFunctionObjArgs(sorted, + abstract_methods, + NULL); + if (sorted_methods == NULL) + goto error; + if (comma == NULL) { + comma = PyUnicode_InternFromString(", "); + if (comma == NULL) + goto error; + } + joined = PyObject_CallMethod(comma, "join", + "O", sorted_methods); + if (joined == NULL) + goto error; + + PyErr_Format(PyExc_TypeError, + "Can't instantiate abstract class %s " + "with abstract methods %U", + type->tp_name, + joined); + error: + Py_XDECREF(joined); + Py_XDECREF(sorted_methods); + Py_XDECREF(abstract_methods); + return NULL; + } return type->tp_alloc(type, 0); } @@ -3125,6 +3219,20 @@ return _common_reduce(self, proto); } +static PyObject * +object_subclasshook(PyObject *cls, PyObject *args) +{ + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; +} + +PyDoc_STRVAR(object_subclasshook_doc, +"Abstract classes can override this to customize issubclass().\n" +"\n" +"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" +"It should return True, False or NotImplemented. If it returns\n" +"NotImplemented, the normal algorithm is used. Otherwise, it\n" +"overrides the normal algorithm (and the outcome is cached).\n"); /* from PEP 3101, this code implements: @@ -3165,6 +3273,8 @@ PyDoc_STR("helper for pickle")}, {"__reduce__", object_reduce, METH_VARARGS, PyDoc_STR("helper for pickle")}, + {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS, + object_subclasshook_doc}, {"__format__", object_format, METH_VARARGS, PyDoc_STR("default object formatter")}, {0} Modified: python/branches/py3k-ctypes-pep3118/Objects/unicodeobject.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Objects/unicodeobject.c (original) +++ python/branches/py3k-ctypes-pep3118/Objects/unicodeobject.c Wed Apr 30 15:57:13 2008 @@ -54,7 +54,7 @@ /* Limit for the Unicode object free list */ -#define MAX_UNICODE_FREELIST_SIZE 1024 +#define PyUnicode_MAXFREELIST 1024 /* Limit for the Unicode object free list stay alive optimization. @@ -62,7 +62,7 @@ all objects on the free list having a size less than this limit. This reduces malloc() overhead for small Unicode objects. - At worst this will result in MAX_UNICODE_FREELIST_SIZE * + At worst this will result in PyUnicode_MAXFREELIST * (sizeof(PyUnicodeObject) + KEEPALIVE_SIZE_LIMIT + malloc()-overhead) bytes of unused garbage. @@ -106,8 +106,8 @@ static PyObject *interned; /* Free list for Unicode objects */ -static PyUnicodeObject *unicode_freelist; -static int unicode_freelist_size; +static PyUnicodeObject *free_list; +static int numfree; /* The empty Unicode object is shared to improve performance. */ static PyUnicodeObject *unicode_empty; @@ -125,6 +125,64 @@ */ static const char unicode_default_encoding[] = "utf-8"; +/* Fast detection of the most frequent whitespace characters */ +const unsigned char _Py_ascii_whitespace[] = { + 0, 0, 0, 0, 0, 0, 0, 0, +// case 0x0009: /* HORIZONTAL TABULATION */ +// case 0x000A: /* LINE FEED */ +// case 0x000B: /* VERTICAL TABULATION */ +// case 0x000C: /* FORM FEED */ +// case 0x000D: /* CARRIAGE RETURN */ + 0, 1, 1, 1, 1, 1, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, +// case 0x001C: /* FILE SEPARATOR */ +// case 0x001D: /* GROUP SEPARATOR */ +// case 0x001E: /* RECORD SEPARATOR */ +// case 0x001F: /* UNIT SEPARATOR */ + 0, 0, 0, 0, 1, 1, 1, 1, +// case 0x0020: /* SPACE */ + 1, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0 +}; + +/* Same for linebreaks */ +static unsigned char ascii_linebreak[] = { + 0, 0, 0, 0, 0, 0, 0, 0, +// 0x000A, /* LINE FEED */ +// 0x000D, /* CARRIAGE RETURN */ + 0, 0, 1, 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, +// 0x001C, /* FILE SEPARATOR */ +// 0x001D, /* GROUP SEPARATOR */ +// 0x001E, /* RECORD SEPARATOR */ + 0, 0, 0, 0, 1, 1, 1, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0 +}; + + Py_UNICODE PyUnicode_GetMax(void) { @@ -151,8 +209,9 @@ #define BLOOM(mask, ch) ((mask & (1 << ((ch) & 0x1F)))) -#define BLOOM_LINEBREAK(ch)\ - (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK((ch))) +#define BLOOM_LINEBREAK(ch) \ + ((ch) < 128U ? ascii_linebreak[(ch)] : \ + (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch))) Py_LOCAL_INLINE(BLOOM_MASK) make_bloom_mask(Py_UNICODE* ptr, Py_ssize_t len) { @@ -213,7 +272,8 @@ it contains). */ oldstr = unicode->str; - PyMem_RESIZE(unicode->str, Py_UNICODE, length + 1); + unicode->str = PyObject_REALLOC(unicode->str, + sizeof(Py_UNICODE) * (length + 1)); if (!unicode->str) { unicode->str = (Py_UNICODE *)oldstr; PyErr_NoMemory(); @@ -254,29 +314,32 @@ } /* Unicode freelist & memory allocation */ - if (unicode_freelist) { - unicode = unicode_freelist; - unicode_freelist = *(PyUnicodeObject **)unicode; - unicode_freelist_size--; + if (free_list) { + unicode = free_list; + free_list = *(PyUnicodeObject **)unicode; + numfree--; if (unicode->str) { /* Keep-Alive optimization: we only upsize the buffer, never downsize it. */ if ((unicode->length < length) && unicode_resize(unicode, length) < 0) { - PyMem_DEL(unicode->str); + PyObject_DEL(unicode->str); goto onError; } } else { - unicode->str = PyMem_NEW(Py_UNICODE, length + 1); + size_t new_size = sizeof(Py_UNICODE) * ((size_t)length + 1); + unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size); } PyObject_INIT(unicode, &PyUnicode_Type); } else { + size_t new_size; unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type); if (unicode == NULL) return NULL; - unicode->str = PyMem_NEW(Py_UNICODE, length + 1); + new_size = sizeof(Py_UNICODE) * ((size_t)length + 1); + unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size); } if (!unicode->str) { @@ -327,10 +390,10 @@ } if (PyUnicode_CheckExact(unicode) && - unicode_freelist_size < MAX_UNICODE_FREELIST_SIZE) { + numfree < PyUnicode_MAXFREELIST) { /* Keep-Alive optimization */ if (unicode->length >= KEEPALIVE_SIZE_LIMIT) { - PyMem_DEL(unicode->str); + PyObject_DEL(unicode->str); unicode->str = NULL; unicode->length = 0; } @@ -339,12 +402,12 @@ unicode->defenc = NULL; } /* Add to free list */ - *(PyUnicodeObject **)unicode = unicode_freelist; - unicode_freelist = unicode; - unicode_freelist_size++; + *(PyUnicodeObject **)unicode = free_list; + free_list = unicode; + numfree++; } else { - PyMem_DEL(unicode->str); + PyObject_DEL(unicode->str); Py_XDECREF(unicode->defenc); Py_TYPE(unicode)->tp_free((PyObject *)unicode); } @@ -434,6 +497,13 @@ PyObject *PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size) { PyUnicodeObject *unicode; + + if (size < 0) { + PyErr_SetString(PyExc_SystemError, + "Negative size passed to PyUnicode_FromStringAndSize"); + return NULL; + } + /* If the Unicode data is known at construction time, we can apply some optimizations which share commonly used objects. Also, this means the input must be UTF-8, so fall back to the @@ -490,10 +560,16 @@ PyUnicodeObject *unicode; if (w == NULL) { + if (size == 0) + return PyUnicode_FromStringAndSize(NULL, 0); PyErr_BadInternalCall(); return NULL; } + if (size == -1) { + size = wcslen(w); + } + unicode = _PyUnicode_New(size); if (!unicode) return NULL; @@ -581,7 +657,7 @@ /* step 2: allocate memory for the results of * PyObject_Str()/PyObject_Repr() calls */ if (callcount) { - callresults = PyMem_Malloc(sizeof(PyObject *)*callcount); + callresults = PyObject_Malloc(sizeof(PyObject *)*callcount); if (!callresults) { PyErr_NoMemory(); return NULL; @@ -593,9 +669,9 @@ if (*f == '%') { const char* p = f; width = 0; - while (ISDIGIT(*f)) + while (ISDIGIT((unsigned)*f)) width = (width*10) + *f++ - '0'; - while (*++f && *f != '%' && !ISALPHA(*f)) + while (*++f && *f != '%' && !ISALPHA((unsigned)*f)) ; /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since @@ -728,7 +804,7 @@ } expand: if (abuffersize > 20) { - abuffer = PyMem_Malloc(abuffersize); + abuffer = PyObject_Malloc(abuffersize); if (!abuffer) { PyErr_NoMemory(); goto fail; @@ -756,12 +832,12 @@ zeropad = (*f == '0'); /* parse the width.precision part */ width = 0; - while (ISDIGIT(*f)) + while (ISDIGIT((unsigned)*f)) width = (width*10) + *f++ - '0'; precision = 0; if (*f == '.') { f++; - while (ISDIGIT(*f)) + while (ISDIGIT((unsigned)*f)) precision = (precision*10) + *f++ - '0'; } /* handle the long flag, but only for %ld and %lu. @@ -891,9 +967,9 @@ end: if (callresults) - PyMem_Free(callresults); + PyObject_Free(callresults); if (abuffer) - PyMem_Free(abuffer); + PyObject_Free(abuffer); _PyUnicode_Resize(&string, s - PyUnicode_AS_UNICODE(string)); return string; fail: @@ -903,10 +979,10 @@ Py_DECREF(*callresult2); ++callresult2; } - PyMem_Free(callresults); + PyObject_Free(callresults); } if (abuffer) - PyMem_Free(abuffer); + PyObject_Free(abuffer); return NULL; } @@ -3134,8 +3210,22 @@ else x += 10 + c - 'A'; } -#ifndef Py_UNICODE_WIDE - if (x > 0x10000) { + if (x <= 0xffff) + /* UCS-2 character */ + *p++ = (Py_UNICODE) x; + else if (x <= 0x10ffff) { + /* UCS-4 character. Either store directly, or as + surrogate pair. */ +#ifdef Py_UNICODE_WIDE + *p++ = (Py_UNICODE) x; +#else + x -= 0x10000L; + *p++ = 0xD800 + (Py_UNICODE) (x >> 10); + *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF); +#endif + } else { + endinpos = s-starts; + outpos = p-PyUnicode_AS_UNICODE(v); if (unicode_decode_call_errorhandler( errors, &errorHandler, "rawunicodeescape", "\\Uxxxxxxxx out of range", @@ -3143,8 +3233,6 @@ (PyObject **)&v, &outpos, &p)) goto onError; } -#endif - *p++ = x; nextByte: ; } @@ -3196,6 +3284,32 @@ *p++ = hexdigits[ch & 15]; } else +#else + /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */ + if (ch >= 0xD800 && ch < 0xDC00) { + Py_UNICODE ch2; + Py_UCS4 ucs; + + ch2 = *s++; + size--; + if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) { + ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000; + *p++ = '\\'; + *p++ = 'U'; + *p++ = hexdigits[(ucs >> 28) & 0xf]; + *p++ = hexdigits[(ucs >> 24) & 0xf]; + *p++ = hexdigits[(ucs >> 20) & 0xf]; + *p++ = hexdigits[(ucs >> 16) & 0xf]; + *p++ = hexdigits[(ucs >> 12) & 0xf]; + *p++ = hexdigits[(ucs >> 8) & 0xf]; + *p++ = hexdigits[(ucs >> 4) & 0xf]; + *p++ = hexdigits[ucs & 0xf]; + continue; + } + /* Fall through: isolated surrogates are copied as-is */ + s--; + size++; + } #endif /* Map 16-bit characters to '\uxxxx' */ if (ch >= 256) { @@ -5602,25 +5716,26 @@ register Py_ssize_t j; Py_ssize_t len = self->length; PyObject *str; + register const Py_UNICODE *buf = self->str; for (i = j = 0; i < len; ) { /* find a token */ - while (i < len && Py_UNICODE_ISSPACE(self->str[i])) + while (i < len && Py_UNICODE_ISSPACE(buf[i])) i++; j = i; - while (i < len && !Py_UNICODE_ISSPACE(self->str[i])) + while (i < len && !Py_UNICODE_ISSPACE(buf[i])) i++; if (j < i) { if (maxcount-- <= 0) break; - SPLIT_APPEND(self->str, j, i); - while (i < len && Py_UNICODE_ISSPACE(self->str[i])) + SPLIT_APPEND(buf, j, i); + while (i < len && Py_UNICODE_ISSPACE(buf[i])) i++; j = i; } } if (j < len) { - SPLIT_APPEND(self->str, j, len); + SPLIT_APPEND(buf, j, len); } return list; @@ -5693,18 +5808,19 @@ register Py_ssize_t j; Py_ssize_t len = self->length; PyObject *str; + register const Py_UNICODE *buf = self->str; for (i = j = 0; i < len; ) { - if (self->str[i] == ch) { + if (buf[i] == ch) { if (maxcount-- <= 0) break; - SPLIT_APPEND(self->str, j, i); + SPLIT_APPEND(buf, j, i); i = j = i + 1; } else i++; } if (j <= len) { - SPLIT_APPEND(self->str, j, len); + SPLIT_APPEND(buf, j, len); } return list; @@ -5753,25 +5869,26 @@ register Py_ssize_t j; Py_ssize_t len = self->length; PyObject *str; + register const Py_UNICODE *buf = self->str; for (i = j = len - 1; i >= 0; ) { /* find a token */ - while (i >= 0 && Py_UNICODE_ISSPACE(self->str[i])) + while (i >= 0 && Py_UNICODE_ISSPACE(buf[i])) i--; j = i; - while (i >= 0 && !Py_UNICODE_ISSPACE(self->str[i])) + while (i >= 0 && !Py_UNICODE_ISSPACE(buf[i])) i--; if (j > i) { if (maxcount-- <= 0) break; - SPLIT_APPEND(self->str, i + 1, j + 1); - while (i >= 0 && Py_UNICODE_ISSPACE(self->str[i])) + SPLIT_APPEND(buf, i + 1, j + 1); + while (i >= 0 && Py_UNICODE_ISSPACE(buf[i])) i--; j = i; } } if (j >= 0) { - SPLIT_APPEND(self->str, 0, j + 1); + SPLIT_APPEND(buf, 0, j + 1); } if (PyList_Reverse(list) < 0) goto onError; @@ -5792,18 +5909,19 @@ register Py_ssize_t j; Py_ssize_t len = self->length; PyObject *str; + register const Py_UNICODE *buf = self->str; for (i = j = len - 1; i >= 0; ) { - if (self->str[i] == ch) { + if (buf[i] == ch) { if (maxcount-- <= 0) break; - SPLIT_APPEND(self->str, i + 1, j + 1); + SPLIT_APPEND(buf, i + 1, j + 1); j = i = i - 1; } else i--; } if (j >= -1) { - SPLIT_APPEND(self->str, 0, j + 1); + SPLIT_APPEND(buf, 0, j + 1); } if (PyList_Reverse(list) < 0) goto onError; @@ -6527,7 +6645,8 @@ Py_UNICODE *e; Py_UNICODE *p; Py_UNICODE *q; - Py_ssize_t i, j, old_j; + Py_UNICODE *qe; + Py_ssize_t i, j, incr; PyUnicodeObject *u; int tabsize = 8; @@ -6535,63 +6654,70 @@ return NULL; /* First pass: determine size of output string */ - i = j = old_j = 0; - e = self->str + self->length; + i = 0; /* chars up to and including most recent \n or \r */ + j = 0; /* chars since most recent \n or \r (use in tab calculations) */ + e = self->str + self->length; /* end of input */ for (p = self->str; p < e; p++) if (*p == '\t') { if (tabsize > 0) { - j += tabsize - (j % tabsize); - if (old_j > j) { - PyErr_SetString(PyExc_OverflowError, - "new string is too long"); - return NULL; - } - old_j = j; - } + incr = tabsize - (j % tabsize); /* cannot overflow */ + if (j > PY_SSIZE_T_MAX - incr) + goto overflow1; + j += incr; + } } else { + if (j > PY_SSIZE_T_MAX - 1) + goto overflow1; j++; if (*p == '\n' || *p == '\r') { + if (i > PY_SSIZE_T_MAX - j) + goto overflow1; i += j; - old_j = j = 0; - if (i < 0) { - PyErr_SetString(PyExc_OverflowError, - "new string is too long"); - return NULL; - } + j = 0; } } - if ((i + j) < 0) { - PyErr_SetString(PyExc_OverflowError, "new string is too long"); - return NULL; - } + if (i > PY_SSIZE_T_MAX - j) + goto overflow1; /* Second pass: create output string and fill it */ u = _PyUnicode_New(i + j); if (!u) return NULL; - j = 0; - q = u->str; + j = 0; /* same as in first pass */ + q = u->str; /* next output char */ + qe = u->str + u->length; /* end of output */ for (p = self->str; p < e; p++) if (*p == '\t') { if (tabsize > 0) { i = tabsize - (j % tabsize); j += i; - while (i--) + while (i--) { + if (q >= qe) + goto overflow2; *q++ = ' '; + } } } else { - j++; + if (q >= qe) + goto overflow2; *q++ = *p; + j++; if (*p == '\n' || *p == '\r') j = 0; } return (PyObject*) u; + + overflow2: + Py_DECREF(u); + overflow1: + PyErr_SetString(PyExc_OverflowError, "new string is too long"); + return NULL; } PyDoc_STRVAR(find__doc__, @@ -7271,7 +7397,7 @@ done = str->length; } while (done < nchars) { - int n = (done <= nchars-done) ? done : nchars-done; + Py_ssize_t n = (done <= nchars-done) ? done : nchars-done; Py_UNICODE_COPY(p+done, p, n); done += n; } @@ -7970,7 +8096,7 @@ static PyObject* unicode_freelistsize(PyUnicodeObject *self) { - return PyLong_FromLong(unicode_freelist_size); + return PyLong_FromLong(numfree); } #endif @@ -8206,8 +8332,8 @@ return PyUnicode_FromUnicode(self->str + start, slicelength); } else { source_buf = PyUnicode_AS_UNICODE((PyObject*)self); - result_buf = (Py_UNICODE *)PyMem_MALLOC(slicelength* - sizeof(Py_UNICODE)); + result_buf = (Py_UNICODE *)PyObject_MALLOC(slicelength* + sizeof(Py_UNICODE)); if (result_buf == NULL) return PyErr_NoMemory(); @@ -8217,7 +8343,7 @@ } result = PyUnicode_FromUnicode(result_buf, slicelength); - PyMem_FREE(result_buf); + PyObject_FREE(result_buf); return result; } } else { @@ -8272,6 +8398,7 @@ return Py_SAFE_DOWNCAST(result, Py_ssize_t, int); } +#if 0 static int longtounicode(Py_UNICODE *buffer, size_t len, const char *format, long x) { @@ -8281,6 +8408,7 @@ result = strtounicode(buffer, (char *)buffer); return Py_SAFE_DOWNCAST(result, Py_ssize_t, int); } +#endif /* XXX To save some code duplication, formatfloat/long/int could have been shared with stringobject.c, converting from 8-bit to Unicode after the @@ -8351,6 +8479,7 @@ return result; } +#if 0 static int formatint(Py_UNICODE *buf, size_t buflen, @@ -8426,6 +8555,7 @@ else return longtounicode(buf, buflen, fmt, x); } +#endif static int formatchar(Py_UNICODE *buf, @@ -8537,6 +8667,7 @@ int prec = -1; Py_UNICODE c = '\0'; Py_UNICODE fill; + int isnumok; PyObject *v = NULL; PyObject *temp = NULL; Py_UNICODE *pbuf; @@ -8741,21 +8872,38 @@ case 'X': if (c == 'i') c = 'd'; - if (PyLong_Check(v)) { - temp = formatlong(v, flags, prec, c); - if (!temp) - goto onError; - pbuf = PyUnicode_AS_UNICODE(temp); - len = PyUnicode_GET_SIZE(temp); - sign = 1; + isnumok = 0; + if (PyNumber_Check(v)) { + PyObject *iobj=NULL; + + if (PyLong_Check(v)) { + iobj = v; + Py_INCREF(iobj); + } + else { + iobj = PyNumber_Long(v); + } + if (iobj!=NULL) { + if (PyLong_Check(iobj)) { + isnumok = 1; + temp = formatlong(iobj, flags, prec, c); + Py_DECREF(iobj); + if (!temp) + goto onError; + pbuf = PyUnicode_AS_UNICODE(temp); + len = PyUnicode_GET_SIZE(temp); + sign = 1; + } + else { + Py_DECREF(iobj); + } + } } - else { - pbuf = formatbuf; - len = formatint(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE), - flags, prec, c, v); - if (len < 0) + if (!isnumok) { + PyErr_Format(PyExc_TypeError, + "%%%c format: a number is required, " + "not %.200s", (char)c, Py_TYPE(v)->tp_name); goto onError; - sign = 1; } if (flags & F_ZERO) fill = '0'; @@ -8941,7 +9089,7 @@ Py_DECREF(tmp); return NULL; } - pnew->str = PyMem_NEW(Py_UNICODE, n+1); + pnew->str = (Py_UNICODE*) PyObject_MALLOC(sizeof(Py_UNICODE) * (n+1)); if (pnew->str == NULL) { _Py_ForgetReference((PyObject *)pnew); PyObject_Del(pnew); @@ -9027,8 +9175,8 @@ }; /* Init the implementation */ - unicode_freelist = NULL; - unicode_freelist_size = 0; + free_list = NULL; + numfree = 0; unicode_empty = _PyUnicode_New(0); if (!unicode_empty) return; @@ -9048,10 +9196,29 @@ /* Finalize the Unicode implementation */ +int +PyUnicode_ClearFreeList(void) +{ + int freelist_size = numfree; + PyUnicodeObject *u; + + for (u = free_list; u != NULL;) { + PyUnicodeObject *v = u; + u = *(PyUnicodeObject **)u; + if (v->str) + PyObject_DEL(v->str); + Py_XDECREF(v->defenc); + PyObject_Del(v); + numfree--; + } + free_list = NULL; + assert(numfree == 0); + return freelist_size; +} + void _PyUnicode_Fini(void) { - PyUnicodeObject *u; int i; Py_XDECREF(unicode_empty); @@ -9063,17 +9230,7 @@ unicode_latin1[i] = NULL; } } - - for (u = unicode_freelist; u != NULL;) { - PyUnicodeObject *v = u; - u = *(PyUnicodeObject **)u; - if (v->str) - PyMem_DEL(v->str); - Py_XDECREF(v->defenc); - PyObject_Del(v); - } - unicode_freelist = NULL; - unicode_freelist_size = 0; + (void)PyUnicode_ClearFreeList(); } void Modified: python/branches/py3k-ctypes-pep3118/PC/VC6/pythoncore.dsp ============================================================================== --- python/branches/py3k-ctypes-pep3118/PC/VC6/pythoncore.dsp (original) +++ python/branches/py3k-ctypes-pep3118/PC/VC6/pythoncore.dsp Wed Apr 30 15:57:13 2008 @@ -125,6 +125,10 @@ # End Source File # Begin Source File +SOURCE=..\..\Modules\_collectionsmodule.c +# End Source File +# Begin Source File + SOURCE=..\..\Modules\_csv.c # End Source File # Begin Source File @@ -165,10 +169,6 @@ # End Source File # Begin Source File -SOURCE=..\..\Modules\_typesmodule.c -# End Source File -# Begin Source File - SOURCE=..\..\Modules\_weakref.c # End Source File # Begin Source File @@ -193,6 +193,10 @@ # End Source File # Begin Source File +SOURCE=..\..\Python\_warnings.c +# End Source File +# Begin Source File + SOURCE=..\..\Python\asdl.c # End Source File # Begin Source File @@ -349,6 +353,14 @@ # End Source File # Begin Source File +SOURCE=..\..\Python\formatter_string.c +# End Source File +# Begin Source File + +SOURCE=..\..\Python\formatter_unicode.c +# End Source File +# Begin Source File + SOURCE=..\..\Objects\frameobject.c # End Source File # Begin Source File @@ -575,6 +587,10 @@ # End Source File # Begin Source File +SOURCE=..\..\Python\pymath.c +# End Source File +# Begin Source File + SOURCE=..\..\Python\pystate.c # End Source File # Begin Source File Modified: python/branches/py3k-ctypes-pep3118/PC/VS7.1/pythoncore.vcproj ============================================================================== --- python/branches/py3k-ctypes-pep3118/PC/VS7.1/pythoncore.vcproj (original) +++ python/branches/py3k-ctypes-pep3118/PC/VS7.1/pythoncore.vcproj Wed Apr 30 15:57:13 2008 @@ -395,9 +395,6 @@ RelativePath="..\..\Pc\_subprocess.c"> - - + + + + + + - - @@ -1591,6 +1587,10 @@ Name="Python" > + + @@ -1707,6 +1707,10 @@ > + + Modified: python/branches/py3k-ctypes-pep3118/PC/WinMain.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/PC/WinMain.c (original) +++ python/branches/py3k-ctypes-pep3118/PC/WinMain.c Wed Apr 30 15:57:13 2008 @@ -12,5 +12,5 @@ int nCmdShow /* show state of window */ ) { - return Py_Main(__argc, __argv); + return Py_Main(__argc, __wargv); } Modified: python/branches/py3k-ctypes-pep3118/PC/_msi.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/PC/_msi.c (original) +++ python/branches/py3k-ctypes-pep3118/PC/_msi.c Wed Apr 30 15:57:13 2008 @@ -180,12 +180,12 @@ static PyObject* fcicreate(PyObject* obj, PyObject* args) { - char *cabname; + char *cabname, *p; PyObject *files; CCAB ccab; HFCI hfci; ERF erf; - int i; + Py_ssize_t i; if (!PyArg_ParseTuple(args, "sO:FCICreate", &cabname, &files)) @@ -208,22 +208,22 @@ ccab.setID = 0; ccab.szDisk[0] = '\0'; - for (i=0; cabname[i]; i++) - if (cabname[i] == '\\' || cabname[i] == '/') - break; + for (i = 0, p = cabname; *p; p = CharNext(p)) + if (*p == '\\' || *p == '/') + i = p - cabname + 1; - if (i > sizeof(ccab.szCabPath) || - strlen(cabname+i) > sizeof(ccab.szCab)) { + if (i >= sizeof(ccab.szCabPath) || + strlen(cabname+i) >= sizeof(ccab.szCab)) { PyErr_SetString(PyExc_ValueError, "path name too long"); return 0; } - if (cabname[i]) { + if (i > 0) { memcpy(ccab.szCabPath, cabname, i); ccab.szCabPath[i] = '\0'; strcpy(ccab.szCab, cabname+i); } else { - strcpy(ccab.szCabPath, "."); + strcpy(ccab.szCabPath, ".\\"); strcpy(ccab.szCab, cabname); } Modified: python/branches/py3k-ctypes-pep3118/PC/_winreg.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/PC/_winreg.c (original) +++ python/branches/py3k-ctypes-pep3118/PC/_winreg.c Wed Apr 30 15:57:13 2008 @@ -289,6 +289,22 @@ "2048 bytes) should be stored as files with the filenames stored in \n" "the configuration registry. This helps the registry perform efficiently."); +PyDoc_STRVAR(DisableReflectionKey_doc, +"Disables registry reflection for 32-bit processes running on a 64-bit\n" +"Operating System. Will generally raise NotImplemented if executed on\n" +"a 32-bit Operating System.\n" +"If the key is not on the reflection list, the function succeeds but has no effect.\n" +"Disabling reflection for a key does not affect reflection of any subkeys."); + +PyDoc_STRVAR(EnableReflectionKey_doc, +"Restores registry reflection for the specified disabled key.\n" +"Will generally raise NotImplemented if executed on a 32-bit Operating System.\n" +"Restoring reflection for a key does not affect reflection of any subkeys."); + +PyDoc_STRVAR(QueryReflectionKey_doc, +"bool = QueryReflectionKey(hkey) - Determines the reflection state for the specified key.\n" +"Will generally raise NotImplemented if executed on a 32-bit Operating System.\n"); + /* PyHKEY docstrings */ PyDoc_STRVAR(PyHKEY_doc, "PyHKEY Object - A Python object, representing a win32 registry key.\n" @@ -703,6 +719,7 @@ static BOOL Py2Reg(PyObject *value, DWORD typ, BYTE **retDataBuf, DWORD *retDataSize) { + Py_ssize_t i,j; switch (typ) { case REG_DWORD: if (value != Py_None && !PyLong_Check(value)) @@ -749,7 +766,6 @@ { DWORD size = 0; wchar_t *P; - int i,j; if (value == Py_None) i = 0; @@ -1393,12 +1409,122 @@ return Py_None; } +static PyObject * +PyDisableReflectionKey(PyObject *self, PyObject *args) +{ + HKEY hKey; + PyObject *obKey; + HMODULE hMod; + typedef LONG (WINAPI *RDRKFunc)(HKEY); + RDRKFunc pfn = NULL; + LONG rc; + + if (!PyArg_ParseTuple(args, "O:DisableReflectionKey", &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + // Only available on 64bit platforms, so we must load it + // dynamically. + hMod = GetModuleHandle("advapi32.dll"); + if (hMod) + pfn = (RDRKFunc)GetProcAddress(hMod, + "RegDisableReflectionKey"); + if (!pfn) { + PyErr_SetString(PyExc_NotImplementedError, + "not implemented on this platform"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = (*pfn)(hKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegDisableReflectionKey"); + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject * +PyEnableReflectionKey(PyObject *self, PyObject *args) +{ + HKEY hKey; + PyObject *obKey; + HMODULE hMod; + typedef LONG (WINAPI *RERKFunc)(HKEY); + RERKFunc pfn = NULL; + LONG rc; + + if (!PyArg_ParseTuple(args, "O:EnableReflectionKey", &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + // Only available on 64bit platforms, so we must load it + // dynamically. + hMod = GetModuleHandle("advapi32.dll"); + if (hMod) + pfn = (RERKFunc)GetProcAddress(hMod, + "RegEnableReflectionKey"); + if (!pfn) { + PyErr_SetString(PyExc_NotImplementedError, + "not implemented on this platform"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = (*pfn)(hKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegEnableReflectionKey"); + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject * +PyQueryReflectionKey(PyObject *self, PyObject *args) +{ + HKEY hKey; + PyObject *obKey; + HMODULE hMod; + typedef LONG (WINAPI *RQRKFunc)(HKEY, BOOL *); + RQRKFunc pfn = NULL; + BOOL result; + LONG rc; + + if (!PyArg_ParseTuple(args, "O:QueryReflectionKey", &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + // Only available on 64bit platforms, so we must load it + // dynamically. + hMod = GetModuleHandle("advapi32.dll"); + if (hMod) + pfn = (RQRKFunc)GetProcAddress(hMod, + "RegQueryReflectionKey"); + if (!pfn) { + PyErr_SetString(PyExc_NotImplementedError, + "not implemented on this platform"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = (*pfn)(hKey, &result); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryReflectionKey"); + return PyBool_FromLong(rc); +} + static struct PyMethodDef winreg_methods[] = { {"CloseKey", PyCloseKey, METH_VARARGS, CloseKey_doc}, {"ConnectRegistry", PyConnectRegistry, METH_VARARGS, ConnectRegistry_doc}, {"CreateKey", PyCreateKey, METH_VARARGS, CreateKey_doc}, {"DeleteKey", PyDeleteKey, METH_VARARGS, DeleteKey_doc}, {"DeleteValue", PyDeleteValue, METH_VARARGS, DeleteValue_doc}, + {"DisableReflectionKey", PyDisableReflectionKey, METH_VARARGS, DisableReflectionKey_doc}, + {"EnableReflectionKey", PyEnableReflectionKey, METH_VARARGS, EnableReflectionKey_doc}, {"EnumKey", PyEnumKey, METH_VARARGS, EnumKey_doc}, {"EnumValue", PyEnumValue, METH_VARARGS, EnumValue_doc}, {"ExpandEnvironmentStrings", PyExpandEnvironmentStrings, METH_VARARGS, @@ -1410,6 +1536,7 @@ {"QueryValue", PyQueryValue, METH_VARARGS, QueryValue_doc}, {"QueryValueEx", PyQueryValueEx, METH_VARARGS, QueryValueEx_doc}, {"QueryInfoKey", PyQueryInfoKey, METH_VARARGS, QueryInfoKey_doc}, + {"QueryReflectionKey",PyQueryReflectionKey,METH_VARARGS, QueryReflectionKey_doc}, {"SaveKey", PySaveKey, METH_VARARGS, SaveKey_doc}, {"SetValue", PySetValue, METH_VARARGS, SetValue_doc}, {"SetValueEx", PySetValueEx, METH_VARARGS, SetValueEx_doc}, @@ -1478,6 +1605,12 @@ ADD_INT(KEY_WRITE); ADD_INT(KEY_EXECUTE); ADD_INT(KEY_ALL_ACCESS); +#ifdef KEY_WOW64_64KEY + ADD_INT(KEY_WOW64_64KEY); +#endif +#ifdef KEY_WOW64_32KEY + ADD_INT(KEY_WOW64_32KEY); +#endif ADD_INT(REG_OPTION_RESERVED); ADD_INT(REG_OPTION_NON_VOLATILE); ADD_INT(REG_OPTION_VOLATILE); Modified: python/branches/py3k-ctypes-pep3118/PC/config.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/PC/config.c (original) +++ python/branches/py3k-ctypes-pep3118/PC/config.c Wed Apr 30 15:57:13 2008 @@ -58,9 +58,9 @@ extern void init_subprocess(void); extern void init_lsprof(void); extern void init_ast(void); -extern void init_types(void); extern void init_fileio(void); extern void initatexit(void); +extern void _PyWarnings_Init(void); /* tools/freeze/makeconfig.py marker for additional "extern" */ /* -- ADDMODULE MARKER 1 -- */ @@ -145,8 +145,8 @@ {"__main__", NULL}, {"builtins", NULL}, {"sys", NULL}, - - {"_types", init_types}, + {"_warnings", _PyWarnings_Init}, + {"_fileio", init_fileio}, {"atexit", initatexit}, Modified: python/branches/py3k-ctypes-pep3118/PC/example_nt/readme.txt ============================================================================== --- python/branches/py3k-ctypes-pep3118/PC/example_nt/readme.txt (original) +++ python/branches/py3k-ctypes-pep3118/PC/example_nt/readme.txt Wed Apr 30 15:57:13 2008 @@ -2,12 +2,34 @@ ======================================= This directory contains everything needed (except for the Python -distribution!) to build a Python extension module using Microsoft VC++ -("Developer Studio") version 7.1. It has been tested with VC++ 7.1 on -Python 2.4. You can also use earlier versions of VC to build Python -extensions, but the sample VC project file (example.dsw in this directory) -is in VC 7.1 format. Notice that you need to use the same compiler version -that was used to build Python itself. +distribution!) to build a Python extension module using Microsoft VC++. +Notice that you need to use the same compiler version that was used to build +Python itself. + +The simplest way to build this example is to use the distutils script +'setup.py'. To do this, simply execute: + + % python setup.py install + +after everything builds and installs, you can test it: + + % python -c "import example; example.foo()" + Hello, world + +See setup.py for more details. alternatively, see below for instructions on +how to build inside the Visual Studio environment. + +Visual Studio Build Instructions +================================ + +These are instructions how to build an extension using Visual C++. The +instructions and project files have not been updated to the latest VC +version. In general, it is recommended you use the 'setup.py' instructions +above. + +It has been tested with VC++ 7.1 on Python 2.4. You can also use earlier +versions of VC to build Python extensions, but the sample VC project file +(example.dsw in this directory) is in VC 7.1 format. COPY THIS DIRECTORY! -------------------- Modified: python/branches/py3k-ctypes-pep3118/PC/getpathp.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/PC/getpathp.c (original) +++ python/branches/py3k-ctypes-pep3118/PC/getpathp.c Wed Apr 30 15:57:13 2008 @@ -56,10 +56,10 @@ #include "Python.h" #include "osdefs.h" +#include #ifdef MS_WINDOWS #include -#include #endif #ifdef HAVE_SYS_TYPES_H @@ -82,17 +82,17 @@ */ #ifndef LANDMARK -#define LANDMARK "lib\\os.py" +#define LANDMARK L"lib\\os.py" #endif -static char prefix[MAXPATHLEN+1]; -static char progpath[MAXPATHLEN+1]; -static char dllpath[MAXPATHLEN+1]; -static char *module_search_path = NULL; +static wchar_t prefix[MAXPATHLEN+1]; +static wchar_t progpath[MAXPATHLEN+1]; +static wchar_t dllpath[MAXPATHLEN+1]; +static wchar_t *module_search_path = NULL; static int -is_sep(char ch) /* determine if "ch" is a separator character */ +is_sep(wchar_t ch) /* determine if "ch" is a separator character */ { #ifdef ALTSEP return ch == SEP || ch == ALTSEP; @@ -105,9 +105,9 @@ beyond existing terminator. */ static void -reduce(char *dir) +reduce(wchar_t *dir) { - size_t i = strlen(dir); + size_t i = wcslen(dir); while (i > 0 && !is_sep(dir[i])) --i; dir[i] = '\0'; @@ -115,24 +115,24 @@ static int -exists(char *filename) +exists(wchar_t *filename) { - struct stat buf; - return stat(filename, &buf) == 0; + struct _stat64 buf; + return _wstat64(filename, &buf) == 0; } /* Assumes 'filename' MAXPATHLEN+1 bytes long - may extend 'filename' by one character. */ static int -ismodule(char *filename) /* Is module -- check for .pyc/.pyo too */ +ismodule(wchar_t *filename) /* Is module -- check for .pyc/.pyo too */ { if (exists(filename)) return 1; /* Check for the compiled version of prefix. */ - if (strlen(filename) < MAXPATHLEN) { - strcat(filename, Py_OptimizeFlag ? "o" : "c"); + if (wcslen(filename) < MAXPATHLEN) { + wcscat(filename, Py_OptimizeFlag ? L"o" : L"c"); if (exists(filename)) return 1; } @@ -149,22 +149,22 @@ stuff as fits will be appended. */ static void -join(char *buffer, char *stuff) +join(wchar_t *buffer, wchar_t *stuff) { size_t n, k; if (is_sep(stuff[0])) n = 0; else { - n = strlen(buffer); + n = wcslen(buffer); if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) buffer[n++] = SEP; } if (n > MAXPATHLEN) Py_FatalError("buffer overflow in getpathp.c's joinpath()"); - k = strlen(stuff); + k = wcslen(stuff); if (n + k > MAXPATHLEN) k = MAXPATHLEN - n; - strncpy(buffer+n, stuff, k); + wcsncpy(buffer+n, stuff, k); buffer[n+k] = '\0'; } @@ -173,12 +173,12 @@ 'landmark' can not overflow prefix if too long. */ static int -gotlandmark(char *landmark) +gotlandmark(wchar_t *landmark) { int ok; Py_ssize_t n; - n = strlen(prefix); + n = wcslen(prefix); join(prefix, landmark); ok = ismodule(prefix); prefix[n] = '\0'; @@ -188,10 +188,10 @@ /* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd. assumption provided by only caller, calculate_path() */ static int -search_for_prefix(char *argv0_path, char *landmark) +search_for_prefix(wchar_t *argv0_path, wchar_t *landmark) { /* Search from argv0_path, until landmark is found */ - strcpy(prefix, argv0_path); + wcscpy(prefix, argv0_path); do { if (gotlandmark(landmark)) return 1; @@ -219,39 +219,39 @@ in advance. It could be simplied now Win16/Win32s is dead! */ -static char * +static wchar_t * getpythonregpath(HKEY keyBase, int skipcore) { HKEY newKey = 0; DWORD dataSize = 0; DWORD numKeys = 0; LONG rc; - char *retval = NULL; - TCHAR *dataBuf = NULL; - static const TCHAR keyPrefix[] = _T("Software\\Python\\PythonCore\\"); - static const TCHAR keySuffix[] = _T("\\PythonPath"); + wchar_t *retval = NULL; + WCHAR *dataBuf = NULL; + static const WCHAR keyPrefix[] = L"Software\\Python\\PythonCore\\"; + static const WCHAR keySuffix[] = L"\\PythonPath"; size_t versionLen; DWORD index; - TCHAR *keyBuf = NULL; - TCHAR *keyBufPtr; - TCHAR **ppPaths = NULL; - + WCHAR *keyBuf = NULL; + WCHAR *keyBufPtr; + WCHAR **ppPaths = NULL; + /* Tried to use sysget("winver") but here is too early :-( */ - versionLen = _tcslen(PyWin_DLLVersionString); + versionLen = strlen(PyWin_DLLVersionString); /* Space for all the chars, plus one \0 */ keyBuf = keyBufPtr = malloc(sizeof(keyPrefix) + - sizeof(TCHAR)*(versionLen-1) + + sizeof(WCHAR)*(versionLen-1) + sizeof(keySuffix)); if (keyBuf==NULL) goto done; - memcpy(keyBufPtr, keyPrefix, sizeof(keyPrefix)-sizeof(TCHAR)); - keyBufPtr += sizeof(keyPrefix)/sizeof(TCHAR) - 1; - memcpy(keyBufPtr, PyWin_DLLVersionString, versionLen * sizeof(TCHAR)); + memcpy(keyBufPtr, keyPrefix, sizeof(keyPrefix)-sizeof(WCHAR)); + keyBufPtr += sizeof(keyPrefix)/sizeof(WCHAR) - 1; + mbstowcs(keyBufPtr, PyWin_DLLVersionString, versionLen); keyBufPtr += versionLen; /* NULL comes with this one! */ memcpy(keyBufPtr, keySuffix, sizeof(keySuffix)); /* Open the root Python key */ - rc=RegOpenKeyEx(keyBase, + rc=RegOpenKeyExW(keyBase, keyBuf, /* subkey */ 0, /* reserved */ KEY_READ, @@ -265,31 +265,31 @@ /* Allocate a temp array of char buffers, so we only need to loop reading the registry once */ - ppPaths = malloc( sizeof(TCHAR *) * numKeys ); + ppPaths = malloc( sizeof(WCHAR *) * numKeys ); if (ppPaths==NULL) goto done; - memset(ppPaths, 0, sizeof(TCHAR *) * numKeys); + memset(ppPaths, 0, sizeof(WCHAR *) * numKeys); /* Loop over all subkeys, allocating a temp sub-buffer. */ for(index=0;index 0) { - *(szCur++) = _T(';'); + *(szCur++) = L';'; dataSize--; } if (ppPaths[index]) { - Py_ssize_t len = _tcslen(ppPaths[index]); - _tcsncpy(szCur, ppPaths[index], len); + Py_ssize_t len = wcslen(ppPaths[index]); + wcsncpy(szCur, ppPaths[index], len); szCur += len; assert(dataSize > (DWORD)len); dataSize -= (DWORD)len; @@ -325,30 +325,17 @@ else { /* If we have no values, we dont need a ';' */ if (numKeys) { - *(szCur++) = _T(';'); + *(szCur++) = L';'; dataSize--; } /* Now append the core path entries - this will include the NULL */ - rc = RegQueryValueEx(newKey, NULL, 0, NULL, - (LPBYTE)szCur, &dataSize); + rc = RegQueryValueExW(newKey, NULL, 0, NULL, + (LPBYTE)szCur, &dataSize); } - /* And set the result - caller must free - If MBCS, it is fine as is. If Unicode, allocate new - buffer and convert. - */ -#ifdef UNICODE - retval = (char *)malloc(reqdSize+1); - if (retval) - WideCharToMultiByte(CP_ACP, 0, - dataBuf, -1, /* source */ - retval, reqdSize+1, /* dest */ - NULL, NULL); - free(dataBuf); -#else + /* And set the result - caller must free */ retval = dataBuf; -#endif } done: /* Loop freeing my temp buffers */ @@ -368,45 +355,21 @@ static void get_progpath(void) { - extern char *Py_GetProgramName(void); - char *path = getenv("PATH"); - char *prog = Py_GetProgramName(); + extern wchar_t *Py_GetProgramName(void); + wchar_t *path = _wgetenv(L"PATH"); + wchar_t *prog = Py_GetProgramName(); #ifdef MS_WINDOWS extern HANDLE PyWin_DLLhModule; -#ifdef UNICODE - WCHAR wprogpath[MAXPATHLEN+1]; - /* Windows documents that GetModuleFileName() will "truncate", - but makes no mention of the null terminator. Play it safe. - PLUS Windows itself defines MAX_PATH as the same, but anyway... - */ - wprogpath[MAXPATHLEN]=_T('\0'); - if (PyWin_DLLhModule && - GetModuleFileName(PyWin_DLLhModule, wprogpath, MAXPATHLEN)) { - WideCharToMultiByte(CP_ACP, 0, - wprogpath, -1, - dllpath, MAXPATHLEN+1, - NULL, NULL); - } - wprogpath[MAXPATHLEN]=_T('\0'); - if (GetModuleFileName(NULL, wprogpath, MAXPATHLEN)) { - WideCharToMultiByte(CP_ACP, 0, - wprogpath, -1, - progpath, MAXPATHLEN+1, - NULL, NULL); - return; - } -#else /* static init of progpath ensures final char remains \0 */ if (PyWin_DLLhModule) - if (!GetModuleFileName(PyWin_DLLhModule, dllpath, MAXPATHLEN)) + if (!GetModuleFileNameW(PyWin_DLLhModule, dllpath, MAXPATHLEN)) dllpath[0] = 0; - if (GetModuleFileName(NULL, progpath, MAXPATHLEN)) + if (GetModuleFileNameW(NULL, progpath, MAXPATHLEN)) return; #endif -#endif if (prog == NULL || *prog == '\0') - prog = "python"; + prog = L"python"; /* If there is no slash in the argv0 path, then we have to * assume python is on the user's $PATH, since there's no @@ -414,24 +377,24 @@ * $PATH isn't exported, you lose. */ #ifdef ALTSEP - if (strchr(prog, SEP) || strchr(prog, ALTSEP)) + if (wcschr(prog, SEP) || wcschr(prog, ALTSEP)) #else - if (strchr(prog, SEP)) + if (wcschr(prog, SEP)) #endif - strncpy(progpath, prog, MAXPATHLEN); + wcsncpy(progpath, prog, MAXPATHLEN); else if (path) { while (1) { - char *delim = strchr(path, DELIM); + wchar_t *delim = wcschr(path, DELIM); if (delim) { size_t len = delim - path; /* ensure we can't overwrite buffer */ len = min(MAXPATHLEN,len); - strncpy(progpath, path, len); + wcsncpy(progpath, path, len); *(progpath + len) = '\0'; } else - strncpy(progpath, path, MAXPATHLEN); + wcsncpy(progpath, path, MAXPATHLEN); /* join() is safe for MAXPATHLEN+1 size buffer */ join(progpath, prog); @@ -452,23 +415,31 @@ static void calculate_path(void) { - char argv0_path[MAXPATHLEN+1]; - char *buf; + wchar_t argv0_path[MAXPATHLEN+1]; + wchar_t *buf; size_t bufsz; - char *pythonhome = Py_GetPythonHome(); - char *envpath = Py_GETENV("PYTHONPATH"); + wchar_t *pythonhome = Py_GetPythonHome(); + char *_envpath = Py_GETENV("PYTHONPATH"); + wchar_t wenvpath[MAXPATHLEN+1]; + wchar_t *envpath = NULL; #ifdef MS_WINDOWS int skiphome, skipdefault; - char *machinepath = NULL; - char *userpath = NULL; - char zip_path[MAXPATHLEN+1]; + wchar_t *machinepath = NULL; + wchar_t *userpath = NULL; + wchar_t zip_path[MAXPATHLEN+1]; size_t len; #endif + if (_envpath) { + size_t r = mbstowcs(wenvpath, _envpath, MAXPATHLEN+1); + envpath = wenvpath; + if (r == (size_t)-1 || r >= MAXPATHLEN) + envpath = NULL; + } get_progpath(); /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */ - strcpy(argv0_path, progpath); + wcscpy(argv0_path, progpath); reduce(argv0_path); if (pythonhome == NULL || *pythonhome == '\0') { if (search_for_prefix(argv0_path, LANDMARK)) @@ -477,7 +448,7 @@ pythonhome = NULL; } else - strncpy(prefix, pythonhome, MAXPATHLEN); + wcsncpy(prefix, pythonhome, MAXPATHLEN); if (envpath && *envpath == '\0') envpath = NULL; @@ -486,11 +457,11 @@ #ifdef MS_WINDOWS /* Calculate zip archive path */ if (dllpath[0]) /* use name of python DLL */ - strncpy(zip_path, dllpath, MAXPATHLEN); + wcsncpy(zip_path, dllpath, MAXPATHLEN); else /* use name of executable program */ - strncpy(zip_path, progpath, MAXPATHLEN); + wcsncpy(zip_path, progpath, MAXPATHLEN); zip_path[MAXPATHLEN] = '\0'; - len = strlen(zip_path); + len = wcslen(zip_path); if (len > 4) { zip_path[len-3] = 'z'; /* change ending to "zip" */ zip_path[len-2] = 'i'; @@ -524,29 +495,29 @@ /* Calculate size of return buffer */ if (pythonhome != NULL) { - char *p; + wchar_t *p; bufsz = 1; for (p = PYTHONPATH; *p; p++) { if (*p == DELIM) bufsz++; /* number of DELIM plus one */ } - bufsz *= strlen(pythonhome); + bufsz *= wcslen(pythonhome); } else bufsz = 0; - bufsz += strlen(PYTHONPATH) + 1; - bufsz += strlen(argv0_path) + 1; + bufsz += wcslen(PYTHONPATH) + 1; + bufsz += wcslen(argv0_path) + 1; #ifdef MS_WINDOWS if (userpath) - bufsz += strlen(userpath) + 1; + bufsz += wcslen(userpath) + 1; if (machinepath) - bufsz += strlen(machinepath) + 1; - bufsz += strlen(zip_path) + 1; + bufsz += wcslen(machinepath) + 1; + bufsz += wcslen(zip_path) + 1; #endif if (envpath != NULL) - bufsz += strlen(envpath) + 1; + bufsz += wcslen(envpath) + 1; - module_search_path = buf = malloc(bufsz); + module_search_path = buf = malloc(bufsz*sizeof(wchar_t)); if (buf == NULL) { /* We can't exit, so print a warning and limp along */ fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); @@ -568,57 +539,57 @@ } if (envpath) { - strcpy(buf, envpath); - buf = strchr(buf, '\0'); + wcscpy(buf, envpath); + buf = wcschr(buf, L'\0'); *buf++ = DELIM; } #ifdef MS_WINDOWS if (zip_path[0]) { - strcpy(buf, zip_path); - buf = strchr(buf, '\0'); + wcscpy(buf, zip_path); + buf = wcschr(buf, L'\0'); *buf++ = DELIM; } if (userpath) { - strcpy(buf, userpath); - buf = strchr(buf, '\0'); + wcscpy(buf, userpath); + buf = wcschr(buf, L'\0'); *buf++ = DELIM; free(userpath); } if (machinepath) { - strcpy(buf, machinepath); - buf = strchr(buf, '\0'); + wcscpy(buf, machinepath); + buf = wcschr(buf, L'\0'); *buf++ = DELIM; free(machinepath); } if (pythonhome == NULL) { if (!skipdefault) { - strcpy(buf, PYTHONPATH); - buf = strchr(buf, '\0'); + wcscpy(buf, PYTHONPATH); + buf = wcschr(buf, L'\0'); } } #else if (pythonhome == NULL) { - strcpy(buf, PYTHONPATH); - buf = strchr(buf, '\0'); + wcscpy(buf, PYTHONPATH); + buf = wcschr(buf, L'\0'); } #endif /* MS_WINDOWS */ else { - char *p = PYTHONPATH; - char *q; + wchar_t *p = PYTHONPATH; + wchar_t *q; size_t n; for (;;) { - q = strchr(p, DELIM); + q = wcschr(p, DELIM); if (q == NULL) - n = strlen(p); + n = wcslen(p); else n = q-p; if (p[0] == '.' && is_sep(p[1])) { - strcpy(buf, pythonhome); - buf = strchr(buf, '\0'); + wcscpy(buf, pythonhome); + buf = wcschr(buf, L'\0'); p++; n--; } - strncpy(buf, p, n); + wcsncpy(buf, p, n); buf += n; if (q == NULL) break; @@ -628,10 +599,10 @@ } if (argv0_path) { *buf++ = DELIM; - strcpy(buf, argv0_path); - buf = strchr(buf, '\0'); + wcscpy(buf, argv0_path); + buf = wcschr(buf, L'\0'); } - *buf = '\0'; + *buf = L'\0'; /* Now to pull one last hack/trick. If sys.prefix is empty, then try and find it somewhere on the paths we calculated. We scan backwards, as our general policy @@ -640,12 +611,12 @@ on the path, and that our 'prefix' directory is the parent of that. */ - if (*prefix=='\0') { - char lookBuf[MAXPATHLEN+1]; - char *look = buf - 1; /* 'buf' is at the end of the buffer */ + if (*prefix==L'\0') { + wchar_t lookBuf[MAXPATHLEN+1]; + wchar_t *look = buf - 1; /* 'buf' is at the end of the buffer */ while (1) { Py_ssize_t nchars; - char *lookEnd = look; + wchar_t *lookEnd = look; /* 'look' will end up one character before the start of the path in question - even if this is one character before the start of the buffer @@ -653,8 +624,8 @@ while (look >= module_search_path && *look != DELIM) look--; nchars = lookEnd-look; - strncpy(lookBuf, look+1, nchars); - lookBuf[nchars] = '\0'; + wcsncpy(lookBuf, look+1, nchars); + lookBuf[nchars] = L'\0'; /* Up one level to the parent */ reduce(lookBuf); if (search_for_prefix(lookBuf, LANDMARK)) { @@ -671,7 +642,7 @@ /* External interface */ -char * +wchar_t * Py_GetPath(void) { if (!module_search_path) @@ -679,7 +650,7 @@ return module_search_path; } -char * +wchar_t * Py_GetPrefix(void) { if (!module_search_path) @@ -687,13 +658,13 @@ return prefix; } -char * +wchar_t * Py_GetExecPrefix(void) { return Py_GetPrefix(); } -char * +wchar_t * Py_GetProgramFullPath(void) { if (!module_search_path) Modified: python/branches/py3k-ctypes-pep3118/PC/os2emx/Makefile ============================================================================== --- python/branches/py3k-ctypes-pep3118/PC/os2emx/Makefile (original) +++ python/branches/py3k-ctypes-pep3118/PC/os2emx/Makefile Wed Apr 30 15:57:13 2008 @@ -1,16 +1,16 @@ #####################==================---------------- # -# Top-Level Makefile for Building Python 2.4 for OS/2 using GCC/EMX +# Top-Level Makefile for Building Python 2.6 for OS/2 using GCC/EMX # Originally written by Andrew Zabolotny, for Python 1.5.2 -# Modified by Andrew MacIntyre, for Python 2.5 +# Modified by Andrew MacIntyre, for Python 2.6 # # This makefile was developed for use with [P]GCC/EMX compiler any # version and GNU Make. # -# The output of the build is a largish Python25.DLL containing the +# The output of the build is a largish Python26.DLL containing the # essential modules of Python and a small Python.exe program to start # the interpreter. When embedding Python within another program, only -# Python25.DLL is needed. We also build python_s.a static library (which +# Python26.DLL is needed. We also build python_s.a static library (which # can be converted into OMF (.lib) format using emxomf tool) and both # python.a and python.lib import libraries. Then the optional # extension modules, which are OS/2 DLLs renamed with a PYD file extension. @@ -64,7 +64,7 @@ # === install locations === # default value of PYTHONHOME -LIB_DIR=C:/Python25 +LIB_DIR=C:/Python26 # default is to have everything in or under PYTHONHOME EXE_DIR=$(LIB_DIR) DLL_DIR=$(EXE_DIR) @@ -236,8 +236,8 @@ @echo STACKSIZE 2097152 >>$@ # Output file names -PYTHON_VER= 2.5 -PYTHON_LIB= python25 +PYTHON_VER= 2.6 +PYTHON_LIB= python26 PYTHON.LIB= $(PYTHON_LIB)_s$A PYTHON.IMPLIB= $(PYTHON_LIB)$A ifeq ($(EXEOMF),yes) @@ -290,7 +290,6 @@ Modules/cStringIO.c \ Modules/_csv.c \ Modules/datetimemodule.c \ - Modules/dlmodule.c \ Modules/errnomodule.c \ Modules/fcntlmodule.c \ Modules/_functoolsmodule.c \ Modified: python/branches/py3k-ctypes-pep3118/PC/os2emx/README.os2emx ============================================================================== --- python/branches/py3k-ctypes-pep3118/PC/os2emx/README.os2emx (original) +++ python/branches/py3k-ctypes-pep3118/PC/os2emx/README.os2emx Wed Apr 30 15:57:13 2008 @@ -1,4 +1,4 @@ -This is a port of Python 2.5 to OS/2 using the EMX development tools +This is a port of Python 2.6 to OS/2 using the EMX development tools ========================================================================= What's new since the previous release @@ -10,11 +10,11 @@ Licenses and info about Python and EMX -------------------------------------- -Please read the file README.Python-2.5 included in this package for -information about Python 2.5. This file is the README file from the -Python 2.5 source distribution available via http://www.python.org/ -and its mirrors. The file LICENCE.Python-2.5 is the text of the Licence -from the Python 2.5 source distribution. +Please read the file README.Python-2.6 included in this package for +information about Python 2.6. This file is the README file from the +Python 2.6 source distribution available via http://www.python.org/ +and its mirrors. The file LICENCE.Python-2.6 is the text of the Licence +from the Python 2.6 source distribution. Note that the EMX package that this package depends on is released under the GNU General Public Licence. Please refer to the documentation @@ -46,7 +46,7 @@ The best known would be that by Jeff Rush, most recently of version 1.5.2. Jeff used IBM's Visual Age C++ (v3) for his ports, and his -patches have been included in the Python 2.5 source distribution. +patches have been included in the Python 2.6 source distribution. Andy Zabolotny implemented a port of Python v1.5.2 using the EMX development tools. His patches against the Python v1.5.2 source @@ -92,7 +92,7 @@ to compile & link the executable. This is so that fork() works (see "YOU HAVE BEEN WARNED" item 1). -Python25.dll is created as a normal OMF DLL, with an OMF import +Python26.dll is created as a normal OMF DLL, with an OMF import library and module definition file. There is also an a.out (.a) import library to support linking the DLL to a.out executables. The DLL requires the EMX runtime DLLs. @@ -148,7 +148,7 @@ Upstream source patches: -No updates to the Python 2.5 release have become available. +No updates to the Python 2.6 release have become available. Eberhard Mattes' EMXFIX04 update to his EMX 0.9d tools suite includes bug fixes for the BSD DB library. The bsddb module included in this @@ -157,7 +157,7 @@ Library and other distributed Python code: The Python standard library lives in the Lib directory. All the standard -library code included with the Python 2.5 source distribution is included +library code included with the Python 2.6 source distribution is included in the binary archive, with the exception of the dos-8x3 and tkinter subdirectories which have been omitted to reduce the size of the binary archive - the dos-8x3 components are unnecessary duplicates and Tkinter @@ -172,7 +172,7 @@ also been omitted. All subdirectories omitted from the binary archive can be reconstituted -from the Python 2.5 source distribution, if desired. +from the Python 2.6 source distribution, if desired. Support for building Python extensions: @@ -190,15 +190,15 @@ --------- This port is packaged as follows: -- python-2.5-os2emx-bin-03????.zip (binaries, library modules) -- python-2.5-os2emx-src-03???? (patches+makefiles for non-Python code) +- python-2.6-os2emx-bin-03????.zip (binaries, library modules) +- python-2.6-os2emx-src-03???? (patches+makefiles for non-Python code) As all the Python specific patches for the port are now part of the Python release tarball, only the patches and makefiles involved in building external libraries for optional extensions are included in the source archive. -Documentation for the Python language, as well as the Python 2.5 +Documentation for the Python language, as well as the Python 2.6 source distibution, can be obtained from the Python website (http://www.python.org/) or the Python project pages at Sourceforge (http://sf.net/projects/python/). @@ -213,7 +213,7 @@ Unpack this archive, preserving the subdirectories, in the root directory of the drive where you want Python to live. -Add the Python directory (eg C:\Python25) to the PATH and LIBPATH +Add the Python directory (eg C:\Python26) to the PATH and LIBPATH variables in CONFIG.SYS. You should then set the PYTHONHOME and PYTHONPATH environment variables @@ -223,9 +223,9 @@ should be set to the semicolon separated list of principal Python library directories. I use: - SET PYTHONHOME=F:/Python25 - SET PYTHONPATH=F:/Python25/Lib;F:/Python25/Lib/plat-os2emx; - F:/Python25/Lib/lib-dynload;F:/Python25/Lib/site-packages + SET PYTHONHOME=F:/Python26 + SET PYTHONPATH=F:/Python26/Lib;F:/Python26/Lib/plat-os2emx; + F:/Python26/Lib/lib-dynload;F:/Python26/Lib/site-packages NOTE!: the PYTHONPATH setting above is linewrapped for this document - it should all be on one line in CONFIG.SYS! @@ -238,7 +238,7 @@ distribution. This can be used by setting the TERMINFO environment variable to the path of the Terminfo subdirectory below the Python home directory. On my system this looks like: - SET TERMINFO=F:/Python25/Terminfo + SET TERMINFO=F:/Python26/Terminfo For the TERM environment variable, I would try one of the following: SET TERM=ansi @@ -252,8 +252,8 @@ you can change into the Python home directory and run the COMPILEALL.CMD batch file. -You can execute the regression tests included with the Python 2.5 source -distribution by changing to the Python 2.5 home directory and executing the +You can execute the regression tests included with the Python 2.6 source +distribution by changing to the Python 2.6 home directory and executing the REGRTEST.CMD batch file. The following tests are known to fail at this time: - test_mhlib (I don't know of any port of MH to OS/2); @@ -299,7 +299,7 @@ 1. decide if you need to change the location of the Python installation. If you wish to do this, set the value of the Makefile variable LIB_DIR to the directory you wish to use for PYTHONHOME - (eg /usr/local/lib/python2.5). + (eg /usr/local/lib/python2.6). If you want Python to find its library without the PYTHONHOME environment variable set, set the value of the Makefile variable @@ -309,7 +309,7 @@ to be installed in a directory other than the PYTHONHOME directory, set the value of the Makefile variable EXE_DIR to the appropriate directory. -3. If you wish the Python core DLL (python25.dll) to be installed in a +3. If you wish the Python core DLL (python26.dll) to be installed in a directory other than the directory in which the Python executables are installed (by default, the PYTHONHOME directory), set the value of the Makefile variable DLL_DIR to the appropriate directory. This DLL must @@ -698,4 +698,4 @@ E-mail: andymac at bullseye.apana.org.au, or andymac at pcug.org.au Web: http://www.andymac.org/ -23 July, 2006. +28 January, 2008. Deleted: python/branches/py3k-ctypes-pep3118/PC/os2emx/python25.def ============================================================================== --- python/branches/py3k-ctypes-pep3118/PC/os2emx/python25.def Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,1263 +0,0 @@ -LIBRARY python25 INITINSTANCE TERMINSTANCE -DESCRIPTION "Python 2.5 Core DLL" -PROTMODE -DATA MULTIPLE NONSHARED -EXPORTS - -; From python25_s.lib(config) - "_PyImport_Inittab" - -; From python25_s.lib(dlfcn) -; "dlopen" -; "dlsym" -; "dlclose" -; "dlerror" - -; From python25_s.lib(getpathp) - "Py_GetProgramFullPath" - "Py_GetPrefix" - "Py_GetExecPrefix" - "Py_GetPath" - -; From python25_s.lib(getbuildinfo) - "Py_GetBuildInfo" - "_Py_svnversion" - -; From python25_s.lib(main) - "Py_Main" - "Py_GetArgcArgv" - -; From python25_s.lib(acceler) - "PyGrammar_AddAccelerators" - "PyGrammar_RemoveAccelerators" - -; From python25_s.lib(grammar1) - "PyGrammar_FindDFA" - "PyGrammar_LabelRepr" - -; From python25_s.lib(listnode) - "PyNode_ListTree" - -; From python25_s.lib(node) - "PyNode_New" - "PyNode_AddChild" - "PyNode_Free" - -; From python25_s.lib(parser) - "PyParser_AddToken" - "PyParser_New" - "PyParser_Delete" - -; From python25_s.lib(parsetok) - "Py_TabcheckFlag" - "PyParser_ParseString" - "PyParser_ParseStringFlagsFilename" - "PyParser_ParseFile" - "PyParser_ParseFileFlags" - "PyParser_ParseStringFlags" - -; From python25_s.lib(bitset) - "_Py_newbitset" - "_Py_delbitset" - "_Py_addbit" - "_Py_samebitset" - "_Py_mergebitset" - -; From python25_s.lib(metagrammar) - "_Py_meta_grammar" - "Py_meta_grammar" - -; From python25_s.lib(tokenizer) - "PyToken_OneChar" - "PyToken_TwoChars" - "PyToken_ThreeChars" - "PyTokenizer_FromString" - "PyTokenizer_Free" - "PyTokenizer_FromFile" - "PyTokenizer_Get" - "_PyParser_TokenNames" - -; From python25_s.lib(myreadline) - "_PyOS_ReadlineTState" - "PyOS_ReadlineFunctionPointer" - "PyOS_StdioReadline" - "PyOS_Readline" - "PyOS_InputHook" - -; From python25_s.lib(abstract) - "_PyObject_LengthHint" - "PyMapping_Size" - "PyObject_CallMethod" - "PyObject_GetItem" - "PySequence_GetItem" - "PyObject_SetItem" - "PySequence_SetItem" - "PyObject_DelItem" - "PySequence_DelItem" - "PyNumber_Multiply" - "PyNumber_InPlaceAdd" - "PyNumber_InPlaceMultiply" - "PyNumber_Int" - "PyNumber_Long" - "PyNumber_Float" - "PySequence_Concat" - "PySequence_Repeat" - "PySequence_InPlaceConcat" - "PySequence_InPlaceRepeat" - "PySequence_GetSlice" - "PySequence_SetSlice" - "PySequence_Tuple" - "PyObject_GetIter" - "PyIter_Next" - "PySequence_Fast" - "_PySequence_IterSearch" - "PyObject_CallFunction" - "_PyObject_CallFunction_SizeT" - "_PyObject_CallMethod_SizeT" - "PyObject_CallMethodObjArgs" - "PyObject_CallFunctionObjArgs" - "PyObject_Cmp" - "PyObject_Call" - "PyObject_CallObject" - "PyObject_Type" - "PyObject_Size" - "PyObject_Length" - "PyObject_DelItemString" - "PyObject_AsCharBuffer" - "PyObject_CheckReadBuffer" - "PyObject_AsReadBuffer" - "PyObject_AsWriteBuffer" - "PyNumber_Check" - "PyNumber_Add" - "PyNumber_Subtract" - "PyNumber_Divide" - "PyNumber_FloorDivide" - "PyNumber_TrueDivide" - "PyNumber_Remainder" - "PyNumber_Divmod" - "PyNumber_Power" - "PyNumber_Negative" - "PyNumber_Positive" - "PyNumber_Absolute" - "PyNumber_Invert" - "PyNumber_Lshift" - "PyNumber_Rshift" - "PyNumber_And" - "PyNumber_Xor" - "PyNumber_Or" - "PyNumber_Index" - "PyNumber_InPlaceSubtract" - "PyNumber_InPlaceDivide" - "PyNumber_InPlaceFloorDivide" - "PyNumber_InPlaceTrueDivide" - "PyNumber_InPlaceRemainder" - "PyNumber_InPlacePower" - "PyNumber_InPlaceLshift" - "PyNumber_InPlaceRshift" - "PyNumber_InPlaceAnd" - "PyNumber_InPlaceXor" - "PyNumber_InPlaceOr" - "PySequence_Check" - "PySequence_Size" - "PySequence_Length" - "PySequence_DelSlice" - "PySequence_List" - "PySequence_Count" - "PySequence_Contains" - "PySequence_In" - "PySequence_Index" - "PyMapping_Check" - "PyMapping_Length" - "PyMapping_HasKeyString" - "PyMapping_HasKey" - "PyMapping_GetItemString" - "PyMapping_SetItemString" - "PyObject_IsInstance" - "PyObject_IsSubclass" - -; From python25_s.lib(boolobject) - "PyBool_FromLong" - "PyBool_Type" - "_Py_ZeroStruct" - "_Py_TrueStruct" - -; From python25_s.lib(cellobject) - "PyCell_New" - "PyCell_Get" - "PyCell_Set" - "PyCell_Type" - -; From python25_s.lib(classobject) - "PyClass_New" - "PyClass_IsSubclass" - "PyInstance_New" - "PyInstance_NewRaw" - "PyMethod_New" - "PyMethod_Function" - "PyMethod_Self" - "PyMethod_Class" - "_PyInstance_Lookup" - "PyMethod_Fini" - "PyClass_Type" - "PyInstance_Type" - "PyMethod_Type" - -; From python25_s.lib(cobject) - "PyCObject_FromVoidPtr" - "PyCObject_FromVoidPtrAndDesc" - "PyCObject_AsVoidPtr" - "PyCObject_GetDesc" - "PyCObject_Import" - "PyCObject_SetVoidPtr" - "PyCObject_Type" - -; From python25_s.lib(codeobject) - "PyCode_New" - "PyCode_Addr2Line" - "PyCode_CheckLineNumber" - "PyCode_Type" - -; From python25_s.lib(complexobject) - "_Py_c_pow" - "_Py_c_sum" - "_Py_c_diff" - "_Py_c_neg" - "_Py_c_prod" - "_Py_c_quot" - "PyComplex_FromCComplex" - "PyComplex_FromDoubles" - "PyComplex_RealAsDouble" - "PyComplex_ImagAsDouble" - "PyComplex_AsCComplex" - "PyComplex_Type" - -; From python25_s.lib(descrobject) - "PyWrapper_New" - "PyDescr_NewMethod" - "PyDescr_NewClassMethod" - "PyDescr_NewMember" - "PyDescr_NewGetSet" - "PyDescr_NewWrapper" - "PyDictProxy_New" - "PyWrapperDescr_Type" - "PyProperty_Type" - -; From python25_s.lib(dictobject) - "PyDict_New" - "PyDict_GetItem" - "PyDict_SetItem" - "PyDict_DelItem" - "PyDict_Clear" - "PyDict_MergeFromSeq2" - "PyDict_Merge" - "PyDict_Keys" - "PyDict_Values" - "PyDict_Contains" - "PyDict_Next" - "PyDict_Items" - "PyDict_Size" - "PyDict_Copy" - "PyDict_Update" - "PyDict_GetItemString" - "PyDict_SetItemString" - "PyDict_DelItemString" - "PyDict_Type" - "PyDictIterKey_Type" - "PyDictIterValue_Type" - "PyDictIterItem_Type" - -; From python25_s.lib(enumobject) - "PyEnum_Type" - "PyReversed_Type" - -; From python25_s.lib(fileobject) - "PyFile_FromString" - "Py_UniversalNewlineFread" - "PyFile_GetLine" - "PyFile_SoftSpace" - "PyFile_WriteObject" - "PyFile_WriteString" - "PyObject_AsFileDescriptor" - "Py_UniversalNewlineFgets" - "PyFile_SetBufSize" - "PyFile_SetEncoding" - "PyFile_FromFile" - "PyFile_AsFile" - "PyFile_Name" - "PyFile_Type" - -; From python25_s.lib(floatobject) - "PyFloat_FromString" - "PyFloat_AsDouble" - "PyFloat_Fini" - "_PyFloat_Pack4" - "_PyFloat_Pack8" - "_PyFloat_Unpack4" - "_PyFloat_Unpack8" - "PyFloat_FromDouble" - "PyFloat_AsReprString" - "PyFloat_AsString" - "_PyFloat_Init" - "PyFloat_AsStringEx" - "PyFloat_Type" - -; From python25_s.lib(frameobject) - "PyFrame_New" - "PyFrame_FastToLocals" - "PyFrame_LocalsToFast" - "_PyFrame_Init" - "PyFrame_Fini" - "PyFrame_BlockSetup" - "PyFrame_BlockPop" - "PyFrame_Type" - -; From python25_s.lib(funcobject) - "PyFunction_New" - "PyFunction_GetCode" - "PyFunction_GetGlobals" - "PyFunction_GetModule" - "PyFunction_GetDefaults" - "PyFunction_SetDefaults" - "PyFunction_GetClosure" - "PyFunction_SetClosure" - "PyClassMethod_New" - "PyStaticMethod_New" - "PyFunction_Type" - "PyClassMethod_Type" - "PyStaticMethod_Type" - -; From python25_s.lib(genobject) - "PyGen_New" - "PyGen_NeedsFinalizing" - "PyGen_Type" - -; From python25_s.lib(iterobject) - "PySeqIter_New" - "PyCallIter_New" - "PySeqIter_Type" - "PyCallIter_Type" - -; From python25_s.lib(listobject) - "PyList_New" - "PyList_Append" - "PyList_Size" - "PyList_GetItem" - "PyList_SetItem" - "PyList_Insert" - "PyList_GetSlice" - "PyList_SetSlice" - "PyList_Sort" - "PyList_Reverse" - "PyList_AsTuple" - "_PyList_Extend" - "PyList_Fini" - "PyList_Type" - "PyListIter_Type" - "PyListRevIter_Type" - -; From python25_s.lib(longobject) - "PyLong_FromDouble" - "PyLong_AsLong" - "_PyLong_AsSsize_t" - "PyLong_AsUnsignedLong" - "_PyLong_FromByteArray" - "_PyLong_AsByteArray" - "PyLong_AsDouble" - "PyLong_FromLongLong" - "PyLong_AsLongLong" - "PyLong_FromString" - "PyLong_FromLong" - "PyLong_FromUnsignedLong" - "PyLong_AsUnsignedLongMask" - "_PyLong_FromSize_t" - "_PyLong_FromSsize_t" - "_PyLong_AsScaledDouble" - "PyLong_FromVoidPtr" - "PyLong_AsVoidPtr" - "PyLong_FromUnsignedLongLong" - "PyLong_AsUnsignedLongLong" - "PyLong_AsUnsignedLongLongMask" - "PyLong_FromUnicode" - "_PyLong_Sign" - "_PyLong_NumBits" - "_PyLong_New" - "_PyLong_Copy" - "PyLong_Type" - "_PyLong_DigitValue" - -; From python25_s.lib(methodobject) - "PyCFunction_Call" - "Py_FindMethodInChain" - "PyCFunction_GetFunction" - "PyCFunction_GetSelf" - "PyCFunction_GetFlags" - "Py_FindMethod" - "PyCFunction_NewEx" - "PyCFunction_Fini" - "PyCFunction_New" - "PyCFunction_Type" - -; From python25_s.lib(moduleobject) - "PyModule_New" - "_PyModule_Clear" - "PyModule_GetDict" - "PyModule_GetName" - "PyModule_GetFilename" - "PyModule_Type" - -; From python25_s.lib(object) - "Py_DivisionWarningFlag" - "PyObject_Str" - "PyObject_Repr" - "_PyObject_Str" - "PyObject_Unicode" - "PyObject_GetAttr" - "PyObject_IsTrue" - "PyNumber_CoerceEx" - "PyObject_Compare" - "PyObject_RichCompare" - "_Py_HashDouble" - "PyObject_Hash" - "PyObject_SetAttr" - "PyObject_GenericGetAttr" - "PyObject_GenericSetAttr" - "PyCallable_Check" - "PyObject_Dir" - "PyMem_Malloc" - "PyMem_Realloc" - "PyMem_Free" - "PyObject_Print" - "_PyObject_Dump" - "PyObject_RichCompareBool" - "PyObject_GetAttrString" - "PyObject_SetAttrString" - "PyObject_HasAttrString" - "PyObject_HasAttr" - "_PyObject_GetDictPtr" - "PyObject_SelfIter" - "PyObject_Not" - "PyNumber_Coerce" - "Py_ReprEnter" - "Py_ReprLeave" - "_Py_HashPointer" - "Py_IncRef" - "Py_DecRef" - "_PyTrash_deposit_object" - "_PyTrash_destroy_chain" - "PyObject_Init" - "PyObject_InitVar" - "_PyObject_New" - "_PyObject_NewVar" - "_Py_ReadyTypes" - "_Py_SwappedOp" - "_Py_NotImplementedStruct" - "_Py_NoneStruct" - "_Py_cobject_hack" - "_Py_abstract_hack" - "_PyTrash_delete_nesting" - "_PyTrash_delete_later" - -; From python25_s.lib(obmalloc) - "PyObject_Malloc" - "PyObject_Free" - "PyObject_Realloc" - -; From python25_s.lib(rangeobject) - "PyRange_Type" - -; From python25_s.lib(setobject) - "PySet_Pop" - "PySet_New" - "PyFrozenSet_New" - "PySet_Size" - "PySet_Clear" - "PySet_Contains" - "PySet_Discard" - "PySet_Add" - "_PySet_Next" - "_PySet_Update" - "PySet_Fini" - "PySet_Type" - "PyFrozenSet_Type" - -; From python25_s.lib(sliceobject) - "_PySlice_FromIndices" - "PySlice_GetIndices" - "PySlice_GetIndicesEx" - "PySlice_New" - "_Py_EllipsisObject" - "PySlice_Type" - -; From python25_s.lib(stringobject) - "PyString_FromStringAndSize" - "PyString_InternInPlace" - "PyString_FromString" - "PyString_FromFormatV" - "PyString_AsString" - "_PyString_Resize" - "PyString_FromFormat" - "PyString_AsDecodedString" - "PyString_AsEncodedString" - "PyString_DecodeEscape" - "PyString_Repr" - "PyString_AsStringAndSize" - "_PyString_FormatLong" - "PyString_Format" - "_Py_ReleaseInternedStrings" - "PyString_Size" - "PyString_Concat" - "PyString_ConcatAndDel" - "_PyString_Eq" - "PyString_InternImmortal" - "PyString_InternFromString" - "_PyString_Join" - "PyString_Decode" - "PyString_Encode" - "PyString_AsEncodedObject" - "PyString_AsDecodedObject" - "PyString_Fini" - "PyString_Type" - "PyBaseString_Type" - -; From python25_s.lib(structseq) - "PyStructSequence_InitType" - "PyStructSequence_New" - "PyStructSequence_UnnamedField" - -; From python25_s.lib(tupleobject) - "PyTuple_New" - "PyTuple_Pack" - "_PyTuple_Resize" - "PyTuple_Size" - "PyTuple_GetItem" - "PyTuple_SetItem" - "PyTuple_GetSlice" - "PyTuple_Fini" - "PyTuple_Type" - "PyTupleIter_Type" - -; From python25_s.lib(typeobject) - "PyType_IsSubtype" - "_PyType_Lookup" - "PyType_Ready" - "PyType_GenericAlloc" - "_PyObject_SlotCompare" - "PyType_GenericNew" - "PyType_Type" - "PyBaseObject_Type" - "PySuper_Type" - -; From python25_s.lib(unicodeobject) - "PyUnicodeUCS2_Resize" - "PyUnicodeUCS2_FromOrdinal" - "PyUnicodeUCS2_FromObject" - "PyUnicodeUCS2_FromEncodedObject" - "PyUnicodeUCS2_Decode" - "PyUnicodeUCS2_GetDefaultEncoding" - "PyUnicodeUCS2_DecodeUTF8" - "PyUnicodeUCS2_DecodeLatin1" - "PyUnicodeUCS2_DecodeASCII" - "PyUnicodeUCS2_AsEncodedString" - "PyUnicodeUCS2_AsUTF8String" - "PyUnicodeUCS2_AsLatin1String" - "PyUnicodeUCS2_AsASCIIString" - "PyUnicode_DecodeUTF7" - "PyUnicode_EncodeUTF7" - "PyUnicodeUCS2_DecodeUTF8Stateful" - "PyUnicodeUCS2_EncodeUTF8" - "PyUnicodeUCS2_DecodeUTF16Stateful" - "PyUnicodeUCS2_AsUTF16String" - "PyUnicodeUCS2_DecodeUnicodeEscape" - "PyUnicodeUCS2_DecodeRawUnicodeEscape" - "PyUnicodeUCS2_EncodeRawUnicodeEscape" - "_PyUnicode_DecodeUnicodeInternal" - "PyUnicodeUCS2_DecodeCharmap" - "PyUnicode_BuildEncodingMap" - "PyUnicodeUCS2_EncodeCharmap" - "PyUnicodeUCS2_TranslateCharmap" - "PyUnicodeUCS2_EncodeDecimal" - "PyUnicodeUCS2_Count" - "PyUnicodeUCS2_Find" - "PyUnicodeUCS2_Join" - "PyUnicodeUCS2_Splitlines" - "PyUnicodeUCS2_Compare" - "PyUnicodeUCS2_Contains" - "PyUnicodeUCS2_Concat" - "_PyUnicode_XStrip" - "PyUnicodeUCS2_Replace" - "PyUnicodeUCS2_Split" - "PyUnicodeUCS2_RSplit" - "PyUnicodeUCS2_Format" - "_PyUnicodeUCS2_Init" - "_PyUnicodeUCS2_Fini" - "PyUnicodeUCS2_FromUnicode" - "PyUnicodeUCS2_AsUnicode" - "PyUnicodeUCS2_GetSize" - "PyUnicodeUCS2_GetMax" - "_PyUnicodeUCS2_AsDefaultEncodedString" - "PyUnicodeUCS2_SetDefaultEncoding" - "PyUnicodeUCS2_Encode" - "PyUnicodeUCS2_AsEncodedObject" - "PyUnicodeUCS2_DecodeUTF16" - "PyUnicodeUCS2_EncodeUTF16" - "PyUnicodeUCS2_AsUnicodeEscapeString" - "PyUnicodeUCS2_EncodeUnicodeEscape" - "PyUnicodeUCS2_AsRawUnicodeEscapeString" - "PyUnicodeUCS2_EncodeLatin1" - "PyUnicodeUCS2_EncodeASCII" - "PyUnicodeUCS2_AsCharmapString" - "PyUnicodeUCS2_Partition" - "PyUnicodeUCS2_RPartition" - "PyUnicodeUCS2_Translate" - "PyUnicodeUCS2_Tailmatch" - "PyUnicode_AsDecodedObject" - "PyUnicode_Type" - -; From python25_s.lib(unicodectype) - "_PyUnicode_TypeRecords" - "_PyUnicodeUCS2_ToNumeric" - "_PyUnicodeUCS2_IsLowercase" - "_PyUnicodeUCS2_IsUppercase" - "_PyUnicodeUCS2_IsTitlecase" - "_PyUnicodeUCS2_IsWhitespace" - "_PyUnicodeUCS2_IsLinebreak" - "_PyUnicodeUCS2_ToLowercase" - "_PyUnicodeUCS2_ToUppercase" - "_PyUnicodeUCS2_ToTitlecase" - "_PyUnicodeUCS2_ToDecimalDigit" - "_PyUnicodeUCS2_ToDigit" - "_PyUnicodeUCS2_IsDecimalDigit" - "_PyUnicodeUCS2_IsDigit" - "_PyUnicodeUCS2_IsNumeric" - "_PyUnicodeUCS2_IsAlpha" - -; From python25_s.lib(weakrefobject) - "PyWeakref_NewRef" - "PyWeakref_NewProxy" - "PyObject_ClearWeakRefs" - "PyWeakref_GetObject" - "_PyWeakref_GetWeakrefCount" - "_PyWeakref_ClearRef" - "_PyWeakref_RefType" - "_PyWeakref_ProxyType" - "_PyWeakref_CallableProxyType" - -; From python25_s.lib(Python-ast) -; "init_ast" - "Module" - "Interactive" - "Expression" - "Suite" - "FunctionDef" - "ClassDef" - "Return" - "Delete" - "Assign" - "AugAssign" - "Print" - "For" - "While" - "If" - "With" - "Raise" - "TryExcept" - "TryFinally" - "Assert" - "Import" - "ImportFrom" - "Exec" - "Global" - "Expr" - "Pass" - "Break" - "Continue" - "BoolOp" - "BinOp" - "UnaryOp" - "Lambda" - "IfExp" - "Dict" - "ListComp" - "GeneratorExp" - "Yield" - "Compare" - "Call" - "Repr" - "Num" - "Str" - "Attribute" - "Subscript" - "Name" - "List" - "Tuple" - "Ellipsis" - "Slice" - "ExtSlice" - "Index" - "comprehension" - "excepthandler" - "arguments" - "keyword" - "alias" - "PyAST_mod2obj" - -; From python25_s.lib(asdl) - "asdl_seq_new" - "asdl_int_seq_new" - -; From python25_s.lib(ast) - "PyAST_FromNode" - -; From python25_s.lib(bltinmodule) - "_PyBuiltin_Init" - "Py_FileSystemDefaultEncoding" - -; From python25_s.lib(exceptions) - "PyUnicodeEncodeError_GetStart" - "PyUnicodeDecodeError_GetStart" - "PyUnicodeEncodeError_GetEnd" - "PyUnicodeDecodeError_GetEnd" - "_PyExc_Init" - "PyUnicodeDecodeError_Create" - "PyUnicodeEncodeError_Create" - "PyUnicodeTranslateError_Create" - "PyUnicodeEncodeError_GetEncoding" - "PyUnicodeDecodeError_GetEncoding" - "PyUnicodeEncodeError_GetObject" - "PyUnicodeDecodeError_GetObject" - "PyUnicodeTranslateError_GetObject" - "PyUnicodeTranslateError_GetStart" - "PyUnicodeEncodeError_SetStart" - "PyUnicodeDecodeError_SetStart" - "PyUnicodeTranslateError_SetStart" - "PyUnicodeTranslateError_GetEnd" - "PyUnicodeEncodeError_SetEnd" - "PyUnicodeDecodeError_SetEnd" - "PyUnicodeTranslateError_SetEnd" - "PyUnicodeEncodeError_GetReason" - "PyUnicodeDecodeError_GetReason" - "PyUnicodeTranslateError_GetReason" - "PyUnicodeEncodeError_SetReason" - "PyUnicodeDecodeError_SetReason" - "PyUnicodeTranslateError_SetReason" - "_PyExc_Fini" - "PyExc_BaseException" - "PyExc_Exception" - "PyExc_TypeError" - "PyExc_StopIteration" - "PyExc_GeneratorExit" - "PyExc_SystemExit" - "PyExc_KeyboardInterrupt" - "PyExc_ImportError" - "PyExc_EnvironmentError" - "PyExc_IOError" - "PyExc_OSError" - "PyExc_EOFError" - "PyExc_RuntimeError" - "PyExc_NotImplementedError" - "PyExc_NameError" - "PyExc_UnboundLocalError" - "PyExc_AttributeError" - "PyExc_IndexError" - "PyExc_SyntaxError" - "PyExc_IndentationError" - "PyExc_TabError" - "PyExc_LookupError" - "PyExc_KeyError" - "PyExc_ValueError" - "PyExc_UnicodeError" - "PyExc_UnicodeEncodeError" - "PyExc_UnicodeDecodeError" - "PyExc_UnicodeTranslateError" - "PyExc_AssertionError" - "PyExc_ArithmeticError" - "PyExc_FloatingPointError" - "PyExc_OverflowError" - "PyExc_ZeroDivisionError" - "PyExc_SystemError" - "PyExc_ReferenceError" - "PyExc_MemoryError" - "PyExc_Warning" - "PyExc_UserWarning" - "PyExc_DeprecationWarning" - "PyExc_PendingDeprecationWarning" - "PyExc_SyntaxWarning" - "PyExc_RuntimeWarning" - "PyExc_FutureWarning" - "PyExc_ImportWarning" - "PyExc_MemoryErrorInst" - -; From python25_s.lib(ceval) - "PyEval_EvalFrameEx" - "PyEval_CallObjectWithKeywords" - "PyEval_EvalCodeEx" - "PyEval_GetFrame" - "PyEval_CallObject" - "PyEval_SetProfile" - "PyEval_SetTrace" - "PyEval_GetBuiltins" - "PyEval_GetGlobals" - "PyEval_GetLocals" - "PyEval_GetRestricted" - "PyEval_MergeCompilerFlags" - "Py_FlushLine" - "Py_AddPendingCall" - "Py_MakePendingCalls" - "Py_SetRecursionLimit" - "Py_GetRecursionLimit" - "_Py_CheckRecursiveCall" - "PyEval_GetFuncName" - "PyEval_GetFuncDesc" - "PyEval_GetCallStats" - "PyEval_EvalFrame" - "PyEval_SaveThread" - "PyEval_RestoreThread" - "PyEval_ThreadsInitialized" - "PyEval_InitThreads" - "PyEval_AcquireLock" - "PyEval_ReleaseLock" - "PyEval_AcquireThread" - "PyEval_ReleaseThread" - "PyEval_ReInitThreads" - "_PyEval_SliceIndex" - "PyEval_EvalCode" - "_PyEval_CallTracing" - "_Py_CheckRecursionLimit" - "_Py_CheckInterval" - "_Py_Ticker" - -; From python25_s.lib(compile) - "_Py_Mangle" - "PyAST_Compile" - "PyNode_Compile" - "Py_OptimizeFlag" - -; From python25_s.lib(codecs) - "_PyCodec_Lookup" - "PyCodec_Encode" - "PyCodec_Decode" - "PyCodec_IgnoreErrors" - "PyCodec_ReplaceErrors" - "PyCodec_XMLCharRefReplaceErrors" - "PyCodec_BackslashReplaceErrors" - "PyCodec_Register" - "PyCodec_Encoder" - "PyCodec_Decoder" - "PyCodec_IncrementalEncoder" - "PyCodec_IncrementalDecoder" - "PyCodec_StreamReader" - "PyCodec_StreamWriter" - "PyCodec_RegisterError" - "PyCodec_LookupError" - "PyCodec_StrictErrors" - -; From python25_s.lib(errors) - "PyErr_SetNone" - "PyErr_SetString" - "PyErr_GivenExceptionMatches" - "PyErr_NormalizeException" - "PyErr_Fetch" - "PyErr_Clear" - "PyErr_NoMemory" - "PyErr_SetFromErrnoWithFilenameObject" - "PyErr_Format" - "PyErr_NewException" - "PyErr_WriteUnraisable" - "PyErr_SyntaxLocation" - "PyErr_ProgramText" - "PyErr_SetObject" - "PyErr_Occurred" - "PyErr_Restore" - "PyErr_ExceptionMatches" - "PyErr_BadArgument" - "PyErr_SetFromErrno" - "PyErr_SetFromErrnoWithFilename" - "PyErr_BadInternalCall" - "_PyErr_BadInternalCall" - "PyErr_Warn" - "PyErr_WarnExplicit" - -; From python25_s.lib(frozen) - "PyImport_FrozenModules" - -; From python25_s.lib(frozenmain) - "Py_FrozenMain" - -; From python25_s.lib(future) - "PyFuture_FromAST" - -; From python25_s.lib(getargs) - "PyArg_Parse" - "_PyArg_Parse_SizeT" - "PyArg_ParseTuple" - "_PyArg_ParseTuple_SizeT" - "PyArg_ParseTupleAndKeywords" - "_PyArg_ParseTupleAndKeywords_SizeT" - "PyArg_UnpackTuple" - "_PyArg_NoKeywords" - "PyArg_VaParse" - "PyArg_VaParseTupleAndKeywords" - "_PyArg_VaParse_SizeT" - "_PyArg_VaParseTupleAndKeywords_SizeT" - -; From python25_s.lib(getcompiler) - "Py_GetCompiler" - -; From python25_s.lib(getcopyright) - "Py_GetCopyright" - -; From python25_s.lib(getmtime) - "PyOS_GetLastModificationTime" - -; From python25_s.lib(getplatform) - "Py_GetPlatform" - -; From python25_s.lib(getversion) - "Py_GetVersion" - -; From python25_s.lib(graminit) - "_PyParser_Grammar" - -; From python25_s.lib(import) - "_PyImport_Init" - "_PyImportHooks_Init" - "PyImport_ImportModule" - "PyImport_Cleanup" - "_PyImport_FixupExtension" - "PyImport_AddModule" - "PyImport_ExecCodeModuleEx" - "PyImport_ImportFrozenModule" - "PyImport_ImportModuleEx" - "PyImport_ImportModuleLevel" - "PyImport_ReloadModule" - "PyImport_Import" -; "initimp" - "_PyImport_Fini" - "PyImport_GetMagicNumber" - "PyImport_ExecCodeModule" - "PyImport_GetModuleDict" - "_PyImport_FindModule" - "_PyImport_IsScript" - "_PyImport_ReInitLock" - "_PyImport_FindExtension" - "PyImport_AppendInittab" - "PyImport_ExtendInittab" - "PyImport_Inittab" - "_PyImport_Filetab" - -; From python25_s.lib(importdl) - "_PyImport_LoadDynamicModule" - -; From python25_s.lib(marshal) - "PyMarshal_ReadLongFromFile" - "PyMarshal_WriteObjectToString" - "PyMarshal_WriteLongToFile" - "PyMarshal_WriteObjectToFile" - "PyMarshal_ReadShortFromFile" - "PyMarshal_ReadObjectFromFile" - "PyMarshal_ReadLastObjectFromFile" - "PyMarshal_ReadObjectFromString" - "PyMarshal_Init" - -; From python25_s.lib(modsupport) - "Py_InitModule4" - "Py_BuildValue" - "_Py_BuildValue_SizeT" - "PyEval_CallFunction" - "PyEval_CallMethod" - "_Py_VaBuildValue_SizeT" - "Py_VaBuildValue" - "PyModule_AddObject" - "PyModule_AddIntConstant" - "PyModule_AddStringConstant" - "_Py_PackageContext" - -; From python25_s.lib(mysnprintf) - "PyOS_snprintf" - "PyOS_vsnprintf" - -; From python25_s.lib(mystrtoul) - "PyOS_strtoul" - "PyOS_strtol" - -; From python25_s.lib(pyarena) - "PyArena_New" - "PyArena_Free" - "PyArena_Malloc" - "PyArena_AddPyObject" - -; From python25_s.lib(pyfpe) - "PyFPE_dummy" - -; From python25_s.lib(pystate) - "PyInterpreterState_Clear" - "PyThreadState_Clear" - "_PyThread_CurrentFrames" - "PyGILState_Ensure" - "PyGILState_Release" - "PyInterpreterState_New" - "PyInterpreterState_Delete" - "PyThreadState_Delete" - "PyThreadState_New" - "PyThreadState_DeleteCurrent" - "PyThreadState_Get" - "PyThreadState_Swap" - "PyThreadState_GetDict" - "PyThreadState_SetAsyncExc" - "PyGILState_GetThisThreadState" - "PyInterpreterState_Head" - "PyInterpreterState_Next" - "PyInterpreterState_ThreadHead" - "PyThreadState_Next" - "_PyGILState_Init" - "_PyGILState_Fini" - "_PyThreadState_Current" - "_PyThreadState_GetFrame" - -; From python25_s.lib(pystrtod) - "PyOS_ascii_strtod" - "PyOS_ascii_formatd" - "PyOS_ascii_atof" - -; From python25_s.lib(pythonrun) - "Py_IgnoreEnvironmentFlag" - "Py_DebugFlag" - "Py_VerboseFlag" - "Py_NoSiteFlag" - "Py_InteractiveFlag" - "Py_FrozenFlag" - "Py_InitializeEx" - "Py_FatalError" - "Py_NewInterpreter" - "PyErr_Print" - "PyRun_InteractiveOneFlags" - "PyParser_ASTFromFile" - "PyRun_SimpleFileExFlags" - "PyRun_FileExFlags" - "Py_Exit" - "PyErr_PrintEx" - "PyErr_Display" - "Py_SetProgramName" - "Py_GetProgramName" - "Py_SetPythonHome" - "Py_GetPythonHome" - "Py_Initialize" - "Py_Finalize" - "Py_IsInitialized" - "Py_EndInterpreter" - "PyRun_AnyFileFlags" - "Py_FdIsInteractive" - "PyRun_InteractiveLoopFlags" - "PyRun_AnyFileExFlags" - "PyRun_SimpleStringFlags" - "PyRun_StringFlags" - "PyParser_ASTFromString" - "PyParser_SimpleParseStringFlags" - "PyParser_SimpleParseFileFlags" - "Py_CompileStringFlags" - "Py_SymtableString" - "Py_AtExit" - "PyOS_getsig" - "PyOS_setsig" - "PyParser_SetError" - "PyModule_GetWarningsModule" - "PyParser_SimpleParseStringFlagsFilename" - "PyParser_SimpleParseStringFilename" - "PyParser_SimpleParseFile" - "PyParser_SimpleParseString" - "PyRun_AnyFile" - "PyRun_AnyFileEx" - "PyRun_File" - "PyRun_FileEx" - "PyRun_FileFlags" - "PyRun_SimpleFile" - "PyRun_SimpleFileEx" - "PyRun_String" - "PyRun_SimpleString" - "Py_CompileString" - "PyRun_InteractiveOne" - "PyRun_InteractiveLoop" - "Py_UseClassExceptionsFlag" - "Py_UnicodeFlag" - "_Py_QnewFlag" - -; From python25_s.lib(structmember) - "PyMember_GetOne" - "PyMember_SetOne" - -; From python25_s.lib(symtable) - "PySymtable_Build" - "PySymtable_Free" - "PyST_GetScope" - "PySymtable_Lookup" - "PySTEntry_Type" - -; From python25_s.lib(sysmodule) - "_PySys_Init" - "PySys_WriteStderr" - "PySys_SetPath" - "PySys_SetArgv" - "PySys_WriteStdout" - "Py_SubversionRevision" - "Py_SubversionShortBranch" - "PySys_GetObject" - "PySys_SetObject" - "PySys_GetFile" - "PySys_ResetWarnOptions" - "PySys_AddWarnOption" - -; From python25_s.lib(traceback) - "PyTraceBack_Here" - "PyTraceBack_Print" - "PyTraceBack_Type" - -; From python25_s.lib(getopt) - "_PyOS_GetOpt" - "_PyOS_opterr" - "_PyOS_optind" - "_PyOS_optarg" - -; From python25_s.lib(dynload_shlib) - "_PyImport_DynLoadFiletab" - "_PyImport_GetDynLoadFunc" - -; From python25_s.lib(thread) - "PyThread_delete_key_value" - "PyThread_init_thread" - "PyThread_start_new_thread" - "PyThread_exit_thread" - "PyThread_get_thread_ident" - "PyThread_allocate_lock" - "PyThread_free_lock" - "PyThread_acquire_lock" - "PyThread_release_lock" - "PyThread_get_stacksize" - "PyThread_set_stacksize" - "PyThread_create_key" - "PyThread_delete_key" - "PyThread_set_key_value" - "PyThread_get_key_value" - "PyThread__exit_thread" - -; From python25_s.lib(gcmodule) -; "initgc" - "_PyObject_GC_New" - "_PyObject_GC_NewVar" - "PyGC_Collect" - "_PyObject_GC_Resize" - "_PyObject_GC_Malloc" - "PyObject_GC_Track" - "PyObject_GC_UnTrack" - "PyObject_GC_Del" - "_PyGC_Dump" - "_PyObject_GC_Track" - "_PyObject_GC_UnTrack" - "_PyObject_GC_Del" - "_PyGC_generation0" - -; From python25_s.lib(signalmodule) -; "initsignal" - "PyErr_CheckSignals" - "PyErr_SetInterrupt" - "PyOS_FiniInterrupts" - "PyOS_InterruptOccurred" - "PyOS_InitInterrupts" - "PyOS_AfterFork" - -; From python25_s.lib(posixmodule) -; "initos2" - -; From python25_s.lib(threadmodule) -; "initthread" - -; From python25_s.lib(arraymodule) -; "initarray" -; "array_methods" - -; From python25_s.lib(binascii) -; "initbinascii" - -; From python25_s.lib(cmathmodule) -; "initcmath" - -; From python25_s.lib(_codecsmodule) -; "init_codecs" - -; From python25_s.lib(collectionsmodule) -; "initcollections" - "dequeiter_type" - "dequereviter_type" - -; From python25_s.lib(cStringIO) -; "initcStringIO" - -; From python25_s.lib(_csv) -; "init_csv" - -; From python25_s.lib(datetimemodule) -; "initdatetime" - -; From python25_s.lib(dlmodule) -; "initdl" - -; From python25_s.lib(errnomodule) -; "initerrno" - -; From python25_s.lib(fcntlmodule) -; "initfcntl" - -; From python25_s.lib(_functoolsmodule) -; "init_functools" - -; From python25_s.lib(_heapqmodule) -; "init_heapq" - -; From python25_s.lib(imageop) -; "initimageop" - -; From python25_s.lib(itertoolsmodule) -; "inititertools" - -; From python25_s.lib(_localemodule) -; "init_locale" - -; From python25_s.lib(mathmodule) -; "initmath" - -; From python25_s.lib(operator) -; "initoperator" - -; From python25_s.lib(_randommodule) -; "init_random" - -; From python25_s.lib(sha256module) -; "init_sha256" - -; From python25_s.lib(sha512module) -; "init_sha512" - -; From python25_s.lib(_sre) -; "init_sre" - -; From python25_s.lib(_struct) -; "init_struct" - -; From python25_s.lib(symtablemodule) -; "init_symtable" - -; From python25_s.lib(termios) -; "inittermios" - -; From python25_s.lib(timemodule) -; "inittime" - "_PyTime_DoubleToTimet" -; "inittimezone" - -; From python25_s.lib(_weakref) -; "init_weakref" - -; From python25_s.lib(xxsubtype) -; "initxxsubtype" - -; From python25_s.lib(zipimport) -; "initzipimport" Modified: python/branches/py3k-ctypes-pep3118/PC/os2vacpp/makefile ============================================================================== --- python/branches/py3k-ctypes-pep3118/PC/os2vacpp/makefile (original) +++ python/branches/py3k-ctypes-pep3118/PC/os2vacpp/makefile Wed Apr 30 15:57:13 2008 @@ -507,19 +507,6 @@ $(PY_INCLUDE)\sliceobject.h $(PY_INCLUDE)\stringobject.h \ $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h -dlmodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h $(PY_INCLUDE)\classobject.h \ - $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h pyconfig.h \ - $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h $(PY_INCLUDE)\floatobject.h \ - $(PY_INCLUDE)\funcobject.h $(PY_INCLUDE)\import.h $(PY_INCLUDE)\intobject.h \ - $(PY_INCLUDE)\intrcheck.h $(PY_INCLUDE)\listobject.h $(PY_INCLUDE)\longobject.h \ - $(PY_INCLUDE)\methodobject.h $(PY_INCLUDE)\modsupport.h \ - $(PY_INCLUDE)\moduleobject.h $(PY_INCLUDE)\mymalloc.h $(PY_INCLUDE)\myproto.h \ - $(PY_INCLUDE)\object.h $(PY_INCLUDE)\objimpl.h $(PY_INCLUDE)\pydebug.h \ - $(PY_INCLUDE)\pyerrors.h $(PY_INCLUDE)\pyfpe.h $(PY_INCLUDE)\pystate.h \ - $(PY_INCLUDE)\python.h $(PY_INCLUDE)\pythonrun.h $(PY_INCLUDE)\rangeobject.h \ - $(PY_INCLUDE)\sliceobject.h $(PY_INCLUDE)\stringobject.h \ - $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h - errno.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h $(PY_INCLUDE)\classobject.h \ $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h pyconfig.h \ $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h $(PY_INCLUDE)\floatobject.h \ Modified: python/branches/py3k-ctypes-pep3118/PC/os2vacpp/makefile.omk ============================================================================== --- python/branches/py3k-ctypes-pep3118/PC/os2vacpp/makefile.omk (original) +++ python/branches/py3k-ctypes-pep3118/PC/os2vacpp/makefile.omk Wed Apr 30 15:57:13 2008 @@ -201,7 +201,6 @@ # zlibmodule.c -- Wrapper of ZLib Compression API (GZip Format) # puremodule.c -- Wrapper of Purify Debugging API (Probably Non-OS/2) - # dlmodule.c -- Some Wierd Form of Data Processing Module # xxmodule.c -- Template to Create Your Own Module # @@ -419,14 +418,6 @@ pythonrun.h rangeobject.h sliceobject.h stringobject.h sysmodule.h \ traceback.h tupleobject.h -dlmodule.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \ - pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \ - import.h intobject.h intrcheck.h listobject.h longobject.h \ - methodobject.h modsupport.h moduleobject.h mymalloc.h myproto.h \ - object.h objimpl.h pydebug.h pyerrors.h pyfpe.h pystate.h python.h \ - pythonrun.h rangeobject.h sliceobject.h stringobject.h sysmodule.h \ - traceback.h tupleobject.h - errno.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \ pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \ import.h intobject.h intrcheck.h listobject.h longobject.h \ Modified: python/branches/py3k-ctypes-pep3118/PC/pyconfig.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/PC/pyconfig.h (original) +++ python/branches/py3k-ctypes-pep3118/PC/pyconfig.h Wed Apr 30 15:57:13 2008 @@ -80,7 +80,7 @@ #define MS_WIN32 /* only support win32 and greater. */ #define MS_WINDOWS #ifndef PYTHONPATH -# define PYTHONPATH ".\\DLLs;.\\lib;.\\lib\\plat-win;.\\lib\\lib-tk" +# define PYTHONPATH L".\\DLLs;.\\lib;.\\lib\\plat-win;.\\lib\\lib-tk" #endif #define NT_THREADS #define WITH_THREAD @@ -158,10 +158,12 @@ /* set the version macros for the windows headers */ #ifdef MS_WINX64 /* 64 bit only runs on XP or greater */ -#define Py_WINVER 0x0501 +#define Py_WINVER _WIN32_WINNT_WINXP +#define Py_NTDDI NTDDI_WINXP #else -/* NT 4.0 or greater required otherwise */ -#define Py_WINVER 0x0400 +/* Python 2.6+ requires Windows 2000 or greater */ +#define Py_WINVER _WIN32_WINNT_WIN2K +#define Py_NTDDI NTDDI_WIN2KSP4 #endif /* We only set these values when building Python - we don't want to force @@ -171,7 +173,10 @@ structures etc so it can optionally use new Windows features if it determines at runtime they are available. */ -#ifdef Py_BUILD_CORE +#if defined(Py_BUILD_CORE) || defined(Py_BUILD_CORE_MODULE) +#ifndef NTDDI_VERSION +#define NTDDI_VERSION Py_NTDDI +#endif #ifndef WINVER #define WINVER Py_WINVER #endif @@ -202,12 +207,13 @@ #endif /* MS_WIN32 && !MS_WIN64 */ typedef int pid_t; -#define hypot _hypot #include #define Py_IS_NAN _isnan #define Py_IS_INFINITY(X) (!_finite(X) && !_isnan(X)) #define Py_IS_FINITE(X) _finite(X) +#define copysign _copysign +#define hypot _hypot #endif /* _MSC_VER */ @@ -387,7 +393,7 @@ /* Fairly standard from here! */ /* Define to 1 if you have the `copysign' function. */ -/* #define HAVE_COPYSIGN 1*/ +#define HAVE_COPYSIGN 1 /* Define to 1 if you have the `isinf' function. */ #define HAVE_ISINF 1 Modified: python/branches/py3k-ctypes-pep3118/PC/python_nt.rc ============================================================================== --- python/branches/py3k-ctypes-pep3118/PC/python_nt.rc (original) +++ python/branches/py3k-ctypes-pep3118/PC/python_nt.rc Wed Apr 30 15:57:13 2008 @@ -61,7 +61,7 @@ VALUE "FileDescription", "Python Core\0" VALUE "FileVersion", PYTHON_VERSION VALUE "InternalName", "Python DLL\0" - VALUE "LegalCopyright", "Copyright ? 2001-2007 Python Software Foundation. Copyright ? 2000 BeOpen.com. Copyright ? 1995-2001 CNRI. Copyright ? 1991-1995 SMC.\0" + VALUE "LegalCopyright", "Copyright ? 2001-2008 Python Software Foundation. Copyright ? 2000 BeOpen.com. Copyright ? 1995-2001 CNRI. Copyright ? 1991-1995 SMC.\0" VALUE "OriginalFilename", PYTHON_DLL_NAME "\0" VALUE "ProductName", "Python\0" VALUE "ProductVersion", PYTHON_VERSION Modified: python/branches/py3k-ctypes-pep3118/PC/readme.txt ============================================================================== --- python/branches/py3k-ctypes-pep3118/PC/readme.txt (original) +++ python/branches/py3k-ctypes-pep3118/PC/readme.txt Wed Apr 30 15:57:13 2008 @@ -1,11 +1,6 @@ Welcome to the "PC" subdirectory of the Python distribution *********************************************************** -*** Note: the project files for MS VC++ 7.1 are now in the -*** PCbuild directory. See the file readme.txt there for build -*** instructions. There is some information below that might -*** still be relevant. - This "PC" subdirectory contains complete project files to make several older PC ports of Python, as well as all the PC-specific Python source files. It should be located in the root of the @@ -79,18 +74,23 @@ example_nt A subdirectory showing how to build an extension as a DLL. -Visual Studio 6.0 -================= -The subdirectory VC6 contains Visual Studio 6 project files. These -were originally located in the PCBuild directory, but are no longer -maintained. +Legacy support for older versions of Visual Studio +================================================== +The subdirectories VC6, VS7.1 and VS8.0 contain legacy support older +versions of Microsoft Visual Studio. See PCbuild/readme.txt. + +EMX development tools for OS/2 +============================== +See os2emx/readme.txt. This platform is maintained by Andrew MacIntyre. IBM VisualAge C/C++ for OS/2 ============================ See os2vacpp/readme.txt. This platform is supported by Jeff Rush. +NOTE: Support for os2vacpp may be dropped in the near future. Please move + to EMX. Note for Windows 3.x and DOS users ================================== Modified: python/branches/py3k-ctypes-pep3118/PC/w9xpopen.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/PC/w9xpopen.c (original) +++ python/branches/py3k-ctypes-pep3118/PC/w9xpopen.c Wed Apr 30 15:57:13 2008 @@ -30,7 +30,7 @@ STARTUPINFO si; PROCESS_INFORMATION pi; DWORD exit_code=0; - int cmdlen = 0; + size_t cmdlen = 0; int i; char *cmdline, *cmdlinefill; Modified: python/branches/py3k-ctypes-pep3118/PCbuild/_bsddb.vcproj ============================================================================== --- python/branches/py3k-ctypes-pep3118/PCbuild/_bsddb.vcproj (original) +++ python/branches/py3k-ctypes-pep3118/PCbuild/_bsddb.vcproj Wed Apr 30 15:57:13 2008 @@ -1,7 +1,7 @@ @@ -423,7 +418,7 @@ /> Modified: python/branches/py3k-ctypes-pep3118/PCbuild/_sqlite3.vcproj ============================================================================== --- python/branches/py3k-ctypes-pep3118/PCbuild/_sqlite3.vcproj (original) +++ python/branches/py3k-ctypes-pep3118/PCbuild/_sqlite3.vcproj Wed Apr 30 15:57:13 2008 @@ -1,7 +1,7 @@ @@ -446,12 +428,9 @@ /> Modified: python/branches/py3k-ctypes-pep3118/PCbuild/_ssl.vcproj ============================================================================== --- python/branches/py3k-ctypes-pep3118/PCbuild/_ssl.vcproj (original) +++ python/branches/py3k-ctypes-pep3118/PCbuild/_ssl.vcproj Wed Apr 30 15:57:13 2008 @@ -27,7 +27,7 @@ > - - Modified: python/branches/py3k-ctypes-pep3118/PCbuild/_tkinter.vcproj ============================================================================== --- python/branches/py3k-ctypes-pep3118/PCbuild/_tkinter.vcproj (original) +++ python/branches/py3k-ctypes-pep3118/PCbuild/_tkinter.vcproj Wed Apr 30 15:57:13 2008 @@ -56,7 +56,7 @@ /> + @@ -104,6 +107,96 @@ Name="VCPostBuildEventTool" /> + + + + + + + + + + + + + + + + + + + Modified: python/branches/py3k-ctypes-pep3118/PCbuild/build.bat ============================================================================== --- python/branches/py3k-ctypes-pep3118/PCbuild/build.bat (original) +++ python/branches/py3k-ctypes-pep3118/PCbuild/build.bat Wed Apr 30 15:57:13 2008 @@ -5,13 +5,14 @@ setlocal set platf=Win32 set conf=Release -set build=/build +set build= :CheckOpts -if "%1"=="-c" (set conf=%2) & shift & shift & goto CheckOpts +if "%1"=="-c" (set conf=%2) & shift & shift & goto CheckOpts if "%1"=="-p" (set platf=%2) & shift & shift & goto CheckOpts -if "%1"=="-r" (set build=/rebuild) & shift & goto CheckOpts +if "%1"=="-r" (set build=/rebuild) & shift & goto CheckOpts +if "%1"=="-d" (set conf=Debug) & shift & goto CheckOpts -set cmd=devenv pcbuild.sln %build% "%conf%|%platf%" +set cmd=vcbuild /useenv pcbuild.sln %build% "%conf%|%platf%" echo %cmd% %cmd% Modified: python/branches/py3k-ctypes-pep3118/PCbuild/build_ssl.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/PCbuild/build_ssl.py (original) +++ python/branches/py3k-ctypes-pep3118/PCbuild/build_ssl.py Wed Apr 30 15:57:13 2008 @@ -102,8 +102,11 @@ """ if not os.path.isfile(m32): return - with open(m32) as fin: - with open(makefile, 'w') as fout: + # 2.4 compatibility + fin = open(m32) + if 1: # with open(m32) as fin: + fout = open(makefile, 'w') + if 1: # with open(makefile, 'w') as fout: for line in fin: line = line.replace("=tmp32", "=tmp64") line = line.replace("=out32", "=out64") @@ -121,9 +124,13 @@ """ if not os.path.isfile(makefile): return - with open(makefile) as fin: + # 2.4 compatibility + fin = open(makefile) + if 1: # with open(makefile) as fin: lines = fin.readlines() - with open(makefile, 'w') as fout: + fin.close() + fout = open(makefile, 'w') + if 1: # with open(makefile, 'w') as fout: for line in lines: if line.startswith("PERL="): continue @@ -139,6 +146,7 @@ line = line + noalgo line = line + '\n' fout.write(line) + fout.close() def run_configure(configure, do_script): print("perl Configure "+configure) @@ -225,7 +233,7 @@ # Now run make. if arch == "amd64": - rc = os.system(r"ml64 -c -Foms\uptable.obj ms\uptable.asm") + rc = os.system("ml64 -c -Foms\\uptable.obj ms\\uptable.asm") if rc: print("ml64 assembler has failed.") sys.exit(rc) Modified: python/branches/py3k-ctypes-pep3118/PCbuild/build_tkinter.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/PCbuild/build_tkinter.py (original) +++ python/branches/py3k-ctypes-pep3118/PCbuild/build_tkinter.py Wed Apr 30 15:57:13 2008 @@ -7,7 +7,6 @@ import os import sys -import shutil here = os.path.abspath(os.path.dirname(__file__)) par = os.path.pardir Modified: python/branches/py3k-ctypes-pep3118/PCbuild/debug.vsprops ============================================================================== --- python/branches/py3k-ctypes-pep3118/PCbuild/debug.vsprops (original) +++ python/branches/py3k-ctypes-pep3118/PCbuild/debug.vsprops Wed Apr 30 15:57:13 2008 @@ -8,4 +8,8 @@ Name="VCCLCompilerTool" PreprocessorDefinitions="_DEBUG" /> - \ No newline at end of file + + Modified: python/branches/py3k-ctypes-pep3118/PCbuild/pcbuild.sln ============================================================================== --- python/branches/py3k-ctypes-pep3118/PCbuild/pcbuild.sln (original) +++ python/branches/py3k-ctypes-pep3118/PCbuild/pcbuild.sln Wed Apr 30 15:57:13 2008 @@ -11,6 +11,7 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pythoncore", "pythoncore.vcproj", "{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}" ProjectSection(ProjectDependencies) = postProject {F0E0541E-F17D-430B-97C4-93ADF0DD284E} = {F0E0541E-F17D-430B-97C4-93ADF0DD284E} + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31} = {6DE10744-E396-40A5-B4E2-1B69AA7C8D31} {C73F0EC1-358B-4177-940F-0846AC8B04CD} = {C73F0EC1-358B-4177-940F-0846AC8B04CD} EndProjectSection EndProject @@ -20,6 +21,9 @@ EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "w9xpopen", "w9xpopen.vcproj", "{E9E0A1F6-0009-4E8C-B8F8-1B8F5D49A058}" + ProjectSection(ProjectDependencies) = postProject + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31} = {6DE10744-E396-40A5-B4E2-1B69AA7C8D31} + EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "make_buildinfo", "make_buildinfo.vcproj", "{C73F0EC1-358B-4177-940F-0846AC8B04CD}" EndProject @@ -36,6 +40,8 @@ EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_bsddb", "_bsddb.vcproj", "{B4D38F3F-68FB-42EC-A45D-E00657BB3627}" ProjectSection(ProjectDependencies) = postProject + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31} = {6DE10744-E396-40A5-B4E2-1B69AA7C8D31} + {62172C7D-B39E-409A-B352-370FF5098C19} = {62172C7D-B39E-409A-B352-370FF5098C19} {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} = {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} EndProjectSection EndProject @@ -67,6 +73,7 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_sqlite3", "_sqlite3.vcproj", "{13CECB97-4119-4316-9D42-8534019A5A44}" ProjectSection(ProjectDependencies) = postProject {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} = {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} + {A1A295E5-463C-437F-81CA-1F32367685DA} = {A1A295E5-463C-437F-81CA-1F32367685DA} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_ssl", "_ssl.vcproj", "{C6E20F84-3247-4AD6-B051-B073268F73BA}" @@ -108,6 +115,24 @@ EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "bdist_wininst", "bdist_wininst.vcproj", "{EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}" EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_hashlib", "_hashlib.vcproj", "{447F05A8-F581-4CAC-A466-5AC7936E207E}" + ProjectSection(ProjectDependencies) = postProject + {B11D750F-CD1F-4A96-85CE-E69A5C5259F9} = {B11D750F-CD1F-4A96-85CE-E69A5C5259F9} + {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} = {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_bsddb44", "_bsddb44.vcproj", "{62172C7D-B39E-409A-B352-370FF5098C19}" + ProjectSection(ProjectDependencies) = postProject + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31} = {6DE10744-E396-40A5-B4E2-1B69AA7C8D31} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "sqlite3", "sqlite3.vcproj", "{A1A295E5-463C-437F-81CA-1F32367685DA}" + ProjectSection(ProjectDependencies) = postProject + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31} = {6DE10744-E396-40A5-B4E2-1B69AA7C8D31} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "kill_python", "kill_python.vcproj", "{6DE10744-E396-40A5-B4E2-1B69AA7C8D31}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 @@ -457,13 +482,77 @@ {D06B6426-4762-44CC-8BAD-D79052507F2F}.Release|x64.ActiveCfg = Release|x64 {D06B6426-4762-44CC-8BAD-D79052507F2F}.Release|x64.Build.0 = Release|x64 {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.Debug|Win32.ActiveCfg = Release|Win32 - {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.Debug|x64.ActiveCfg = Release|Win32 + {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.Debug|x64.ActiveCfg = Release|x64 {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.PGInstrument|Win32.ActiveCfg = Release|Win32 - {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.PGInstrument|x64.ActiveCfg = Release|Win32 + {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.PGInstrument|x64.ActiveCfg = Release|x64 {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.PGUpdate|Win32.ActiveCfg = Release|Win32 - {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.PGUpdate|x64.ActiveCfg = Release|Win32 + {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.PGUpdate|x64.ActiveCfg = Release|x64 {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.Release|Win32.ActiveCfg = Release|Win32 - {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.Release|x64.ActiveCfg = Release|Win32 + {EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.Release|x64.ActiveCfg = Release|x64 + {447F05A8-F581-4CAC-A466-5AC7936E207E}.Debug|Win32.ActiveCfg = Debug|Win32 + {447F05A8-F581-4CAC-A466-5AC7936E207E}.Debug|Win32.Build.0 = Debug|Win32 + {447F05A8-F581-4CAC-A466-5AC7936E207E}.Debug|x64.ActiveCfg = Debug|x64 + {447F05A8-F581-4CAC-A466-5AC7936E207E}.Debug|x64.Build.0 = Debug|x64 + {447F05A8-F581-4CAC-A466-5AC7936E207E}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32 + {447F05A8-F581-4CAC-A466-5AC7936E207E}.PGInstrument|Win32.Build.0 = PGInstrument|Win32 + {447F05A8-F581-4CAC-A466-5AC7936E207E}.PGInstrument|x64.ActiveCfg = PGInstrument|x64 + {447F05A8-F581-4CAC-A466-5AC7936E207E}.PGInstrument|x64.Build.0 = PGInstrument|x64 + {447F05A8-F581-4CAC-A466-5AC7936E207E}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32 + {447F05A8-F581-4CAC-A466-5AC7936E207E}.PGUpdate|Win32.Build.0 = PGUpdate|Win32 + {447F05A8-F581-4CAC-A466-5AC7936E207E}.PGUpdate|x64.ActiveCfg = PGUpdate|x64 + {447F05A8-F581-4CAC-A466-5AC7936E207E}.PGUpdate|x64.Build.0 = PGUpdate|x64 + {447F05A8-F581-4CAC-A466-5AC7936E207E}.Release|Win32.ActiveCfg = Release|Win32 + {447F05A8-F581-4CAC-A466-5AC7936E207E}.Release|Win32.Build.0 = Release|Win32 + {447F05A8-F581-4CAC-A466-5AC7936E207E}.Release|x64.ActiveCfg = Release|x64 + {447F05A8-F581-4CAC-A466-5AC7936E207E}.Release|x64.Build.0 = Release|x64 + {62172C7D-B39E-409A-B352-370FF5098C19}.Debug|Win32.ActiveCfg = Debug|Win32 + {62172C7D-B39E-409A-B352-370FF5098C19}.Debug|Win32.Build.0 = Debug|Win32 + {62172C7D-B39E-409A-B352-370FF5098C19}.Debug|x64.ActiveCfg = Debug|x64 + {62172C7D-B39E-409A-B352-370FF5098C19}.Debug|x64.Build.0 = Debug|x64 + {62172C7D-B39E-409A-B352-370FF5098C19}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32 + {62172C7D-B39E-409A-B352-370FF5098C19}.PGInstrument|Win32.Build.0 = PGInstrument|Win32 + {62172C7D-B39E-409A-B352-370FF5098C19}.PGInstrument|x64.ActiveCfg = PGInstrument|x64 + {62172C7D-B39E-409A-B352-370FF5098C19}.PGInstrument|x64.Build.0 = PGInstrument|x64 + {62172C7D-B39E-409A-B352-370FF5098C19}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32 + {62172C7D-B39E-409A-B352-370FF5098C19}.PGUpdate|Win32.Build.0 = PGUpdate|Win32 + {62172C7D-B39E-409A-B352-370FF5098C19}.PGUpdate|x64.ActiveCfg = PGUpdate|x64 + {62172C7D-B39E-409A-B352-370FF5098C19}.PGUpdate|x64.Build.0 = PGUpdate|x64 + {62172C7D-B39E-409A-B352-370FF5098C19}.Release|Win32.ActiveCfg = Release|Win32 + {62172C7D-B39E-409A-B352-370FF5098C19}.Release|Win32.Build.0 = Release|Win32 + {62172C7D-B39E-409A-B352-370FF5098C19}.Release|x64.ActiveCfg = Release|x64 + {62172C7D-B39E-409A-B352-370FF5098C19}.Release|x64.Build.0 = Release|x64 + {A1A295E5-463C-437F-81CA-1F32367685DA}.Debug|Win32.ActiveCfg = Debug|Win32 + {A1A295E5-463C-437F-81CA-1F32367685DA}.Debug|Win32.Build.0 = Debug|Win32 + {A1A295E5-463C-437F-81CA-1F32367685DA}.Debug|x64.ActiveCfg = Debug|x64 + {A1A295E5-463C-437F-81CA-1F32367685DA}.Debug|x64.Build.0 = Debug|x64 + {A1A295E5-463C-437F-81CA-1F32367685DA}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32 + {A1A295E5-463C-437F-81CA-1F32367685DA}.PGInstrument|Win32.Build.0 = PGInstrument|Win32 + {A1A295E5-463C-437F-81CA-1F32367685DA}.PGInstrument|x64.ActiveCfg = PGInstrument|x64 + {A1A295E5-463C-437F-81CA-1F32367685DA}.PGInstrument|x64.Build.0 = PGInstrument|x64 + {A1A295E5-463C-437F-81CA-1F32367685DA}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32 + {A1A295E5-463C-437F-81CA-1F32367685DA}.PGUpdate|Win32.Build.0 = PGUpdate|Win32 + {A1A295E5-463C-437F-81CA-1F32367685DA}.PGUpdate|x64.ActiveCfg = PGUpdate|x64 + {A1A295E5-463C-437F-81CA-1F32367685DA}.PGUpdate|x64.Build.0 = PGUpdate|x64 + {A1A295E5-463C-437F-81CA-1F32367685DA}.Release|Win32.ActiveCfg = Release|Win32 + {A1A295E5-463C-437F-81CA-1F32367685DA}.Release|Win32.Build.0 = Release|Win32 + {A1A295E5-463C-437F-81CA-1F32367685DA}.Release|x64.ActiveCfg = Release|x64 + {A1A295E5-463C-437F-81CA-1F32367685DA}.Release|x64.Build.0 = Release|x64 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Debug|Win32.ActiveCfg = Debug|Win32 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Debug|Win32.Build.0 = Debug|Win32 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Debug|x64.ActiveCfg = Debug|x64 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Debug|x64.Build.0 = Debug|x64 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGInstrument|Win32.ActiveCfg = Release|Win32 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGInstrument|Win32.Build.0 = Release|Win32 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGInstrument|x64.ActiveCfg = Release|x64 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGInstrument|x64.Build.0 = Release|x64 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGUpdate|Win32.ActiveCfg = Release|Win32 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGUpdate|Win32.Build.0 = Release|Win32 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGUpdate|x64.ActiveCfg = Release|x64 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGUpdate|x64.Build.0 = Release|x64 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Release|Win32.ActiveCfg = Release|Win32 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Release|Win32.Build.0 = Release|Win32 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Release|x64.ActiveCfg = Release|x64 + {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE Modified: python/branches/py3k-ctypes-pep3118/PCbuild/pyd.vsprops ============================================================================== --- python/branches/py3k-ctypes-pep3118/PCbuild/pyd.vsprops (original) +++ python/branches/py3k-ctypes-pep3118/PCbuild/pyd.vsprops Wed Apr 30 15:57:13 2008 @@ -7,6 +7,7 @@ > + + + + + + + Modified: python/branches/py3k-ctypes-pep3118/PCbuild/python.vcproj ============================================================================== --- python/branches/py3k-ctypes-pep3118/PCbuild/python.vcproj (original) +++ python/branches/py3k-ctypes-pep3118/PCbuild/python.vcproj Wed Apr 30 15:57:13 2008 @@ -290,7 +290,7 @@ AdditionalDependencies="odbccp32.lib" OutputFile="$(OutDir)\python_d.exe" SubSystem="1" - StackReserveSize="2000000" + StackReserveSize="2100000" BaseAddress="0x1d000000" /> + + @@ -1019,10 +1023,6 @@ > - - @@ -1591,6 +1591,10 @@ Name="Python" > + + @@ -1707,6 +1711,10 @@ > + + Modified: python/branches/py3k-ctypes-pep3118/PCbuild/readme.txt ============================================================================== --- python/branches/py3k-ctypes-pep3118/PCbuild/readme.txt (original) +++ python/branches/py3k-ctypes-pep3118/PCbuild/readme.txt Wed Apr 30 15:57:13 2008 @@ -1,10 +1,17 @@ Building Python using VC++ 9.0 ------------------------------ -This directory is used to build Python for Win32 platforms, e.g. Windows -2000, XP and Vista. It requires Microsoft Visual C++ 9.0 -(a.k.a. Visual Studio .NET 2008). -(For other Windows platforms and compilers, see ../PC/readme.txt.) +This directory is used to build Python for Win32 and x64 platforms, e.g. +Windows 2000, XP, Vista and Windows Server 2008. In order to build 32-bit +debug and release executables, Microsoft Visual C++ 2008 Express Edition is +required at the very least. In order to build 64-bit debug and release +executables, Visual Studio 2008 Standard Edition is required at the very +least. In order to build all of the above, as well as generate release builds +that make use of Profile Guided Optimisation (PG0), Visual Studio 2008 +Professional Edition is required at the very least. The official Python +releases are built with this version of Visual Studio. + +For other Windows platforms and compilers, see ../PC/readme.txt. All you need to do is open the workspace "pcbuild.sln" in Visual Studio, select the desired combination of configuration and platform and eventually @@ -19,11 +26,10 @@ won't stop you from building Python. The solution is configured to build the projects in the correct order. "Build -Solution" or F6 takes care of dependencies except for x64 builds. To make +Solution" or F7 takes care of dependencies except for x64 builds. To make cross compiling x64 builds on a 32bit OS possible the x64 builds require a 32bit version of Python. - NOTE: You probably don't want to build most of the other subprojects, unless you're building an entire Python distribution from scratch, or @@ -31,7 +37,8 @@ running a Python core buildbot test slave; see SUBPROJECTS below) When using the Debug setting, the output files have a _d added to -their name: python30_d.dll, python_d.exe, parser_d.pyd, and so on. +their name: python30_d.dll, python_d.exe, parser_d.pyd, and so on. Both +the build and rt batch files accept a -d option for debug builds. The 32bit builds end up in the solution folder PCbuild while the x64 builds land in the amd64 subfolder. The PGI and PGO builds for profile guided @@ -59,7 +66,7 @@ are linked to a CRT "side by side" assembly which must be present on the target machine. This is avalible under the VC/Redist folder of your visual studio distribution. On XP and later operating systems that support -side-by-side assemblies it is not enough to have the msvcrt80.dll present, +side-by-side assemblies it is not enough to have the msvcrt90.dll present, it has to be there as a whole assembly, that is, a folder with the .dll and a .manifest. Also, a check is made for the correct version. Therefore, one should distribute this assembly with the dlls, and keep @@ -95,77 +102,19 @@ winsound play sounds (typically .wav files) under Windows -The following subprojects will generally NOT build out of the box. They -wrap code Python doesn't control, and you'll need to download the base -packages first and unpack them into siblings of PCbuilds's parent -directory; for example, if your PCbuild is ..\dist\py3k\PCbuild\, -unpack into new subdirectories of ..\dist\. - +Python-controlled subprojects that wrap external projects: +_bsddb + Wraps Berkeley DB 4.4.20, which is currently built by _bsddb44.vcproj. + project (see below). +_sqlite3 + Wraps SQLite 3.3.4, which is currently built by sqlite3.vcproj (see below). _tkinter - Python wrapper for the Tk windowing system. Requires building - Tcl/Tk first. Following are instructions for Tcl/Tk 8.4.16. - - NOTE: The 64 build builds must land in tcltk64 instead of tcltk. - - Get source - ---------- - In the dist directory, run - svn export http://svn.python.org/projects/external/tcl8.4.16 - svn export http://svn.python.org/projects/external/tk8.4.16 - svn export http://svn.python.org/projects/external/tix-8.4.0 - - Build with build_tkinter.py - --------------------------- - The PCbuild directory contains a Python script which automates all - steps. Run the script in a Visual Studio 2008 command prompt with - - python build_tkinter.py Win32 - - Use x64 instead of Win32 for the x64 platform. - - Build Tcl first - --------------- - Use "Start -> All Programs -> Microsoft Visual Studio 2008 - -> Visual Studio Tools -> Visual Studio 2008 Command Prompt" - to get a shell window with the correct environment settings - cd dist\tcl8.4.16\win - nmake -f makefile.vc - nmake -f makefile.vc INSTALLDIR=..\..\tcltk install - - XXX Should we compile with OPTS=threads? - - Optional: run tests, via - nmake -f makefile.vc test - - On WinXP Pro, wholly up to date as of 30-Aug-2004: - all.tcl: Total 10678 Passed 9969 Skipped 709 Failed 0 - Sourced 129 Test Files. - - Build Tk - -------- - cd dist\tk8.4.16\win - nmake -f makefile.vc TCLDIR=..\..\tcl8.4.16 - nmake -f makefile.vc TCLDIR=..\..\tcl8.4.16 INSTALLDIR=..\..\tcltk install - - XXX Should we compile with OPTS=threads? - - XXX Our installer copies a lot of stuff out of the Tcl/Tk install - XXX directory. Is all of that really needed for Python use of Tcl/Tk? - - Optional: run tests, via - nmake -f makefile.vc TCLDIR=..\..\tcl8.4.16 test - - On WinXP Pro, wholly up to date as of 30-Aug-2004: - all.tcl: Total 8420 Passed 6826 Skipped 1581 Failed 13 - Sourced 91 Test Files. - Files with failing tests: canvImg.test scrollbar.test textWind.test winWm.test - - Built Tix - --------- - cd dist\tix-8.4.0\win - nmake -f python9.mak - nmake -f python9.mak install - + Wraps the Tk windowing system. Unlike _bsddb and _sqlite3, there's no + corresponding tcltk.vcproj-type project that builds Tcl/Tk from vcproj's + within our pcbuild.sln, which means this module expects to find a + pre-built Tcl/Tk in either ..\..\tcltk for 32-bit or ..\..\tcltk64 for + 64-bit (relative to this directory). See below for instructions to build + Tcl/Tk. bz2 Python wrapper for the libbz2 compression library. Homepage http://sources.redhat.com/bzip2/ @@ -174,6 +123,10 @@ svn export http://svn.python.org/projects/external/bzip2-1.0.3 + ** NOTE: if you use the Tools\buildbot\external(-amd64).bat approach for + obtaining external sources then you don't need to manually get the source + above via subversion. ** + A custom pre-link step in the bz2 project settings should manage to build bzip2-1.0.3\libbz2.lib by magic before bz2.pyd (or bz2_d.pyd) is linked in PCbuild\. @@ -184,60 +137,6 @@ All of this managed to build libbz2.lib in bzip2-1.0.3\$platform-$configuration\, which the Python project links in. - -_bsddb - To use the version of bsddb that Python is built with by default, invoke - (in the dist directory) - - svn export http://svn.python.org/projects/external/db-4.4.20 - - Next open the solution file db-4.4.20\build_win32\Berkeley_DB.sln with - Visual Studio and convert the projects to the new format. The standard - and professional version of VS 2008 builds the necessary libraries - in a pre-link step of _bsddb. However the express edition is missing - some pieces and you have to build the libs yourself. - - The _bsddb subprojects depends only on the db_static project of - Berkeley DB. You have to choose either "Release", "Release AMD64", "Debug" - or "Debug AMD64" as configuration. - - Alternatively, if you want to start with the original sources, - go to Sleepycat's download page: - http://www.sleepycat.com/downloads/releasehistorybdb.html - - and download version 4.4.20. - - With or without strong cryptography? You can choose either with or - without strong cryptography, as per the instructions below. By - default, Python is built and distributed WITHOUT strong crypto. - - Unpack the sources; if you downloaded the non-crypto version, rename - the directory from db-4.4.20.NC to db-4.4.20. - - Now apply any patches that apply to your version. - - Open - db-4.4.20\docs\ref\build_win\intro.html - - and follow the "Windows->Building Berkeley DB with Visual C++ .NET" - instructions for building the Sleepycat - software. Note that Berkeley_DB.dsw is in the build_win32 subdirectory. - Build the "db_static" project, for "Release" mode. - - To run extensive tests, pass "-u bsddb" to regrtest.py. test_bsddb3.py - is then enabled. Running in verbose mode may be helpful. - -_sqlite3 - Python wrapper for SQLite library. - - Get the source code through - - svn export http://svn.python.org/projects/external/sqlite-source-3.3.4 - - To use the extension module in a Python build tree, copy sqlite3.dll into - the PCbuild folder. The source directory in svn also contains a .def file - from the binary release of sqlite3. - _ssl Python wrapper for the secure sockets library. @@ -245,6 +144,10 @@ svn export http://svn.python.org/projects/external/openssl-0.9.8g + ** NOTE: if you use the Tools\buildbot\external(-amd64).bat approach for + obtaining external sources then you don't need to manually get the source + above via subversion. ** + Alternatively, get the latest version from http://www.openssl.org. You can (theoretically) use any version of OpenSSL you like - the build process will automatically select the latest version. @@ -280,12 +183,75 @@ build_ssl.py/MSVC isn't clever enough to clean OpenSSL - you must do this by hand. +The subprojects above wrap external projects Python doesn't control, and as +such, a little more work is required in order to download the relevant source +files for each project before they can be built. The buildbots do this each +time they're built, so the easiest approach is to run either external.bat or +external-amd64.bat in the ..\Tools\buildbot directory from ..\, i.e.: + + C:\..\svn.python.org\projects\python\trunk\PCbuild>cd .. + C:\..\svn.python.org\projects\python\trunk>Tools\buildbot\external.bat + +This extracts all the external subprojects from http://svn.python.org/external +via Subversion (so you'll need an svn.exe on your PATH) and places them in +..\.. (relative to this directory). The external(-amd64).bat scripts will +also build a debug build of Tcl/Tk; there aren't any equivalent batch files +for building release versions of Tcl/Tk lying around in the Tools\buildbot +directory. If you need to build a release version of Tcl/Tk it isn't hard +though, take a look at the relevant external(-amd64).bat file and find the +two nmake lines, then call each one without the 'DEBUG=1' parameter, i.e.: + +The external-amd64.bat file contains this for tcl: + nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 clean all install + +So for a release build, you'd call it as: + nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 clean all install + + XXX Should we compile with OPTS=threads? + XXX Our installer copies a lot of stuff out of the Tcl/Tk install + XXX directory. Is all of that really needed for Python use of Tcl/Tk? + +This will be cleaned up in the future; ideally Tcl/Tk will be brought into our +pcbuild.sln as custom .vcproj files, just as we've recently done with the +_bsddb44.vcproj and sqlite3.vcproj files, which will remove the need for +Tcl/Tk to be built separately via a batch file. + +XXX trent.nelson 02-Apr-08: + Having the external subprojects in ..\.. relative to this directory is a + bit of a nuisance when you're working on py3k and trunk in parallel and + your directory layout mimics that of Python's subversion layout, e.g.: + + C:\..\svn.python.org\projects\python\trunk + C:\..\svn.python.org\projects\python\branches\py3k + C:\..\svn.python.org\projects\python\branches\release25-maint + + I'd like to change things so that external subprojects are fetched from + ..\external instead of ..\.., then provide some helper scripts or batch + files that would set up a new ..\external directory with svn checkouts of + the relevant branches in http://svn.python.org/projects/external/, or + alternatively, use junctions to link ..\external with a pre-existing + externals directory being used by another branch. i.e. if I'm usually + working on trunk (and have previously created trunk\external via the + provided batch file), and want to do some work on py3k, I'd set up a + junction as follows (using the directory structure above as an example): + + C:\..\python\trunk\external <- already exists and has built versions + of the external subprojects + + C:\..\python\branches\py3k>linkd.exe external ..\..\trunk\external + Link created at: external + + Only a slight tweak would be needed to the buildbots such that bots + building trunk and py3k could make use of the same facility. (2.5.x + builds need to be kept separate as they're using Visual Studio 7.1.) +/XXX trent.nelson 02-Apr-08 + Building for Itanium -------------------- NOTE: Official support for Itanium builds have been dropped from the build. Please -contact as and provide patches if you are interested in Itanium builds. +contact us and provide patches if you are interested in Itanium builds. The project files support a ReleaseItanium configuration which creates Win64/Itanium binaries. For this to work, you need to install the Platform @@ -300,7 +266,8 @@ ------------------ The build process for AMD64 / x64 is very similar to standard builds. You just -have to set x64 as platform. +have to set x64 as platform. In addition, the HOST_PYTHON environment variable +must point to a Python interpreter (at least 2.4), to support cross-compilation. Building Python Using the free MS Toolkit Compiler -------------------------------------------------- Modified: python/branches/py3k-ctypes-pep3118/PCbuild/release.vsprops ============================================================================== --- python/branches/py3k-ctypes-pep3118/PCbuild/release.vsprops (original) +++ python/branches/py3k-ctypes-pep3118/PCbuild/release.vsprops Wed Apr 30 15:57:13 2008 @@ -8,4 +8,8 @@ Name="VCCLCompilerTool" PreprocessorDefinitions="NDEBUG" /> + Modified: python/branches/py3k-ctypes-pep3118/PCbuild/rt.bat ============================================================================== --- python/branches/py3k-ctypes-pep3118/PCbuild/rt.bat (original) +++ python/branches/py3k-ctypes-pep3118/PCbuild/rt.bat Wed Apr 30 15:57:13 2008 @@ -1,11 +1,13 @@ @echo off rem Run Tests. Run the regression test suite. -rem Usage: rt [-d] [-O] [-q] regrtest_args +rem Usage: rt [-d] [-O] [-q] [-x64] regrtest_args rem -d Run Debug build (python_d.exe). Else release build. rem -O Run python.exe or python_d.exe (see -d) with -O. rem -q "quick" -- normally the tests are run twice, the first time rem after deleting all the .py[co] files reachable from Lib/. rem -q runs the tests just once, and without deleting .py[co] files. +rem -x64 Run the 64-bit build of python (or python_d if -d was specified) +rem from the 'amd64' dir instead of the 32-bit build in this dir. rem All leading instances of these switches are shifted off, and rem whatever remains is passed to regrtest.py. For example, rem rt -O -d -x test_thread @@ -24,16 +26,20 @@ setlocal -set exe=python +set prefix=.\ +set suffix= set qmode= set dashO= -PATH %PATH%;..\..\tcltk\bin +set tcltk= :CheckOpts if "%1"=="-O" (set dashO=-O) & shift & goto CheckOpts if "%1"=="-q" (set qmode=yes) & shift & goto CheckOpts -if "%1"=="-d" (set exe=python_d) & shift & goto CheckOpts +if "%1"=="-d" (set suffix=_d) & shift & goto CheckOpts +if "%1"=="-x64" (set prefix=amd64) & (set tcltk=tcltk64) & shift & goto CheckOpts +PATH %PATH%;..\..\%tcltk%\bin +set exe=%prefix%\python%suffix% set cmd=%exe% %dashO% -E -tt ../lib/test/regrtest.py %1 %2 %3 %4 %5 %6 %7 %8 %9 if defined qmode goto Qmode Modified: python/branches/py3k-ctypes-pep3118/PCbuild/x64.vsprops ============================================================================== --- python/branches/py3k-ctypes-pep3118/PCbuild/x64.vsprops (original) +++ python/branches/py3k-ctypes-pep3118/PCbuild/x64.vsprops Wed Apr 30 15:57:13 2008 @@ -15,4 +15,8 @@ Name="VCLinkerTool" TargetMachine="17" /> + Modified: python/branches/py3k-ctypes-pep3118/Parser/Python.asdl ============================================================================== --- python/branches/py3k-ctypes-pep3118/Parser/Python.asdl (original) +++ python/branches/py3k-ctypes-pep3118/Parser/Python.asdl Wed Apr 30 15:57:13 2008 @@ -101,11 +101,8 @@ comprehension = (expr target, expr iter, expr* ifs) -- not sure what to call the first argument for raise and except - -- TODO(jhylton): Figure out if there is a better way to handle - -- lineno and col_offset fields, particularly when - -- ast is exposed to Python. - excepthandler = (expr? type, identifier? name, stmt* body, int lineno, - int col_offset) + excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body) + attributes (int lineno, int col_offset) arguments = (arg* args, identifier? vararg, expr? varargannotation, arg* kwonlyargs, identifier? kwarg, Modified: python/branches/py3k-ctypes-pep3118/Parser/asdl.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Parser/asdl.py (original) +++ python/branches/py3k-ctypes-pep3118/Parser/asdl.py Wed Apr 30 15:57:13 2008 @@ -181,7 +181,7 @@ " sum ::= constructor """ return [constructor[0]] - def p_sum_1(self, ): + def p_sum_1(self, info): " sum ::= constructor | sum " constructor, _, sum = info return [constructor] + sum Modified: python/branches/py3k-ctypes-pep3118/Parser/asdl_c.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Parser/asdl_c.py (original) +++ python/branches/py3k-ctypes-pep3118/Parser/asdl_c.py Wed Apr 30 15:57:13 2008 @@ -4,7 +4,7 @@ # TO DO # handle fields that have a type but no name -import os, sys, traceback +import os, sys import asdl @@ -73,12 +73,12 @@ A sum is simple if its types have no fields, e.g. unaryop = Invert | Not | UAdd | USub """ - for t in sum.types: if t.fields: return False return True + class EmitVisitor(asdl.VisitorBase): """Visit that emits lines""" @@ -96,6 +96,7 @@ line = (" " * TABSIZE * depth) + line + "\n" self.file.write(line) + class TypeDefVisitor(EmitVisitor): def visitModule(self, mod): for dfn in mod.dfns: @@ -133,6 +134,7 @@ self.emit(s, depth) self.emit("", depth) + class StructVisitor(EmitVisitor): """Visitor to generate typdefs for AST.""" @@ -202,6 +204,7 @@ self.emit("};", depth) self.emit("", depth) + class PrototypeVisitor(EmitVisitor): """Generate function prototypes for the .h file""" @@ -271,6 +274,7 @@ self.emit_function(name, get_c_type(name), self.get_args(prod.fields), [], union=0) + class FunctionVisitor(PrototypeVisitor): """Visitor to generate constructor functions for AST.""" @@ -324,6 +328,7 @@ emit("p->%s = %s;" % (argname, argname), 1) assert not attrs + class PickleVisitor(EmitVisitor): def visitModule(self, mod): @@ -345,6 +350,181 @@ def visitField(self, sum): pass + +class Obj2ModPrototypeVisitor(PickleVisitor): + def visitProduct(self, prod, name): + code = "static int obj2ast_%s(PyObject* obj, %s* out, PyArena* arena);" + self.emit(code % (name, get_c_type(name)), 0) + + visitSum = visitProduct + + +class Obj2ModVisitor(PickleVisitor): + def funcHeader(self, name): + ctype = get_c_type(name) + self.emit("int", 0) + self.emit("obj2ast_%s(PyObject* obj, %s* out, PyArena* arena)" % (name, ctype), 0) + self.emit("{", 0) + self.emit("PyObject* tmp = NULL;", 1) + self.emit("", 0) + + def sumTrailer(self, name): + self.emit("", 0) + self.emit("tmp = PyObject_Repr(obj);", 1) + # there's really nothing more we can do if this fails ... + self.emit("if (tmp == NULL) goto failed;", 1) + error = "expected some sort of %s, but got %%.400s" % name + format = "PyErr_Format(PyExc_TypeError, \"%s\", PyString_AS_STRING(tmp));" + self.emit(format % error, 1, reflow=False) + self.emit("failed:", 0) + self.emit("Py_XDECREF(tmp);", 1) + self.emit("return 1;", 1) + self.emit("}", 0) + self.emit("", 0) + + def simpleSum(self, sum, name): + self.funcHeader(name) + for t in sum.types: + self.emit("if (PyObject_IsInstance(obj, (PyObject*)%s_type)) {" % t.name, 1) + self.emit("*out = %s;" % t.name, 2) + self.emit("return 0;", 2) + self.emit("}", 1) + self.sumTrailer(name) + + def buildArgs(self, fields): + return ", ".join(fields + ["arena"]) + + def complexSum(self, sum, name): + self.funcHeader(name) + for a in sum.attributes: + self.visitAttributeDeclaration(a, name, sum=sum) + self.emit("", 0) + # XXX: should we only do this for 'expr'? + self.emit("if (obj == Py_None) {", 1) + self.emit("*out = NULL;", 2) + self.emit("return 0;", 2) + self.emit("}", 1) + for a in sum.attributes: + self.visitField(a, name, sum=sum, depth=1) + for t in sum.types: + self.emit("if (PyObject_IsInstance(obj, (PyObject*)%s_type)) {" % t.name, 1) + for f in t.fields: + self.visitFieldDeclaration(f, t.name, sum=sum, depth=2) + self.emit("", 0) + for f in t.fields: + self.visitField(f, t.name, sum=sum, depth=2) + args = [f.name.value for f in t.fields] + [a.name.value for a in sum.attributes] + self.emit("*out = %s(%s);" % (t.name, self.buildArgs(args)), 2) + self.emit("if (*out == NULL) goto failed;", 2) + self.emit("return 0;", 2) + self.emit("}", 1) + self.sumTrailer(name) + + def visitAttributeDeclaration(self, a, name, sum=sum): + ctype = get_c_type(a.type) + self.emit("%s %s;" % (ctype, a.name), 1) + + def visitSum(self, sum, name): + if is_simple(sum): + self.simpleSum(sum, name) + else: + self.complexSum(sum, name) + + def visitProduct(self, prod, name): + ctype = get_c_type(name) + self.emit("int", 0) + self.emit("obj2ast_%s(PyObject* obj, %s* out, PyArena* arena)" % (name, ctype), 0) + self.emit("{", 0) + self.emit("PyObject* tmp = NULL;", 1) + for f in prod.fields: + self.visitFieldDeclaration(f, name, prod=prod, depth=1) + self.emit("", 0) + for f in prod.fields: + self.visitField(f, name, prod=prod, depth=1) + args = [f.name.value for f in prod.fields] + self.emit("*out = %s(%s);" % (name, self.buildArgs(args)), 1) + self.emit("return 0;", 1) + self.emit("failed:", 0) + self.emit("Py_XDECREF(tmp);", 1) + self.emit("return 1;", 1) + self.emit("}", 0) + self.emit("", 0) + + def visitFieldDeclaration(self, field, name, sum=None, prod=None, depth=0): + ctype = get_c_type(field.type) + if field.seq: + if self.isSimpleType(field): + self.emit("asdl_int_seq* %s;" % field.name, depth) + else: + self.emit("asdl_seq* %s;" % field.name, depth) + else: + ctype = get_c_type(field.type) + self.emit("%s %s;" % (ctype, field.name), depth) + + def isSimpleSum(self, field): + # XXX can the members of this list be determined automatically? + return field.type.value in ('expr_context', 'boolop', 'operator', + 'unaryop', 'cmpop') + + def isNumeric(self, field): + return get_c_type(field.type) in ("int", "bool") + + def isSimpleType(self, field): + return self.isSimpleSum(field) or self.isNumeric(field) + + def visitField(self, field, name, sum=None, prod=None, depth=0): + ctype = get_c_type(field.type) + self.emit("if (PyObject_HasAttrString(obj, \"%s\")) {" % field.name, depth) + self.emit("int res;", depth+1) + if field.seq: + self.emit("Py_ssize_t len;", depth+1) + self.emit("Py_ssize_t i;", depth+1) + self.emit("tmp = PyObject_GetAttrString(obj, \"%s\");" % field.name, depth+1) + self.emit("if (tmp == NULL) goto failed;", depth+1) + if field.seq: + self.emit("if (!PyList_Check(tmp)) {", depth+1) + self.emit("PyErr_Format(PyExc_TypeError, \"%s field \\\"%s\\\" must " + "be a list, not a %%.200s\", tmp->ob_type->tp_name);" % + (name, field.name), + depth+2, reflow=False) + self.emit("goto failed;", depth+2) + self.emit("}", depth+1) + self.emit("len = PyList_GET_SIZE(tmp);", depth+1) + if self.isSimpleType(field): + self.emit("%s = asdl_int_seq_new(len, arena);" % field.name, depth+1) + else: + self.emit("%s = asdl_seq_new(len, arena);" % field.name, depth+1) + self.emit("if (%s == NULL) goto failed;" % field.name, depth+1) + self.emit("for (i = 0; i < len; i++) {", depth+1) + self.emit("%s value;" % ctype, depth+2) + self.emit("res = obj2ast_%s(PyList_GET_ITEM(tmp, i), &value, arena);" % + field.type, depth+2, reflow=False) + self.emit("if (res != 0) goto failed;", depth+2) + self.emit("asdl_seq_SET(%s, i, value);" % field.name, depth+2) + self.emit("}", depth+1) + else: + self.emit("res = obj2ast_%s(tmp, &%s, arena);" % + (field.type, field.name), depth+1) + self.emit("if (res != 0) goto failed;", depth+1) + + self.emit("Py_XDECREF(tmp);", depth+1) + self.emit("tmp = NULL;", depth+1) + self.emit("} else {", depth) + if not field.opt: + message = "required field \\\"%s\\\" missing from %s" % (field.name, name) + format = "PyErr_SetString(PyExc_TypeError, \"%s\");" + self.emit(format % message, depth+1, reflow=False) + self.emit("return 1;", depth+1) + else: + if self.isNumeric(field): + self.emit("%s = 0;" % field.name, depth+1) + elif not self.isSimpleType(field): + self.emit("%s = NULL;" % field.name, depth+1) + else: + raise TypeError("could not determine the default value for %s" % field.name) + self.emit("}", depth) + + class MarshalPrototypeVisitor(PickleVisitor): def prototype(self, sum, name): @@ -354,6 +534,7 @@ visitProduct = visitSum = prototype + class PyTypesDeclareVisitor(PickleVisitor): def visitProduct(self, prod, name): @@ -396,18 +577,132 @@ def visitModule(self, mod): self.emit(""" +static int +ast_type_init(PyObject *self, PyObject *args, PyObject *kw) +{ + Py_ssize_t i, numfields = 0; + int res = -1; + PyObject *key, *value, *fields; + fields = PyObject_GetAttrString((PyObject*)Py_TYPE(self), "_fields"); + if (!fields) + PyErr_Clear(); + if (fields) { + numfields = PySequence_Size(fields); + if (numfields == -1) + goto cleanup; + } + res = 0; /* if no error occurs, this stays 0 to the end */ + if (PyTuple_GET_SIZE(args) > 0) { + if (numfields != PyTuple_GET_SIZE(args)) { + PyErr_Format(PyExc_TypeError, "%.400s constructor takes %s" + "%" PY_FORMAT_SIZE_T "d positional argument%s", + Py_TYPE(self)->tp_name, + numfields == 0 ? "" : "either 0 or ", + numfields, numfields == 1 ? "" : "s"); + res = -1; + goto cleanup; + } + for (i = 0; i < PyTuple_GET_SIZE(args); i++) { + /* cannot be reached when fields is NULL */ + PyObject *name = PySequence_GetItem(fields, i); + if (!name) { + res = -1; + goto cleanup; + } + res = PyObject_SetAttr(self, name, PyTuple_GET_ITEM(args, i)); + Py_DECREF(name); + if (res < 0) + goto cleanup; + } + } + if (kw) { + i = 0; /* needed by PyDict_Next */ + while (PyDict_Next(kw, &i, &key, &value)) { + res = PyObject_SetAttr(self, key, value); + if (res < 0) + goto cleanup; + } + } + cleanup: + Py_XDECREF(fields); + return res; +} + +/* Pickling support */ +static PyObject * +ast_type_reduce(PyObject *self, PyObject *unused) +{ + PyObject *res; + PyObject *dict = PyObject_GetAttrString(self, "__dict__"); + if (dict == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) + PyErr_Clear(); + else + return NULL; + } + if (dict) { + res = Py_BuildValue("O()O", Py_TYPE(self), dict); + Py_DECREF(dict); + return res; + } + return Py_BuildValue("O()", Py_TYPE(self)); +} + +static PyMethodDef ast_type_methods[] = { + {"__reduce__", ast_type_reduce, METH_NOARGS, NULL}, + {NULL} +}; + +static PyTypeObject AST_type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "_ast.AST", + sizeof(PyObject), + 0, + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + ast_type_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)ast_type_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_Del, /* tp_free */ +}; + + static PyTypeObject* make_type(char *type, PyTypeObject* base, char**fields, int num_fields) { PyObject *fnames, *result; int i; - if (num_fields) { - fnames = PyTuple_New(num_fields); - if (!fnames) return NULL; - } else { - fnames = Py_None; - Py_INCREF(Py_None); - } - for(i=0; i < num_fields; i++) { + fnames = PyTuple_New(num_fields); + if (!fnames) return NULL; + for (i = 0; i < num_fields; i++) { PyObject *field = PyUnicode_FromString(fields[i]); if (!field) { Py_DECREF(fnames); @@ -424,7 +719,7 @@ static int add_attributes(PyTypeObject* type, char**attrs, int num_fields) { int i, result; - PyObject *s, *l = PyList_New(num_fields); + PyObject *s, *l = PyTuple_New(num_fields); if (!l) return 0; for(i = 0; i < num_fields; i++) { s = PyUnicode_FromString(attrs[i]); @@ -432,13 +727,15 @@ Py_DECREF(l); return 0; } - PyList_SET_ITEM(l, i, s); + PyTuple_SET_ITEM(l, i, s); } result = PyObject_SetAttrString((PyObject*)type, "_attributes", l) >= 0; Py_DECREF(l); return result; } +/* Conversion AST -> Python */ + static PyObject* ast2obj_list(asdl_seq *seq, PyObject* (*func)(void*)) { int i, n = asdl_seq_LEN(seq); @@ -471,13 +768,48 @@ { return PyLong_FromLong(b); } + +/* Conversion Python -> AST */ + +static int obj2ast_object(PyObject* obj, PyObject** out, PyArena* arena) +{ + if (obj == Py_None) + obj = NULL; + if (obj) + PyArena_AddPyObject(arena, obj); + Py_XINCREF(obj); + *out = obj; + return 0; +} + +#define obj2ast_identifier obj2ast_object +#define obj2ast_string obj2ast_object + +static int obj2ast_int(PyObject* obj, int* out, PyArena* arena) +{ + int i; + if (!PyLong_Check(obj)) { + PyObject *s = PyObject_Repr(obj); + if (s == NULL) return 1; + PyErr_Format(PyExc_ValueError, "invalid integer value: %.400s", + PyString_AS_STRING(s)); + Py_DECREF(s); + return 1; + } + + i = (int)PyLong_AsLong(obj); + if (i == -1 && PyErr_Occurred()) + return 1; + *out = i; + return 0; +} + """, 0, reflow=False) self.emit("static int init_types(void)",0) self.emit("{", 0) self.emit("static int initialized;", 1) self.emit("if (initialized) return 1;", 1) - self.emit('AST_type = make_type("AST", &PyBaseObject_Type, NULL, 0);', 1) for dfn in mod.dfns: self.visit(dfn) self.emit("initialized = 1;", 1) @@ -489,12 +821,13 @@ fields = name.value+"_fields" else: fields = "NULL" - self.emit('%s_type = make_type("%s", AST_type, %s, %d);' % + self.emit('%s_type = make_type("%s", &AST_type, %s, %d);' % (name, name, fields, len(prod.fields)), 1) self.emit("if (!%s_type) return 0;" % name, 1) def visitSum(self, sum, name): - self.emit('%s_type = make_type("%s", AST_type, NULL, 0);' % (name, name), 1) + self.emit('%s_type = make_type("%s", &AST_type, NULL, 0);' % + (name, name), 1) self.emit("if (!%s_type) return 0;" % name, 1) if sum.attributes: self.emit("if (!add_attributes(%s_type, %s_attributes, %d)) return 0;" % @@ -518,6 +851,7 @@ (cons.name, cons.name), 1) self.emit("if (!%s_singleton) return 0;" % cons.name, 1) + def parse_version(mod): return mod.version.value[12:-3] @@ -532,7 +866,7 @@ self.emit('m = Py_InitModule3("_ast", NULL, NULL);', 1) self.emit("if (!m) return;", 1) self.emit("d = PyModule_GetDict(m);", 1) - self.emit('if (PyDict_SetItemString(d, "AST", (PyObject*)AST_type) < 0) return;', 1) + self.emit('if (PyDict_SetItemString(d, "AST", (PyObject*)&AST_type) < 0) return;', 1) self.emit('if (PyModule_AddIntConstant(m, "PyCF_ONLY_AST", PyCF_ONLY_AST) < 0)', 1) self.emit("return;", 2) # Value of version: "$Revision$" @@ -557,6 +891,7 @@ def addObj(self, name): self.emit('if (PyDict_SetItemString(d, "%s", (PyObject*)%s_type) < 0) return;' % (name, name), 1) + _SPECIALIZED_SEQUENCES = ('stmt', 'expr') def find_sequence(fields, doing_specialization): @@ -582,6 +917,7 @@ def visit(self, object): self.emit(self.CODE, 0, reflow=False) + class ObjVisitor(PickleVisitor): def func_begin(self, name): @@ -632,8 +968,12 @@ self.emit("case %s:" % t.name, 2) self.emit("Py_INCREF(%s_singleton);" % t.name, 3) self.emit("return %s_singleton;" % t.name, 3) + self.emit("default:" % name, 2) + self.emit('/* should never happen, but just in case ... */', 3) + code = "PyErr_Format(PyExc_SystemError, \"unknown %s found\");" % name + self.emit(code, 3, reflow=False) + self.emit("return NULL;", 3) self.emit("}", 1) - self.emit("return NULL; /* cannot happen */", 1) self.emit("}", 0) def visitProduct(self, prod, name): @@ -707,6 +1047,34 @@ init_types(); return ast2obj_mod(t); } + +/* mode is 0 for "exec", 1 for "eval" and 2 for "single" input */ +mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode) +{ + mod_ty res; + PyObject *req_type[] = {(PyObject*)Module_type, (PyObject*)Expression_type, + (PyObject*)Interactive_type}; + char *req_name[] = {"Module", "Expression", "Interactive"}; + assert(0 <= mode && mode <= 2); + + init_types(); + + if (!PyObject_IsInstance(ast, req_type[mode])) { + PyErr_Format(PyExc_TypeError, "expected %s node, got %.400s", + req_name[mode], Py_TYPE(ast)->tp_name); + return NULL; + } + if (obj2ast_mod(ast, &res, arena) != 0) + return NULL; + else + return res; +} + +int PyAST_Check(PyObject* obj) +{ + init_types(); + return PyObject_IsInstance(obj, (PyObject*)&AST_type); +} """ class ChainOfVisitors: @@ -750,6 +1118,8 @@ ) c.visit(mod) f.write("PyObject* PyAST_mod2obj(mod_ty t);\n") + f.write("mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode);\n") + f.write("int PyAST_Check(PyObject* obj);\n") f.close() if SRC_DIR: @@ -760,12 +1130,14 @@ f.write('#include "Python.h"\n') f.write('#include "%s-ast.h"\n' % mod.name) f.write('\n') - f.write("static PyTypeObject* AST_type;\n") + f.write("static PyTypeObject AST_type;\n") v = ChainOfVisitors( PyTypesDeclareVisitor(f), PyTypesVisitor(f), + Obj2ModPrototypeVisitor(f), FunctionVisitor(f), ObjVisitor(f), + Obj2ModVisitor(f), ASTModuleVisitor(f), PartingShots(f), ) Modified: python/branches/py3k-ctypes-pep3118/Parser/parser.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Parser/parser.c (original) +++ python/branches/py3k-ctypes-pep3118/Parser/parser.c Wed Apr 30 15:57:13 2008 @@ -206,10 +206,18 @@ for (i = 0; i < NCH(ch); i += 2) { cch = CHILD(ch, i); - if (NCH(cch) >= 1 && TYPE(CHILD(cch, 0)) == NAME && - strcmp(STR(CHILD(cch, 0)), "with_statement") == 0) { - ps->p_flags |= CO_FUTURE_WITH_STATEMENT; - break; + if (NCH(cch) >= 1 && TYPE(CHILD(cch, 0)) == NAME) { + char *str_ch = STR(CHILD(cch, 0)); + if (strcmp(str_ch, FUTURE_WITH_STATEMENT) == 0) { + ps->p_flags |= CO_FUTURE_WITH_STATEMENT; + break; + } else if (strcmp(str_ch, FUTURE_PRINT_FUNCTION) == 0) { + ps->p_flags |= CO_FUTURE_PRINT_FUNCTION; + break; + } else if (strcmp(str_ch, FUTURE_UNICODE_LITERALS) == 0) { + ps->p_flags |= CO_FUTURE_UNICODE_LITERALS; + break; + } } } } Modified: python/branches/py3k-ctypes-pep3118/Parser/parser.h ============================================================================== --- python/branches/py3k-ctypes-pep3118/Parser/parser.h (original) +++ python/branches/py3k-ctypes-pep3118/Parser/parser.h Wed Apr 30 15:57:13 2008 @@ -7,7 +7,7 @@ /* Parser interface */ -#define MAXSTACK 500 +#define MAXSTACK 1500 typedef struct { int s_state; /* State in current DFA */ Modified: python/branches/py3k-ctypes-pep3118/Parser/parsetok.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Parser/parsetok.c (original) +++ python/branches/py3k-ctypes-pep3118/Parser/parsetok.c Wed Apr 30 15:57:13 2008 @@ -14,7 +14,7 @@ /* Forward */ -static node *parsetok(struct tok_state *, grammar *, int, perrdetail *, int); +static node *parsetok(struct tok_state *, grammar *, int, perrdetail *, int *); static void initerr(perrdetail *err_ret, const char* filename); /* Parse input coming from a string. Return error code, print some errors. */ @@ -37,6 +37,16 @@ grammar *g, int start, perrdetail *err_ret, int flags) { + int iflags = flags; + return PyParser_ParseStringFlagsFilenameEx(s, filename, g, start, + err_ret, &iflags); +} + +node * +PyParser_ParseStringFlagsFilenameEx(const char *s, const char *filename, + grammar *g, int start, + perrdetail *err_ret, int *flags) +{ struct tok_state *tok; initerr(err_ret, filename); @@ -64,10 +74,20 @@ } node * -PyParser_ParseFileFlags(FILE *fp, const char *filename, const char* enc, +PyParser_ParseFileFlags(FILE *fp, const char *filename, const char *enc, grammar *g, int start, char *ps1, char *ps2, perrdetail *err_ret, int flags) { + int iflags = flags; + return PyParser_ParseFileFlagsEx(fp, filename, enc, g, start, ps1, + ps2, err_ret, &iflags); +} + +node * +PyParser_ParseFileFlagsEx(FILE *fp, const char *filename, + const char *enc, grammar *g, int start, + char *ps1, char *ps2, perrdetail *err_ret, int *flags) +{ struct tok_state *tok; initerr(err_ret, filename); @@ -104,7 +124,7 @@ static node * parsetok(struct tok_state *tok, grammar *g, int start, perrdetail *err_ret, - int flags) + int *flags) { parser_state *ps; node *n; @@ -117,7 +137,7 @@ return NULL; } #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD - if (flags & PyPARSE_WITH_IS_KEYWORD) + if (*flags & PyPARSE_WITH_IS_KEYWORD) ps->p_flags |= CO_FUTURE_WITH_STATEMENT; #endif @@ -141,7 +161,7 @@ except if a certain flag is given -- codeop.py uses this. */ if (tok->indent && - !(flags & PyPARSE_DONT_IMPLY_DEDENT)) + !(*flags & PyPARSE_DONT_IMPLY_DEDENT)) { tok->pendin = -tok->indent; tok->indent = 0; @@ -206,6 +226,9 @@ else n = NULL; +#ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD + *flags = ps->p_flags; +#endif PyParser_Delete(ps); if (n == NULL) { @@ -213,21 +236,16 @@ err_ret->error = E_EOF; err_ret->lineno = tok->lineno; if (tok->buf != NULL) { - char *text = NULL; size_t len; assert(tok->cur - tok->buf < INT_MAX); err_ret->offset = (int)(tok->cur - tok->buf); len = tok->inp - tok->buf; - text = PyTokenizer_RestoreEncoding(tok, len, &err_ret->offset); - if (text == NULL) { - text = (char *) PyObject_MALLOC(len + 1); - if (text != NULL) { - if (len > 0) - strncpy(text, tok->buf, len); - text[len] = '\0'; - } + err_ret->text = (char *) PyObject_MALLOC(len + 1); + if (err_ret->text != NULL) { + if (len > 0) + strncpy(err_ret->text, tok->buf, len); + err_ret->text[len] = '\0'; } - err_ret->text = text; } } else if (tok->encoding != NULL) { node* r = PyNode_New(encoding_decl); Modified: python/branches/py3k-ctypes-pep3118/Parser/printgrammar.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Parser/printgrammar.c (original) +++ python/branches/py3k-ctypes-pep3118/Parser/printgrammar.c Wed Apr 30 15:57:13 2008 @@ -13,6 +13,7 @@ void printgrammar(grammar *g, FILE *fp) { + fprintf(fp, "/* Generated by Parser/pgen */\n\n"); fprintf(fp, "#include \"pgenheaders.h\"\n"); fprintf(fp, "#include \"grammar.h\"\n"); printdfas(g, fp); @@ -31,6 +32,8 @@ dfa *d; int i; + fprintf(fp, "/* Generated by Parser/pgen */\n\n"); + d = g->g_dfa; for (i = g->g_ndfas; --i >= 0; d++) fprintf(fp, "#define %s %d\n", d->d_name, d->d_type); Modified: python/branches/py3k-ctypes-pep3118/Parser/spark.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Parser/spark.py (original) +++ python/branches/py3k-ctypes-pep3118/Parser/spark.py Wed Apr 30 15:57:13 2008 @@ -22,7 +22,6 @@ __version__ = 'SPARK-0.7 (pre-alpha-5)' import re -import sys # Compatability with older pythons. def output(string='', end='\n'): Modified: python/branches/py3k-ctypes-pep3118/Parser/tokenizer.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Parser/tokenizer.c (original) +++ python/branches/py3k-ctypes-pep3118/Parser/tokenizer.c Wed Apr 30 15:57:13 2008 @@ -39,14 +39,6 @@ /* Don't ever change this -- it would break the portability of Python code */ #define TABSIZE 8 -/* Convert a possibly signed character to a nonnegative int */ -/* XXX This assumes characters are 8 bits wide */ -#ifdef __CHAR_UNSIGNED__ -#define Py_CHARMASK(c) (c) -#else -#define Py_CHARMASK(c) ((c) & 0xff) -#endif - /* Forward */ static struct tok_state *tok_new(void); static int tok_nextc(struct tok_state *tok); @@ -657,6 +649,7 @@ for (s = str;; s++) { if (*s == '\0') break; else if (*s == '\n') { + assert(lineno < 2); newl[lineno] = s; lineno++; if (lineno == 2) break; @@ -1578,70 +1571,6 @@ return result; } -/* This function is only called from parsetok. However, it cannot live - there, as it must be empty for PGEN, and we can check for PGEN only - in this file. */ - -#ifdef PGEN -char* -PyTokenizer_RestoreEncoding(struct tok_state* tok, int len, int* offset) -{ - return NULL; -} -#else -static PyObject * -dec_utf8(const char *enc, const char *text, size_t len) { - PyObject *ret = NULL; - PyObject *unicode_text = PyUnicode_DecodeUTF8(text, len, "replace"); - if (unicode_text) { - ret = PyUnicode_AsEncodedString(unicode_text, enc, "replace"); - Py_DECREF(unicode_text); - } - if (!ret) { - PyErr_Clear(); - } - else { - assert(PyString_Check(ret)); - } - return ret; -} - -char * -PyTokenizer_RestoreEncoding(struct tok_state* tok, int len, int *offset) -{ - char *text = NULL; - if (tok->encoding) { - /* convert source to original encondig */ - PyObject *lineobj = dec_utf8(tok->encoding, tok->buf, len); - if (lineobj != NULL) { - int linelen = PyString_GET_SIZE(lineobj); - const char *line = PyString_AS_STRING(lineobj); - text = PyObject_MALLOC(linelen + 1); - if (text != NULL && line != NULL) { - if (linelen) - strncpy(text, line, linelen); - text[linelen] = '\0'; - } - Py_DECREF(lineobj); - - /* adjust error offset */ - if (*offset > 1) { - PyObject *offsetobj = dec_utf8(tok->encoding, - tok->buf, - *offset-1); - if (offsetobj) { - *offset = 1 + Py_SIZE(offsetobj); - Py_DECREF(offsetobj); - } - } - - } - } - return text; - -} -#endif - /* Get -*- encoding -*- from a Python file. PyTokenizer_FindEncoding returns NULL when it can't find the encoding in Modified: python/branches/py3k-ctypes-pep3118/Python/Python-ast.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/Python-ast.c (original) +++ python/branches/py3k-ctypes-pep3118/Python/Python-ast.c Wed Apr 30 15:57:13 2008 @@ -12,7 +12,7 @@ #include "Python.h" #include "Python-ast.h" -static PyTypeObject* AST_type; +static PyTypeObject AST_type; static PyTypeObject *mod_type; static PyObject* ast2obj_mod(void*); static PyTypeObject *Module_type; @@ -351,13 +351,16 @@ "ifs", }; static PyTypeObject *excepthandler_type; +static char *excepthandler_attributes[] = { + "lineno", + "col_offset", +}; static PyObject* ast2obj_excepthandler(void*); -static char *excepthandler_fields[]={ +static PyTypeObject *ExceptHandler_type; +static char *ExceptHandler_fields[]={ "type", "name", "body", - "lineno", - "col_offset", }; static PyTypeObject *arguments_type; static PyObject* ast2obj_arguments(void*); @@ -391,18 +394,132 @@ }; +static int +ast_type_init(PyObject *self, PyObject *args, PyObject *kw) +{ + Py_ssize_t i, numfields = 0; + int res = -1; + PyObject *key, *value, *fields; + fields = PyObject_GetAttrString((PyObject*)Py_TYPE(self), "_fields"); + if (!fields) + PyErr_Clear(); + if (fields) { + numfields = PySequence_Size(fields); + if (numfields == -1) + goto cleanup; + } + res = 0; /* if no error occurs, this stays 0 to the end */ + if (PyTuple_GET_SIZE(args) > 0) { + if (numfields != PyTuple_GET_SIZE(args)) { + PyErr_Format(PyExc_TypeError, "%.400s constructor takes %s" + "%" PY_FORMAT_SIZE_T "d positional argument%s", + Py_TYPE(self)->tp_name, + numfields == 0 ? "" : "either 0 or ", + numfields, numfields == 1 ? "" : "s"); + res = -1; + goto cleanup; + } + for (i = 0; i < PyTuple_GET_SIZE(args); i++) { + /* cannot be reached when fields is NULL */ + PyObject *name = PySequence_GetItem(fields, i); + if (!name) { + res = -1; + goto cleanup; + } + res = PyObject_SetAttr(self, name, PyTuple_GET_ITEM(args, i)); + Py_DECREF(name); + if (res < 0) + goto cleanup; + } + } + if (kw) { + i = 0; /* needed by PyDict_Next */ + while (PyDict_Next(kw, &i, &key, &value)) { + res = PyObject_SetAttr(self, key, value); + if (res < 0) + goto cleanup; + } + } + cleanup: + Py_XDECREF(fields); + return res; +} + +/* Pickling support */ +static PyObject * +ast_type_reduce(PyObject *self, PyObject *unused) +{ + PyObject *res; + PyObject *dict = PyObject_GetAttrString(self, "__dict__"); + if (dict == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) + PyErr_Clear(); + else + return NULL; + } + if (dict) { + res = Py_BuildValue("O()O", Py_TYPE(self), dict); + Py_DECREF(dict); + return res; + } + return Py_BuildValue("O()", Py_TYPE(self)); +} + +static PyMethodDef ast_type_methods[] = { + {"__reduce__", ast_type_reduce, METH_NOARGS, NULL}, + {NULL} +}; + +static PyTypeObject AST_type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "_ast.AST", + sizeof(PyObject), + 0, + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + ast_type_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)ast_type_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_Del, /* tp_free */ +}; + + static PyTypeObject* make_type(char *type, PyTypeObject* base, char**fields, int num_fields) { PyObject *fnames, *result; int i; - if (num_fields) { - fnames = PyTuple_New(num_fields); - if (!fnames) return NULL; - } else { - fnames = Py_None; - Py_INCREF(Py_None); - } - for(i=0; i < num_fields; i++) { + fnames = PyTuple_New(num_fields); + if (!fnames) return NULL; + for (i = 0; i < num_fields; i++) { PyObject *field = PyUnicode_FromString(fields[i]); if (!field) { Py_DECREF(fnames); @@ -419,7 +536,7 @@ static int add_attributes(PyTypeObject* type, char**attrs, int num_fields) { int i, result; - PyObject *s, *l = PyList_New(num_fields); + PyObject *s, *l = PyTuple_New(num_fields); if (!l) return 0; for(i = 0; i < num_fields; i++) { s = PyUnicode_FromString(attrs[i]); @@ -427,13 +544,15 @@ Py_DECREF(l); return 0; } - PyList_SET_ITEM(l, i, s); + PyTuple_SET_ITEM(l, i, s); } result = PyObject_SetAttrString((PyObject*)type, "_attributes", l) >= 0; Py_DECREF(l); return result; } +/* Conversion AST -> Python */ + static PyObject* ast2obj_list(asdl_seq *seq, PyObject* (*func)(void*)) { int i, n = asdl_seq_LEN(seq); @@ -467,12 +586,47 @@ return PyLong_FromLong(b); } +/* Conversion Python -> AST */ + +static int obj2ast_object(PyObject* obj, PyObject** out, PyArena* arena) +{ + if (obj == Py_None) + obj = NULL; + if (obj) + PyArena_AddPyObject(arena, obj); + Py_XINCREF(obj); + *out = obj; + return 0; +} + +#define obj2ast_identifier obj2ast_object +#define obj2ast_string obj2ast_object + +static int obj2ast_int(PyObject* obj, int* out, PyArena* arena) +{ + int i; + if (!PyLong_Check(obj)) { + PyObject *s = PyObject_Repr(obj); + if (s == NULL) return 1; + PyErr_Format(PyExc_ValueError, "invalid integer value: %.400s", + PyString_AS_STRING(s)); + Py_DECREF(s); + return 1; + } + + i = (int)PyLong_AsLong(obj); + if (i == -1 && PyErr_Occurred()) + return 1; + *out = i; + return 0; +} + + static int init_types(void) { static int initialized; if (initialized) return 1; - AST_type = make_type("AST", &PyBaseObject_Type, NULL, 0); - mod_type = make_type("mod", AST_type, NULL, 0); + mod_type = make_type("mod", &AST_type, NULL, 0); if (!mod_type) return 0; if (!add_attributes(mod_type, NULL, 0)) return 0; Module_type = make_type("Module", mod_type, Module_fields, 1); @@ -485,7 +639,7 @@ if (!Expression_type) return 0; Suite_type = make_type("Suite", mod_type, Suite_fields, 1); if (!Suite_type) return 0; - stmt_type = make_type("stmt", AST_type, NULL, 0); + stmt_type = make_type("stmt", &AST_type, NULL, 0); if (!stmt_type) return 0; if (!add_attributes(stmt_type, stmt_attributes, 2)) return 0; FunctionDef_type = make_type("FunctionDef", stmt_type, @@ -535,7 +689,7 @@ if (!Break_type) return 0; Continue_type = make_type("Continue", stmt_type, NULL, 0); if (!Continue_type) return 0; - expr_type = make_type("expr", AST_type, NULL, 0); + expr_type = make_type("expr", &AST_type, NULL, 0); if (!expr_type) return 0; if (!add_attributes(expr_type, expr_attributes, 2)) return 0; BoolOp_type = make_type("BoolOp", expr_type, BoolOp_fields, 2); @@ -587,7 +741,7 @@ if (!List_type) return 0; Tuple_type = make_type("Tuple", expr_type, Tuple_fields, 2); if (!Tuple_type) return 0; - expr_context_type = make_type("expr_context", AST_type, NULL, 0); + expr_context_type = make_type("expr_context", &AST_type, NULL, 0); if (!expr_context_type) return 0; if (!add_attributes(expr_context_type, NULL, 0)) return 0; Load_type = make_type("Load", expr_context_type, NULL, 0); @@ -614,7 +768,7 @@ if (!Param_type) return 0; Param_singleton = PyType_GenericNew(Param_type, NULL, NULL); if (!Param_singleton) return 0; - slice_type = make_type("slice", AST_type, NULL, 0); + slice_type = make_type("slice", &AST_type, NULL, 0); if (!slice_type) return 0; if (!add_attributes(slice_type, NULL, 0)) return 0; Slice_type = make_type("Slice", slice_type, Slice_fields, 3); @@ -623,7 +777,7 @@ if (!ExtSlice_type) return 0; Index_type = make_type("Index", slice_type, Index_fields, 1); if (!Index_type) return 0; - boolop_type = make_type("boolop", AST_type, NULL, 0); + boolop_type = make_type("boolop", &AST_type, NULL, 0); if (!boolop_type) return 0; if (!add_attributes(boolop_type, NULL, 0)) return 0; And_type = make_type("And", boolop_type, NULL, 0); @@ -634,7 +788,7 @@ if (!Or_type) return 0; Or_singleton = PyType_GenericNew(Or_type, NULL, NULL); if (!Or_singleton) return 0; - operator_type = make_type("operator", AST_type, NULL, 0); + operator_type = make_type("operator", &AST_type, NULL, 0); if (!operator_type) return 0; if (!add_attributes(operator_type, NULL, 0)) return 0; Add_type = make_type("Add", operator_type, NULL, 0); @@ -685,7 +839,7 @@ if (!FloorDiv_type) return 0; FloorDiv_singleton = PyType_GenericNew(FloorDiv_type, NULL, NULL); if (!FloorDiv_singleton) return 0; - unaryop_type = make_type("unaryop", AST_type, NULL, 0); + unaryop_type = make_type("unaryop", &AST_type, NULL, 0); if (!unaryop_type) return 0; if (!add_attributes(unaryop_type, NULL, 0)) return 0; Invert_type = make_type("Invert", unaryop_type, NULL, 0); @@ -704,7 +858,7 @@ if (!USub_type) return 0; USub_singleton = PyType_GenericNew(USub_type, NULL, NULL); if (!USub_singleton) return 0; - cmpop_type = make_type("cmpop", AST_type, NULL, 0); + cmpop_type = make_type("cmpop", &AST_type, NULL, 0); if (!cmpop_type) return 0; if (!add_attributes(cmpop_type, NULL, 0)) return 0; Eq_type = make_type("Eq", cmpop_type, NULL, 0); @@ -747,24 +901,47 @@ if (!NotIn_type) return 0; NotIn_singleton = PyType_GenericNew(NotIn_type, NULL, NULL); if (!NotIn_singleton) return 0; - comprehension_type = make_type("comprehension", AST_type, + comprehension_type = make_type("comprehension", &AST_type, comprehension_fields, 3); if (!comprehension_type) return 0; - excepthandler_type = make_type("excepthandler", AST_type, - excepthandler_fields, 5); + excepthandler_type = make_type("excepthandler", &AST_type, NULL, 0); if (!excepthandler_type) return 0; - arguments_type = make_type("arguments", AST_type, arguments_fields, 8); + if (!add_attributes(excepthandler_type, excepthandler_attributes, 2)) + return 0; + ExceptHandler_type = make_type("ExceptHandler", excepthandler_type, + ExceptHandler_fields, 3); + if (!ExceptHandler_type) return 0; + arguments_type = make_type("arguments", &AST_type, arguments_fields, 8); if (!arguments_type) return 0; - arg_type = make_type("arg", AST_type, arg_fields, 2); + arg_type = make_type("arg", &AST_type, arg_fields, 2); if (!arg_type) return 0; - keyword_type = make_type("keyword", AST_type, keyword_fields, 2); + keyword_type = make_type("keyword", &AST_type, keyword_fields, 2); if (!keyword_type) return 0; - alias_type = make_type("alias", AST_type, alias_fields, 2); + alias_type = make_type("alias", &AST_type, alias_fields, 2); if (!alias_type) return 0; initialized = 1; return 1; } +static int obj2ast_mod(PyObject* obj, mod_ty* out, PyArena* arena); +static int obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena); +static int obj2ast_expr(PyObject* obj, expr_ty* out, PyArena* arena); +static int obj2ast_expr_context(PyObject* obj, expr_context_ty* out, PyArena* + arena); +static int obj2ast_slice(PyObject* obj, slice_ty* out, PyArena* arena); +static int obj2ast_boolop(PyObject* obj, boolop_ty* out, PyArena* arena); +static int obj2ast_operator(PyObject* obj, operator_ty* out, PyArena* arena); +static int obj2ast_unaryop(PyObject* obj, unaryop_ty* out, PyArena* arena); +static int obj2ast_cmpop(PyObject* obj, cmpop_ty* out, PyArena* arena); +static int obj2ast_comprehension(PyObject* obj, comprehension_ty* out, PyArena* + arena); +static int obj2ast_excepthandler(PyObject* obj, excepthandler_ty* out, PyArena* + arena); +static int obj2ast_arguments(PyObject* obj, arguments_ty* out, PyArena* arena); +static int obj2ast_arg(PyObject* obj, arg_ty* out, PyArena* arena); +static int obj2ast_keyword(PyObject* obj, keyword_ty* out, PyArena* arena); +static int obj2ast_alias(PyObject* obj, alias_ty* out, PyArena* arena); + mod_ty Module(asdl_seq * body, PyArena *arena) { @@ -1852,16 +2029,17 @@ } excepthandler_ty -excepthandler(expr_ty type, identifier name, asdl_seq * body, int lineno, int +ExceptHandler(expr_ty type, identifier name, asdl_seq * body, int lineno, int col_offset, PyArena *arena) { excepthandler_ty p; p = (excepthandler_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; - p->type = type; - p->name = name; - p->body = body; + p->kind = ExceptHandler_kind; + p->v.ExceptHandler.type = type; + p->v.ExceptHandler.name = name; + p->v.ExceptHandler.body = body; p->lineno = lineno; p->col_offset = col_offset; return p; @@ -2768,8 +2946,11 @@ case Param: Py_INCREF(Param_singleton); return Param_singleton; + default: + /* should never happen, but just in case ... */ + PyErr_Format(PyExc_SystemError, "unknown expr_context found"); + return NULL; } - return NULL; /* cannot happen */ } PyObject* ast2obj_slice(void* _o) @@ -2836,8 +3017,11 @@ case Or: Py_INCREF(Or_singleton); return Or_singleton; + default: + /* should never happen, but just in case ... */ + PyErr_Format(PyExc_SystemError, "unknown boolop found"); + return NULL; } - return NULL; /* cannot happen */ } PyObject* ast2obj_operator(operator_ty o) { @@ -2878,8 +3062,11 @@ case FloorDiv: Py_INCREF(FloorDiv_singleton); return FloorDiv_singleton; + default: + /* should never happen, but just in case ... */ + PyErr_Format(PyExc_SystemError, "unknown operator found"); + return NULL; } - return NULL; /* cannot happen */ } PyObject* ast2obj_unaryop(unaryop_ty o) { @@ -2896,8 +3083,11 @@ case USub: Py_INCREF(USub_singleton); return USub_singleton; + default: + /* should never happen, but just in case ... */ + PyErr_Format(PyExc_SystemError, "unknown unaryop found"); + return NULL; } - return NULL; /* cannot happen */ } PyObject* ast2obj_cmpop(cmpop_ty o) { @@ -2932,8 +3122,11 @@ case NotIn: Py_INCREF(NotIn_singleton); return NotIn_singleton; + default: + /* should never happen, but just in case ... */ + PyErr_Format(PyExc_SystemError, "unknown cmpop found"); + return NULL; } - return NULL; /* cannot happen */ } PyObject* ast2obj_comprehension(void* _o) @@ -2979,31 +3172,35 @@ return Py_None; } - result = PyType_GenericNew(excepthandler_type, NULL, NULL); - if (!result) return NULL; - value = ast2obj_expr(o->type); - if (!value) goto failed; - if (PyObject_SetAttrString(result, "type", value) == -1) - goto failed; - Py_DECREF(value); - value = ast2obj_identifier(o->name); - if (!value) goto failed; - if (PyObject_SetAttrString(result, "name", value) == -1) - goto failed; - Py_DECREF(value); - value = ast2obj_list(o->body, ast2obj_stmt); - if (!value) goto failed; - if (PyObject_SetAttrString(result, "body", value) == -1) - goto failed; - Py_DECREF(value); + switch (o->kind) { + case ExceptHandler_kind: + result = PyType_GenericNew(ExceptHandler_type, NULL, NULL); + if (!result) goto failed; + value = ast2obj_expr(o->v.ExceptHandler.type); + if (!value) goto failed; + if (PyObject_SetAttrString(result, "type", value) == -1) + goto failed; + Py_DECREF(value); + value = ast2obj_identifier(o->v.ExceptHandler.name); + if (!value) goto failed; + if (PyObject_SetAttrString(result, "name", value) == -1) + goto failed; + Py_DECREF(value); + value = ast2obj_list(o->v.ExceptHandler.body, ast2obj_stmt); + if (!value) goto failed; + if (PyObject_SetAttrString(result, "body", value) == -1) + goto failed; + Py_DECREF(value); + break; + } value = ast2obj_int(o->lineno); if (!value) goto failed; - if (PyObject_SetAttrString(result, "lineno", value) == -1) + if (PyObject_SetAttrString(result, "lineno", value) < 0) goto failed; Py_DECREF(value); value = ast2obj_int(o->col_offset); if (!value) goto failed; - if (PyObject_SetAttrString(result, "col_offset", value) == -1) + if (PyObject_SetAttrString(result, "col_offset", value) < 0) goto failed; Py_DECREF(value); return result; @@ -3160,6 +3357,3033 @@ } +int +obj2ast_mod(PyObject* obj, mod_ty* out, PyArena* arena) +{ + PyObject* tmp = NULL; + + + if (obj == Py_None) { + *out = NULL; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Module_type)) { + asdl_seq* body; + + if (PyObject_HasAttrString(obj, "body")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "body"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "Module field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + body = asdl_seq_new(len, arena); + if (body == NULL) goto failed; + for (i = 0; i < len; i++) { + stmt_ty value; + res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(body, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from Module"); + return 1; + } + *out = Module(body, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Interactive_type)) { + asdl_seq* body; + + if (PyObject_HasAttrString(obj, "body")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "body"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "Interactive field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + body = asdl_seq_new(len, arena); + if (body == NULL) goto failed; + for (i = 0; i < len; i++) { + stmt_ty value; + res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(body, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from Interactive"); + return 1; + } + *out = Interactive(body, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Expression_type)) { + expr_ty body; + + if (PyObject_HasAttrString(obj, "body")) { + int res; + tmp = PyObject_GetAttrString(obj, "body"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &body, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from Expression"); + return 1; + } + *out = Expression(body, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Suite_type)) { + asdl_seq* body; + + if (PyObject_HasAttrString(obj, "body")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "body"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "Suite field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + body = asdl_seq_new(len, arena); + if (body == NULL) goto failed; + for (i = 0; i < len; i++) { + stmt_ty value; + res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(body, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from Suite"); + return 1; + } + *out = Suite(body, arena); + if (*out == NULL) goto failed; + return 0; + } + + tmp = PyObject_Repr(obj); + if (tmp == NULL) goto failed; + PyErr_Format(PyExc_TypeError, "expected some sort of mod, but got %.400s", PyString_AS_STRING(tmp)); +failed: + Py_XDECREF(tmp); + return 1; +} + +int +obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena) +{ + PyObject* tmp = NULL; + + int lineno; + int col_offset; + + if (obj == Py_None) { + *out = NULL; + return 0; + } + if (PyObject_HasAttrString(obj, "lineno")) { + int res; + tmp = PyObject_GetAttrString(obj, "lineno"); + if (tmp == NULL) goto failed; + res = obj2ast_int(tmp, &lineno, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"lineno\" missing from stmt"); + return 1; + } + if (PyObject_HasAttrString(obj, "col_offset")) { + int res; + tmp = PyObject_GetAttrString(obj, "col_offset"); + if (tmp == NULL) goto failed; + res = obj2ast_int(tmp, &col_offset, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"col_offset\" missing from stmt"); + return 1; + } + if (PyObject_IsInstance(obj, (PyObject*)FunctionDef_type)) { + identifier name; + arguments_ty args; + asdl_seq* body; + asdl_seq* decorator_list; + expr_ty returns; + + if (PyObject_HasAttrString(obj, "name")) { + int res; + tmp = PyObject_GetAttrString(obj, "name"); + if (tmp == NULL) goto failed; + res = obj2ast_identifier(tmp, &name, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"name\" missing from FunctionDef"); + return 1; + } + if (PyObject_HasAttrString(obj, "args")) { + int res; + tmp = PyObject_GetAttrString(obj, "args"); + if (tmp == NULL) goto failed; + res = obj2ast_arguments(tmp, &args, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"args\" missing from FunctionDef"); + return 1; + } + if (PyObject_HasAttrString(obj, "body")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "body"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "FunctionDef field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + body = asdl_seq_new(len, arena); + if (body == NULL) goto failed; + for (i = 0; i < len; i++) { + stmt_ty value; + res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(body, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from FunctionDef"); + return 1; + } + if (PyObject_HasAttrString(obj, "decorator_list")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "decorator_list"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "FunctionDef field \"decorator_list\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + decorator_list = asdl_seq_new(len, arena); + if (decorator_list == NULL) goto failed; + for (i = 0; i < len; i++) { + expr_ty value; + res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(decorator_list, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"decorator_list\" missing from FunctionDef"); + return 1; + } + if (PyObject_HasAttrString(obj, "returns")) { + int res; + tmp = PyObject_GetAttrString(obj, "returns"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &returns, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + returns = NULL; + } + *out = FunctionDef(name, args, body, decorator_list, returns, + lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)ClassDef_type)) { + identifier name; + asdl_seq* bases; + asdl_seq* keywords; + expr_ty starargs; + expr_ty kwargs; + asdl_seq* body; + asdl_seq* decorator_list; + + if (PyObject_HasAttrString(obj, "name")) { + int res; + tmp = PyObject_GetAttrString(obj, "name"); + if (tmp == NULL) goto failed; + res = obj2ast_identifier(tmp, &name, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"name\" missing from ClassDef"); + return 1; + } + if (PyObject_HasAttrString(obj, "bases")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "bases"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "ClassDef field \"bases\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + bases = asdl_seq_new(len, arena); + if (bases == NULL) goto failed; + for (i = 0; i < len; i++) { + expr_ty value; + res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(bases, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"bases\" missing from ClassDef"); + return 1; + } + if (PyObject_HasAttrString(obj, "keywords")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "keywords"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "ClassDef field \"keywords\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + keywords = asdl_seq_new(len, arena); + if (keywords == NULL) goto failed; + for (i = 0; i < len; i++) { + keyword_ty value; + res = obj2ast_keyword(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(keywords, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"keywords\" missing from ClassDef"); + return 1; + } + if (PyObject_HasAttrString(obj, "starargs")) { + int res; + tmp = PyObject_GetAttrString(obj, "starargs"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &starargs, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + starargs = NULL; + } + if (PyObject_HasAttrString(obj, "kwargs")) { + int res; + tmp = PyObject_GetAttrString(obj, "kwargs"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &kwargs, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + kwargs = NULL; + } + if (PyObject_HasAttrString(obj, "body")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "body"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "ClassDef field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + body = asdl_seq_new(len, arena); + if (body == NULL) goto failed; + for (i = 0; i < len; i++) { + stmt_ty value; + res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(body, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from ClassDef"); + return 1; + } + if (PyObject_HasAttrString(obj, "decorator_list")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "decorator_list"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "ClassDef field \"decorator_list\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + decorator_list = asdl_seq_new(len, arena); + if (decorator_list == NULL) goto failed; + for (i = 0; i < len; i++) { + expr_ty value; + res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(decorator_list, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"decorator_list\" missing from ClassDef"); + return 1; + } + *out = ClassDef(name, bases, keywords, starargs, kwargs, body, + decorator_list, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Return_type)) { + expr_ty value; + + if (PyObject_HasAttrString(obj, "value")) { + int res; + tmp = PyObject_GetAttrString(obj, "value"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &value, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + value = NULL; + } + *out = Return(value, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Delete_type)) { + asdl_seq* targets; + + if (PyObject_HasAttrString(obj, "targets")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "targets"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "Delete field \"targets\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + targets = asdl_seq_new(len, arena); + if (targets == NULL) goto failed; + for (i = 0; i < len; i++) { + expr_ty value; + res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(targets, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"targets\" missing from Delete"); + return 1; + } + *out = Delete(targets, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Assign_type)) { + asdl_seq* targets; + expr_ty value; + + if (PyObject_HasAttrString(obj, "targets")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "targets"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "Assign field \"targets\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + targets = asdl_seq_new(len, arena); + if (targets == NULL) goto failed; + for (i = 0; i < len; i++) { + expr_ty value; + res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(targets, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"targets\" missing from Assign"); + return 1; + } + if (PyObject_HasAttrString(obj, "value")) { + int res; + tmp = PyObject_GetAttrString(obj, "value"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &value, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from Assign"); + return 1; + } + *out = Assign(targets, value, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)AugAssign_type)) { + expr_ty target; + operator_ty op; + expr_ty value; + + if (PyObject_HasAttrString(obj, "target")) { + int res; + tmp = PyObject_GetAttrString(obj, "target"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &target, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"target\" missing from AugAssign"); + return 1; + } + if (PyObject_HasAttrString(obj, "op")) { + int res; + tmp = PyObject_GetAttrString(obj, "op"); + if (tmp == NULL) goto failed; + res = obj2ast_operator(tmp, &op, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"op\" missing from AugAssign"); + return 1; + } + if (PyObject_HasAttrString(obj, "value")) { + int res; + tmp = PyObject_GetAttrString(obj, "value"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &value, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from AugAssign"); + return 1; + } + *out = AugAssign(target, op, value, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)For_type)) { + expr_ty target; + expr_ty iter; + asdl_seq* body; + asdl_seq* orelse; + + if (PyObject_HasAttrString(obj, "target")) { + int res; + tmp = PyObject_GetAttrString(obj, "target"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &target, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"target\" missing from For"); + return 1; + } + if (PyObject_HasAttrString(obj, "iter")) { + int res; + tmp = PyObject_GetAttrString(obj, "iter"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &iter, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"iter\" missing from For"); + return 1; + } + if (PyObject_HasAttrString(obj, "body")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "body"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "For field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + body = asdl_seq_new(len, arena); + if (body == NULL) goto failed; + for (i = 0; i < len; i++) { + stmt_ty value; + res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(body, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from For"); + return 1; + } + if (PyObject_HasAttrString(obj, "orelse")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "orelse"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "For field \"orelse\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + orelse = asdl_seq_new(len, arena); + if (orelse == NULL) goto failed; + for (i = 0; i < len; i++) { + stmt_ty value; + res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(orelse, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"orelse\" missing from For"); + return 1; + } + *out = For(target, iter, body, orelse, lineno, col_offset, + arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)While_type)) { + expr_ty test; + asdl_seq* body; + asdl_seq* orelse; + + if (PyObject_HasAttrString(obj, "test")) { + int res; + tmp = PyObject_GetAttrString(obj, "test"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &test, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"test\" missing from While"); + return 1; + } + if (PyObject_HasAttrString(obj, "body")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "body"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "While field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + body = asdl_seq_new(len, arena); + if (body == NULL) goto failed; + for (i = 0; i < len; i++) { + stmt_ty value; + res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(body, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from While"); + return 1; + } + if (PyObject_HasAttrString(obj, "orelse")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "orelse"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "While field \"orelse\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + orelse = asdl_seq_new(len, arena); + if (orelse == NULL) goto failed; + for (i = 0; i < len; i++) { + stmt_ty value; + res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(orelse, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"orelse\" missing from While"); + return 1; + } + *out = While(test, body, orelse, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)If_type)) { + expr_ty test; + asdl_seq* body; + asdl_seq* orelse; + + if (PyObject_HasAttrString(obj, "test")) { + int res; + tmp = PyObject_GetAttrString(obj, "test"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &test, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"test\" missing from If"); + return 1; + } + if (PyObject_HasAttrString(obj, "body")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "body"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "If field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + body = asdl_seq_new(len, arena); + if (body == NULL) goto failed; + for (i = 0; i < len; i++) { + stmt_ty value; + res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(body, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from If"); + return 1; + } + if (PyObject_HasAttrString(obj, "orelse")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "orelse"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "If field \"orelse\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + orelse = asdl_seq_new(len, arena); + if (orelse == NULL) goto failed; + for (i = 0; i < len; i++) { + stmt_ty value; + res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(orelse, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"orelse\" missing from If"); + return 1; + } + *out = If(test, body, orelse, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)With_type)) { + expr_ty context_expr; + expr_ty optional_vars; + asdl_seq* body; + + if (PyObject_HasAttrString(obj, "context_expr")) { + int res; + tmp = PyObject_GetAttrString(obj, "context_expr"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &context_expr, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"context_expr\" missing from With"); + return 1; + } + if (PyObject_HasAttrString(obj, "optional_vars")) { + int res; + tmp = PyObject_GetAttrString(obj, "optional_vars"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &optional_vars, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + optional_vars = NULL; + } + if (PyObject_HasAttrString(obj, "body")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "body"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "With field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + body = asdl_seq_new(len, arena); + if (body == NULL) goto failed; + for (i = 0; i < len; i++) { + stmt_ty value; + res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(body, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from With"); + return 1; + } + *out = With(context_expr, optional_vars, body, lineno, + col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Raise_type)) { + expr_ty exc; + expr_ty cause; + + if (PyObject_HasAttrString(obj, "exc")) { + int res; + tmp = PyObject_GetAttrString(obj, "exc"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &exc, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + exc = NULL; + } + if (PyObject_HasAttrString(obj, "cause")) { + int res; + tmp = PyObject_GetAttrString(obj, "cause"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &cause, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + cause = NULL; + } + *out = Raise(exc, cause, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)TryExcept_type)) { + asdl_seq* body; + asdl_seq* handlers; + asdl_seq* orelse; + + if (PyObject_HasAttrString(obj, "body")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "body"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "TryExcept field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + body = asdl_seq_new(len, arena); + if (body == NULL) goto failed; + for (i = 0; i < len; i++) { + stmt_ty value; + res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(body, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from TryExcept"); + return 1; + } + if (PyObject_HasAttrString(obj, "handlers")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "handlers"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "TryExcept field \"handlers\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + handlers = asdl_seq_new(len, arena); + if (handlers == NULL) goto failed; + for (i = 0; i < len; i++) { + excepthandler_ty value; + res = obj2ast_excepthandler(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(handlers, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"handlers\" missing from TryExcept"); + return 1; + } + if (PyObject_HasAttrString(obj, "orelse")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "orelse"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "TryExcept field \"orelse\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + orelse = asdl_seq_new(len, arena); + if (orelse == NULL) goto failed; + for (i = 0; i < len; i++) { + stmt_ty value; + res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(orelse, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"orelse\" missing from TryExcept"); + return 1; + } + *out = TryExcept(body, handlers, orelse, lineno, col_offset, + arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)TryFinally_type)) { + asdl_seq* body; + asdl_seq* finalbody; + + if (PyObject_HasAttrString(obj, "body")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "body"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "TryFinally field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + body = asdl_seq_new(len, arena); + if (body == NULL) goto failed; + for (i = 0; i < len; i++) { + stmt_ty value; + res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(body, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from TryFinally"); + return 1; + } + if (PyObject_HasAttrString(obj, "finalbody")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "finalbody"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "TryFinally field \"finalbody\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + finalbody = asdl_seq_new(len, arena); + if (finalbody == NULL) goto failed; + for (i = 0; i < len; i++) { + stmt_ty value; + res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(finalbody, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"finalbody\" missing from TryFinally"); + return 1; + } + *out = TryFinally(body, finalbody, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Assert_type)) { + expr_ty test; + expr_ty msg; + + if (PyObject_HasAttrString(obj, "test")) { + int res; + tmp = PyObject_GetAttrString(obj, "test"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &test, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"test\" missing from Assert"); + return 1; + } + if (PyObject_HasAttrString(obj, "msg")) { + int res; + tmp = PyObject_GetAttrString(obj, "msg"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &msg, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + msg = NULL; + } + *out = Assert(test, msg, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Import_type)) { + asdl_seq* names; + + if (PyObject_HasAttrString(obj, "names")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "names"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "Import field \"names\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + names = asdl_seq_new(len, arena); + if (names == NULL) goto failed; + for (i = 0; i < len; i++) { + alias_ty value; + res = obj2ast_alias(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(names, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"names\" missing from Import"); + return 1; + } + *out = Import(names, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)ImportFrom_type)) { + identifier module; + asdl_seq* names; + int level; + + if (PyObject_HasAttrString(obj, "module")) { + int res; + tmp = PyObject_GetAttrString(obj, "module"); + if (tmp == NULL) goto failed; + res = obj2ast_identifier(tmp, &module, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"module\" missing from ImportFrom"); + return 1; + } + if (PyObject_HasAttrString(obj, "names")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "names"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "ImportFrom field \"names\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + names = asdl_seq_new(len, arena); + if (names == NULL) goto failed; + for (i = 0; i < len; i++) { + alias_ty value; + res = obj2ast_alias(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(names, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"names\" missing from ImportFrom"); + return 1; + } + if (PyObject_HasAttrString(obj, "level")) { + int res; + tmp = PyObject_GetAttrString(obj, "level"); + if (tmp == NULL) goto failed; + res = obj2ast_int(tmp, &level, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + level = 0; + } + *out = ImportFrom(module, names, level, lineno, col_offset, + arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Global_type)) { + asdl_seq* names; + + if (PyObject_HasAttrString(obj, "names")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "names"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "Global field \"names\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + names = asdl_seq_new(len, arena); + if (names == NULL) goto failed; + for (i = 0; i < len; i++) { + identifier value; + res = obj2ast_identifier(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(names, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"names\" missing from Global"); + return 1; + } + *out = Global(names, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Nonlocal_type)) { + asdl_seq* names; + + if (PyObject_HasAttrString(obj, "names")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "names"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "Nonlocal field \"names\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + names = asdl_seq_new(len, arena); + if (names == NULL) goto failed; + for (i = 0; i < len; i++) { + identifier value; + res = obj2ast_identifier(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(names, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"names\" missing from Nonlocal"); + return 1; + } + *out = Nonlocal(names, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Expr_type)) { + expr_ty value; + + if (PyObject_HasAttrString(obj, "value")) { + int res; + tmp = PyObject_GetAttrString(obj, "value"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &value, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from Expr"); + return 1; + } + *out = Expr(value, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Pass_type)) { + + *out = Pass(lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Break_type)) { + + *out = Break(lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Continue_type)) { + + *out = Continue(lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + + tmp = PyObject_Repr(obj); + if (tmp == NULL) goto failed; + PyErr_Format(PyExc_TypeError, "expected some sort of stmt, but got %.400s", PyString_AS_STRING(tmp)); +failed: + Py_XDECREF(tmp); + return 1; +} + +int +obj2ast_expr(PyObject* obj, expr_ty* out, PyArena* arena) +{ + PyObject* tmp = NULL; + + int lineno; + int col_offset; + + if (obj == Py_None) { + *out = NULL; + return 0; + } + if (PyObject_HasAttrString(obj, "lineno")) { + int res; + tmp = PyObject_GetAttrString(obj, "lineno"); + if (tmp == NULL) goto failed; + res = obj2ast_int(tmp, &lineno, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"lineno\" missing from expr"); + return 1; + } + if (PyObject_HasAttrString(obj, "col_offset")) { + int res; + tmp = PyObject_GetAttrString(obj, "col_offset"); + if (tmp == NULL) goto failed; + res = obj2ast_int(tmp, &col_offset, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"col_offset\" missing from expr"); + return 1; + } + if (PyObject_IsInstance(obj, (PyObject*)BoolOp_type)) { + boolop_ty op; + asdl_seq* values; + + if (PyObject_HasAttrString(obj, "op")) { + int res; + tmp = PyObject_GetAttrString(obj, "op"); + if (tmp == NULL) goto failed; + res = obj2ast_boolop(tmp, &op, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"op\" missing from BoolOp"); + return 1; + } + if (PyObject_HasAttrString(obj, "values")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "values"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "BoolOp field \"values\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + values = asdl_seq_new(len, arena); + if (values == NULL) goto failed; + for (i = 0; i < len; i++) { + expr_ty value; + res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(values, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"values\" missing from BoolOp"); + return 1; + } + *out = BoolOp(op, values, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)BinOp_type)) { + expr_ty left; + operator_ty op; + expr_ty right; + + if (PyObject_HasAttrString(obj, "left")) { + int res; + tmp = PyObject_GetAttrString(obj, "left"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &left, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"left\" missing from BinOp"); + return 1; + } + if (PyObject_HasAttrString(obj, "op")) { + int res; + tmp = PyObject_GetAttrString(obj, "op"); + if (tmp == NULL) goto failed; + res = obj2ast_operator(tmp, &op, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"op\" missing from BinOp"); + return 1; + } + if (PyObject_HasAttrString(obj, "right")) { + int res; + tmp = PyObject_GetAttrString(obj, "right"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &right, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"right\" missing from BinOp"); + return 1; + } + *out = BinOp(left, op, right, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)UnaryOp_type)) { + unaryop_ty op; + expr_ty operand; + + if (PyObject_HasAttrString(obj, "op")) { + int res; + tmp = PyObject_GetAttrString(obj, "op"); + if (tmp == NULL) goto failed; + res = obj2ast_unaryop(tmp, &op, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"op\" missing from UnaryOp"); + return 1; + } + if (PyObject_HasAttrString(obj, "operand")) { + int res; + tmp = PyObject_GetAttrString(obj, "operand"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &operand, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"operand\" missing from UnaryOp"); + return 1; + } + *out = UnaryOp(op, operand, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Lambda_type)) { + arguments_ty args; + expr_ty body; + + if (PyObject_HasAttrString(obj, "args")) { + int res; + tmp = PyObject_GetAttrString(obj, "args"); + if (tmp == NULL) goto failed; + res = obj2ast_arguments(tmp, &args, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"args\" missing from Lambda"); + return 1; + } + if (PyObject_HasAttrString(obj, "body")) { + int res; + tmp = PyObject_GetAttrString(obj, "body"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &body, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from Lambda"); + return 1; + } + *out = Lambda(args, body, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)IfExp_type)) { + expr_ty test; + expr_ty body; + expr_ty orelse; + + if (PyObject_HasAttrString(obj, "test")) { + int res; + tmp = PyObject_GetAttrString(obj, "test"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &test, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"test\" missing from IfExp"); + return 1; + } + if (PyObject_HasAttrString(obj, "body")) { + int res; + tmp = PyObject_GetAttrString(obj, "body"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &body, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from IfExp"); + return 1; + } + if (PyObject_HasAttrString(obj, "orelse")) { + int res; + tmp = PyObject_GetAttrString(obj, "orelse"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &orelse, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"orelse\" missing from IfExp"); + return 1; + } + *out = IfExp(test, body, orelse, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Dict_type)) { + asdl_seq* keys; + asdl_seq* values; + + if (PyObject_HasAttrString(obj, "keys")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "keys"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "Dict field \"keys\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + keys = asdl_seq_new(len, arena); + if (keys == NULL) goto failed; + for (i = 0; i < len; i++) { + expr_ty value; + res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(keys, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"keys\" missing from Dict"); + return 1; + } + if (PyObject_HasAttrString(obj, "values")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "values"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "Dict field \"values\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + values = asdl_seq_new(len, arena); + if (values == NULL) goto failed; + for (i = 0; i < len; i++) { + expr_ty value; + res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(values, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"values\" missing from Dict"); + return 1; + } + *out = Dict(keys, values, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Set_type)) { + asdl_seq* elts; + + if (PyObject_HasAttrString(obj, "elts")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "elts"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "Set field \"elts\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + elts = asdl_seq_new(len, arena); + if (elts == NULL) goto failed; + for (i = 0; i < len; i++) { + expr_ty value; + res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(elts, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"elts\" missing from Set"); + return 1; + } + *out = Set(elts, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)ListComp_type)) { + expr_ty elt; + asdl_seq* generators; + + if (PyObject_HasAttrString(obj, "elt")) { + int res; + tmp = PyObject_GetAttrString(obj, "elt"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &elt, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"elt\" missing from ListComp"); + return 1; + } + if (PyObject_HasAttrString(obj, "generators")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "generators"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "ListComp field \"generators\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + generators = asdl_seq_new(len, arena); + if (generators == NULL) goto failed; + for (i = 0; i < len; i++) { + comprehension_ty value; + res = obj2ast_comprehension(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(generators, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"generators\" missing from ListComp"); + return 1; + } + *out = ListComp(elt, generators, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)SetComp_type)) { + expr_ty elt; + asdl_seq* generators; + + if (PyObject_HasAttrString(obj, "elt")) { + int res; + tmp = PyObject_GetAttrString(obj, "elt"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &elt, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"elt\" missing from SetComp"); + return 1; + } + if (PyObject_HasAttrString(obj, "generators")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "generators"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "SetComp field \"generators\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + generators = asdl_seq_new(len, arena); + if (generators == NULL) goto failed; + for (i = 0; i < len; i++) { + comprehension_ty value; + res = obj2ast_comprehension(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(generators, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"generators\" missing from SetComp"); + return 1; + } + *out = SetComp(elt, generators, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)DictComp_type)) { + expr_ty key; + expr_ty value; + asdl_seq* generators; + + if (PyObject_HasAttrString(obj, "key")) { + int res; + tmp = PyObject_GetAttrString(obj, "key"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &key, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"key\" missing from DictComp"); + return 1; + } + if (PyObject_HasAttrString(obj, "value")) { + int res; + tmp = PyObject_GetAttrString(obj, "value"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &value, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from DictComp"); + return 1; + } + if (PyObject_HasAttrString(obj, "generators")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "generators"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "DictComp field \"generators\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + generators = asdl_seq_new(len, arena); + if (generators == NULL) goto failed; + for (i = 0; i < len; i++) { + comprehension_ty value; + res = obj2ast_comprehension(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(generators, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"generators\" missing from DictComp"); + return 1; + } + *out = DictComp(key, value, generators, lineno, col_offset, + arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)GeneratorExp_type)) { + expr_ty elt; + asdl_seq* generators; + + if (PyObject_HasAttrString(obj, "elt")) { + int res; + tmp = PyObject_GetAttrString(obj, "elt"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &elt, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"elt\" missing from GeneratorExp"); + return 1; + } + if (PyObject_HasAttrString(obj, "generators")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "generators"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "GeneratorExp field \"generators\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + generators = asdl_seq_new(len, arena); + if (generators == NULL) goto failed; + for (i = 0; i < len; i++) { + comprehension_ty value; + res = obj2ast_comprehension(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(generators, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"generators\" missing from GeneratorExp"); + return 1; + } + *out = GeneratorExp(elt, generators, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Yield_type)) { + expr_ty value; + + if (PyObject_HasAttrString(obj, "value")) { + int res; + tmp = PyObject_GetAttrString(obj, "value"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &value, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + value = NULL; + } + *out = Yield(value, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Compare_type)) { + expr_ty left; + asdl_int_seq* ops; + asdl_seq* comparators; + + if (PyObject_HasAttrString(obj, "left")) { + int res; + tmp = PyObject_GetAttrString(obj, "left"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &left, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"left\" missing from Compare"); + return 1; + } + if (PyObject_HasAttrString(obj, "ops")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "ops"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "Compare field \"ops\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + ops = asdl_int_seq_new(len, arena); + if (ops == NULL) goto failed; + for (i = 0; i < len; i++) { + cmpop_ty value; + res = obj2ast_cmpop(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(ops, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"ops\" missing from Compare"); + return 1; + } + if (PyObject_HasAttrString(obj, "comparators")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "comparators"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "Compare field \"comparators\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + comparators = asdl_seq_new(len, arena); + if (comparators == NULL) goto failed; + for (i = 0; i < len; i++) { + expr_ty value; + res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(comparators, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"comparators\" missing from Compare"); + return 1; + } + *out = Compare(left, ops, comparators, lineno, col_offset, + arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Call_type)) { + expr_ty func; + asdl_seq* args; + asdl_seq* keywords; + expr_ty starargs; + expr_ty kwargs; + + if (PyObject_HasAttrString(obj, "func")) { + int res; + tmp = PyObject_GetAttrString(obj, "func"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &func, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"func\" missing from Call"); + return 1; + } + if (PyObject_HasAttrString(obj, "args")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "args"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "Call field \"args\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + args = asdl_seq_new(len, arena); + if (args == NULL) goto failed; + for (i = 0; i < len; i++) { + expr_ty value; + res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(args, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"args\" missing from Call"); + return 1; + } + if (PyObject_HasAttrString(obj, "keywords")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "keywords"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "Call field \"keywords\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + keywords = asdl_seq_new(len, arena); + if (keywords == NULL) goto failed; + for (i = 0; i < len; i++) { + keyword_ty value; + res = obj2ast_keyword(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(keywords, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"keywords\" missing from Call"); + return 1; + } + if (PyObject_HasAttrString(obj, "starargs")) { + int res; + tmp = PyObject_GetAttrString(obj, "starargs"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &starargs, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + starargs = NULL; + } + if (PyObject_HasAttrString(obj, "kwargs")) { + int res; + tmp = PyObject_GetAttrString(obj, "kwargs"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &kwargs, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + kwargs = NULL; + } + *out = Call(func, args, keywords, starargs, kwargs, lineno, + col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Num_type)) { + object n; + + if (PyObject_HasAttrString(obj, "n")) { + int res; + tmp = PyObject_GetAttrString(obj, "n"); + if (tmp == NULL) goto failed; + res = obj2ast_object(tmp, &n, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"n\" missing from Num"); + return 1; + } + *out = Num(n, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Str_type)) { + string s; + + if (PyObject_HasAttrString(obj, "s")) { + int res; + tmp = PyObject_GetAttrString(obj, "s"); + if (tmp == NULL) goto failed; + res = obj2ast_string(tmp, &s, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"s\" missing from Str"); + return 1; + } + *out = Str(s, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Bytes_type)) { + string s; + + if (PyObject_HasAttrString(obj, "s")) { + int res; + tmp = PyObject_GetAttrString(obj, "s"); + if (tmp == NULL) goto failed; + res = obj2ast_string(tmp, &s, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"s\" missing from Bytes"); + return 1; + } + *out = Bytes(s, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Ellipsis_type)) { + + *out = Ellipsis(lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Attribute_type)) { + expr_ty value; + identifier attr; + expr_context_ty ctx; + + if (PyObject_HasAttrString(obj, "value")) { + int res; + tmp = PyObject_GetAttrString(obj, "value"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &value, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from Attribute"); + return 1; + } + if (PyObject_HasAttrString(obj, "attr")) { + int res; + tmp = PyObject_GetAttrString(obj, "attr"); + if (tmp == NULL) goto failed; + res = obj2ast_identifier(tmp, &attr, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"attr\" missing from Attribute"); + return 1; + } + if (PyObject_HasAttrString(obj, "ctx")) { + int res; + tmp = PyObject_GetAttrString(obj, "ctx"); + if (tmp == NULL) goto failed; + res = obj2ast_expr_context(tmp, &ctx, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"ctx\" missing from Attribute"); + return 1; + } + *out = Attribute(value, attr, ctx, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Subscript_type)) { + expr_ty value; + slice_ty slice; + expr_context_ty ctx; + + if (PyObject_HasAttrString(obj, "value")) { + int res; + tmp = PyObject_GetAttrString(obj, "value"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &value, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from Subscript"); + return 1; + } + if (PyObject_HasAttrString(obj, "slice")) { + int res; + tmp = PyObject_GetAttrString(obj, "slice"); + if (tmp == NULL) goto failed; + res = obj2ast_slice(tmp, &slice, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"slice\" missing from Subscript"); + return 1; + } + if (PyObject_HasAttrString(obj, "ctx")) { + int res; + tmp = PyObject_GetAttrString(obj, "ctx"); + if (tmp == NULL) goto failed; + res = obj2ast_expr_context(tmp, &ctx, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"ctx\" missing from Subscript"); + return 1; + } + *out = Subscript(value, slice, ctx, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Starred_type)) { + expr_ty value; + expr_context_ty ctx; + + if (PyObject_HasAttrString(obj, "value")) { + int res; + tmp = PyObject_GetAttrString(obj, "value"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &value, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from Starred"); + return 1; + } + if (PyObject_HasAttrString(obj, "ctx")) { + int res; + tmp = PyObject_GetAttrString(obj, "ctx"); + if (tmp == NULL) goto failed; + res = obj2ast_expr_context(tmp, &ctx, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"ctx\" missing from Starred"); + return 1; + } + *out = Starred(value, ctx, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Name_type)) { + identifier id; + expr_context_ty ctx; + + if (PyObject_HasAttrString(obj, "id")) { + int res; + tmp = PyObject_GetAttrString(obj, "id"); + if (tmp == NULL) goto failed; + res = obj2ast_identifier(tmp, &id, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"id\" missing from Name"); + return 1; + } + if (PyObject_HasAttrString(obj, "ctx")) { + int res; + tmp = PyObject_GetAttrString(obj, "ctx"); + if (tmp == NULL) goto failed; + res = obj2ast_expr_context(tmp, &ctx, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"ctx\" missing from Name"); + return 1; + } + *out = Name(id, ctx, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)List_type)) { + asdl_seq* elts; + expr_context_ty ctx; + + if (PyObject_HasAttrString(obj, "elts")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "elts"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "List field \"elts\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + elts = asdl_seq_new(len, arena); + if (elts == NULL) goto failed; + for (i = 0; i < len; i++) { + expr_ty value; + res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(elts, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"elts\" missing from List"); + return 1; + } + if (PyObject_HasAttrString(obj, "ctx")) { + int res; + tmp = PyObject_GetAttrString(obj, "ctx"); + if (tmp == NULL) goto failed; + res = obj2ast_expr_context(tmp, &ctx, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"ctx\" missing from List"); + return 1; + } + *out = List(elts, ctx, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Tuple_type)) { + asdl_seq* elts; + expr_context_ty ctx; + + if (PyObject_HasAttrString(obj, "elts")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "elts"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "Tuple field \"elts\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + elts = asdl_seq_new(len, arena); + if (elts == NULL) goto failed; + for (i = 0; i < len; i++) { + expr_ty value; + res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(elts, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"elts\" missing from Tuple"); + return 1; + } + if (PyObject_HasAttrString(obj, "ctx")) { + int res; + tmp = PyObject_GetAttrString(obj, "ctx"); + if (tmp == NULL) goto failed; + res = obj2ast_expr_context(tmp, &ctx, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"ctx\" missing from Tuple"); + return 1; + } + *out = Tuple(elts, ctx, lineno, col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } + + tmp = PyObject_Repr(obj); + if (tmp == NULL) goto failed; + PyErr_Format(PyExc_TypeError, "expected some sort of expr, but got %.400s", PyString_AS_STRING(tmp)); +failed: + Py_XDECREF(tmp); + return 1; +} + +int +obj2ast_expr_context(PyObject* obj, expr_context_ty* out, PyArena* arena) +{ + PyObject* tmp = NULL; + + if (PyObject_IsInstance(obj, (PyObject*)Load_type)) { + *out = Load; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Store_type)) { + *out = Store; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Del_type)) { + *out = Del; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)AugLoad_type)) { + *out = AugLoad; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)AugStore_type)) { + *out = AugStore; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Param_type)) { + *out = Param; + return 0; + } + + tmp = PyObject_Repr(obj); + if (tmp == NULL) goto failed; + PyErr_Format(PyExc_TypeError, "expected some sort of expr_context, but got %.400s", PyString_AS_STRING(tmp)); +failed: + Py_XDECREF(tmp); + return 1; +} + +int +obj2ast_slice(PyObject* obj, slice_ty* out, PyArena* arena) +{ + PyObject* tmp = NULL; + + + if (obj == Py_None) { + *out = NULL; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Slice_type)) { + expr_ty lower; + expr_ty upper; + expr_ty step; + + if (PyObject_HasAttrString(obj, "lower")) { + int res; + tmp = PyObject_GetAttrString(obj, "lower"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &lower, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + lower = NULL; + } + if (PyObject_HasAttrString(obj, "upper")) { + int res; + tmp = PyObject_GetAttrString(obj, "upper"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &upper, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + upper = NULL; + } + if (PyObject_HasAttrString(obj, "step")) { + int res; + tmp = PyObject_GetAttrString(obj, "step"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &step, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + step = NULL; + } + *out = Slice(lower, upper, step, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)ExtSlice_type)) { + asdl_seq* dims; + + if (PyObject_HasAttrString(obj, "dims")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "dims"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "ExtSlice field \"dims\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + dims = asdl_seq_new(len, arena); + if (dims == NULL) goto failed; + for (i = 0; i < len; i++) { + slice_ty value; + res = obj2ast_slice(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(dims, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"dims\" missing from ExtSlice"); + return 1; + } + *out = ExtSlice(dims, arena); + if (*out == NULL) goto failed; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Index_type)) { + expr_ty value; + + if (PyObject_HasAttrString(obj, "value")) { + int res; + tmp = PyObject_GetAttrString(obj, "value"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &value, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from Index"); + return 1; + } + *out = Index(value, arena); + if (*out == NULL) goto failed; + return 0; + } + + tmp = PyObject_Repr(obj); + if (tmp == NULL) goto failed; + PyErr_Format(PyExc_TypeError, "expected some sort of slice, but got %.400s", PyString_AS_STRING(tmp)); +failed: + Py_XDECREF(tmp); + return 1; +} + +int +obj2ast_boolop(PyObject* obj, boolop_ty* out, PyArena* arena) +{ + PyObject* tmp = NULL; + + if (PyObject_IsInstance(obj, (PyObject*)And_type)) { + *out = And; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Or_type)) { + *out = Or; + return 0; + } + + tmp = PyObject_Repr(obj); + if (tmp == NULL) goto failed; + PyErr_Format(PyExc_TypeError, "expected some sort of boolop, but got %.400s", PyString_AS_STRING(tmp)); +failed: + Py_XDECREF(tmp); + return 1; +} + +int +obj2ast_operator(PyObject* obj, operator_ty* out, PyArena* arena) +{ + PyObject* tmp = NULL; + + if (PyObject_IsInstance(obj, (PyObject*)Add_type)) { + *out = Add; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Sub_type)) { + *out = Sub; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Mult_type)) { + *out = Mult; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Div_type)) { + *out = Div; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Mod_type)) { + *out = Mod; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Pow_type)) { + *out = Pow; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)LShift_type)) { + *out = LShift; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)RShift_type)) { + *out = RShift; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)BitOr_type)) { + *out = BitOr; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)BitXor_type)) { + *out = BitXor; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)BitAnd_type)) { + *out = BitAnd; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)FloorDiv_type)) { + *out = FloorDiv; + return 0; + } + + tmp = PyObject_Repr(obj); + if (tmp == NULL) goto failed; + PyErr_Format(PyExc_TypeError, "expected some sort of operator, but got %.400s", PyString_AS_STRING(tmp)); +failed: + Py_XDECREF(tmp); + return 1; +} + +int +obj2ast_unaryop(PyObject* obj, unaryop_ty* out, PyArena* arena) +{ + PyObject* tmp = NULL; + + if (PyObject_IsInstance(obj, (PyObject*)Invert_type)) { + *out = Invert; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Not_type)) { + *out = Not; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)UAdd_type)) { + *out = UAdd; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)USub_type)) { + *out = USub; + return 0; + } + + tmp = PyObject_Repr(obj); + if (tmp == NULL) goto failed; + PyErr_Format(PyExc_TypeError, "expected some sort of unaryop, but got %.400s", PyString_AS_STRING(tmp)); +failed: + Py_XDECREF(tmp); + return 1; +} + +int +obj2ast_cmpop(PyObject* obj, cmpop_ty* out, PyArena* arena) +{ + PyObject* tmp = NULL; + + if (PyObject_IsInstance(obj, (PyObject*)Eq_type)) { + *out = Eq; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)NotEq_type)) { + *out = NotEq; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Lt_type)) { + *out = Lt; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)LtE_type)) { + *out = LtE; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Gt_type)) { + *out = Gt; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)GtE_type)) { + *out = GtE; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)Is_type)) { + *out = Is; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)IsNot_type)) { + *out = IsNot; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)In_type)) { + *out = In; + return 0; + } + if (PyObject_IsInstance(obj, (PyObject*)NotIn_type)) { + *out = NotIn; + return 0; + } + + tmp = PyObject_Repr(obj); + if (tmp == NULL) goto failed; + PyErr_Format(PyExc_TypeError, "expected some sort of cmpop, but got %.400s", PyString_AS_STRING(tmp)); +failed: + Py_XDECREF(tmp); + return 1; +} + +int +obj2ast_comprehension(PyObject* obj, comprehension_ty* out, PyArena* arena) +{ + PyObject* tmp = NULL; + expr_ty target; + expr_ty iter; + asdl_seq* ifs; + + if (PyObject_HasAttrString(obj, "target")) { + int res; + tmp = PyObject_GetAttrString(obj, "target"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &target, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"target\" missing from comprehension"); + return 1; + } + if (PyObject_HasAttrString(obj, "iter")) { + int res; + tmp = PyObject_GetAttrString(obj, "iter"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &iter, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"iter\" missing from comprehension"); + return 1; + } + if (PyObject_HasAttrString(obj, "ifs")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "ifs"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "comprehension field \"ifs\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + ifs = asdl_seq_new(len, arena); + if (ifs == NULL) goto failed; + for (i = 0; i < len; i++) { + expr_ty value; + res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(ifs, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"ifs\" missing from comprehension"); + return 1; + } + *out = comprehension(target, iter, ifs, arena); + return 0; +failed: + Py_XDECREF(tmp); + return 1; +} + +int +obj2ast_excepthandler(PyObject* obj, excepthandler_ty* out, PyArena* arena) +{ + PyObject* tmp = NULL; + + int lineno; + int col_offset; + + if (obj == Py_None) { + *out = NULL; + return 0; + } + if (PyObject_HasAttrString(obj, "lineno")) { + int res; + tmp = PyObject_GetAttrString(obj, "lineno"); + if (tmp == NULL) goto failed; + res = obj2ast_int(tmp, &lineno, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"lineno\" missing from excepthandler"); + return 1; + } + if (PyObject_HasAttrString(obj, "col_offset")) { + int res; + tmp = PyObject_GetAttrString(obj, "col_offset"); + if (tmp == NULL) goto failed; + res = obj2ast_int(tmp, &col_offset, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"col_offset\" missing from excepthandler"); + return 1; + } + if (PyObject_IsInstance(obj, (PyObject*)ExceptHandler_type)) { + expr_ty type; + identifier name; + asdl_seq* body; + + if (PyObject_HasAttrString(obj, "type")) { + int res; + tmp = PyObject_GetAttrString(obj, "type"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &type, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + type = NULL; + } + if (PyObject_HasAttrString(obj, "name")) { + int res; + tmp = PyObject_GetAttrString(obj, "name"); + if (tmp == NULL) goto failed; + res = obj2ast_identifier(tmp, &name, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + name = NULL; + } + if (PyObject_HasAttrString(obj, "body")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "body"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "ExceptHandler field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + body = asdl_seq_new(len, arena); + if (body == NULL) goto failed; + for (i = 0; i < len; i++) { + stmt_ty value; + res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(body, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from ExceptHandler"); + return 1; + } + *out = ExceptHandler(type, name, body, lineno, col_offset, + arena); + if (*out == NULL) goto failed; + return 0; + } + + tmp = PyObject_Repr(obj); + if (tmp == NULL) goto failed; + PyErr_Format(PyExc_TypeError, "expected some sort of excepthandler, but got %.400s", PyString_AS_STRING(tmp)); +failed: + Py_XDECREF(tmp); + return 1; +} + +int +obj2ast_arguments(PyObject* obj, arguments_ty* out, PyArena* arena) +{ + PyObject* tmp = NULL; + asdl_seq* args; + identifier vararg; + expr_ty varargannotation; + asdl_seq* kwonlyargs; + identifier kwarg; + expr_ty kwargannotation; + asdl_seq* defaults; + asdl_seq* kw_defaults; + + if (PyObject_HasAttrString(obj, "args")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "args"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "arguments field \"args\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + args = asdl_seq_new(len, arena); + if (args == NULL) goto failed; + for (i = 0; i < len; i++) { + arg_ty value; + res = obj2ast_arg(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(args, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"args\" missing from arguments"); + return 1; + } + if (PyObject_HasAttrString(obj, "vararg")) { + int res; + tmp = PyObject_GetAttrString(obj, "vararg"); + if (tmp == NULL) goto failed; + res = obj2ast_identifier(tmp, &vararg, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + vararg = NULL; + } + if (PyObject_HasAttrString(obj, "varargannotation")) { + int res; + tmp = PyObject_GetAttrString(obj, "varargannotation"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &varargannotation, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + varargannotation = NULL; + } + if (PyObject_HasAttrString(obj, "kwonlyargs")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "kwonlyargs"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "arguments field \"kwonlyargs\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + kwonlyargs = asdl_seq_new(len, arena); + if (kwonlyargs == NULL) goto failed; + for (i = 0; i < len; i++) { + arg_ty value; + res = obj2ast_arg(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(kwonlyargs, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"kwonlyargs\" missing from arguments"); + return 1; + } + if (PyObject_HasAttrString(obj, "kwarg")) { + int res; + tmp = PyObject_GetAttrString(obj, "kwarg"); + if (tmp == NULL) goto failed; + res = obj2ast_identifier(tmp, &kwarg, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + kwarg = NULL; + } + if (PyObject_HasAttrString(obj, "kwargannotation")) { + int res; + tmp = PyObject_GetAttrString(obj, "kwargannotation"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &kwargannotation, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + kwargannotation = NULL; + } + if (PyObject_HasAttrString(obj, "defaults")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "defaults"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "arguments field \"defaults\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + defaults = asdl_seq_new(len, arena); + if (defaults == NULL) goto failed; + for (i = 0; i < len; i++) { + expr_ty value; + res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(defaults, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"defaults\" missing from arguments"); + return 1; + } + if (PyObject_HasAttrString(obj, "kw_defaults")) { + int res; + Py_ssize_t len; + Py_ssize_t i; + tmp = PyObject_GetAttrString(obj, "kw_defaults"); + if (tmp == NULL) goto failed; + if (!PyList_Check(tmp)) { + PyErr_Format(PyExc_TypeError, "arguments field \"kw_defaults\" must be a list, not a %.200s", tmp->ob_type->tp_name); + goto failed; + } + len = PyList_GET_SIZE(tmp); + kw_defaults = asdl_seq_new(len, arena); + if (kw_defaults == NULL) goto failed; + for (i = 0; i < len; i++) { + expr_ty value; + res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena); + if (res != 0) goto failed; + asdl_seq_SET(kw_defaults, i, value); + } + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"kw_defaults\" missing from arguments"); + return 1; + } + *out = arguments(args, vararg, varargannotation, kwonlyargs, kwarg, + kwargannotation, defaults, kw_defaults, arena); + return 0; +failed: + Py_XDECREF(tmp); + return 1; +} + +int +obj2ast_arg(PyObject* obj, arg_ty* out, PyArena* arena) +{ + PyObject* tmp = NULL; + identifier arg; + expr_ty annotation; + + if (PyObject_HasAttrString(obj, "arg")) { + int res; + tmp = PyObject_GetAttrString(obj, "arg"); + if (tmp == NULL) goto failed; + res = obj2ast_identifier(tmp, &arg, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"arg\" missing from arg"); + return 1; + } + if (PyObject_HasAttrString(obj, "annotation")) { + int res; + tmp = PyObject_GetAttrString(obj, "annotation"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &annotation, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + annotation = NULL; + } + *out = arg(arg, annotation, arena); + return 0; +failed: + Py_XDECREF(tmp); + return 1; +} + +int +obj2ast_keyword(PyObject* obj, keyword_ty* out, PyArena* arena) +{ + PyObject* tmp = NULL; + identifier arg; + expr_ty value; + + if (PyObject_HasAttrString(obj, "arg")) { + int res; + tmp = PyObject_GetAttrString(obj, "arg"); + if (tmp == NULL) goto failed; + res = obj2ast_identifier(tmp, &arg, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"arg\" missing from keyword"); + return 1; + } + if (PyObject_HasAttrString(obj, "value")) { + int res; + tmp = PyObject_GetAttrString(obj, "value"); + if (tmp == NULL) goto failed; + res = obj2ast_expr(tmp, &value, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from keyword"); + return 1; + } + *out = keyword(arg, value, arena); + return 0; +failed: + Py_XDECREF(tmp); + return 1; +} + +int +obj2ast_alias(PyObject* obj, alias_ty* out, PyArena* arena) +{ + PyObject* tmp = NULL; + identifier name; + identifier asname; + + if (PyObject_HasAttrString(obj, "name")) { + int res; + tmp = PyObject_GetAttrString(obj, "name"); + if (tmp == NULL) goto failed; + res = obj2ast_identifier(tmp, &name, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "required field \"name\" missing from alias"); + return 1; + } + if (PyObject_HasAttrString(obj, "asname")) { + int res; + tmp = PyObject_GetAttrString(obj, "asname"); + if (tmp == NULL) goto failed; + res = obj2ast_identifier(tmp, &asname, arena); + if (res != 0) goto failed; + Py_XDECREF(tmp); + tmp = NULL; + } else { + asname = NULL; + } + *out = alias(name, asname, arena); + return 0; +failed: + Py_XDECREF(tmp); + return 1; +} + + PyMODINIT_FUNC init_ast(void) { @@ -3168,7 +6392,7 @@ m = Py_InitModule3("_ast", NULL, NULL); if (!m) return; d = PyModule_GetDict(m); - if (PyDict_SetItemString(d, "AST", (PyObject*)AST_type) < 0) return; + if (PyDict_SetItemString(d, "AST", (PyObject*)&AST_type) < 0) return; if (PyModule_AddIntConstant(m, "PyCF_ONLY_AST", PyCF_ONLY_AST) < 0) return; if (PyModule_AddStringConstant(m, "__version__", "57783") < 0) @@ -3315,6 +6539,8 @@ (PyObject*)comprehension_type) < 0) return; if (PyDict_SetItemString(d, "excepthandler", (PyObject*)excepthandler_type) < 0) return; + if (PyDict_SetItemString(d, "ExceptHandler", + (PyObject*)ExceptHandler_type) < 0) return; if (PyDict_SetItemString(d, "arguments", (PyObject*)arguments_type) < 0) return; if (PyDict_SetItemString(d, "arg", (PyObject*)arg_type) < 0) return; @@ -3330,4 +6556,32 @@ return ast2obj_mod(t); } +/* mode is 0 for "exec", 1 for "eval" and 2 for "single" input */ +mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode) +{ + mod_ty res; + PyObject *req_type[] = {(PyObject*)Module_type, (PyObject*)Expression_type, + (PyObject*)Interactive_type}; + char *req_name[] = {"Module", "Expression", "Interactive"}; + assert(0 <= mode && mode <= 2); + + init_types(); + + if (!PyObject_IsInstance(ast, req_type[mode])) { + PyErr_Format(PyExc_TypeError, "expected %s node, got %.400s", + req_name[mode], Py_TYPE(ast)->tp_name); + return NULL; + } + if (obj2ast_mod(ast, &res, arena) != 0) + return NULL; + else + return res; +} + +int PyAST_Check(PyObject* obj) +{ + init_types(); + return PyObject_IsInstance(obj, (PyObject*)&AST_type); +} + Modified: python/branches/py3k-ctypes-pep3118/Python/ast.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/ast.c (original) +++ python/branches/py3k-ctypes-pep3118/Python/ast.c Wed Apr 30 15:57:13 2008 @@ -35,7 +35,7 @@ static expr_ty ast_for_call(struct compiling *, const node *, expr_ty); static PyObject *parsenumber(const char *); -static PyObject *parsestr(const node *n, const char *encoding, int *bytesmode); +static PyObject *parsestr(struct compiling *, const node *n, int *bytesmode); static PyObject *parsestrplus(struct compiling *, const node *n, int *bytesmode); @@ -1015,6 +1015,12 @@ } else if (TYPE(CHILD(n, 1)) == classdef) { thing = ast_for_classdef(c, CHILD(n, 1), decorator_seq); } + /* we count the decorators in when talking about the class' or + * function's line number */ + if (thing) { + thing->lineno = LINENO(n); + thing->col_offset = n->n_col_offset; + } return thing; } @@ -1988,10 +1994,14 @@ } else if (TYPE(ch) == STAR) { vararg = ast_for_expr(c, CHILD(n, i+1)); + if (!vararg) + return NULL; i++; } else if (TYPE(ch) == DOUBLESTAR) { kwarg = ast_for_expr(c, CHILD(n, i+1)); + if (!kwarg) + return NULL; i++; } } @@ -2376,10 +2386,6 @@ /* from ... import * */ n = CHILD(n, idx); n_children = 1; - if (ndots) { - ast_error(n, "'import *' not allowed with 'from .'"); - return NULL; - } break; case LPAR: /* from ... import (x, y, z) */ @@ -2781,7 +2787,7 @@ if (!suite_seq) return NULL; - return excepthandler(NULL, NULL, suite_seq, LINENO(exc), + return ExceptHandler(NULL, NULL, suite_seq, LINENO(exc), exc->n_col_offset, c->c_arena); } else if (NCH(exc) == 2) { @@ -2795,7 +2801,7 @@ if (!suite_seq) return NULL; - return excepthandler(expression, NULL, suite_seq, LINENO(exc), + return ExceptHandler(expression, NULL, suite_seq, LINENO(exc), exc->n_col_offset, c->c_arena); } else if (NCH(exc) == 4) { @@ -2811,7 +2817,7 @@ if (!suite_seq) return NULL; - return excepthandler(expression, e, suite_seq, LINENO(exc), + return ExceptHandler(expression, e, suite_seq, LINENO(exc), exc->n_col_offset, c->c_arena); } @@ -3185,14 +3191,13 @@ * parsestr parses it, and returns the decoded Python string object. */ static PyObject * -parsestr(const node *n, const char *encoding, int *bytesmode) +parsestr(struct compiling *c, const node *n, int *bytesmode) { size_t len; const char *s = STR(n); int quote = Py_CHARMASK(*s); int rawmode = 0; int need_encoding; - if (isalpha(quote)) { if (quote == 'b' || quote == 'B') { quote = *++s; @@ -3227,7 +3232,7 @@ } } if (!*bytesmode && !rawmode) { - return decode_unicode(s, len, rawmode, encoding); + return decode_unicode(s, len, rawmode, c->c_encoding); } if (*bytesmode) { /* Disallow non-ascii characters (but not escapes) */ @@ -3240,28 +3245,27 @@ } } } - need_encoding = (!*bytesmode && encoding != NULL && - strcmp(encoding, "utf-8") != 0 && - strcmp(encoding, "iso-8859-1") != 0); + need_encoding = (!*bytesmode && c->c_encoding != NULL && + strcmp(c->c_encoding, "utf-8") != 0 && + strcmp(c->c_encoding, "iso-8859-1") != 0); if (rawmode || strchr(s, '\\') == NULL) { if (need_encoding) { PyObject *v, *u = PyUnicode_DecodeUTF8(s, len, NULL); if (u == NULL || !*bytesmode) return u; - v = PyUnicode_AsEncodedString(u, encoding, NULL); + v = PyUnicode_AsEncodedString(u, c->c_encoding, NULL); Py_DECREF(u); return v; } else if (*bytesmode) { return PyString_FromStringAndSize(s, len); - } else if (strcmp(encoding, "utf-8") == 0) { + } else if (strcmp(c->c_encoding, "utf-8") == 0) { return PyUnicode_FromStringAndSize(s, len); } else { return PyUnicode_DecodeLatin1(s, len, NULL); } } - return PyString_DecodeEscape(s, len, NULL, 1, - need_encoding ? encoding : NULL); + need_encoding ? c->c_encoding : NULL); } /* Build a Python string object out of a STRING+ atom. This takes care of @@ -3274,13 +3278,13 @@ PyObject *v; int i; REQ(CHILD(n, 0), STRING); - v = parsestr(CHILD(n, 0), c->c_encoding, bytesmode); + v = parsestr(c, CHILD(n, 0), bytesmode); if (v != NULL) { /* String literal concatenation */ for (i = 1; i < NCH(n); i++) { PyObject *s; int subbm = 0; - s = parsestr(CHILD(n, i), c->c_encoding, &subbm); + s = parsestr(c, CHILD(n, i), &subbm); if (s == NULL) goto onError; if (*bytesmode != subbm) { Modified: python/branches/py3k-ctypes-pep3118/Python/bltinmodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/bltinmodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Python/bltinmodule.c Wed Apr 30 15:57:13 2008 @@ -1,6 +1,7 @@ /* Built-in functions */ #include "Python.h" +#include "Python-ast.h" #include "node.h" #include "code.h" @@ -277,85 +278,157 @@ Return the binary representation of an integer or long integer."); +typedef struct { + PyObject_HEAD + PyObject *func; + PyObject *it; +} filterobject; + +PyTypeObject PyFilter_Type; + static PyObject * -builtin_filter(PyObject *self, PyObject *args) +filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *itertools, *ifilter, *result; - itertools = PyImport_ImportModuleNoBlock("itertools"); - if (itertools == NULL) - return NULL; - ifilter = PyObject_GetAttrString(itertools, "ifilter"); - Py_DECREF(itertools); - if (ifilter == NULL) + PyObject *func, *seq; + PyObject *it; + filterobject *lz; + + if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds)) return NULL; - result = PyObject_Call(ifilter, args, NULL); - Py_DECREF(ifilter); - return result; + + if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq)) + return NULL; + + /* Get iterator. */ + it = PyObject_GetIter(seq); + if (it == NULL) + return NULL; + + /* create filterobject structure */ + lz = (filterobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(it); + return NULL; + } + Py_INCREF(func); + lz->func = func; + lz->it = it; + + return (PyObject *)lz; +} + +static void +filter_dealloc(filterobject *lz) +{ + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->func); + Py_XDECREF(lz->it); + Py_TYPE(lz)->tp_free(lz); +} + +static int +filter_traverse(filterobject *lz, visitproc visit, void *arg) +{ + Py_VISIT(lz->it); + Py_VISIT(lz->func); + return 0; +} + +static PyObject * +filter_next(filterobject *lz) +{ + PyObject *item; + PyObject *it = lz->it; + long ok; + PyObject *(*iternext)(PyObject *); + + assert(PyIter_Check(it)); + iternext = *Py_TYPE(it)->tp_iternext; + for (;;) { + item = iternext(it); + if (item == NULL) + return NULL; + + if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) { + ok = PyObject_IsTrue(item); + } else { + PyObject *good; + good = PyObject_CallFunctionObjArgs(lz->func, + item, NULL); + if (good == NULL) { + Py_DECREF(item); + return NULL; + } + ok = PyObject_IsTrue(good); + Py_DECREF(good); + } + if (ok) + return item; + Py_DECREF(item); + } } PyDoc_STRVAR(filter_doc, -"filter(predicate, iterable) -> iterator\n\ +"filter(function or None, sequence) --> filter object\n\ \n\ -Return an iterator yielding only those elements of the input iterable\n\ -for which the predicate (a Boolean function) returns true.\n\ -If the predicate is None, 'lambda x: bool(x)' is assumed.\n\ -(This is identical to itertools.ifilter().)"); +Return an iterator yielding those items of sequence for which function(item)\n\ +is true. If function is None, return the items that are true."); + +PyTypeObject PyFilter_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "filter", /* tp_name */ + sizeof(filterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)filter_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + filter_doc, /* tp_doc */ + (traverseproc)filter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)filter_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + filter_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ +}; + static PyObject * builtin_format(PyObject *self, PyObject *args) { - static PyObject * format_str = NULL; PyObject *value; - PyObject *spec = NULL; - PyObject *meth; - PyObject *empty = NULL; - PyObject *result = NULL; - - /* Initialize cached value */ - if (format_str == NULL) { - /* Initialize static variable needed by _PyType_Lookup */ - format_str = PyUnicode_FromString("__format__"); - if (format_str == NULL) - goto done; - } - - if (!PyArg_ParseTuple(args, "O|U:format", &value, &spec)) - goto done; - - /* initialize the default value */ - if (spec == NULL) { - empty = PyUnicode_FromUnicode(NULL, 0); - spec = empty; - } - - /* Make sure the type is initialized. float gets initialized late */ - if (Py_TYPE(value)->tp_dict == NULL) - if (PyType_Ready(Py_TYPE(value)) < 0) - goto done; - - /* Find the (unbound!) __format__ method (a borrowed reference) */ - meth = _PyType_Lookup(Py_TYPE(value), format_str); - if (meth == NULL) { - PyErr_Format(PyExc_TypeError, - "Type %.100s doesn't define __format__", - Py_TYPE(value)->tp_name); - goto done; - } - - /* And call it, binding it to the value */ - result = PyObject_CallFunctionObjArgs(meth, value, spec, NULL); - - if (result && !PyUnicode_Check(result)) { - PyErr_SetString(PyExc_TypeError, - "__format__ method did not return string"); - Py_DECREF(result); - result = NULL; - goto done; - } - -done: - Py_XDECREF(empty); - return result; + PyObject *format_spec = NULL; + + if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec)) + return NULL; + + return PyObject_Format(value, format_spec); } PyDoc_STRVAR(format_doc, @@ -440,13 +513,14 @@ char *str; char *filename; char *startstr; - int start; + int mode = -1; int dont_inherit = 0; int supplied_flags = 0; PyCompilerFlags cf; PyObject *cmd; static char *kwlist[] = {"source", "filename", "mode", "flags", "dont_inherit", NULL}; + int start[] = {Py_file_input, Py_eval_input, Py_single_input}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile", kwlist, &cmd, &filename, &startstr, @@ -455,22 +529,6 @@ cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8; - str = source_as_string(cmd); - if (str == NULL) - return NULL; - - if (strcmp(startstr, "exec") == 0) - start = Py_file_input; - else if (strcmp(startstr, "eval") == 0) - start = Py_eval_input; - else if (strcmp(startstr, "single") == 0) - start = Py_single_input; - else { - PyErr_SetString(PyExc_ValueError, - "compile() arg 3 must be 'exec' or 'eval' or 'single'"); - return NULL; - } - if (supplied_flags & ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST)) { @@ -483,7 +541,47 @@ if (!dont_inherit) { PyEval_MergeCompilerFlags(&cf); } - return Py_CompileStringFlags(str, filename, start, &cf); + + if (strcmp(startstr, "exec") == 0) + mode = 0; + else if (strcmp(startstr, "eval") == 0) + mode = 1; + else if (strcmp(startstr, "single") == 0) + mode = 2; + else { + PyErr_SetString(PyExc_ValueError, + "compile() arg 3 must be 'exec', 'eval' or 'single'"); + return NULL; + } + + if (PyAST_Check(cmd)) { + PyObject *result; + if (supplied_flags & PyCF_ONLY_AST) { + Py_INCREF(cmd); + result = cmd; + } + else { + PyArena *arena; + mod_ty mod; + + arena = PyArena_New(); + mod = PyAST_obj2mod(cmd, arena, mode); + if (mod == NULL) { + PyArena_Free(arena); + return NULL; + } + result = (PyObject*)PyAST_Compile(mod, filename, + &cf, arena); + PyArena_Free(arena); + } + return result; + } + + str = source_as_string(cmd); + if (str == NULL) + return NULL; + + return Py_CompileStringFlags(str, filename, start[mode], &cf); } PyDoc_STRVAR(compile_doc, @@ -792,31 +890,153 @@ simultaneously existing objects. (Hint: it's the object's memory address.)"); +/* map object ************************************************************/ + +typedef struct { + PyObject_HEAD + PyObject *iters; + PyObject *func; +} mapobject; + +PyTypeObject PyMap_Type; + +static PyObject * +map_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + PyObject *it, *iters, *func; + mapobject *lz; + Py_ssize_t numargs, i; + + if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds)) + return NULL; + + numargs = PyTuple_Size(args); + if (numargs < 2) { + PyErr_SetString(PyExc_TypeError, + "map() must have at least two arguments."); + return NULL; + } + + iters = PyTuple_New(numargs-1); + if (iters == NULL) + return NULL; + + for (i=1 ; itp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(iters); + return NULL; + } + lz->iters = iters; + func = PyTuple_GET_ITEM(args, 0); + Py_INCREF(func); + lz->func = func; + + return (PyObject *)lz; +} + +static void +map_dealloc(mapobject *lz) +{ + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->iters); + Py_XDECREF(lz->func); + Py_TYPE(lz)->tp_free(lz); +} + +static int +map_traverse(mapobject *lz, visitproc visit, void *arg) +{ + Py_VISIT(lz->iters); + Py_VISIT(lz->func); + return 0; +} + static PyObject * -builtin_map(PyObject *self, PyObject *args) +map_next(mapobject *lz) { - PyObject *itertools, *imap, *result; - itertools = PyImport_ImportModuleNoBlock("itertools"); - if (itertools == NULL) - return NULL; - imap = PyObject_GetAttrString(itertools, "imap"); - Py_DECREF(itertools); - if (imap == NULL) + PyObject *val; + PyObject *argtuple; + PyObject *result; + Py_ssize_t numargs, i; + + numargs = PyTuple_Size(lz->iters); + argtuple = PyTuple_New(numargs); + if (argtuple == NULL) return NULL; - result = PyObject_Call(imap, args, NULL); - Py_DECREF(imap); + + for (i=0 ; iiters, i)); + if (val == NULL) { + Py_DECREF(argtuple); + return NULL; + } + PyTuple_SET_ITEM(argtuple, i, val); + } + result = PyObject_Call(lz->func, argtuple, NULL); + Py_DECREF(argtuple); return result; } PyDoc_STRVAR(map_doc, -"map(function, iterable[, iterable, ...]) -> iterator\n\ +"map(func, *iterables) --> map object\n\ \n\ -Return an iterator yielding the results of applying the function to the\n\ -items of the argument iterables(s). If more than one iterable is given,\n\ -the function is called with an argument list consisting of the\n\ -corresponding item of each iterable, until an iterable is exhausted.\n\ -(This is identical to itertools.imap().)"); +Make an iterator that computes the function using arguments from\n\ +each of the iterables. Stops when the shortest iterable is exhausted."); +PyTypeObject PyMap_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "map", /* tp_name */ + sizeof(mapobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)map_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + map_doc, /* tp_doc */ + (traverseproc)map_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)map_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + map_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ +}; static PyObject * builtin_next(PyObject *self, PyObject *args) @@ -1267,7 +1487,7 @@ } PyDoc_STRVAR(print_doc, -"print(value, ..., file=None, sep=' ', end='\\n')\n\ +"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\ \n\ Prints the values to a stream, or to sys.stdout by default.\n\ Optional keyword arguments:\n\ @@ -1463,7 +1683,7 @@ } if (round_str == NULL) { - round_str = PyUnicode_FromString("__round__"); + round_str = PyUnicode_InternFromString("__round__"); if (round_str == NULL) return NULL; } @@ -1494,14 +1714,14 @@ static PyObject * builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds) { - PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs; + PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs; PyObject *callable; - static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0}; + static char *kwlist[] = {"iterable", "key", "reverse", 0}; int reverse; - /* args 1-4 should match listsort in Objects/listobject.c */ - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted", - kwlist, &seq, &compare, &keyfunc, &reverse)) + /* args 1-3 should match listsort in Objects/listobject.c */ + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted", + kwlist, &seq, &keyfunc, &reverse)) return NULL; newlist = PySequence_List(seq); @@ -1533,7 +1753,7 @@ } PyDoc_STRVAR(sorted_doc, -"sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list"); +"sorted(iterable, key=None, reverse=False) --> new sorted list"); static PyObject * builtin_vars(PyObject *self, PyObject *args) @@ -1570,40 +1790,6 @@ Without arguments, equivalent to locals().\n\ With an argument, equivalent to object.__dict__."); -static PyObject * -builtin_trunc(PyObject *self, PyObject *number) -{ - static PyObject *trunc_str = NULL; - PyObject *trunc; - - if (Py_TYPE(number)->tp_dict == NULL) { - if (PyType_Ready(Py_TYPE(number)) < 0) - return NULL; - } - - if (trunc_str == NULL) { - trunc_str = PyUnicode_FromString("__trunc__"); - if (trunc_str == NULL) - return NULL; - } - - trunc = _PyType_Lookup(Py_TYPE(number), trunc_str); - if (trunc == NULL) { - PyErr_Format(PyExc_TypeError, - "type %.100s doesn't define __trunc__ method", - Py_TYPE(number)->tp_name); - return NULL; - } - return PyObject_CallFunction(trunc, "O", number); -} - -PyDoc_STRVAR(trunc_doc, -"trunc(Real) -> Integral\n\ -\n\ -returns the integral closest to x between 0 and x."); - - - static PyObject* builtin_sum(PyObject *self, PyObject *args) { @@ -1807,23 +1993,187 @@ is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.)."); -static PyObject* -builtin_zip(PyObject *self, PyObject *args) +typedef struct { + PyObject_HEAD + Py_ssize_t tuplesize; + PyObject *ittuple; /* tuple of iterators */ + PyObject *result; +} zipobject; + +PyTypeObject PyZip_Type; + +static PyObject * +zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { + zipobject *lz; + Py_ssize_t i; + PyObject *ittuple; /* tuple of iterators */ + PyObject *result; + Py_ssize_t tuplesize = PySequence_Length(args); + + if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds)) + return NULL; + /* args must be a tuple */ assert(PyTuple_Check(args)); - return _PyZip_CreateIter(args); + /* obtain iterators */ + ittuple = PyTuple_New(tuplesize); + if (ittuple == NULL) + return NULL; + for (i=0; i < tuplesize; ++i) { + PyObject *item = PyTuple_GET_ITEM(args, i); + PyObject *it = PyObject_GetIter(item); + if (it == NULL) { + if (PyErr_ExceptionMatches(PyExc_TypeError)) + PyErr_Format(PyExc_TypeError, + "zip argument #%zd must support iteration", + i+1); + Py_DECREF(ittuple); + return NULL; + } + PyTuple_SET_ITEM(ittuple, i, it); + } + + /* create a result holder */ + result = PyTuple_New(tuplesize); + if (result == NULL) { + Py_DECREF(ittuple); + return NULL; + } + for (i=0 ; i < tuplesize ; i++) { + Py_INCREF(Py_None); + PyTuple_SET_ITEM(result, i, Py_None); + } + + /* create zipobject structure */ + lz = (zipobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(ittuple); + Py_DECREF(result); + return NULL; + } + lz->ittuple = ittuple; + lz->tuplesize = tuplesize; + lz->result = result; + + return (PyObject *)lz; } +static void +zip_dealloc(zipobject *lz) +{ + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->ittuple); + Py_XDECREF(lz->result); + Py_TYPE(lz)->tp_free(lz); +} + +static int +zip_traverse(zipobject *lz, visitproc visit, void *arg) +{ + Py_VISIT(lz->ittuple); + Py_VISIT(lz->result); + return 0; +} + +static PyObject * +zip_next(zipobject *lz) +{ + Py_ssize_t i; + Py_ssize_t tuplesize = lz->tuplesize; + PyObject *result = lz->result; + PyObject *it; + PyObject *item; + PyObject *olditem; + + if (tuplesize == 0) + return NULL; + if (Py_REFCNT(result) == 1) { + Py_INCREF(result); + for (i=0 ; i < tuplesize ; i++) { + it = PyTuple_GET_ITEM(lz->ittuple, i); + assert(PyIter_Check(it)); + item = (*Py_TYPE(it)->tp_iternext)(it); + if (item == NULL) { + Py_DECREF(result); + return NULL; + } + olditem = PyTuple_GET_ITEM(result, i); + PyTuple_SET_ITEM(result, i, item); + Py_DECREF(olditem); + } + } else { + result = PyTuple_New(tuplesize); + if (result == NULL) + return NULL; + for (i=0 ; i < tuplesize ; i++) { + it = PyTuple_GET_ITEM(lz->ittuple, i); + assert(PyIter_Check(it)); + item = (*Py_TYPE(it)->tp_iternext)(it); + if (item == NULL) { + Py_DECREF(result); + return NULL; + } + PyTuple_SET_ITEM(result, i, item); + } + } + return result; +} PyDoc_STRVAR(zip_doc, -"zip(it1 [, it2 [...]]) -> iter([(it1[0], it2[0] ...), ...])\n\ +"zip(iter1 [,iter2 [...]]) --> zip object\n\ \n\ -Return an iterator yielding tuples, where each tuple contains the\n\ -corresponding element from each of the argument iterables.\n\ -The returned iterator ends when the shortest argument iterable is exhausted.\n\ -(This is identical to itertools.izip().)"); +Return a zip object whose .__next__() method returns a tuple where\n\ +the i-th element comes from the i-th iterable argument. The .__next__()\n\ +method continues until the shortest iterable in the argument sequence\n\ +is exhausted and then it raises StopIteration. Works like the zip()\n\ +function but consumes less memory by returning an iterator instead of\n\ +a list."); + +PyTypeObject PyZip_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "zip", /* tp_name */ + sizeof(zipobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)zip_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + zip_doc, /* tp_doc */ + (traverseproc)zip_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)zip_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + zip_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ +}; static PyMethodDef builtin_methods[] = { @@ -1842,7 +2192,6 @@ {"divmod", builtin_divmod, METH_VARARGS, divmod_doc}, {"eval", builtin_eval, METH_VARARGS, eval_doc}, {"exec", builtin_exec, METH_VARARGS, exec_doc}, - {"filter", builtin_filter, METH_VARARGS, filter_doc}, {"format", builtin_format, METH_VARARGS, format_doc}, {"getattr", builtin_getattr, METH_VARARGS, getattr_doc}, {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc}, @@ -1856,7 +2205,6 @@ {"iter", builtin_iter, METH_VARARGS, iter_doc}, {"len", builtin_len, METH_O, len_doc}, {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc}, - {"map", builtin_map, METH_VARARGS, map_doc}, {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc}, {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc}, {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc}, @@ -1870,8 +2218,6 @@ {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc}, {"sum", builtin_sum, METH_VARARGS, sum_doc}, {"vars", builtin_vars, METH_VARARGS, vars_doc}, - {"trunc", builtin_trunc, METH_O, trunc_doc}, - {"zip", builtin_zip, METH_VARARGS, zip_doc}, {NULL, NULL}, }; @@ -1923,11 +2269,13 @@ #endif SETBUILTIN("dict", &PyDict_Type); SETBUILTIN("enumerate", &PyEnum_Type); + SETBUILTIN("filter", &PyFilter_Type); SETBUILTIN("float", &PyFloat_Type); SETBUILTIN("frozenset", &PyFrozenSet_Type); SETBUILTIN("property", &PyProperty_Type); SETBUILTIN("int", &PyLong_Type); SETBUILTIN("list", &PyList_Type); + SETBUILTIN("map", &PyMap_Type); SETBUILTIN("object", &PyBaseObject_Type); SETBUILTIN("range", &PyRange_Type); SETBUILTIN("reversed", &PyReversed_Type); @@ -1938,6 +2286,7 @@ SETBUILTIN("super", &PySuper_Type); SETBUILTIN("tuple", &PyTuple_Type); SETBUILTIN("type", &PyType_Type); + SETBUILTIN("zip", &PyZip_Type); debug = PyBool_FromLong(Py_OptimizeFlag == 0); if (PyDict_SetItemString(dict, "__debug__", debug) < 0) { Py_XDECREF(debug); Modified: python/branches/py3k-ctypes-pep3118/Python/ceval.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/ceval.c (original) +++ python/branches/py3k-ctypes-pep3118/Python/ceval.c Wed Apr 30 15:57:13 2008 @@ -1455,6 +1455,7 @@ } continue; + PREDICTED(END_FINALLY); case END_FINALLY: v = POP(); if (PyLong_Check(v)) { @@ -2020,17 +2021,20 @@ case WITH_CLEANUP: { - /* TOP is the context.__exit__ bound method. - Below that are 1-3 values indicating how/why - we entered the finally clause: - - SECOND = None - - (SECOND, THIRD) = (WHY_{RETURN,CONTINUE}), retval - - SECOND = WHY_*; no retval below it - - (SECOND, THIRD, FOURTH) = exc_info() + /* At the top of the stack are 1-3 values indicating + how/why we entered the finally clause: + - TOP = None + - (TOP, SECOND) = (WHY_{RETURN,CONTINUE}), retval + - TOP = WHY_*; no retval below it + - (TOP, SECOND, THIRD) = exc_info() + Below them is EXIT, the context.__exit__ bound method. In the last case, we must call - TOP(SECOND, THIRD, FOURTH) + EXIT(TOP, SECOND, THIRD) otherwise we must call - TOP(None, None, None) + EXIT(None, None, None) + + In all cases, we remove EXIT from the stack, leaving + the rest in the same order. In addition, if the stack represents an exception, *and* the function call returns a 'true' value, we @@ -2039,36 +2043,60 @@ should still be resumed.) */ - x = TOP(); - u = SECOND(); - if (PyLong_Check(u) || u == Py_None) { + PyObject *exit_func; + + u = POP(); + if (u == Py_None) { + exit_func = TOP(); + SET_TOP(u); + v = w = Py_None; + } + else if (PyLong_Check(u)) { + switch(PyLong_AS_LONG(u)) { + case WHY_RETURN: + case WHY_CONTINUE: + /* Retval in TOP. */ + exit_func = SECOND(); + SET_SECOND(TOP()); + SET_TOP(u); + break; + default: + exit_func = TOP(); + SET_TOP(u); + break; + } u = v = w = Py_None; } else { - v = THIRD(); - w = FOURTH(); + v = TOP(); + w = SECOND(); + exit_func = THIRD(); + SET_TOP(u); + SET_SECOND(v); + SET_THIRD(w); } /* XXX Not the fastest way to call it... */ - x = PyObject_CallFunctionObjArgs(x, u, v, w, NULL); - if (x == NULL) + x = PyObject_CallFunctionObjArgs(exit_func, u, v, w, + NULL); + if (x == NULL) { + Py_DECREF(exit_func); break; /* Go to error exit */ + } if (u != Py_None && PyObject_IsTrue(x)) { /* There was an exception and a true return */ - Py_DECREF(x); - x = TOP(); /* Again */ - STACKADJ(-3); + STACKADJ(-2); Py_INCREF(Py_None); SET_TOP(Py_None); - Py_DECREF(x); Py_DECREF(u); Py_DECREF(v); Py_DECREF(w); } else { - /* Let END_FINALLY do its thing */ - Py_DECREF(x); - x = POP(); - Py_DECREF(x); + /* The stack was rearranged to remove EXIT + above. Let END_FINALLY do its thing */ } + Py_DECREF(x); + Py_DECREF(exit_func); + PREDICT(END_FINALLY); break; } @@ -2288,7 +2316,7 @@ else { /* This check is expensive! */ if (PyErr_Occurred()) { - char buf[1024]; + char buf[128]; sprintf(buf, "Stack unwind with exception " "set and why=%d", why); Py_FatalError(buf); Modified: python/branches/py3k-ctypes-pep3118/Python/compile.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/compile.c (original) +++ python/branches/py3k-ctypes-pep3118/Python/compile.c Wed Apr 30 15:57:13 2008 @@ -405,9 +405,9 @@ { basicblock *block; for (block = u->u_blocks; block != NULL; block = block->b_list) { - assert(block != (void *)0xcbcbcbcb); - assert(block != (void *)0xfbfbfbfb); - assert(block != (void *)0xdbdbdbdb); + assert((void *)block != (void *)0xcbcbcbcb); + assert((void *)block != (void *)0xfbfbfbfb); + assert((void *)block != (void *)0xdbdbdbdb); if (block->b_instr != NULL) { assert(block->b_ialloc > 0); assert(block->b_iused > 0); @@ -652,11 +652,16 @@ return b->b_iused++; } -/* Set the i_lineno member of the instruction at offse off if the - line number for the current expression/statement (?) has not +/* Set the i_lineno member of the instruction at offset off if the + line number for the current expression/statement has not already been set. If it has been set, the call has no effect. - Every time a new node is b + The line number is reset in the following cases: + - when entering a new scope + - on each statement + - on each expression that start a new line + - before the "except" clause + - before the "for" and "while" expressions */ static void @@ -885,24 +890,59 @@ { PyObject *t, *v; Py_ssize_t arg; + unsigned char *p, *q; + Py_complex z; + double d; + int real_part_zero, imag_part_zero; /* necessary to make sure types aren't coerced (e.g., int and long) */ /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */ if (PyFloat_Check(o)) { - double d = PyFloat_AS_DOUBLE(o); - unsigned char* p = (unsigned char*) &d; - /* all we need is to make the tuple different in either the 0.0 - * or -0.0 case from all others, just to avoid the "coercion". - */ - if (*p==0 && p[sizeof(double)-1]==0) - t = PyTuple_Pack(3, o, o->ob_type, Py_None); - else - t = PyTuple_Pack(2, o, o->ob_type); - } else { - t = PyTuple_Pack(2, o, o->ob_type); + d = PyFloat_AS_DOUBLE(o); + p = (unsigned char*) &d; + /* all we need is to make the tuple different in either the 0.0 + * or -0.0 case from all others, just to avoid the "coercion". + */ + if (*p==0 && p[sizeof(double)-1]==0) + t = PyTuple_Pack(3, o, o->ob_type, Py_None); + else + t = PyTuple_Pack(2, o, o->ob_type); + } + else if (PyComplex_Check(o)) { + /* complex case is even messier: we need to make complex(x, + 0.) different from complex(x, -0.) and complex(0., y) + different from complex(-0., y), for any x and y. In + particular, all four complex zeros should be + distinguished.*/ + z = PyComplex_AsCComplex(o); + p = (unsigned char*) &(z.real); + q = (unsigned char*) &(z.imag); + /* all that matters here is that on IEEE platforms + real_part_zero will be true if z.real == 0., and false if + z.real == -0. In fact, real_part_zero will also be true + for some other rarely occurring nonzero floats, but this + doesn't matter. Similar comments apply to + imag_part_zero. */ + real_part_zero = *p==0 && p[sizeof(double)-1]==0; + imag_part_zero = *q==0 && q[sizeof(double)-1]==0; + if (real_part_zero && imag_part_zero) { + t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_True); + } + else if (real_part_zero && !imag_part_zero) { + t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_False); + } + else if (!real_part_zero && imag_part_zero) { + t = PyTuple_Pack(4, o, o->ob_type, Py_False, Py_True); + } + else { + t = PyTuple_Pack(2, o, o->ob_type); + } + } + else { + t = PyTuple_Pack(2, o, o->ob_type); } if (t == NULL) - return -1; + return -1; v = PyDict_GetItem(dict, t); if (!v) { @@ -1133,7 +1173,7 @@ int addNone = 1; static PyObject *module; if (!module) { - module = PyUnicode_FromString(""); + module = PyUnicode_InternFromString(""); if (!module) return NULL; } @@ -1477,7 +1517,7 @@ /* initialize statics */ if (locals == NULL) { - locals = PyUnicode_FromString("__locals__"); + locals = PyUnicode_InternFromString("__locals__"); if (locals == NULL) return 0; } @@ -1511,6 +1551,7 @@ { /* use the class name for name mangling */ Py_INCREF(s->v.ClassDef.name); + Py_XDECREF(c->u->u_private); c->u->u_private = s->v.ClassDef.name; /* force it to have one mandatory argument */ c->u->u_argcount = 1; @@ -1715,9 +1756,8 @@ VISIT(c, expr, s->v.For.iter); ADDOP(c, GET_ITER); compiler_use_next_block(c, start); - /* XXX(nnorwitz): is there a better way to handle this? - for loops are special, we want to be able to trace them - each time around, so we need to set an extra line number. */ + /* for expressions must be traced on each iteration, + so we need to set an extra line number. */ c->u->u_lineno_set = 0; ADDOP_JREL(c, FOR_ITER, cleanup); VISIT(c, expr, s->v.For.target); @@ -1764,6 +1804,9 @@ if (!compiler_push_fblock(c, LOOP, loop)) return 0; if (constant == -1) { + /* while expressions must be traced on each iteration, + so we need to set an extra line number. */ + c->u->u_lineno_set = 0; VISIT(c, expr, s->v.While.test); ADDOP_JREL(c, JUMP_IF_FALSE, anchor); ADDOP(c, POP_TOP); @@ -1942,22 +1985,22 @@ for (i = 0; i < n; i++) { excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET( s->v.TryExcept.handlers, i); - if (!handler->type && i < n-1) + if (!handler->v.ExceptHandler.type && i < n-1) return compiler_error(c, "default 'except:' must be last"); - c->u->u_lineno_set = 0; - c->u->u_lineno = handler->lineno; + c->u->u_lineno_set = 0; + c->u->u_lineno = handler->lineno; except = compiler_new_block(c); if (except == NULL) return 0; - if (handler->type) { + if (handler->v.ExceptHandler.type) { ADDOP(c, DUP_TOP); - VISIT(c, expr, handler->type); + VISIT(c, expr, handler->v.ExceptHandler.type); ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH); ADDOP_JREL(c, JUMP_IF_FALSE, except); ADDOP(c, POP_TOP); } ADDOP(c, POP_TOP); - if (handler->name) { + if (handler->v.ExceptHandler.name) { basicblock *cleanup_end, *cleanup_body; cleanup_end = compiler_new_block(c); @@ -1965,7 +2008,7 @@ if(!(cleanup_end || cleanup_body)) return 0; - compiler_nameop(c, handler->name, Store); + compiler_nameop(c, handler->v.ExceptHandler.name, Store); ADDOP(c, POP_TOP); /* @@ -1986,7 +2029,7 @@ return 0; /* second # body */ - VISIT_SEQ(c, stmt, handler->body); + VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body); ADDOP(c, POP_BLOCK); compiler_pop_fblock(c, FINALLY_TRY, cleanup_body); @@ -1998,10 +2041,10 @@ /* name = None */ ADDOP_O(c, LOAD_CONST, Py_None, consts); - compiler_nameop(c, handler->name, Store); + compiler_nameop(c, handler->v.ExceptHandler.name, Store); /* del name */ - compiler_nameop(c, handler->name, Del); + compiler_nameop(c, handler->v.ExceptHandler.name, Del); ADDOP(c, END_FINALLY); compiler_pop_fblock(c, FINALLY_END, cleanup_end); @@ -2009,11 +2052,11 @@ else { ADDOP(c, POP_TOP); ADDOP(c, POP_TOP); - VISIT_SEQ(c, stmt, handler->body); + VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body); } ADDOP_JREL(c, JUMP_FORWARD, end); compiler_use_next_block(c, except); - if (handler->type) + if (handler->v.ExceptHandler.type) ADDOP(c, POP_TOP); } ADDOP(c, END_FINALLY); @@ -2177,10 +2220,18 @@ if (Py_OptimizeFlag) return 1; if (assertion_error == NULL) { - assertion_error = PyUnicode_FromString("AssertionError"); + assertion_error = PyUnicode_InternFromString("AssertionError"); if (assertion_error == NULL) return 0; } + if (s->v.Assert.test->kind == Tuple_kind && + asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) { + const char* msg = + "assertion is always true, perhaps remove parentheses?"; + if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename, + c->u->u_lineno, NULL, NULL) == -1) + return 0; + } VISIT(c, expr, s->v.Assert.test); end = compiler_new_block(c); if (end == NULL) @@ -2306,8 +2357,11 @@ return UNARY_POSITIVE; case USub: return UNARY_NEGATIVE; + default: + PyErr_Format(PyExc_SystemError, + "unary op %d should not be possible", op); + return 0; } - return 0; } static int @@ -2338,8 +2392,11 @@ return BINARY_AND; case FloorDiv: return BINARY_FLOOR_DIVIDE; + default: + PyErr_Format(PyExc_SystemError, + "binary op %d should not be possible", op); + return 0; } - return 0; } static int @@ -2366,8 +2423,9 @@ return PyCmp_IN; case NotIn: return PyCmp_NOT_IN; + default: + return PyCmp_BAD; } - return PyCmp_BAD; } static int @@ -2398,10 +2456,11 @@ return INPLACE_AND; case FloorDiv: return INPLACE_FLOOR_DIVIDE; + default: + PyErr_Format(PyExc_SystemError, + "inplace binary op %d should not be possible", op); + return 0; } - PyErr_Format(PyExc_SystemError, - "inplace binary op %d should not be possible", op); - return 0; } static int @@ -2572,6 +2631,11 @@ for (i = 0; i < n; i++) { expr_ty elt = asdl_seq_GET(e->v.List.elts, i); if (elt->kind == Starred_kind && !seen_star) { + if ((i >= (1 << 8)) || + (n-i-1 >= (INT_MAX >> 8))) + return compiler_error(c, + "too many expressions in " + "star-unpacking assignment"); ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8))); seen_star = 1; asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value); @@ -2600,6 +2664,11 @@ for (i = 0; i < n; i++) { expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i); if (elt->kind == Starred_kind && !seen_star) { + if ((i >= (1 << 8)) || + (n-i-1 >= (INT_MAX >> 8))) + return compiler_error(c, + "too many expressions in " + "star-unpacking assignment"); ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8))); seen_star = 1; asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value); @@ -3040,7 +3109,7 @@ { static identifier enter_attr, exit_attr; basicblock *block, *finally; - identifier tmpexit, tmpvalue = NULL; + identifier tmpvalue = NULL; assert(s->kind == With_kind); @@ -3060,12 +3129,6 @@ if (!block || !finally) return 0; - /* Create a temporary variable to hold context.__exit__ */ - tmpexit = compiler_new_tmpname(c); - if (tmpexit == NULL) - return 0; - PyArena_AddPyObject(c->c_arena, tmpexit); - if (s->v.With.optional_vars) { /* Create a temporary variable to hold context.__enter__(). We need to do this rather than preserving it on the stack @@ -3085,11 +3148,10 @@ /* Evaluate EXPR */ VISIT(c, expr, s->v.With.context_expr); - /* Squirrel away context.__exit__ */ + /* Squirrel away context.__exit__ by stuffing it under context */ ADDOP(c, DUP_TOP); ADDOP_O(c, LOAD_ATTR, exit_attr, names); - if (!compiler_nameop(c, tmpexit, Store)) - return 0; + ADDOP(c, ROT_TWO); /* Call context.__enter__() */ ADDOP_O(c, LOAD_ATTR, enter_attr, names); @@ -3133,10 +3195,9 @@ if (!compiler_push_fblock(c, FINALLY_END, finally)) return 0; - /* Finally block starts; push tmpexit and issue our magic opcode. */ - if (!compiler_nameop(c, tmpexit, Load) || - !compiler_nameop(c, tmpexit, Del)) - return 0; + /* Finally block starts; context.__exit__ is on the stack under + the exception or return information. Just issue our magic + opcode. */ ADDOP(c, WITH_CLEANUP); /* Finally block ends. */ @@ -3727,10 +3788,7 @@ assert(d_bytecode >= 0); assert(d_lineno >= 0); - /* XXX(nnorwitz): is there a better way to handle this? - for loops are special, we want to be able to trace them - each time around, so we need to set an extra line number. */ - if (d_lineno == 0 && i->i_opcode != FOR_ITER) + if(d_bytecode == 0 && d_lineno == 0) return 1; if (d_bytecode > 255) { Modified: python/branches/py3k-ctypes-pep3118/Python/errors.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/errors.c (original) +++ python/branches/py3k-ctypes-pep3118/Python/errors.c Wed Apr 30 15:57:13 2008 @@ -673,70 +673,6 @@ extern PyObject *PyModule_GetWarningsModule(void); -/* Function to issue a warning message; may raise an exception. */ -int -PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level) -{ - PyObject *dict, *func = NULL; - PyObject *warnings_module = PyModule_GetWarningsModule(); - - if (warnings_module != NULL) { - dict = PyModule_GetDict(warnings_module); - if (dict != NULL) - func = PyDict_GetItemString(dict, "warn"); - } - if (func == NULL) { - PySys_WriteStderr("warning: %s\n", message); - return 0; - } - else { - PyObject *res; - - if (category == NULL) - category = PyExc_RuntimeWarning; - res = PyObject_CallFunction(func, "sOn", - message, category, stack_level); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; - } -} - -/* Warning with explicit origin */ -int -PyErr_WarnExplicit(PyObject *category, const char *message, - const char *filename, int lineno, - const char *module, PyObject *registry) -{ - PyObject *mod, *dict, *func = NULL; - - mod = PyImport_ImportModuleNoBlock("warnings"); - if (mod != NULL) { - dict = PyModule_GetDict(mod); - func = PyDict_GetItemString(dict, "warn_explicit"); - Py_DECREF(mod); - } - if (func == NULL) { - PySys_WriteStderr("warning: %s\n", message); - return 0; - } - else { - PyObject *res; - - if (category == NULL) - category = PyExc_RuntimeWarning; - if (registry == NULL) - registry = Py_None; - res = PyObject_CallFunction(func, "sOsizO", message, category, - filename, lineno, module, registry); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; - } -} - /* Set file and line information for the current exception. If the exception is not a SyntaxError, also sets additional attributes Modified: python/branches/py3k-ctypes-pep3118/Python/frozenmain.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/frozenmain.c (original) +++ python/branches/py3k-ctypes-pep3118/Python/frozenmain.c Wed Apr 30 15:57:13 2008 @@ -2,6 +2,7 @@ /* Python interpreter main program for frozen scripts */ #include "Python.h" +#include #ifdef MS_WINDOWS extern void PyWinFreeze_ExeInit(void); @@ -15,9 +16,13 @@ Py_FrozenMain(int argc, char **argv) { char *p; - int n, sts; + int i, n, sts; int inspect = 0; int unbuffered = 0; + char *oldloc; + wchar_t **argv_copy = PyMem_Malloc(sizeof(wchar_t*)*argc); + /* We need a second copies, as Python might modify the first one. */ + wchar_t **argv_copy2 = PyMem_Malloc(sizeof(wchar_t*)*argc); Py_FrozenFlag = 1; /* Suppress errors from getpath.c */ @@ -32,10 +37,33 @@ setbuf(stderr, (char *)NULL); } + if (!argv_copy) { + fprintf(stderr, "out of memory"); + return 1; + } + + oldloc = setlocale(LC_ALL, NULL); + setlocale(LC_ALL, ""); + for (i = 0; i < argc; i++) { + size_t argsize = mbstowcs(NULL, argv[i], 0); + if (argsize == (size_t)-1) { + fprintf(stderr, "Could not convert argument %d to string", i); + return 1; + } + argv_copy[i] = PyMem_Malloc((argsize+1)*sizeof(wchar_t)); + argv_copy2[i] = argv_copy[i]; + if (!argv_copy[i]) { + fprintf(stderr, "out of memory"); + return 1; + } + mbstowcs(argv_copy[i], argv[i], argsize+1); + } + setlocale(LC_ALL, oldloc); + #ifdef MS_WINDOWS PyInitFrozenExtensions(); #endif /* MS_WINDOWS */ - Py_SetProgramName(argv[0]); + Py_SetProgramName(argv_copy[0]); Py_Initialize(); #ifdef MS_WINDOWS PyWinFreeze_ExeInit(); @@ -45,7 +73,7 @@ fprintf(stderr, "Python %s\n%s\n", Py_GetVersion(), Py_GetCopyright()); - PySys_SetArgv(argc, argv); + PySys_SetArgv(argc, argv_copy); n = PyImport_ImportFrozenModule("__main__"); if (n == 0) @@ -64,5 +92,10 @@ PyWinFreeze_ExeTerm(); #endif Py_Finalize(); + for (i = 0; i < argc; i++) { + PyMem_Free(argv_copy2[i]); + } + PyMem_Free(argv_copy); + PyMem_Free(argv_copy2); return sts; } Modified: python/branches/py3k-ctypes-pep3118/Python/future.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/future.c (original) +++ python/branches/py3k-ctypes-pep3118/Python/future.c Wed Apr 30 15:57:13 2008 @@ -33,6 +33,10 @@ continue; } else if (strcmp(feature, FUTURE_WITH_STATEMENT) == 0) { continue; + } else if (strcmp(feature, FUTURE_PRINT_FUNCTION) == 0) { + continue; + } else if (strcmp(feature, FUTURE_UNICODE_LITERALS) == 0) { + continue; } else if (strcmp(feature, "braces") == 0) { PyErr_SetString(PyExc_SyntaxError, "not a chance"); Modified: python/branches/py3k-ctypes-pep3118/Python/getargs.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/getargs.c (original) +++ python/branches/py3k-ctypes-pep3118/Python/getargs.c Wed Apr 30 15:57:13 2008 @@ -154,7 +154,7 @@ PyMem_FREE(ptr); return -1; } - if(PyList_Append(*freelist, cobj)) { + if (PyList_Append(*freelist, cobj)) { PyMem_FREE(ptr); Py_DECREF(cobj); return -1; @@ -166,8 +166,8 @@ static int cleanreturn(int retval, PyObject *freelist) { - if(freelist) { - if((retval) == 0) { + if (freelist) { + if (retval == 0) { Py_ssize_t len = PyList_GET_SIZE(freelist), i; for (i = 0; i < len; i++) PyMem_FREE(PyCObject_AsVoidPtr( @@ -663,7 +663,6 @@ } case 'n': /* Py_ssize_t */ -#if SIZEOF_SIZE_T != SIZEOF_LONG { PyObject *iobj; Py_ssize_t *p = va_arg(*p_va, Py_ssize_t *); @@ -672,14 +671,12 @@ return converterr("integer", arg, msgbuf, bufsize); iobj = PyNumber_Index(arg); if (iobj != NULL) - ival = PyLong_AsSsize_t(arg); + ival = PyLong_AsSsize_t(iobj); if (ival == -1 && PyErr_Occurred()) return converterr("integer", arg, msgbuf, bufsize); *p = ival; break; } -#endif - /* Fall through from 'n' to 'l' if Py_ssize_t is int */ case 'l': {/* long int */ long *p = va_arg(*p_va, long *); long ival; @@ -708,7 +705,7 @@ case 'L': {/* PY_LONG_LONG */ PY_LONG_LONG *p = va_arg( *p_va, PY_LONG_LONG * ); PY_LONG_LONG ival = PyLong_AsLongLong( arg ); - if( ival == (PY_LONG_LONG)-1 && PyErr_Occurred() ) { + if (ival == (PY_LONG_LONG)-1 && PyErr_Occurred() ) { return converterr("long", arg, msgbuf, bufsize); } else { *p = ival; @@ -823,6 +820,9 @@ } else return converterr("string", arg, msgbuf, bufsize); + /* XXX(gb): this test is completely wrong -- p is a + * byte string while arg is a Unicode. I *think* it should + * check against the size of uarg... */ if ((Py_ssize_t)strlen(*p) != PyUnicode_GetSize(arg)) return converterr("string without null bytes", arg, msgbuf, bufsize); @@ -898,6 +898,7 @@ } format++; } + /* XXX(gb): same comment as for 's' applies here... */ else if (*p != NULL && (Py_ssize_t)strlen(*p) != PyUnicode_GetSize(arg)) return converterr( @@ -1045,7 +1046,7 @@ "(memory error)", arg, msgbuf, bufsize); } - if(addcleanup(*buffer, freelist)) { + if (addcleanup(*buffer, freelist)) { Py_DECREF(s); return converterr( "(cleanup problem)", @@ -1087,7 +1088,7 @@ return converterr("(memory error)", arg, msgbuf, bufsize); } - if(addcleanup(*buffer, freelist)) { + if (addcleanup(*buffer, freelist)) { Py_DECREF(s); return converterr("(cleanup problem)", arg, msgbuf, bufsize); @@ -1401,6 +1402,7 @@ return retval; } +#define IS_END_OF_FORMAT(c) (c == '\0' || c == ';' || c == ':') static int vgetargskeywords(PyObject *args, PyObject *keywords, const char *format, @@ -1408,13 +1410,10 @@ { char msgbuf[512]; int levels[32]; - const char *fname, *message; - int min, max; - const char *formatsave; + const char *fname, *msg, *custom_msg, *keyword; + int min = INT_MAX; int i, len, nargs, nkeywords; - const char *msg; - char **p; - PyObject *freelist = NULL; + PyObject *freelist = NULL, *current_arg; assert(args != NULL && PyTuple_Check(args)); assert(keywords == NULL || PyDict_Check(keywords)); @@ -1422,168 +1421,108 @@ assert(kwlist != NULL); assert(p_va != NULL); - /* Search the format: - message <- error msg, if any (else NULL). - fname <- routine name, if any (else NULL). - min <- # of required arguments, or -1 if all are required. - max <- most arguments (required + optional). - Check that kwlist has a non-NULL entry for each arg. - Raise error if a tuple arg spec is found. - */ - fname = message = NULL; - formatsave = format; - p = kwlist; - min = -1; - max = 0; - while ((i = *format++) != '\0') { - if (isalpha(Py_CHARMASK(i)) && i != 'e') { - max++; - if (*p == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "more argument specifiers than " - "keyword list entries"); - return 0; - } - p++; - } - else if (i == '|') - min = max; - else if (i == ':') { - fname = format; - break; - } - else if (i == ';') { - message = format; - break; - } - else if (i == '(') { - PyErr_SetString(PyExc_RuntimeError, - "tuple found in format when using keyword " - "arguments"); - return 0; - } - } - format = formatsave; - if (*p != NULL) { - PyErr_SetString(PyExc_RuntimeError, - "more keyword list entries than " - "argument specifiers"); - return 0; + /* grab the function name or custom error msg first (mutually exclusive) */ + fname = strchr(format, ':'); + if (fname) { + fname++; + custom_msg = NULL; } - if (min < 0) { - /* All arguments are required. */ - min = max; - } - - nargs = PyTuple_GET_SIZE(args); - nkeywords = keywords == NULL ? 0 : PyDict_Size(keywords); - - /* make sure there are no duplicate values for an argument; - its not clear when to use the term "keyword argument vs. - keyword parameter in messages */ - if (nkeywords > 0) { - for (i = 0; i < nargs; i++) { - const char *thiskw = kwlist[i]; - if (thiskw == NULL) - break; - if (PyDict_GetItemString(keywords, thiskw)) { - PyErr_Format(PyExc_TypeError, - "keyword parameter '%s' was given " - "by position and by name", - thiskw); - return 0; - } - else if (PyErr_Occurred()) - return 0; - } + else { + custom_msg = strchr(format,';'); + if (custom_msg) + custom_msg++; } - /* required arguments missing from args can be supplied by keyword - arguments; set len to the number of positional arguments, and, - if that's less than the minimum required, add in the number of - required arguments that are supplied by keywords */ - len = nargs; - if (nkeywords > 0 && nargs < min) { - for (i = nargs; i < min; i++) { - if (PyDict_GetItemString(keywords, kwlist[i])) - len++; - else if (PyErr_Occurred()) - return 0; - } - } + /* scan kwlist and get greatest possible nbr of args */ + for (len=0; kwlist[len]; len++) + continue; - /* make sure we got an acceptable number of arguments; the message - is a little confusing with keywords since keyword arguments - which are supplied, but don't match the required arguments - are not included in the "%d given" part of the message - XXX and this isn't a bug!? */ - if (len < min || max < len) { - if (message == NULL) { - PyOS_snprintf(msgbuf, sizeof(msgbuf), - "%.200s%s takes %s %d argument%s " - "(%d given)", - fname==NULL ? "function" : fname, - fname==NULL ? "" : "()", - min==max ? "exactly" - : len < min ? "at least" : "at most", - len < min ? min : max, - (len < min ? min : max) == 1 ? "" : "s", - len); - message = msgbuf; - } - PyErr_SetString(PyExc_TypeError, message); + nargs = PyTuple_GET_SIZE(args); + nkeywords = (keywords == NULL) ? 0 : PyDict_Size(keywords); + if (nargs + nkeywords > len) { + PyErr_Format(PyExc_TypeError, "%s%s takes at most %d " + "argument%s (%d given)", + (fname == NULL) ? "function" : fname, + (fname == NULL) ? "" : "()", + len, + (len == 1) ? "" : "s", + nargs + nkeywords); return 0; } - /* convert the positional arguments */ - for (i = 0; i < nargs; i++) { - if (*format == '|') + /* convert tuple args and keyword args in same loop, using kwlist to drive process */ + for (i = 0; i < len; i++) { + keyword = kwlist[i]; + if (*format == '|') { + min = i; format++; - msg = convertitem(PyTuple_GET_ITEM(args, i), &format, p_va, - flags, levels, msgbuf, sizeof(msgbuf), - &freelist); - if (msg) { - seterror(i+1, msg, levels, fname, message); + } + if (IS_END_OF_FORMAT(*format)) { + PyErr_Format(PyExc_RuntimeError, + "More keyword list entries (%d) than " + "format specifiers (%d)", len, i); return cleanreturn(0, freelist); } - } - - /* handle no keyword parameters in call */ - if (nkeywords == 0) - return cleanreturn(1, freelist); - - /* convert the keyword arguments; this uses the format - string where it was left after processing args */ - for (i = nargs; i < max; i++) { - PyObject *item; - if (*format == '|') - format++; - item = PyDict_GetItemString(keywords, kwlist[i]); - if (item != NULL) { - Py_INCREF(item); - msg = convertitem(item, &format, p_va, flags, levels, - msgbuf, sizeof(msgbuf), &freelist); - Py_DECREF(item); - if (msg) { - seterror(i+1, msg, levels, fname, message); + current_arg = NULL; + if (nkeywords) { + current_arg = PyDict_GetItemString(keywords, keyword); + } + if (current_arg) { + --nkeywords; + if (i < nargs) { + /* arg present in tuple and in dict */ + PyErr_Format(PyExc_TypeError, + "Argument given by name ('%s') " + "and position (%d)", + keyword, i+1); return cleanreturn(0, freelist); } - --nkeywords; - if (nkeywords == 0) - break; } - else if (PyErr_Occurred()) + else if (nkeywords && PyErr_Occurred()) return cleanreturn(0, freelist); - else { - msg = skipitem(&format, p_va, flags); + else if (i < nargs) + current_arg = PyTuple_GET_ITEM(args, i); + + if (current_arg) { + msg = convertitem(current_arg, &format, p_va, flags, + levels, msgbuf, sizeof(msgbuf), &freelist); if (msg) { - levels[0] = 0; - seterror(i+1, msg, levels, fname, message); + seterror(i+1, msg, levels, fname, custom_msg); return cleanreturn(0, freelist); } + continue; + } + + if (i < min) { + PyErr_Format(PyExc_TypeError, "Required argument " + "'%s' (pos %d) not found", + keyword, i+1); + return cleanreturn(0, freelist); + } + /* current code reports success when all required args + * fulfilled and no keyword args left, with no further + * validation. XXX Maybe skip this in debug build ? + */ + if (!nkeywords) + return cleanreturn(1, freelist); + + /* We are into optional args, skip thru to any remaining + * keyword args */ + msg = skipitem(&format, p_va, flags); + if (msg) { + PyErr_Format(PyExc_RuntimeError, "%s: '%s'", msg, + format); + return cleanreturn(0, freelist); } } + if (!IS_END_OF_FORMAT(*format)) { + PyErr_Format(PyExc_RuntimeError, + "more argument specifiers than keyword list entries " + "(remaining format:'%s')", format); + return cleanreturn(0, freelist); + } + /* make sure there are no extraneous keyword arguments */ if (nkeywords > 0) { PyObject *key, *value; @@ -1597,7 +1536,7 @@ return cleanreturn(0, freelist); } ks = PyUnicode_AsString(key); - for (i = 0; i < max; i++) { + for (i = 0; i < len; i++) { if (!strcmp(ks, kwlist[i])) { match = 1; break; @@ -1620,7 +1559,7 @@ static char * skipitem(const char **p_format, va_list *p_va, int flags) { - const char *format = *p_format; + const char *format = *p_format; char c = *format++; switch (c) { @@ -1726,15 +1665,32 @@ break; } + case '(': /* bypass tuple, not handled at all previously */ + { + char *msg; + for (;;) { + if (*format==')') + break; + if (IS_END_OF_FORMAT(*format)) + return "Unmatched left paren in format " + "string"; + msg = skipitem(&format, p_va, flags); + if (msg) + return msg; + } + format++; + break; + } + + case ')': + return "Unmatched right paren in format string"; + default: err: return "impossible"; } - /* The "(...)" format code for tuples is not handled here because - * it is not allowed with keyword args. */ - *p_format = format; return NULL; } Modified: python/branches/py3k-ctypes-pep3118/Python/getcopyright.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/getcopyright.c (original) +++ python/branches/py3k-ctypes-pep3118/Python/getcopyright.c Wed Apr 30 15:57:13 2008 @@ -4,7 +4,7 @@ static char cprt[] = "\ -Copyright (c) 2001-2007 Python Software Foundation.\n\ +Copyright (c) 2001-2008 Python Software Foundation.\n\ All Rights Reserved.\n\ \n\ Copyright (c) 2000 BeOpen.com.\n\ Modified: python/branches/py3k-ctypes-pep3118/Python/getopt.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/getopt.c (original) +++ python/branches/py3k-ctypes-pep3118/Python/getopt.c Wed Apr 30 15:57:13 2008 @@ -27,8 +27,11 @@ /* Modified to support --help and --version, as well as /? on Windows * by Georg Brandl. */ +#include #include #include +#include +#include #ifdef __cplusplus extern "C" { @@ -36,40 +39,40 @@ int _PyOS_opterr = 1; /* generate error messages */ int _PyOS_optind = 1; /* index into argv array */ -char *_PyOS_optarg = NULL; /* optional argument */ +wchar_t *_PyOS_optarg = NULL; /* optional argument */ -int _PyOS_GetOpt(int argc, char **argv, char *optstring) +int _PyOS_GetOpt(int argc, wchar_t **argv, wchar_t *optstring) { - static char *opt_ptr = ""; - char *ptr; - int option; + static wchar_t *opt_ptr = L""; + wchar_t *ptr; + wchar_t option; if (*opt_ptr == '\0') { if (_PyOS_optind >= argc) return -1; #ifdef MS_WINDOWS - else if (strcmp(argv[_PyOS_optind], "/?") == 0) { + else if (wcscmp(argv[_PyOS_optind], L"/?") == 0) { ++_PyOS_optind; return 'h'; } #endif - else if (argv[_PyOS_optind][0] != '-' || - argv[_PyOS_optind][1] == '\0' /* lone dash */ ) + else if (argv[_PyOS_optind][0] != L'-' || + argv[_PyOS_optind][1] == L'\0' /* lone dash */ ) return -1; - else if (strcmp(argv[_PyOS_optind], "--") == 0) { + else if (wcscmp(argv[_PyOS_optind], L"--") == 0) { ++_PyOS_optind; return -1; } - else if (strcmp(argv[_PyOS_optind], "--help") == 0) { + else if (wcscmp(argv[_PyOS_optind], L"--help") == 0) { ++_PyOS_optind; return 'h'; } - else if (strcmp(argv[_PyOS_optind], "--version") == 0) { + else if (wcscmp(argv[_PyOS_optind], L"--version") == 0) { ++_PyOS_optind; return 'V'; } @@ -78,27 +81,38 @@ opt_ptr = &argv[_PyOS_optind++][1]; } - if ( (option = *opt_ptr++) == '\0') + if ( (option = *opt_ptr++) == L'\0') return -1; - - if ((ptr = strchr(optstring, option)) == NULL) { + + if (option == 'J') { + fprintf(stderr, "-J is reserved for Jython\n"); + return '_'; + } + + if (option == 'X') { + fprintf(stderr, + "-X is reserved for implementation-specific arguments\n"); + return '_'; + } + + if ((ptr = wcschr(optstring, option)) == NULL) { if (_PyOS_opterr) - fprintf(stderr, "Unknown option: -%c\n", option); + fprintf(stderr, "Unknown option: -%c\n", (char)option); return '_'; } - if (*(ptr + 1) == ':') { - if (*opt_ptr != '\0') { + if (*(ptr + 1) == L':') { + if (*opt_ptr != L'\0') { _PyOS_optarg = opt_ptr; - opt_ptr = ""; + opt_ptr = L""; } else { if (_PyOS_optind >= argc) { if (_PyOS_opterr) fprintf(stderr, - "Argument expected for the -%c option\n", option); + "Argument expected for the -%c option\n", (char)option); return '_'; } Modified: python/branches/py3k-ctypes-pep3118/Python/graminit.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/graminit.c (original) +++ python/branches/py3k-ctypes-pep3118/Python/graminit.c Wed Apr 30 15:57:13 2008 @@ -1,3 +1,5 @@ +/* Generated by Parser/pgen */ + #include "pgenheaders.h" #include "grammar.h" static arc arcs_0_0[3] = { Deleted: python/branches/py3k-ctypes-pep3118/Python/hypot.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/hypot.c Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,25 +0,0 @@ -/* hypot() replacement */ - -#include "Python.h" - -#ifndef HAVE_HYPOT -double hypot(double x, double y) -{ - double yx; - - x = fabs(x); - y = fabs(y); - if (x < y) { - double temp = x; - x = y; - y = temp; - } - if (x == 0.) - return 0.; - else { - yx = y/x; - return x*sqrt(1.+yx*yx); - } -} -#endif /* HAVE_HYPOT */ - Modified: python/branches/py3k-ctypes-pep3118/Python/import.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/import.c (original) +++ python/branches/py3k-ctypes-pep3118/Python/import.c Wed Apr 30 15:57:13 2008 @@ -22,6 +22,11 @@ extern "C" { #endif +#ifdef MS_WINDOWS +/* for stat.st_mode */ +typedef unsigned short mode_t; +#endif + extern time_t PyOS_GetLastModificationTime(char *, FILE *); /* In getmtime.c */ @@ -67,6 +72,7 @@ storing constants that should have been removed) Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp) Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode) + Python 2.6a1: 62161 (WITH_CLEANUP optimization) Python 3000: 3000 3010 (removed UNARY_CONVERT) 3020 (added BUILD_SET) @@ -79,9 +85,9 @@ 3090 (kill str8 interning) 3100 (merge from 2.6a0, see 62151) 3102 (__file__ points to source file) -. + Python 3.0a4: 3110 (WITH_CLEANUP optimization). */ -#define MAGIC (3102 | ((long)'\r'<<16) | ((long)'\n'<<24)) +#define MAGIC (3110 | ((long)'\r'<<16) | ((long)'\n'<<24)) /* Magic word as global; note that _PyImport_Init() can change the value of this global to accommodate for alterations of how the @@ -371,6 +377,8 @@ "path", "argv", "ps1", "ps2", "last_type", "last_value", "last_traceback", "path_hooks", "path_importer_cache", "meta_path", + /* misc stuff */ + "flags", "float_info", NULL }; @@ -813,12 +821,14 @@ { PyCodeObject *co = NULL; mod_ty mod; + PyCompilerFlags flags; PyArena *arena = PyArena_New(); if (arena == NULL) return NULL; + flags.cf_flags = 0; mod = PyParser_ASTFromFile(fp, pathname, NULL, - Py_file_input, 0, 0, 0, + Py_file_input, 0, 0, &flags, NULL, arena); if (mod) { co = PyAST_Compile(mod, pathname, NULL, arena); @@ -831,7 +841,7 @@ /* Helper to open a bytecode file for writing in exclusive mode */ static FILE * -open_exclusive(char *filename) +open_exclusive(char *filename, mode_t mode) { #if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC) /* Use O_EXCL to avoid a race condition when another process tries to @@ -847,9 +857,9 @@ |O_BINARY /* necessary for Windows */ #endif #ifdef __VMS - , 0666, "ctxt=bin", "shr=nil" + , mode, "ctxt=bin", "shr=nil" #else - , 0666 + , mode #endif ); if (fd < 0) @@ -868,11 +878,13 @@ remove the file. */ static void -write_compiled_module(PyCodeObject *co, char *cpathname, time_t mtime) +write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat) { FILE *fp; + time_t mtime = srcstat->st_mtime; + mode_t mode = srcstat->st_mode; - fp = open_exclusive(cpathname); + fp = open_exclusive(cpathname, mode); if (fp == NULL) { if (Py_VerboseFlag) PySys_WriteStderr( @@ -909,17 +921,16 @@ static PyObject * load_source_module(char *name, char *pathname, FILE *fp) { - time_t mtime; + struct stat st; FILE *fpc; char buf[MAXPATHLEN+1]; char *cpathname; PyCodeObject *co; PyObject *m; - - mtime = PyOS_GetLastModificationTime(pathname, fp); - if (mtime == (time_t)(-1)) { + + if (fstat(fileno(fp), &st) != 0) { PyErr_Format(PyExc_RuntimeError, - "unable to get modification time from '%s'", + "unable to get file status from '%s'", pathname); return NULL; } @@ -928,7 +939,7 @@ in 4 bytes. This will be fine until sometime in the year 2038, when a 4-byte signed time_t will overflow. */ - if (mtime >> 32) { + if (st.st_mtime >> 32) { PyErr_SetString(PyExc_OverflowError, "modification time overflows a 4 byte field"); return NULL; @@ -937,7 +948,7 @@ cpathname = make_compiled_pathname(pathname, buf, (size_t)MAXPATHLEN + 1); if (cpathname != NULL && - (fpc = check_compiled_module(pathname, mtime, cpathname))) { + (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) { co = read_compiled_module(cpathname, fpc); fclose(fpc); if (co == NULL) @@ -957,7 +968,7 @@ if (cpathname) { PyObject *ro = PySys_GetObject("dont_write_bytecode"); if (ro == NULL || !PyObject_IsTrue(ro)) - write_compiled_module(co, cpathname, mtime); + write_compiled_module(co, cpathname, &st); } } m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname); @@ -988,7 +999,7 @@ } strncpy(py, file, len-1); - py[len] = '\0'; + py[len-1] = '\0'; if (stat(py, &statbuf) == 0 && S_ISREG(statbuf.st_mode)) { u = PyUnicode_DecodeFSDefault(py); @@ -2675,7 +2686,7 @@ buf[2] = (char) ((pyc_magic >> 16) & 0xff); buf[3] = (char) ((pyc_magic >> 24) & 0xff); - return PyBytes_FromStringAndSize(buf, 4); + return PyString_FromStringAndSize(buf, 4); } static PyObject * Modified: python/branches/py3k-ctypes-pep3118/Python/marshal.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/marshal.c (original) +++ python/branches/py3k-ctypes-pep3118/Python/marshal.c Wed Apr 30 15:57:13 2008 @@ -482,7 +482,7 @@ { /* NULL is a valid return value, it does not necessarily means that an exception is set. */ - PyObject *v, *v2, *v3; + PyObject *v, *v2; long i, n; int type = r_byte(p); PyObject *retval; @@ -812,7 +812,7 @@ retval = NULL; break; } - v = PyTuple_New((int)n); + v = (type == TYPE_SET) ? PySet_New(NULL) : PyFrozenSet_New(NULL); if (v == NULL) { retval = NULL; break; @@ -827,18 +827,15 @@ v = NULL; break; } - PyTuple_SET_ITEM(v, (int)i, v2); + if (PySet_Add(v, v2) == -1) { + Py_DECREF(v); + Py_DECREF(v2); + v = NULL; + break; + } + Py_DECREF(v2); } - if (v == NULL) { - retval = NULL; - break; - } - if (type == TYPE_SET) - v3 = PySet_New(v); - else - v3 = PyFrozenSet_New(v); - Py_DECREF(v); - retval = v3; + retval = v; break; case TYPE_CODE: Deleted: python/branches/py3k-ctypes-pep3118/Python/memmove.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/memmove.c Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,25 +0,0 @@ - -/* A perhaps slow but I hope correct implementation of memmove */ - -extern char *memcpy(char *, char *, int); - -char * -memmove(char *dst, char *src, int n) -{ - char *realdst = dst; - if (n <= 0) - return dst; - if (src >= dst+n || dst >= src+n) - return memcpy(dst, src, n); - if (src > dst) { - while (--n >= 0) - *dst++ = *src++; - } - else if (src < dst) { - src += n; - dst += n; - while (--n >= 0) - *--dst = *--src; - } - return realdst; -} Modified: python/branches/py3k-ctypes-pep3118/Python/mystrtoul.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/mystrtoul.c (original) +++ python/branches/py3k-ctypes-pep3118/Python/mystrtoul.c Wed Apr 30 15:57:13 2008 @@ -5,14 +5,6 @@ #define _SGI_MP_SOURCE #endif -/* Convert a possibly signed character to a nonnegative int */ -/* XXX This assumes characters are 8 bits wide */ -#ifdef __CHAR_UNSIGNED__ -#define Py_CHARMASK(c) (c) -#else -#define Py_CHARMASK(c) ((c) & 0xff) -#endif - /* strtol and strtoul, renamed to avoid conflicts */ Modified: python/branches/py3k-ctypes-pep3118/Python/peephole.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/peephole.c (original) +++ python/branches/py3k-ctypes-pep3118/Python/peephole.c Wed Apr 30 15:57:13 2008 @@ -29,7 +29,7 @@ Also works for BUILD_LIST when followed by an "in" or "not in" test. */ static int -tuple_of_constants(unsigned char *codestr, int n, PyObject *consts) +tuple_of_constants(unsigned char *codestr, Py_ssize_t n, PyObject *consts) { PyObject *newconst, *constant; Py_ssize_t i, arg, len_consts; @@ -220,7 +220,7 @@ } static unsigned int * -markblocks(unsigned char *code, int len) +markblocks(unsigned char *code, Py_ssize_t len) { unsigned int *blocks = (unsigned int *)PyMem_Malloc(len*sizeof(int)); int i,j, opcode, blockcnt = 0; @@ -342,7 +342,7 @@ if (codestr == NULL) goto exitUnchanged; codestr = (unsigned char *)memcpy(codestr, - PyString_AS_STRING(code), codelen); + PyString_AS_STRING(code), codelen); /* Verify that RETURN_VALUE terminates the codestring. This allows the various transformation patterns to look ahead several Modified: python/branches/py3k-ctypes-pep3118/Python/pystrcmp.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/pystrcmp.c (original) +++ python/branches/py3k-ctypes-pep3118/Python/pystrcmp.c Wed Apr 30 15:57:13 2008 @@ -1,4 +1,4 @@ -/* Cross platform case insenstive string compare functions +/* Cross platform case insensitive string compare functions */ #include "Python.h" @@ -8,18 +8,19 @@ { if (size == 0) return 0; - while ((--size > 0) && (tolower(*s1) == tolower(*s2))) { + while ((--size > 0) && + (tolower((unsigned)*s1) == tolower((unsigned)*s2))) { if (!*s1++ || !*s2++) break; } - return tolower(*s1) - tolower(*s2); + return tolower((unsigned)*s1) - tolower((unsigned)*s2); } int PyOS_mystricmp(const char *s1, const char *s2) { - while (*s1 && (tolower(*s1++) == tolower(*s2++))) { + while (*s1 && (tolower((unsigned)*s1++) == tolower((unsigned)*s2++))) { ; } - return (tolower(*s1) - tolower(*s2)); + return (tolower((unsigned)*s1) - tolower((unsigned)*s2)); } Modified: python/branches/py3k-ctypes-pep3118/Python/pystrtod.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/pystrtod.c (original) +++ python/branches/py3k-ctypes-pep3118/Python/pystrtod.c Wed Apr 30 15:57:13 2008 @@ -7,7 +7,6 @@ #define ISSPACE(c) ((c) == ' ' || (c) == '\f' || (c) == '\n' || \ (c) == '\r' || (c) == '\t' || (c) == '\v') #define ISDIGIT(c) ((c) >= '0' && (c) <= '9') -#define ISXDIGIT(c) (ISDIGIT(c) || ((c) >= 'a' && (c) <= 'f') || ((c) >= 'A' && (c) <= 'F')) /** @@ -123,7 +122,8 @@ errno = EINVAL; return val; } - /* For the other cases, we need not convert the decimal point */ + /* For the other cases, we need not convert the decimal + point */ } /* Set errno to zero, so that we can distinguish zero results @@ -134,7 +134,8 @@ { char *copy, *c; - /* We need to convert the '.' to the locale specific decimal point */ + /* We need to convert the '.' to the locale specific decimal + point */ copy = (char *)PyMem_MALLOC(end - digits_pos + 1 + decimal_point_len); if (copy == NULL) { @@ -149,7 +150,8 @@ c += decimal_point_pos - digits_pos; memcpy(c, decimal_point, decimal_point_len); c += decimal_point_len; - memcpy(c, decimal_point_pos + 1, end - (decimal_point_pos + 1)); + memcpy(c, decimal_point_pos + 1, + end - (decimal_point_pos + 1)); c += end - (decimal_point_pos + 1); *c = 0; @@ -185,11 +187,235 @@ return val; } +/* Given a string that may have a decimal point in the current + locale, change it back to a dot. Since the string cannot get + longer, no need for a maximum buffer size parameter. */ +Py_LOCAL_INLINE(void) +change_decimal_from_locale_to_dot(char* buffer) +{ + struct lconv *locale_data = localeconv(); + const char *decimal_point = locale_data->decimal_point; + + if (decimal_point[0] != '.' || decimal_point[1] != 0) { + size_t decimal_point_len = strlen(decimal_point); + + if (*buffer == '+' || *buffer == '-') + buffer++; + while (isdigit(Py_CHARMASK(*buffer))) + buffer++; + if (strncmp(buffer, decimal_point, decimal_point_len) == 0) { + *buffer = '.'; + buffer++; + if (decimal_point_len > 1) { + /* buffer needs to get smaller */ + size_t rest_len = strlen(buffer + + (decimal_point_len - 1)); + memmove(buffer, + buffer + (decimal_point_len - 1), + rest_len); + buffer[rest_len] = 0; + } + } + } +} + + +/* From the C99 standard, section 7.19.6: +The exponent always contains at least two digits, and only as many more digits +as necessary to represent the exponent. +*/ +#define MIN_EXPONENT_DIGITS 2 + +/* Ensure that any exponent, if present, is at least MIN_EXPONENT_DIGITS + in length. */ +Py_LOCAL_INLINE(void) +ensure_minumim_exponent_length(char* buffer, size_t buf_size) +{ + char *p = strpbrk(buffer, "eE"); + if (p && (*(p + 1) == '-' || *(p + 1) == '+')) { + char *start = p + 2; + int exponent_digit_cnt = 0; + int leading_zero_cnt = 0; + int in_leading_zeros = 1; + int significant_digit_cnt; + + /* Skip over the exponent and the sign. */ + p += 2; + + /* Find the end of the exponent, keeping track of leading + zeros. */ + while (*p && isdigit(Py_CHARMASK(*p))) { + if (in_leading_zeros && *p == '0') + ++leading_zero_cnt; + if (*p != '0') + in_leading_zeros = 0; + ++p; + ++exponent_digit_cnt; + } + + significant_digit_cnt = exponent_digit_cnt - leading_zero_cnt; + if (exponent_digit_cnt == MIN_EXPONENT_DIGITS) { + /* If there are 2 exactly digits, we're done, + regardless of what they contain */ + } + else if (exponent_digit_cnt > MIN_EXPONENT_DIGITS) { + int extra_zeros_cnt; + + /* There are more than 2 digits in the exponent. See + if we can delete some of the leading zeros */ + if (significant_digit_cnt < MIN_EXPONENT_DIGITS) + significant_digit_cnt = MIN_EXPONENT_DIGITS; + extra_zeros_cnt = exponent_digit_cnt - + significant_digit_cnt; + + /* Delete extra_zeros_cnt worth of characters from the + front of the exponent */ + assert(extra_zeros_cnt >= 0); + + /* Add one to significant_digit_cnt to copy the + trailing 0 byte, thus setting the length */ + memmove(start, + start + extra_zeros_cnt, + significant_digit_cnt + 1); + } + else { + /* If there are fewer than 2 digits, add zeros + until there are 2, if there's enough room */ + int zeros = MIN_EXPONENT_DIGITS - exponent_digit_cnt; + if (start + zeros + exponent_digit_cnt + 1 + < buffer + buf_size) { + memmove(start + zeros, start, + exponent_digit_cnt + 1); + memset(start, '0', zeros); + } + } + } +} + +/* Ensure that buffer has a decimal point in it. The decimal point + will not be in the current locale, it will always be '.' */ +Py_LOCAL_INLINE(void) +ensure_decimal_point(char* buffer, size_t buf_size) +{ + int insert_count = 0; + char* chars_to_insert; + + /* search for the first non-digit character */ + char *p = buffer; + while (*p && isdigit(Py_CHARMASK(*p))) + ++p; + + if (*p == '.') { + if (isdigit(Py_CHARMASK(*(p+1)))) { + /* Nothing to do, we already have a decimal + point and a digit after it */ + } + else { + /* We have a decimal point, but no following + digit. Insert a zero after the decimal. */ + ++p; + chars_to_insert = "0"; + insert_count = 1; + } + } + else { + chars_to_insert = ".0"; + insert_count = 2; + } + if (insert_count) { + size_t buf_len = strlen(buffer); + if (buf_len + insert_count + 1 >= buf_size) { + /* If there is not enough room in the buffer + for the additional text, just skip it. It's + not worth generating an error over. */ + } + else { + memmove(p + insert_count, p, + buffer + strlen(buffer) - p + 1); + memcpy(p, chars_to_insert, insert_count); + } + } +} + +/* Add the locale specific grouping characters to buffer. Note + that any decimal point (if it's present) in buffer is already + locale-specific. Return 0 on error, else 1. */ +Py_LOCAL_INLINE(int) +add_thousands_grouping(char* buffer, size_t buf_size) +{ + struct lconv *locale_data = localeconv(); + const char *grouping = locale_data->grouping; + const char *thousands_sep = locale_data->thousands_sep; + size_t thousands_sep_len = strlen(thousands_sep); + const char *decimal_point = locale_data->decimal_point; + char *pend = buffer + strlen(buffer); /* current end of buffer */ + char *pmax = buffer + buf_size; /* max of buffer */ + char current_grouping; + + /* Find the decimal point, if any. We're only concerned + about the characters to the left of the decimal when + adding grouping. */ + char *p = strstr(buffer, decimal_point); + if (!p) { + /* No decimal, use the entire string. */ + + /* If any exponent, adjust p. */ + p = strpbrk(buffer, "eE"); + if (!p) + /* No exponent and no decimal. Use the entire + string. */ + p = pend; + } + /* At this point, p points just past the right-most character we + want to format. We need to add the grouping string for the + characters between buffer and p. */ + + /* Starting at p and working right-to-left, keep track of + what grouping needs to be added and insert that. */ + current_grouping = *grouping++; + + /* If the first character is 0, perform no grouping at all. */ + if (current_grouping == 0) + return 1; + + while (p - buffer > current_grouping) { + /* Always leave buffer and pend valid at the end of this + loop, since we might leave with a return statement. */ + + /* Is there room to insert thousands_sep_len chars?. */ + if (pmax - pend <= thousands_sep_len) + /* No room. */ + return 0; + + /* Move the rest of the string down. */ + p -= current_grouping; + memmove(p + thousands_sep_len, + p, + pend - p + 1); + /* Adjust end pointer. */ + pend += thousands_sep_len; + /* Copy the thousands_sep chars into the buffer. */ + memcpy(p, thousands_sep, thousands_sep_len); + + /* Move to the next grouping character, unless we're + repeating (which is designated by a grouping of 0). */ + if (*grouping != 0) { + current_grouping = *grouping++; + if (current_grouping == CHAR_MAX) + /* We're done. */ + return 1; + } + } + return 1; +} + +/* see FORMATBUFLEN in unicodeobject.c */ +#define FLOAT_FORMATBUFLEN 120 /** * PyOS_ascii_formatd: * @buffer: A buffer to place the resulting string in - * @buf_len: The length of the buffer. + * @buf_size: The length of the buffer. * @format: The printf()-style format to use for the * code to use for converting. * @d: The #gdouble to convert @@ -197,76 +423,99 @@ * Converts a #gdouble to a string, using the '.' as * decimal point. To format the number you pass in * a printf()-style format string. Allowed conversion - * specifiers are 'e', 'E', 'f', 'F', 'g' and 'G'. + * specifiers are 'e', 'E', 'f', 'F', 'g', 'G', and 'n'. * + * 'n' is the same as 'g', except it uses the current locale. + * 'Z' is the same as 'g', except it always has a decimal and + * at least one digit after the decimal. + * * Return value: The pointer to the buffer with the converted string. **/ char * PyOS_ascii_formatd(char *buffer, - size_t buf_len, + size_t buf_size, const char *format, double d) { - struct lconv *locale_data; - const char *decimal_point; - size_t decimal_point_len, rest_len; - char *p; char format_char; + size_t format_len = strlen(format); + + /* For type 'n', we need to make a copy of the format string, because + we're going to modify 'n' -> 'g', and format is const char*, so we + can't modify it directly. FLOAT_FORMATBUFLEN should be longer than + we ever need this to be. There's an upcoming check to ensure it's + big enough. */ + /* Issue 2264: code 'Z' requires copying the format. 'Z' is 'g', but + also with at least one character past the decimal. */ + char tmp_format[FLOAT_FORMATBUFLEN]; -/* g_return_val_if_fail (buffer != NULL, NULL); */ -/* g_return_val_if_fail (format[0] == '%', NULL); */ -/* g_return_val_if_fail (strpbrk (format + 1, "'l%") == NULL, NULL); */ - - format_char = format[strlen(format) - 1]; - -/* g_return_val_if_fail (format_char == 'e' || format_char == 'E' || */ -/* format_char == 'f' || format_char == 'F' || */ -/* format_char == 'g' || format_char == 'G', */ -/* NULL); */ + /* The last character in the format string must be the format char */ + format_char = format[format_len - 1]; if (format[0] != '%') return NULL; + /* I'm not sure why this test is here. It's ensuring that the format + string after the first character doesn't have a single quote, a + lowercase l, or a percent. This is the reverse of the commented-out + test about 10 lines ago. */ if (strpbrk(format + 1, "'l%")) return NULL; + /* Also curious about this function is that it accepts format strings + like "%xg", which are invalid for floats. In general, the + interface to this function is not very good, but changing it is + difficult because it's a public API. */ + if (!(format_char == 'e' || format_char == 'E' || format_char == 'f' || format_char == 'F' || - format_char == 'g' || format_char == 'G')) + format_char == 'g' || format_char == 'G' || + format_char == 'n' || format_char == 'Z')) return NULL; + /* Map 'n' or 'Z' format_char to 'g', by copying the format string and + replacing the final char with a 'g' */ + if (format_char == 'n' || format_char == 'Z') { + if (format_len + 1 >= sizeof(tmp_format)) { + /* The format won't fit in our copy. Error out. In + practice, this will never happen and will be + detected by returning NULL */ + return NULL; + } + strcpy(tmp_format, format); + tmp_format[format_len - 1] = 'g'; + format = tmp_format; + } - PyOS_snprintf(buffer, buf_len, format, d); - - locale_data = localeconv(); - decimal_point = locale_data->decimal_point; - decimal_point_len = strlen(decimal_point); - - assert(decimal_point_len != 0); - - if (decimal_point[0] != '.' || - decimal_point[1] != 0) - { - p = buffer; - if (*p == '+' || *p == '-') - p++; + /* Have PyOS_snprintf do the hard work */ + PyOS_snprintf(buffer, buf_size, format, d); - while (isdigit((unsigned char)*p)) - p++; + /* Do various fixups on the return string */ - if (strncmp(p, decimal_point, decimal_point_len) == 0) - { - *p = '.'; - p++; - if (decimal_point_len > 1) { - rest_len = strlen(p + (decimal_point_len - 1)); - memmove(p, p + (decimal_point_len - 1), - rest_len); - p[rest_len] = 0; - } - } - } + /* Get the current locale, and find the decimal point string. + Convert that string back to a dot. Do not do this if using the + 'n' (number) format code, since we want to keep the localized + decimal point in that case. */ + if (format_char != 'n') + change_decimal_from_locale_to_dot(buffer); + + /* If an exponent exists, ensure that the exponent is at least + MIN_EXPONENT_DIGITS digits, providing the buffer is large enough + for the extra zeros. Also, if there are more than + MIN_EXPONENT_DIGITS, remove as many zeros as possible until we get + back to MIN_EXPONENT_DIGITS */ + ensure_minumim_exponent_length(buffer, buf_size); + + /* If format_char is 'Z', make sure we have at least one character + after the decimal point (and make sure we have a decimal point). */ + if (format_char == 'Z') + ensure_decimal_point(buffer, buf_size); + + /* If format_char is 'n', add the thousands grouping. */ + if (format_char == 'n') + if (!add_thousands_grouping(buffer, buf_size)) + return NULL; return buffer; } Modified: python/branches/py3k-ctypes-pep3118/Python/pythonrun.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/pythonrun.c (original) +++ python/branches/py3k-ctypes-pep3118/Python/pythonrun.c Wed Apr 30 15:57:13 2008 @@ -17,6 +17,7 @@ #include "ast.h" #include "eval.h" #include "marshal.h" +#include "osdefs.h" #ifdef HAVE_SIGNAL_H #include @@ -30,6 +31,7 @@ #ifdef MS_WINDOWS #undef BYTE #include "windows.h" +#define PATH_MAX MAXPATHLEN #endif #ifndef Py_REF_DEBUG @@ -44,7 +46,7 @@ extern "C" { #endif -extern char *Py_GetPath(void); +extern wchar_t *Py_GetPath(void); extern grammar _PyParser_Grammar; /* From graminit.c */ @@ -52,6 +54,7 @@ static void initmain(void); static void initsite(void); static int initstdio(void); +static void flush_io(void); static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *, PyCompilerFlags *, PyArena *); static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *, @@ -81,38 +84,12 @@ int Py_FrozenFlag; /* Needed by getpath.c */ int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */ -/* Reference to 'warnings' module, to avoid importing it - on the fly when the import lock may be held. See 683658/771097 -*/ -static PyObject *warnings_module = NULL; - -/* Returns a borrowed reference to the 'warnings' module, or NULL. - If the module is returned, it is guaranteed to have been obtained - without acquiring the import lock -*/ -PyObject *PyModule_GetWarningsModule(void) +/* PyModule_GetWarningsModule is no longer necessary as of 2.6 +since _warnings is builtin. This API should not be used. */ +PyObject * +PyModule_GetWarningsModule(void) { - PyObject *typ, *val, *tb; - PyObject *all_modules; - /* If we managed to get the module at init time, just use it */ - if (warnings_module) - return warnings_module; - /* If it wasn't available at init time, it may be available - now in sys.modules (common scenario is frozen apps: import - at init time fails, but the frozen init code sets up sys.path - correctly, then does an implicit import of warnings for us - */ - /* Save and restore any exceptions */ - PyErr_Fetch(&typ, &val, &tb); - - all_modules = PySys_GetObject("modules"); - if (all_modules) { - warnings_module = PyDict_GetItemString(all_modules, "warnings"); - /* We keep a ref in the global */ - Py_XINCREF(warnings_module); - } - PyErr_Restore(typ, val, tb); - return warnings_module; + return PyImport_ImportModule("warnings"); } static int initialized = 0; @@ -252,6 +229,15 @@ if (install_sigs) initsigs(); /* Signal handling stuff, including initintr() */ + + /* Initialize warnings. */ + _PyWarnings_Init(); + if (PySys_HasWarnOptions()) { + PyObject *warnings_module = PyImport_ImportModule("warnings"); + if (!warnings_module) + PyErr_Clear(); + Py_XDECREF(warnings_module); + } initmain(); /* Module __main__ */ if (initstdio() < 0) @@ -265,30 +251,6 @@ _PyGILState_Init(interp, tstate); #endif /* WITH_THREAD */ - warnings_module = PyImport_ImportModule("warnings"); - if (!warnings_module) { - PyErr_Clear(); - } - else { - PyObject *o; - char *action[8]; - - if (Py_BytesWarningFlag > 1) - *action = "error"; - else if (Py_BytesWarningFlag) - *action = "default"; - else - *action = "ignore"; - - o = PyObject_CallMethod(warnings_module, - "simplefilter", "sO", - *action, PyExc_BytesWarning); - if (o == NULL) - Py_FatalError("Py_Initialize: can't initialize" - "warning filter for BytesWarning."); - Py_DECREF(o); - } - #if defined(HAVE_LANGINFO_H) && defined(CODESET) /* On Unix, set the file system encoding according to the user's preference, if the CODESET names a well-known @@ -400,9 +362,8 @@ /* Disable signal handling */ PyOS_FiniInterrupts(); - /* drop module references we saved */ - Py_XDECREF(warnings_module); - warnings_module = NULL; + /* Clear type lookup cache */ + PyType_ClearCache(); /* Collect garbage. This may call finalizers; it's nice to call these * before all modules are destroyed. @@ -501,6 +462,7 @@ PyBytes_Fini(); PyLong_Fini(); PyFloat_Fini(); + PyDict_Fini(); /* Cleanup Unicode implementation */ _PyUnicode_Fini(); @@ -508,7 +470,7 @@ /* reset file system default encoding */ if (!Py_HasFileSystemDefaultEncoding) { free((char*)Py_FileSystemDefaultEncoding); - Py_FileSystemDefaultEncoding = NULL; + Py_FileSystemDefaultEncoding = NULL; } /* XXX Still allocated: @@ -642,35 +604,43 @@ PyInterpreterState_Delete(interp); } -static char *progname = "python"; +static wchar_t *progname = L"python"; void -Py_SetProgramName(char *pn) +Py_SetProgramName(wchar_t *pn) { if (pn && *pn) progname = pn; } -char * +wchar_t * Py_GetProgramName(void) { return progname; } -static char *default_home = NULL; +static wchar_t *default_home = NULL; +static wchar_t env_home[PATH_MAX+1]; void -Py_SetPythonHome(char *home) +Py_SetPythonHome(wchar_t *home) { default_home = home; } -char * +wchar_t * Py_GetPythonHome(void) { - char *home = default_home; - if (home == NULL && !Py_IgnoreEnvironmentFlag) - home = Py_GETENV("PYTHONHOME"); + wchar_t *home = default_home; + if (home == NULL && !Py_IgnoreEnvironmentFlag) { + char* chome = Py_GETENV("PYTHONHOME"); + if (chome) { + size_t r = mbstowcs(env_home, chome, PATH_MAX+1); + if (r != (size_t)-1 && r <= PATH_MAX) + home = env_home; + } + + } return home; } @@ -729,6 +699,7 @@ PyObject *m; PyObject *std = NULL; int status = 0, fd; + PyObject * encoding_attr; /* Hack to avoid a nasty recursion issue when Python is invoked in verbose mode: pre-import the Latin-1 and UTF-8 codecs */ @@ -819,6 +790,19 @@ goto error; } } /* if (fd < 0) */ + + /* Same as hack above, pre-import stderr's codec to avoid recursion + when import.c tries to write to stderr in verbose mode. */ + encoding_attr = PyObject_GetAttrString(std, "encoding"); + if (encoding_attr != NULL) { + const char * encoding; + encoding = PyUnicode_AsString(encoding_attr); + if (encoding != NULL) { + _PyCodec_Lookup(encoding); + } + } + PyErr_Clear(); /* Not a fatal error if codec isn't available */ + PySys_SetObject("__stderr__", std); PySys_SetObject("stderr", std); Py_DECREF(std); @@ -964,6 +948,7 @@ d = PyModule_GetDict(m); v = run_mod(mod, filename, d, d, flags, arena); PyArena_Free(arena); + flush_io(); if (v == NULL) { PyErr_Print(); return -1; @@ -1054,6 +1039,7 @@ v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d, closeit, flags); } + flush_io(); if (v == NULL) { PyErr_Print(); ret = -1; @@ -1449,6 +1435,11 @@ flush_io(void) { PyObject *f, *r; + PyObject *type, *value, *traceback; + + /* Save the current exception */ + PyErr_Fetch(&type, &value, &traceback); + f = PySys_GetObject("stderr"); if (f != NULL) { r = PyObject_CallMethod(f, "flush", ""); @@ -1465,6 +1456,8 @@ else PyErr_Clear(); } + + PyErr_Restore(type, value, traceback); } static PyObject * @@ -1478,7 +1471,6 @@ return NULL; v = PyEval_EvalCode(co, globals, locals); Py_DECREF(co); - flush_io(); return v; } @@ -1511,7 +1503,6 @@ if (v && flags) flags->cf_flags |= (co->co_flags & PyCF_MASK); Py_DECREF(co); - flush_io(); return v; } @@ -1545,11 +1536,13 @@ { struct symtable *st; mod_ty mod; + PyCompilerFlags flags; PyArena *arena = PyArena_New(); if (arena == NULL) return NULL; - mod = PyParser_ASTFromString(str, filename, start, NULL, arena); + flags.cf_flags = 0; + mod = PyParser_ASTFromString(str, filename, start, &flags, arena); if (mod == NULL) { PyArena_Free(arena); return NULL; @@ -1566,10 +1559,15 @@ { mod_ty mod; perrdetail err; - node *n = PyParser_ParseStringFlagsFilename(s, filename, + int iflags = PARSER_FLAGS(flags); + + node *n = PyParser_ParseStringFlagsFilenameEx(s, filename, &_PyParser_Grammar, start, &err, - PARSER_FLAGS(flags)); + &iflags); if (n) { + if (flags) { + flags->cf_flags |= iflags & PyCF_MASK; + } mod = PyAST_FromNode(n, flags, filename, arena); PyNode_Free(n); return mod; @@ -1588,10 +1586,15 @@ { mod_ty mod; perrdetail err; - node *n = PyParser_ParseFileFlags(fp, filename, enc, + int iflags = PARSER_FLAGS(flags); + + node *n = PyParser_ParseFileFlagsEx(fp, filename, enc, &_PyParser_Grammar, - start, ps1, ps2, &err, PARSER_FLAGS(flags)); + start, ps1, ps2, &err, &iflags); if (n) { + if (flags) { + flags->cf_flags |= iflags & PyCF_MASK; + } mod = PyAST_FromNode(n, flags, filename, arena); PyNode_Free(n); return mod; @@ -1895,8 +1898,14 @@ not enough space left on the stack */ alloca(PYOS_STACK_MARGIN * sizeof(void*)); return 0; - } __except (EXCEPTION_EXECUTE_HANDLER) { - /* just ignore all errors */ + } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ? + EXCEPTION_EXECUTE_HANDLER : + EXCEPTION_CONTINUE_SEARCH) { + int errcode = _resetstkoflw(); + if (errcode) + { + Py_FatalError("Could not reset the stack!"); + } } return 1; } Deleted: python/branches/py3k-ctypes-pep3118/Python/strerror.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/strerror.c Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,19 +0,0 @@ - -/* PD implementation of strerror() for systems that don't have it. - Author: Guido van Rossum, CWI Amsterdam, Oct. 1990, . */ - -#include -#include "Python.h" - -extern int sys_nerr; -extern char *sys_errlist[]; - -char * -strerror(int err) -{ - static char buf[20]; - if (err >= 0 && err < sys_nerr) - return sys_errlist[err]; - PyOS_snprintf(buf, sizeof(buf), "Unknown errno %d", err); - return buf; -} Modified: python/branches/py3k-ctypes-pep3118/Python/strtod.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/strtod.c (original) +++ python/branches/py3k-ctypes-pep3118/Python/strtod.c Wed Apr 30 15:57:13 2008 @@ -44,11 +44,11 @@ I do know about , but the whole point of this file is that we can't always trust that stuff to be there or to be correct. */ -static int MDMINEXPT = {-323}; +static int MDMINEXPT = -323; static char MDMINFRAC[] = "494065645841246544"; static double ZERO = 0.0; -static int MDMAXEXPT = { 309}; +static int MDMAXEXPT = 309; static char MDMAXFRAC[] = "17976931348623157"; static double HUGE = 1.7976931348623157e308; Modified: python/branches/py3k-ctypes-pep3118/Python/symtable.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/symtable.c (original) +++ python/branches/py3k-ctypes-pep3118/Python/symtable.c Wed Apr 30 15:57:13 2008 @@ -33,8 +33,9 @@ k = PyLong_FromVoidPtr(key); if (k == NULL) goto fail; - ste = (PySTEntryObject *)PyObject_New(PySTEntryObject, - &PySTEntry_Type); + ste = PyObject_New(PySTEntryObject, &PySTEntry_Type); + if (ste == NULL) + goto fail; ste->ste_table = st; ste->ste_id = k; ste->ste_tmpname = 0; @@ -1430,12 +1431,12 @@ static int symtable_visit_excepthandler(struct symtable *st, excepthandler_ty eh) { - if (eh->type) - VISIT(st, expr, eh->type); - if (eh->name) - if (!symtable_add_def(st, eh->name, DEF_LOCAL)) + if (eh->v.ExceptHandler.type) + VISIT(st, expr, eh->v.ExceptHandler.type); + if (eh->v.ExceptHandler.name) + if (!symtable_add_def(st, eh->v.ExceptHandler.name, DEF_LOCAL)) return 0; - VISIT_SEQ(st, stmt, eh->body); + VISIT_SEQ(st, stmt, eh->v.ExceptHandler.body); return 1; } Modified: python/branches/py3k-ctypes-pep3118/Python/sysmodule.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/sysmodule.c (original) +++ python/branches/py3k-ctypes-pep3118/Python/sysmodule.c Wed Apr 30 15:57:13 2008 @@ -748,10 +748,41 @@ } #endif +static PyObject * +sys_clear_type_cache(PyObject* self, PyObject* args) +{ + PyType_ClearCache(); + Py_RETURN_NONE; +} + +PyDoc_STRVAR(sys_clear_type_cache__doc__, +"_clear_type_cache() -> None\n\ +Clear the internal type lookup cache."); + + +static PyObject * +sys_compact_freelists(PyObject* self, PyObject* args) +{ + size_t fsum, fbc, fbf; + + PyFloat_CompactFreeList(&fbc, &fbf, &fsum); + + return Py_BuildValue("((kkk))", fsum, fbc, fbf); + +} + +PyDoc_STRVAR(sys_compact_freelists__doc__, +"_compact_freelists() -> ((remaing_objects, total_blocks, freed_blocks),)\n\ +Compact the free lists of floats."); + static PyMethodDef sys_methods[] = { /* Might as well keep this in alphabetic order */ {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS, callstats_doc}, + {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS, + sys_clear_type_cache__doc__}, + {"_compact_freelists", sys_compact_freelists, METH_NOARGS, + sys_compact_freelists__doc__}, {"_current_frames", sys_current_frames, METH_NOARGS, current_frames_doc}, {"displayhook", sys_displayhook, METH_O, displayhook_doc}, @@ -851,7 +882,7 @@ } void -PySys_AddWarnOption(const char *s) +PySys_AddWarnOption(const wchar_t *s) { PyObject *str; @@ -861,13 +892,19 @@ if (warnoptions == NULL) return; } - str = PyUnicode_FromString(s); + str = PyUnicode_FromWideChar(s, -1); if (str != NULL) { PyList_Append(warnoptions, str); Py_DECREF(str); } } +int +PySys_HasWarnOptions(void) +{ + return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0; +} + /* XXX This doc string is too long to be a single string literal in VC++ 5.0. Two literals concatenated works just fine. If you have a K&R compiler or other abomination that however *does* understand longer strings, @@ -1070,6 +1107,7 @@ #endif /* {"unbuffered", "-u"}, */ /* {"skip_first", "-x"}, */ + {"bytes_warning", "-b"}, {0} }; @@ -1113,13 +1151,12 @@ #endif /* SetFlag(saw_unbuffered_flag); */ /* SetFlag(skipfirstline); */ + SetFlag(Py_BytesWarningFlag); #undef SetFlag if (PyErr_Occurred()) { return NULL; } - - Py_INCREF(seq); return seq; } @@ -1133,6 +1170,11 @@ if (m == NULL) return NULL; sysdict = PyModule_GetDict(m); +#define SET_SYS_FROM_STRING(key, value) \ + v = value; \ + if (v != NULL) \ + PyDict_SetItemString(sysdict, key, v); \ + Py_XDECREF(v) { /* XXX: does this work on Win/Win64? (see posix_fstat) */ @@ -1149,22 +1191,19 @@ /* stdin/stdout/stderr are now set by pythonrun.c */ PyDict_SetItemString(sysdict, "__displayhook__", - PyDict_GetItemString(sysdict, "displayhook")); + PyDict_GetItemString(sysdict, "displayhook")); PyDict_SetItemString(sysdict, "__excepthook__", - PyDict_GetItemString(sysdict, "excepthook")); - PyDict_SetItemString(sysdict, "version", - v = PyUnicode_FromString(Py_GetVersion())); - Py_XDECREF(v); - PyDict_SetItemString(sysdict, "hexversion", - v = PyLong_FromLong(PY_VERSION_HEX)); - Py_XDECREF(v); + PyDict_GetItemString(sysdict, "excepthook")); + SET_SYS_FROM_STRING("version", + PyUnicode_FromString(Py_GetVersion())); + SET_SYS_FROM_STRING("hexversion", + PyLong_FromLong(PY_VERSION_HEX)); svnversion_init(); - v = Py_BuildValue("(UUU)", "CPython", branch, svn_revision); - PyDict_SetItemString(sysdict, "subversion", v); - Py_XDECREF(v); - PyDict_SetItemString(sysdict, "dont_write_bytecode", - v = PyBool_FromLong(Py_DontWriteBytecodeFlag)); - Py_XDECREF(v); + SET_SYS_FROM_STRING("subversion", + Py_BuildValue("(UUU)", "CPython", branch, + svn_revision)); + SET_SYS_FROM_STRING("dont_write_bytecode", + PyBool_FromLong(Py_DontWriteBytecodeFlag)); /* * These release level checks are mutually exclusive and cover * the field, so don't get too fancy with the pre-processor! @@ -1179,12 +1218,6 @@ s = "final"; #endif -#define SET_SYS_FROM_STRING(key, value) \ - v = value; \ - if (v != NULL) \ - PyDict_SetItemString(sysdict, key, v); \ - Py_XDECREF(v) - SET_SYS_FROM_STRING("version_info", Py_BuildValue("iiiUi", PY_MAJOR_VERSION, PY_MINOR_VERSION, @@ -1197,12 +1230,12 @@ SET_SYS_FROM_STRING("platform", PyUnicode_FromString(Py_GetPlatform())); SET_SYS_FROM_STRING("executable", - PyUnicode_DecodeFSDefault( - Py_GetProgramFullPath())); + PyUnicode_FromWideChar( + Py_GetProgramFullPath(), -1)); SET_SYS_FROM_STRING("prefix", - PyUnicode_DecodeFSDefault(Py_GetPrefix())); + PyUnicode_FromWideChar(Py_GetPrefix(), -1)); SET_SYS_FROM_STRING("exec_prefix", - PyUnicode_DecodeFSDefault(Py_GetExecPrefix())); + PyUnicode_FromWideChar(Py_GetExecPrefix(), -1)); SET_SYS_FROM_STRING("maxsize", PyLong_FromSsize_t(PY_SSIZE_T_MAX)); SET_SYS_FROM_STRING("float_info", @@ -1231,7 +1264,6 @@ SET_SYS_FROM_STRING("winver", PyUnicode_FromString(PyWin_DLLVersionString)); #endif -#undef SET_SYS_FROM_STRING if (warnoptions == NULL) { warnoptions = PyList_New(0); } @@ -1242,27 +1274,29 @@ PyDict_SetItemString(sysdict, "warnoptions", warnoptions); } - PyStructSequence_InitType(&FlagsType, &flags_desc); - PyDict_SetItemString(sysdict, "flags", make_flags()); + if (FlagsType.tp_name == 0) + PyStructSequence_InitType(&FlagsType, &flags_desc); + SET_SYS_FROM_STRING("flags", make_flags()); /* prevent user from creating new instances */ FlagsType.tp_init = NULL; FlagsType.tp_new = NULL; +#undef SET_SYS_FROM_STRING if (PyErr_Occurred()) return NULL; return m; } static PyObject * -makepathobject(const char *path, int delim) +makepathobject(const wchar_t *path, wchar_t delim) { int i, n; - const char *p; + const wchar_t *p; PyObject *v, *w; n = 1; p = path; - while ((p = strchr(p, delim)) != NULL) { + while ((p = wcschr(p, delim)) != NULL) { n++; p++; } @@ -1270,10 +1304,10 @@ if (v == NULL) return NULL; for (i = 0; ; i++) { - p = strchr(path, delim); + p = wcschr(path, delim); if (p == NULL) - p = strchr(path, '\0'); /* End of string */ - w = PyUnicode_DecodeFSDefaultAndSize(path, (Py_ssize_t) (p - path)); + p = wcschr(path, L'\0'); /* End of string */ + w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path)); if (w == NULL) { Py_DECREF(v); return NULL; @@ -1287,7 +1321,7 @@ } void -PySys_SetPath(const char *path) +PySys_SetPath(const wchar_t *path) { PyObject *v; if ((v = makepathobject(path, DELIM)) == NULL) @@ -1298,12 +1332,12 @@ } static PyObject * -makeargvobject(int argc, char **argv) +makeargvobject(int argc, wchar_t **argv) { PyObject *av; if (argc <= 0 || argv == NULL) { /* Ensure at least one (empty) argument is seen */ - static char *empty_argv[1] = {""}; + static wchar_t *empty_argv[1] = {L""}; argv = empty_argv; argc = 1; } @@ -1325,7 +1359,7 @@ } else v = PyUnicode_FromString(argv[i]); #else - PyObject *v = PyUnicode_FromString(argv[i]); + PyObject *v = PyUnicode_FromWideChar(argv[i], -1); #endif if (v == NULL) { Py_DECREF(av); @@ -1338,13 +1372,38 @@ return av; } +#ifdef HAVE_REALPATH +static wchar_t* +_wrealpath(const wchar_t *path, wchar_t *resolved_path) +{ + char cpath[PATH_MAX]; + char cresolved_path[PATH_MAX]; + char *res; + size_t r; + r = wcstombs(cpath, path, PATH_MAX); + if (r == (size_t)-1 || r >= PATH_MAX) { + errno = EINVAL; + return NULL; + } + res = realpath(cpath, cresolved_path); + if (res == NULL) + return NULL; + r = mbstowcs(resolved_path, cresolved_path, PATH_MAX); + if (r == (size_t)-1 || r >= PATH_MAX) { + errno = EINVAL; + return NULL; + } + return resolved_path; +} +#endif + void -PySys_SetArgv(int argc, char **argv) +PySys_SetArgv(int argc, wchar_t **argv) { #if defined(HAVE_REALPATH) - char fullpath[MAXPATHLEN]; + wchar_t fullpath[MAXPATHLEN]; #elif defined(MS_WINDOWS) - char fullpath[MAX_PATH]; + wchar_t fullpath[MAX_PATH]; #endif PyObject *av = makeargvobject(argc, argv); PyObject *path = PySys_GetObject("path"); @@ -1353,53 +1412,54 @@ if (PySys_SetObject("argv", av) != 0) Py_FatalError("can't assign sys.argv"); if (path != NULL) { - char *argv0 = argv[0]; - char *p = NULL; + wchar_t *argv0 = argv[0]; + wchar_t *p = NULL; Py_ssize_t n = 0; PyObject *a; + extern int _Py_wreadlink(const wchar_t *, wchar_t *, size_t); #ifdef HAVE_READLINK - char link[MAXPATHLEN+1]; - char argv0copy[2*MAXPATHLEN+1]; + wchar_t link[MAXPATHLEN+1]; + wchar_t argv0copy[2*MAXPATHLEN+1]; int nr = 0; - if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) - nr = readlink(argv0, link, MAXPATHLEN); + if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) + nr = _Py_wreadlink(argv0, link, MAXPATHLEN); if (nr > 0) { /* It's a symlink */ link[nr] = '\0'; if (link[0] == SEP) argv0 = link; /* Link to absolute path */ - else if (strchr(link, SEP) == NULL) + else if (wcschr(link, SEP) == NULL) ; /* Link without path */ else { /* Must join(dirname(argv0), link) */ - char *q = strrchr(argv0, SEP); + wchar_t *q = wcsrchr(argv0, SEP); if (q == NULL) argv0 = link; /* argv0 without path */ else { /* Must make a copy */ - strcpy(argv0copy, argv0); - q = strrchr(argv0copy, SEP); - strcpy(q+1, link); + wcscpy(argv0copy, argv0); + q = wcsrchr(argv0copy, SEP); + wcscpy(q+1, link); argv0 = argv0copy; } } } #endif /* HAVE_READLINK */ #if SEP == '\\' /* Special case for MS filename syntax */ - if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) { - char *q; + if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) { + wchar_t *q; #ifdef MS_WINDOWS - char *ptemp; - if (GetFullPathName(argv0, - sizeof(fullpath), + wchar_t *ptemp; + if (GetFullPathNameW(argv0, + sizeof(fullpath)/sizeof(fullpath[0]), fullpath, &ptemp)) { argv0 = fullpath; } #endif - p = strrchr(argv0, SEP); + p = wcsrchr(argv0, SEP); /* Test for alternate separator */ - q = strrchr(p ? p : argv0, '/'); + q = wcsrchr(p ? p : argv0, '/'); if (q != NULL) p = q; if (p != NULL) { @@ -1409,13 +1469,13 @@ } } #else /* All other filename syntaxes */ - if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) { + if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) { #if defined(HAVE_REALPATH) - if (realpath(argv0, fullpath)) { + if (_wrealpath(argv0, fullpath)) { argv0 = fullpath; } #endif - p = strrchr(argv0, SEP); + p = wcsrchr(argv0, SEP); } if (p != NULL) { n = p + 1 - argv0; @@ -1425,7 +1485,7 @@ #endif /* Unix */ } #endif /* All others */ - a = PyUnicode_FromStringAndSize(argv0, n); + a = PyUnicode_FromWideChar(argv0, n); if (a == NULL) Py_FatalError("no mem for sys.path insertion"); if (PyList_Insert(path, 0, a) < 0) Modified: python/branches/py3k-ctypes-pep3118/Python/traceback.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Python/traceback.c (original) +++ python/branches/py3k-ctypes-pep3118/Python/traceback.c Wed Apr 30 15:57:13 2008 @@ -128,16 +128,16 @@ return 0; } -static int -tb_displayline(PyObject *f, char *filename, int lineno, char *name) +int +Py_DisplaySourceLine(PyObject *f, const char *filename, int lineno) { int err = 0; - FILE *xfp; + FILE *xfp = NULL; char linebuf[2000]; int i; char namebuf[MAXPATHLEN+1]; - if (filename == NULL || name == NULL) + if (filename == NULL) return -1; /* This is needed by Emacs' compile command */ #define FMT " File \"%.500s\", line %d, in %.500s\n" @@ -145,7 +145,7 @@ if (xfp == NULL) { /* Search tail of filename in sys.path before giving up */ PyObject *path; - char *tail = strrchr(filename, SEP); + const char *tail = strrchr(filename, SEP); if (tail == NULL) tail = filename; else @@ -181,14 +181,14 @@ } } } - PyOS_snprintf(linebuf, sizeof(linebuf), FMT, filename, lineno, name); - err = PyFile_WriteString(linebuf, f); - if (xfp == NULL) - return err; - else if (err != 0) { - fclose(xfp); - return err; - } + + if (xfp == NULL) + return err; + if (err != 0) { + fclose(xfp); + return err; + } + for (i = 0; i < lineno; i++) { char* pLastChar = &linebuf[sizeof(linebuf)-2]; do { @@ -206,22 +206,38 @@ char *p = linebuf; while (*p == ' ' || *p == '\t' || *p == '\014') p++; - err = PyFile_WriteString(" ", f); - if (err == 0) { - err = PyFile_WriteString(p, f); - if (err == 0 && strchr(p, '\n') == NULL) - err = PyFile_WriteString("\n", f); - } + err = PyFile_WriteString(p, f); + if (err == 0 && strchr(p, '\n') == NULL) + err = PyFile_WriteString("\n", f); } fclose(xfp); return err; } static int -tb_printinternal(PyTracebackObject *tb, PyObject *f, int limit) +tb_displayline(PyObject *f, const char *filename, int lineno, const char *name) +{ + int err = 0; + char linebuf[2000]; + + if (filename == NULL || name == NULL) + return -1; + /* This is needed by Emacs' compile command */ +#define FMT " File \"%.500s\", line %d, in %.500s\n" + PyOS_snprintf(linebuf, sizeof(linebuf), FMT, filename, lineno, name); + err = PyFile_WriteString(linebuf, f); + if (err != 0) + return err; + + err = PyFile_WriteString(" ", f); + return Py_DisplaySourceLine(f, filename, lineno); +} + +static int +tb_printinternal(PyTracebackObject *tb, PyObject *f, long limit) { int err = 0; - int depth = 0; + long depth = 0; PyTracebackObject *tb1 = tb; while (tb1 != NULL) { depth++; @@ -250,7 +266,7 @@ { int err; PyObject *limitv; - int limit = PyTraceBack_LIMIT; + long limit = PyTraceBack_LIMIT; if (v == NULL) return 0; Modified: python/branches/py3k-ctypes-pep3118/README ============================================================================== --- python/branches/py3k-ctypes-pep3118/README (original) +++ python/branches/py3k-ctypes-pep3118/README Wed Apr 30 15:57:13 2008 @@ -1,7 +1,10 @@ -This is Python version 3.0 alpha 2 +This is Python version 3.0 alpha 4 ================================== For notes specific to this release, see RELNOTES in this directory. +Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 +Python Software Foundation. +All rights reserved. Python 3000 (a.k.a. "Py3k", and released as Python 3.0) is a new version of the language, which is incompatible with the 2.x line of @@ -18,13 +21,14 @@ Release Schedule ---------------- -The release plan is to have a series of alpha releases in 2007, beta -releases in 2008, and a final release in August 2008. The alpha -releases are primarily aimed at developers who want a sneak peek at -the new langauge, especially those folks who plan to port their code -to Python 3000. The hope is that by the time of the final release, -many 3rd party packages will already be available in a 3.0-compatible -form. +The release plan is to have a series of alpha releases in 2007 and 2008, +beta releases in 2008, and a final release in August 2008. The alpha +releases are primarily aimed at developers who want a sneak peek at the +new langauge, especially those folks who plan to port their code to +Python 3000. The hope is that by the time of the final release, many +3rd party packages will already be available in a 3.0-compatible form. + +See PEP 361 for release details: http://www.python.org/dev/peps/pep-0361/ Documentation @@ -34,6 +38,14 @@ http://docs.python.org/dev/3.0/ +All documentation is also available online at the Python web site +(http://docs.python.org/, see below). It is available online for +occasional reference, or can be downloaded in many formats for faster +access. The documentation is downloadable in HTML, PostScript, PDF, +LaTeX (through 2.5), and reStructuredText (2.6+) formats; the LaTeX and +reStructuredText versions are primarily for documentation authors, +translators, and people with special formatting requirements. + This is a work in progress; please help improve it! The design documents for Python 3000 are also online. While the @@ -51,8 +63,15 @@ http://www.artima.com/weblogs/index.jsp?blogger=guido -We'll eventually have a comprehensive overview of the changes in a -"What's New in Python 3.0" document. Please help write it! +We try to eventually have a comprehensive overview of the changes in +the "What's New in Python 3.0" document, found at + + http://docs.python.org/dev/3.0/whatsnew/3.0 + +Please help write it! + +If you want to install multiple versions of Python see the section below +entitled "Installing multiple versions". What's New Since 3.0a1 @@ -67,6 +86,14 @@ is incomplete, and also doesn't list anything merged in from the 2.6 release under development). +Proposals for enhancement +------------------------- + +If you have a proposal to change Python, you may want to send an email to the +comp.lang.python or python-ideas mailing lists for inital feedback. A Python +Enhancement Proposal (PEP) may be submitted if your idea gains ground. All +current PEPs, as well as guidelines for submitting a new PEP, are listed at +http://www.python.org/dev/peps/. Converting From Python 2.x to 3.0 --------------------------------- @@ -76,6 +103,29 @@ deprecated features are used, and backported versions of certain key Python 3000 features. + +Installing multiple versions +---------------------------- + +On Unix and Mac systems if you intend to install multiple versions of Python +using the same installation prefix (--prefix argument to the configure +script) you must take care that your primary python executable is not +overwritten by the installation of a different versio. All files and +directories installed using "make altinstall" contain the major and minor +version and can thus live side-by-side. "make install" also creates +${prefix}/bin/python which refers to ${prefix}/bin/pythonX.Y. If you intend +to install multiple versions using the same prefix you must decide which +version (if any) is your "primary" version. Install that version using +"make install". Install all other versions using "make altinstall". + +For example, if you want to install Python 2.5, 2.6 and 3.0 with 2.6 being +the primary version, you would execute "make install" in your 2.6 build +directory and "make altinstall" in the others. + + +Configuration options and variables +----------------------------------- + A source-to-source translation tool, "2to3", can take care of the mundane task of converting large amounts of source code. It is not a complete solution but is complemented by the deprecation warnings in @@ -141,7 +191,7 @@ Copyright and License Information --------------------------------- -Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007 +Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Python Software Foundation. All rights reserved. Modified: python/branches/py3k-ctypes-pep3118/Tools/bgen/bgen/bgenGenerator.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/bgen/bgen/bgenGenerator.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/bgen/bgen/bgenGenerator.py Wed Apr 30 15:57:13 2008 @@ -148,7 +148,7 @@ for arg in self.argumentList: if arg.flags == ErrorMode or arg.flags == SelfMode: continue - if arg.type == None: + if arg.type is None: str = 'void' else: if hasattr(arg.type, 'typeName'): Deleted: python/branches/py3k-ctypes-pep3118/Tools/buildbot/Makefile ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/buildbot/Makefile Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,6 +0,0 @@ -all: kill_python.exe - ./kill_python.exe - -kill_python.exe: kill_python.c - gcc -o kill_python.exe kill_python.c -lpsapi - Modified: python/branches/py3k-ctypes-pep3118/Tools/buildbot/build-amd64.bat ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/buildbot/build-amd64.bat (original) +++ python/branches/py3k-ctypes-pep3118/Tools/buildbot/build-amd64.bat Wed Apr 30 15:57:13 2008 @@ -1,5 +1,6 @@ @rem Used by the buildbot "compile" step. cmd /c Tools\buildbot\external-amd64.bat -call "%VS90COMNTOOLS%vsvars32.bat" -REM cmd /q/c Tools\buildbot\kill_python.bat +call "%VS90COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64 +cmd /c Tools\buildbot\clean-amd64.bat +vcbuild /useenv PCbuild\kill_python.vcproj "Debug|x64" && PCbuild\amd64\kill_python_d.exe vcbuild PCbuild\pcbuild.sln "Debug|x64" Modified: python/branches/py3k-ctypes-pep3118/Tools/buildbot/build.bat ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/buildbot/build.bat (original) +++ python/branches/py3k-ctypes-pep3118/Tools/buildbot/build.bat Wed Apr 30 15:57:13 2008 @@ -1,6 +1,7 @@ @rem Used by the buildbot "compile" step. cmd /c Tools\buildbot\external.bat call "%VS90COMNTOOLS%vsvars32.bat" -cmd /q/c Tools\buildbot\kill_python.bat +cmd /c Tools\buildbot\clean.bat +vcbuild /useenv PCbuild\kill_python.vcproj "Debug|Win32" && PCbuild\kill_python_d.exe vcbuild /useenv PCbuild\pcbuild.sln "Debug|Win32" Modified: python/branches/py3k-ctypes-pep3118/Tools/buildbot/buildmsi.bat ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/buildbot/buildmsi.bat (original) +++ python/branches/py3k-ctypes-pep3118/Tools/buildbot/buildmsi.bat Wed Apr 30 15:57:13 2008 @@ -3,12 +3,8 @@ cmd /c Tools\buildbot\external.bat @rem build release versions of things call "%VS90COMNTOOLS%vsvars32.bat" -if not exist ..\db-4.4.20\build_win32\release\libdb44s.lib ( - vcbuild db-4.4.20\build_win32\Berkeley_DB.sln /build Release /project db_static -) @rem build Python -cmd /q/c Tools\buildbot\kill_python.bat vcbuild /useenv PCbuild\pcbuild.sln "Release|Win32" @rem build the documentation Modified: python/branches/py3k-ctypes-pep3118/Tools/buildbot/clean-amd64.bat ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/buildbot/clean-amd64.bat (original) +++ python/branches/py3k-ctypes-pep3118/Tools/buildbot/clean-amd64.bat Wed Apr 30 15:57:13 2008 @@ -1,5 +1,5 @@ @rem Used by the buildbot "clean" step. -call "%VS90COMNTOOLS%vsvars32.bat" +call "%VS90COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64 cd PCbuild @echo Deleting .pyc/.pyo files ... del /s Lib\*.pyc Lib\*.pyo Modified: python/branches/py3k-ctypes-pep3118/Tools/buildbot/clean.bat ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/buildbot/clean.bat (original) +++ python/branches/py3k-ctypes-pep3118/Tools/buildbot/clean.bat Wed Apr 30 15:57:13 2008 @@ -1,7 +1,7 @@ @rem Used by the buildbot "clean" step. call "%VS90COMNTOOLS%vsvars32.bat" -cd PCbuild @echo Deleting .pyc/.pyo files ... del /s Lib\*.pyc Lib\*.pyo +cd PCbuild vcbuild /clean pcbuild.sln "Release|Win32" vcbuild /clean pcbuild.sln "Debug|Win32" Modified: python/branches/py3k-ctypes-pep3118/Tools/buildbot/external-amd64.bat ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/buildbot/external-amd64.bat (original) +++ python/branches/py3k-ctypes-pep3118/Tools/buildbot/external-amd64.bat Wed Apr 30 15:57:13 2008 @@ -1,43 +1,17 @@ @rem Fetches (and builds if necessary) external dependencies - at REM XXX FIXME - building for x64 disabled for now. - @rem Assume we start inside the Python source directory -cd .. -call "%VS90COMNTOOLS%vsvars32.bat" - - at rem bzip -if not exist bzip2-1.0.3 svn export http://svn.python.org/projects/external/bzip2-1.0.3 +call "Tools\buildbot\external-common.bat" +call "%VS90COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64 - at rem Sleepycat db -if not exist db-4.4.20 svn export http://svn.python.org/projects/external/db-4.4.20 - at REM if not exist db-4.4.20\build_win32\debug\libdb44sd.lib ( - at REM vcbuild db-4.4.20\build_win32\Berkeley_DB.sln /build Debug /project db_static - at REM ) - - at rem OpenSSL -if not exist openssl-0.9.8g ( - if exist openssl-0.9.8a rd /s/q openssl-0.9.8a - svn export http://svn.python.org/projects/external/openssl-0.9.8g +if not exist tcltk64\bin\tcl84g.dll ( + cd tcl-8.4.18.2\win + nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 clean all install + cd ..\.. ) - at rem tcltk -if not exist tcl8.4.16 ( - if exist tcltk rd /s/q tcltk - if exist tcl8.4.12 rd /s/q tcl8.4.12 - if exist tk8.4.12 rd /s/q tk8.4.12 - svn export http://svn.python.org/projects/external/tcl8.4.16 - svn export http://svn.python.org/projects/external/tk8.4.16 - at REM cd tcl8.4.16\win - at REM nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 - at REM nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 INSTALLDIR=..\..\tcltk install - at REM cd ..\.. - at REM cd tk8.4.16\win - at REM nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 TCLDIR=..\..\tcl8.4.16 - at REM nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 TCLDIR=..\..\tcl8.4.16 INSTALLDIR=..\..\tcltk install - at REM cd ..\.. +if not exist tcltk64\bin\tk84g.dll ( + cd tk-8.4.18.1\win + nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 TCLDIR=..\..\tcl-8.4.18.2 clean all install + cd ..\.. ) - - at rem sqlite -if not exist sqlite-source-3.3.4 svn export http://svn.python.org/projects/external/sqlite-source-3.3.4 - at REM if not exist build\PCbuild\sqlite3.dll copy sqlite-source-3.3.4\sqlite3.dll build\PCbuild Modified: python/branches/py3k-ctypes-pep3118/Tools/buildbot/external.bat ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/buildbot/external.bat (original) +++ python/branches/py3k-ctypes-pep3118/Tools/buildbot/external.bat Wed Apr 30 15:57:13 2008 @@ -1,41 +1,17 @@ @rem Fetches (and builds if necessary) external dependencies @rem Assume we start inside the Python source directory -cd .. -call "%VS90COMNTOOLS%vsvars32.bat" +call "Tools\buildbot\external-common.bat" +call "%VS90COMNTOOLS%\vsvars32.bat" - at rem bzip -if not exist bzip2-1.0.3 svn export http://svn.python.org/projects/external/bzip2-1.0.3 - - at rem Sleepycat db -if not exist db-4.4.20 svn export http://svn.python.org/projects/external/db-4.4.20 -if not exist db-4.4.20\build_win32\debug\libdb44sd.lib ( - vcbuild db-4.4.20\build_win32\Berkeley_DB.sln /build Debug /project db_static -) - - at rem OpenSSL -if not exist openssl-0.9.8g ( - if exist openssl-0.9.8a rd /s/q openssl-0.9.8a - svn export http://svn.python.org/projects/external/openssl-0.9.8g +if not exist tcltk\bin\tcl84g.dll ( + cd tcl-8.4.18.2\win + nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 DEBUG=1 INSTALLDIR=..\..\tcltk clean all install + cd ..\.. ) - at rem tcltk -if not exist tcl8.4.16 ( - if exist tcltk rd /s/q tcltk - if exist tcl8.4.12 rd /s/q tcl8.4.12 - if exist tk8.4.12 rd /s/q tk8.4.12 - svn export http://svn.python.org/projects/external/tcl8.4.16 - svn export http://svn.python.org/projects/external/tk8.4.16 - cd tcl8.4.16\win - nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 - nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 INSTALLDIR=..\..\tcltk install - cd ..\.. - cd tk8.4.16\win - nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 TCLDIR=..\..\tcl8.4.16 - nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 TCLDIR=..\..\tcl8.4.16 INSTALLDIR=..\..\tcltk install - cd ..\.. +if not exist tcltk\bin\tk84g.dll ( + cd tk-8.4.18.1\win + nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 DEBUG=1 INSTALLDIR=..\..\tcltk TCLDIR=..\..\tcl-8.4.18.2 clean all install + cd ..\.. ) - - at rem sqlite -if not exist sqlite-source-3.3.4 svn export http://svn.python.org/projects/external/sqlite-source-3.3.4 -if not exist build\PCbuild\sqlite3.dll copy sqlite-source-3.3.4\sqlite3.dll build\PCbuild Deleted: python/branches/py3k-ctypes-pep3118/Tools/buildbot/kill_python.bat ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/buildbot/kill_python.bat Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,3 +0,0 @@ -cd Tools\buildbot -nmake /C /S /f kill_python.mak -kill_python.exe Deleted: python/branches/py3k-ctypes-pep3118/Tools/buildbot/kill_python.c ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/buildbot/kill_python.c Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,68 +0,0 @@ -/* This program looks for processes which have build\PCbuild\python.exe - in their path and terminates them. */ -#include -#include -#include - -int main() -{ - DWORD pids[1024], cbNeeded; - int i, num_processes; - if (!EnumProcesses(pids, sizeof(pids), &cbNeeded)) { - printf("EnumProcesses failed\n"); - return 1; - } - num_processes = cbNeeded/sizeof(pids[0]); - for (i = 0; i < num_processes; i++) { - HANDLE hProcess; - char path[MAX_PATH]; - HMODULE mods[1024]; - int k, num_mods; - hProcess = OpenProcess(PROCESS_QUERY_INFORMATION - | PROCESS_VM_READ - | PROCESS_TERMINATE , - FALSE, pids[i]); - if (!hProcess) - /* process not accessible */ - continue; - if (!EnumProcessModules(hProcess, mods, sizeof(mods), &cbNeeded)) { - /* For unknown reasons, this sometimes returns ERROR_PARTIAL_COPY; - this apparently means we are not supposed to read the process. */ - if (GetLastError() == ERROR_PARTIAL_COPY) { - CloseHandle(hProcess); - continue; - } - printf("EnumProcessModules failed: %d\n", GetLastError()); - return 1; - } - if (!GetModuleFileNameEx(hProcess, NULL, path, sizeof(path))) { - printf("GetProcessImageFileName failed\n"); - return 1; - } - - _strlwr(path); - /* printf("%s\n", path); */ - - /* Check if we are running a buildbot version of Python. - - On Windows, this will always be a debug build from the - PCbuild directory. build\\PCbuild\\python_d.exe - - On Cygwin, the pathname is similar to other Unixes. - Use \\build\\python.exe to ensure we don't match - PCbuild\\python.exe which could be a normal instance - of Python running on vanilla Windows. - */ - if ((strstr(path, "pcbuild\\python_d.exe") != NULL) || - (strstr(path, "\\build\\python.exe") != NULL)) { - printf("Terminating %s (pid %d)\n", path, pids[i]); - if (!TerminateProcess(hProcess, 1)) { - printf("Termination failed: %d\n", GetLastError()); - return 1; - } - return 0; - } - - CloseHandle(hProcess); - } -} Deleted: python/branches/py3k-ctypes-pep3118/Tools/buildbot/kill_python.mak ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/buildbot/kill_python.mak Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,2 +0,0 @@ -kill_python.exe: kill_python.c - cl -nologo -o kill_python.exe kill_python.c psapi.lib Modified: python/branches/py3k-ctypes-pep3118/Tools/buildbot/test-amd64.bat ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/buildbot/test-amd64.bat (original) +++ python/branches/py3k-ctypes-pep3118/Tools/buildbot/test-amd64.bat Wed Apr 30 15:57:13 2008 @@ -1,3 +1,3 @@ @rem Used by the buildbot "test" step. -cd PC\VS7.1 -call rt.bat -q -uall -rw +cd PCbuild +call rt.bat -q -d -x64 -uall -rw Modified: python/branches/py3k-ctypes-pep3118/Tools/faqwiz/faqw.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/faqwiz/faqw.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/faqwiz/faqw.py Wed Apr 30 15:57:13 2008 @@ -20,7 +20,7 @@ try: FAQDIR = "/usr/people/guido/python/FAQ" SRCDIR = "/usr/people/guido/python/src/Tools/faqwiz" - import os, sys, time, operator + import os, sys os.chdir(FAQDIR) sys.path.insert(0, SRCDIR) import faqwiz Modified: python/branches/py3k-ctypes-pep3118/Tools/i18n/pygettext.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/i18n/pygettext.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/i18n/pygettext.py Wed Apr 30 15:57:13 2008 @@ -631,7 +631,9 @@ try: eater.set_filename(filename) try: - tokenize.tokenize(fp.readline, eater) + tokens = tokenize.generate_tokens(fp.readline) + for _token in tokens: + eater(*_token) except tokenize.TokenError as e: print('%s: %s, line %d, column %d' % ( e.args[0], filename, e.args[1][0], e.args[1][1]), Modified: python/branches/py3k-ctypes-pep3118/Tools/modulator/Tkextra.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/modulator/Tkextra.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/modulator/Tkextra.py Wed Apr 30 15:57:13 2008 @@ -218,7 +218,6 @@ 0, 'Save', 'Save as text')) def _test(): - import sys global mainWidget mainWidget = Frame() Pack.config(mainWidget) Modified: python/branches/py3k-ctypes-pep3118/Tools/msi/msi.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/msi/msi.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/msi/msi.py Wed Apr 30 15:57:13 2008 @@ -29,7 +29,6 @@ # path to PCbuild directory PCBUILD="PCbuild" # msvcrt version -#MSVCR = "71" MSVCR = "90" try: @@ -106,8 +105,6 @@ # Using the same UUID is fine since these files are versioned, # so Installer will always keep the newest version. # NOTE: All uuids are self generated. -msvcr71_uuid = "{8666C8DD-D0B4-4B42-928E-A69E32FA5D4D}" -msvcr90_uuid = "{9C28CD84-397C-4045-855C-28B02291A272}" pythondll_uuid = { "24":"{9B81E618-2301-4035-AC77-75D9ABEB7301}", "25":"{2e41b118-38bd-4c1b-a840-6977efd1b911}", @@ -379,7 +376,7 @@ ("VerdanaRed9", "Verdana", 9, 255, 0), ]) - compileargs = r'-Wi "[TARGETDIR]Lib\compileall.py" -f -x bad_coding|badsyntax|site-packages "[TARGETDIR]Lib"' + compileargs = r'-Wi "[TARGETDIR]Lib\compileall.py" -f -x bad_coding|badsyntax|site-packages|py2_ "[TARGETDIR]Lib"' # See "CustomAction Table" add_data(db, "CustomAction", [ # msidbCustomActionTypeFirstSequence + msidbCustomActionTypeTextData + msidbCustomActionTypeProperty @@ -795,10 +792,16 @@ # (i.e. additional Python libraries) need to follow the parent feature. # Features that have no advertisement trigger (e.g. the test suite) # must not support advertisement - global default_feature, tcltk, htmlfiles, tools, testsuite, ext_feature + global default_feature, tcltk, htmlfiles, tools, testsuite, ext_feature, private_crt default_feature = Feature(db, "DefaultFeature", "Python", "Python Interpreter and Libraries", 1, directory = "TARGETDIR") + shared_crt = Feature(db, "SharedCRT", "MSVCRT", "C Run-Time (system-wide)", 0, + level=0) + private_crt = Feature(db, "PrivateCRT", "MSVCRT", "C Run-Time (private)", 0, + level=0) + add_data(db, "Condition", [("SharedCRT", 1, sys32cond), + ("PrivateCRT", 1, "not "+sys32cond)]) # We don't support advertisement of extensions ext_feature = Feature(db, "Extensions", "Register Extensions", "Make this Python installation the default Python installation", 3, @@ -815,51 +818,22 @@ "Python test suite (Lib/test/)", 11, parent = default_feature, attributes=2|8) -def extract_msvcr71(): - import _winreg - # Find the location of the merge modules - k = _winreg.OpenKey( - _winreg.HKEY_LOCAL_MACHINE, - r"Software\Microsoft\VisualStudio\7.1\Setup\VS") - dir = _winreg.QueryValueEx(k, "MSMDir")[0] - _winreg.CloseKey(k) - files = glob.glob1(dir, "*CRT71*") - assert len(files) == 1, (dir, files) - file = os.path.join(dir, files[0]) - # Extract msvcr71.dll - m = msilib.MakeMerge2() - m.OpenModule(file, 0) - m.ExtractFiles(".") - m.CloseModule() - # Find the version/language of msvcr71.dll - installer = msilib.MakeInstaller() - return installer.FileVersion("msvcr71.dll", 0), \ - installer.FileVersion("msvcr71.dll", 1) - def extract_msvcr90(): - import _winreg - # Find the location of the merge modules - k = _winreg.OpenKey( - _winreg.HKEY_LOCAL_MACHINE, - r"Software\Microsoft\VisualStudio\9.0\Setup\VS") - prod_dir = _winreg.QueryValueEx(k, "ProductDir")[0] - _winreg.CloseKey(k) - - # Copy msvcr90* - dir = os.path.join(prod_dir, r'VC\redist\x86\Microsoft.VC90.CRT') - files = glob.glob1(dir, "*CRT*.dll") + glob.glob1(dir, "*VCR*.dll") - for file in files: - shutil.copy(os.path.join(dir, file), '.') - - dir = os.path.join(prod_dir, r'VC\redist\Debug_NonRedist\x86\Microsoft.VC90.DebugCRT') - files = glob.glob1(dir, "*CRT*.dll") + glob.glob1(dir, "*VCR*.dll") - for file in files: - shutil.copy(os.path.join(dir, file), '.') + # Find the redistributable files + dir = os.path.join(os.environ['VS90COMNTOOLS'], r"..\..\VC\redist\x86\Microsoft.VC90.CRT") - # Find the version/language of msvcr90.dll + result = [] installer = msilib.MakeInstaller() - return installer.FileVersion("msvcr90.dll", 0), \ - installer.FileVersion("msvcr90.dll", 1) + # omit msvcm90 and msvcp90, as they aren't really needed + files = ["Microsoft.VC90.CRT.manifest", "msvcr90.dll"] + for f in files: + path = os.path.join(dir, f) + kw = {'src':path} + if f.endswith('.dll'): + kw['version'] = installer.FileVersion(path, 0) + kw['language'] = installer.FileVersion(path, 1) + result.append((f, kw)) + return result class PyDirectory(Directory): """By default, all components in the Python installer @@ -888,7 +862,10 @@ root.add_file("%s/pythonw.exe" % PCBUILD) # msidbComponentAttributesSharedDllRefCount = 8, see "Component Table" - dlldir = PyDirectory(db, cab, root, srcdir, "DLLDIR", ".") + #dlldir = PyDirectory(db, cab, root, srcdir, "DLLDIR", ".") + #install python30.dll into root dir for now + dlldir = root + pydll = "python%s%s.dll" % (major, minor) pydllsrc = os.path.join(srcdir, PCBUILD, pydll) dlldir.start_component("DLLDIR", flags = 8, keyfile = pydll, uuid = pythondll_uuid) @@ -901,25 +878,25 @@ dlldir.add_file("%s/python%s%s.dll" % (PCBUILD, major, minor), version=pyversion, language=installer.FileVersion(pydllsrc, 1)) - # XXX determine dependencies - if MSVCR == "90": - # XXX don't package the CRT for the moment; - # this should probably use the merge module in the long run. - pass - #version, lang = extract_msvcr90() - #dlldir.start_component("msvcr90", flags=8, keyfile="msvcr90.dll", - # uuid=msvcr90_uuid) - #dlldir.add_file("msvcr90.dll", src=os.path.abspath("msvcr90.dll"), - # version=version, language=lang) - #tmpfiles.append("msvcr90.dll") - else: - version, lang = extract_msvcr71() - dlldir.start_component("msvcr71", flags=8, keyfile="msvcr71.dll", - uuid=msvcr71_uuid) - dlldir.add_file("msvcr71.dll", src=os.path.abspath("msvcr71.dll"), - version=version, language=lang) - tmpfiles.append("msvcr71.dll") + DLLs = PyDirectory(db, cab, root, srcdir + "/" + PCBUILD, "DLLs", "DLLS|DLLs") + # msvcr90.dll: Need to place the DLL and the manifest into the root directory, + # plus another copy of the manifest in the DLLs directory, with the manifest + # pointing to the root directory + root.start_component("msvcr90", feature=private_crt) + # Results are ID,keyword pairs + manifest, crtdll = extract_msvcr90() + root.add_file(manifest[0], **manifest[1]) + root.add_file(crtdll[0], **crtdll[1]) + # Copy the manifest + manifest_dlls = manifest[0]+".root" + open(manifest_dlls, "w").write(open(manifest[1]['src']).read().replace("msvcr","../msvcr")) + DLLs.start_component("msvcr90_dlls", feature=private_crt) + DLLs.add_file(manifest[0], src=os.path.abspath(manifest_dlls)) + + # Now start the main component for the DLLs directory; + # no regular files have been added to the directory yet. + DLLs.start_component() # Check if _ctypes.pyd exists have_ctypes = os.path.exists(srcdir+"/%s/_ctypes.pyd" % PCBUILD) @@ -992,10 +969,7 @@ lib.glob("*.gif") lib.add_file("idle.icns") if dir=="command" and parent.physical=="distutils": - lib.add_file("wininst-6.0.exe") - lib.add_file("wininst-7.1.exe") - lib.add_file("wininst-8.0.exe") - lib.add_file("wininst-9.0.exe") + lib.glob("wininst*.exe") if dir=="setuptools": lib.add_file("cli.exe") lib.add_file("gui.exe") @@ -1012,7 +986,7 @@ pydirs.append((lib, f)) # Add DLLs default_feature.set_current() - lib = PyDirectory(db, cab, root, srcdir + "/" + PCBUILD, "DLLs", "DLLS|DLLs") + lib = DLLs lib.add_file("py.ico", src=srcdir+"/PC/py.ico") lib.add_file("pyc.ico", src=srcdir+"/PC/pyc.ico") dlls = [] @@ -1030,8 +1004,10 @@ sqlite_arch = "/ia64" elif msilib.msi_type=="x64;1033": sqlite_arch = "/amd64" + tclsuffix = "64" else: sqlite_arch = "" + tclsuffix = "" lib.add_file(srcdir+"/"+sqlite_dir+sqlite_arch+"/sqlite3.dll") if have_tcl: if not os.path.exists("%s/%s/_tkinter.pyd" % (srcdir, PCBUILD)): @@ -1040,7 +1016,7 @@ lib.start_component("TkDLLs", tcltk) lib.add_file("_tkinter.pyd") dlls.append("_tkinter.pyd") - tcldir = os.path.normpath(srcdir+"/../tcltk/bin") + tcldir = os.path.normpath(srcdir+("/../tcltk%s/bin" % tclsuffix)) for f in glob.glob1(tcldir, "*.dll"): lib.add_file(f, src=os.path.join(tcldir, f)) # check whether there are any unknown extensions @@ -1064,7 +1040,7 @@ lib.add_file('libpython%s%s.a' % (major, minor)) if have_tcl: # Add Tcl/Tk - tcldirs = [(root, '../tcltk/lib', 'tcl')] + tcldirs = [(root, '../tcltk%s/lib' % tclsuffix, 'tcl')] tcltk.set_current() while tcldirs: parent, phys, dir = tcldirs.pop() Modified: python/branches/py3k-ctypes-pep3118/Tools/msi/schema.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/msi/schema.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/msi/schema.py Wed Apr 30 15:57:13 2008 @@ -18,7 +18,7 @@ ActionText.add_field(3,'Template',7936) AdminExecuteSequence = Table('AdminExecuteSequence') -AdminExecuteSequence.add_field(1,'Action',11592) +AdminExecuteSequence.add_field(1,'Action',0x2DFF) AdminExecuteSequence.add_field(2,'Condition',7679) AdminExecuteSequence.add_field(3,'Sequence',5378) @@ -28,12 +28,12 @@ Condition.add_field(3,'Condition',7679) AdminUISequence = Table('AdminUISequence') -AdminUISequence.add_field(1,'Action',11592) +AdminUISequence.add_field(1,'Action',0x2DFF) AdminUISequence.add_field(2,'Condition',7679) AdminUISequence.add_field(3,'Sequence',5378) AdvtExecuteSequence = Table('AdvtExecuteSequence') -AdvtExecuteSequence.add_field(1,'Action',11592) +AdvtExecuteSequence.add_field(1,'Action',0x2DFF) AdvtExecuteSequence.add_field(2,'Condition',7679) AdvtExecuteSequence.add_field(3,'Sequence',5378) @@ -83,7 +83,7 @@ Feature.add_field(4,'Description',8191) Feature.add_field(5,'Display',5378) Feature.add_field(6,'Level',1282) -Feature.add_field(7,'Directory_',7496) +Feature.add_field(7,'Directory_',0x1DFF) Feature.add_field(8,'Attributes',1282) Binary = Table('Binary') @@ -91,15 +91,15 @@ Binary.add_field(2,'Data',2304) BindImage = Table('BindImage') -BindImage.add_field(1,'File_',11592) +BindImage.add_field(1,'File_',0x2DFF) BindImage.add_field(2,'Path',7679) File = Table('File') -File.add_field(1,'File',11592) -File.add_field(2,'Component_',3400) +File.add_field(1,'File',0x2DFF) +File.add_field(2,'Component_',0xDFF) File.add_field(3,'FileName',4095) File.add_field(4,'FileSize',260) -File.add_field(5,'Version',7496) +File.add_field(5,'Version',0x1DFF) File.add_field(6,'Language',7444) File.add_field(7,'Attributes',5378) File.add_field(8,'Sequence',1282) @@ -114,7 +114,7 @@ Class = Table('Class') Class.add_field(1,'CLSID',11558) Class.add_field(2,'Context',11552) -Class.add_field(3,'Component_',11592) +Class.add_field(3,'Component_',0x2DFF) Class.add_field(4,'ProgId_Default',7679) Class.add_field(5,'Description',8191) Class.add_field(6,'AppId_',7462) @@ -127,12 +127,12 @@ Class.add_field(13,'Attributes',5378) Component = Table('Component') -Component.add_field(1,'Component',11592) +Component.add_field(1,'Component',0x2DFF) Component.add_field(2,'ComponentId',7462) -Component.add_field(3,'Directory_',3400) +Component.add_field(3,'Directory_',0xDFF) Component.add_field(4,'Attributes',1282) Component.add_field(5,'Condition',7679) -Component.add_field(6,'KeyPath',7496) +Component.add_field(6,'KeyPath',0x1DFF) Icon = Table('Icon') Icon.add_field(1,'Name',11592) @@ -158,12 +158,12 @@ CompLocator.add_field(3,'Type',5378) Complus = Table('Complus') -Complus.add_field(1,'Component_',11592) +Complus.add_field(1,'Component_',0x2DFF) Complus.add_field(2,'ExpType',13570) Directory = Table('Directory') -Directory.add_field(1,'Directory',11592) -Directory.add_field(2,'Directory_Parent',7496) +Directory.add_field(1,'Directory',0x2DFF) +Directory.add_field(2,'Directory_Parent',0x1DFF) Directory.add_field(3,'DefaultDir',4095) Control = Table('Control') @@ -207,13 +207,13 @@ ControlEvent.add_field(6,'Ordering',5378) CreateFolder = Table('CreateFolder') -CreateFolder.add_field(1,'Directory_',11592) -CreateFolder.add_field(2,'Component_',11592) +CreateFolder.add_field(1,'Directory_',0x2DFF) +CreateFolder.add_field(2,'Component_',0x2DFF) CustomAction = Table('CustomAction') -CustomAction.add_field(1,'Action',11592) +CustomAction.add_field(1,'Action',0x2DFF) CustomAction.add_field(2,'Type',1282) -CustomAction.add_field(3,'Source',7496) +CustomAction.add_field(3,'Source',0x1DFF) CustomAction.add_field(4,'Target',7679) DrLocator = Table('DrLocator') @@ -224,8 +224,8 @@ DuplicateFile = Table('DuplicateFile') DuplicateFile.add_field(1,'FileKey',11592) -DuplicateFile.add_field(2,'Component_',3400) -DuplicateFile.add_field(3,'File_',3400) +DuplicateFile.add_field(2,'Component_',0xDFF) +DuplicateFile.add_field(3,'File_',0xDFF) DuplicateFile.add_field(4,'DestName',8191) DuplicateFile.add_field(5,'DestFolder',7496) @@ -233,7 +233,7 @@ Environment.add_field(1,'Environment',11592) Environment.add_field(2,'Name',4095) Environment.add_field(3,'Value',8191) -Environment.add_field(4,'Component_',3400) +Environment.add_field(4,'Component_',0xDFF) Error = Table('Error') Error.add_field(1,'Error',9474) @@ -247,7 +247,7 @@ Extension = Table('Extension') Extension.add_field(1,'Extension',11775) -Extension.add_field(2,'Component_',11592) +Extension.add_field(2,'Component_',0x2DFF) Extension.add_field(3,'ProgId_',7679) Extension.add_field(4,'MIME_',7488) Extension.add_field(5,'Feature_',3366) @@ -259,10 +259,10 @@ FeatureComponents = Table('FeatureComponents') FeatureComponents.add_field(1,'Feature_',11558) -FeatureComponents.add_field(2,'Component_',11592) +FeatureComponents.add_field(2,'Component_',0x2DFF) FileSFPCatalog = Table('FileSFPCatalog') -FileSFPCatalog.add_field(1,'File_',11592) +FileSFPCatalog.add_field(1,'File_',0x2DFF) FileSFPCatalog.add_field(2,'SFPCatalog_',11775) SFPCatalog = Table('SFPCatalog') @@ -271,7 +271,7 @@ SFPCatalog.add_field(3,'Dependency',7424) Font = Table('Font') -Font.add_field(1,'File_',11592) +Font.add_field(1,'File_',0x2DFF) Font.add_field(2,'FontTitle',7552) IniFile = Table('IniFile') @@ -282,7 +282,7 @@ IniFile.add_field(5,'Key',3968) IniFile.add_field(6,'Value',4095) IniFile.add_field(7,'Action',1282) -IniFile.add_field(8,'Component_',3400) +IniFile.add_field(8,'Component_',0xDFF) IniLocator = Table('IniLocator') IniLocator.add_field(1,'Signature_',11592) @@ -293,18 +293,18 @@ IniLocator.add_field(6,'Type',5378) InstallExecuteSequence = Table('InstallExecuteSequence') -InstallExecuteSequence.add_field(1,'Action',11592) +InstallExecuteSequence.add_field(1,'Action',0x2DFF) InstallExecuteSequence.add_field(2,'Condition',7679) InstallExecuteSequence.add_field(3,'Sequence',5378) InstallUISequence = Table('InstallUISequence') -InstallUISequence.add_field(1,'Action',11592) +InstallUISequence.add_field(1,'Action',0x2DFF) InstallUISequence.add_field(2,'Condition',7679) InstallUISequence.add_field(3,'Sequence',5378) IsolatedComponent = Table('IsolatedComponent') -IsolatedComponent.add_field(1,'Component_Shared',11592) -IsolatedComponent.add_field(2,'Component_Application',11592) +IsolatedComponent.add_field(1,'Component_Shared',0x2DFF) +IsolatedComponent.add_field(2,'Component_Application',0x2DFF) LaunchCondition = Table('LaunchCondition') LaunchCondition.add_field(1,'Condition',11775) @@ -340,7 +340,7 @@ MoveFile = Table('MoveFile') MoveFile.add_field(1,'FileKey',11592) -MoveFile.add_field(2,'Component_',3400) +MoveFile.add_field(2,'Component_',0xDFF) MoveFile.add_field(3,'SourceName',8191) MoveFile.add_field(4,'DestName',8191) MoveFile.add_field(5,'SourceFolder',7496) @@ -348,14 +348,14 @@ MoveFile.add_field(7,'Options',1282) MsiAssembly = Table('MsiAssembly') -MsiAssembly.add_field(1,'Component_',11592) +MsiAssembly.add_field(1,'Component_',0x2DFF) MsiAssembly.add_field(2,'Feature_',3366) -MsiAssembly.add_field(3,'File_Manifest',7496) -MsiAssembly.add_field(4,'File_Application',7496) +MsiAssembly.add_field(3,'File_Manifest',0x1DFF) +MsiAssembly.add_field(4,'File_Application',0x1DFF) MsiAssembly.add_field(5,'Attributes',5378) MsiAssemblyName = Table('MsiAssemblyName') -MsiAssemblyName.add_field(1,'Component_',11592) +MsiAssemblyName.add_field(1,'Component_',0x2DFF) MsiAssemblyName.add_field(2,'Name',11775) MsiAssemblyName.add_field(3,'Value',3583) @@ -370,7 +370,7 @@ MsiDigitalSignature.add_field(4,'Hash',6400) MsiFileHash = Table('MsiFileHash') -MsiFileHash.add_field(1,'File_',11592) +MsiFileHash.add_field(1,'File_',0x2DFF) MsiFileHash.add_field(2,'Options',1282) MsiFileHash.add_field(3,'HashPart1',260) MsiFileHash.add_field(4,'HashPart2',260) @@ -388,14 +388,14 @@ ODBCDriver = Table('ODBCDriver') ODBCDriver.add_field(1,'Driver',11592) -ODBCDriver.add_field(2,'Component_',3400) +ODBCDriver.add_field(2,'Component_',0xDFF) ODBCDriver.add_field(3,'Description',3583) -ODBCDriver.add_field(4,'File_',3400) -ODBCDriver.add_field(5,'File_Setup',7496) +ODBCDriver.add_field(4,'File_',0xDFF) +ODBCDriver.add_field(5,'File_Setup',0x1DFF) ODBCDataSource = Table('ODBCDataSource') -ODBCDataSource.add_field(1,'DataSource',11592) -ODBCDataSource.add_field(2,'Component_',3400) +ODBCDataSource.add_field(1,'DataSource',0x2DFF) +ODBCDataSource.add_field(2,'Component_',0xDFF) ODBCDataSource.add_field(3,'Description',3583) ODBCDataSource.add_field(4,'DriverDescription',3583) ODBCDataSource.add_field(5,'Registration',1282) @@ -407,10 +407,10 @@ ODBCTranslator = Table('ODBCTranslator') ODBCTranslator.add_field(1,'Translator',11592) -ODBCTranslator.add_field(2,'Component_',3400) +ODBCTranslator.add_field(2,'Component_',0xDFF) ODBCTranslator.add_field(3,'Description',3583) -ODBCTranslator.add_field(4,'File_',3400) -ODBCTranslator.add_field(5,'File_Setup',7496) +ODBCTranslator.add_field(4,'File_',0xDFF) +ODBCTranslator.add_field(5,'File_Setup',0x1DFF) Patch = Table('Patch') Patch.add_field(1,'File_',11592) @@ -427,7 +427,7 @@ PublishComponent = Table('PublishComponent') PublishComponent.add_field(1,'ComponentId',11558) PublishComponent.add_field(2,'Qualifier',11775) -PublishComponent.add_field(3,'Component_',11592) +PublishComponent.add_field(3,'Component_',0x2DFF) PublishComponent.add_field(4,'AppData',8191) PublishComponent.add_field(5,'Feature_',3366) @@ -443,12 +443,12 @@ RadioButton.add_field(9,'Help',7986) Registry = Table('Registry') -Registry.add_field(1,'Registry',11592) +Registry.add_field(1,'Registry',0x2DFF) Registry.add_field(2,'Root',1282) Registry.add_field(3,'Key',4095) Registry.add_field(4,'Name',8191) Registry.add_field(5,'Value',7936) -Registry.add_field(6,'Component_',3400) +Registry.add_field(6,'Component_',0xDFF) RegLocator = Table('RegLocator') RegLocator.add_field(1,'Signature_',11592) @@ -459,7 +459,7 @@ RemoveFile = Table('RemoveFile') RemoveFile.add_field(1,'FileKey',11592) -RemoveFile.add_field(2,'Component_',3400) +RemoveFile.add_field(2,'Component_',0xDFF) RemoveFile.add_field(3,'FileName',8191) RemoveFile.add_field(4,'DirProperty',3400) RemoveFile.add_field(5,'InstallMode',1282) @@ -472,24 +472,24 @@ RemoveIniFile.add_field(5,'Key',3968) RemoveIniFile.add_field(6,'Value',8191) RemoveIniFile.add_field(7,'Action',1282) -RemoveIniFile.add_field(8,'Component_',3400) +RemoveIniFile.add_field(8,'Component_',0xDFF) RemoveRegistry = Table('RemoveRegistry') RemoveRegistry.add_field(1,'RemoveRegistry',11592) RemoveRegistry.add_field(2,'Root',1282) RemoveRegistry.add_field(3,'Key',4095) RemoveRegistry.add_field(4,'Name',8191) -RemoveRegistry.add_field(5,'Component_',3400) +RemoveRegistry.add_field(5,'Component_',0xDFF) ReserveCost = Table('ReserveCost') ReserveCost.add_field(1,'ReserveKey',11592) -ReserveCost.add_field(2,'Component_',3400) +ReserveCost.add_field(2,'Component_',0xDFF) ReserveCost.add_field(3,'ReserveFolder',7496) ReserveCost.add_field(4,'ReserveLocal',260) ReserveCost.add_field(5,'ReserveSource',260) SelfReg = Table('SelfReg') -SelfReg.add_field(1,'File_',11592) +SelfReg.add_field(1,'File_',0x2DFF) SelfReg.add_field(2,'Cost',5378) ServiceControl = Table('ServiceControl') @@ -498,7 +498,7 @@ ServiceControl.add_field(3,'Event',1282) ServiceControl.add_field(4,'Arguments',8191) ServiceControl.add_field(5,'Wait',5378) -ServiceControl.add_field(6,'Component_',3400) +ServiceControl.add_field(6,'Component_',0xDFF) ServiceInstall = Table('ServiceInstall') ServiceInstall.add_field(1,'ServiceInstall',11592) @@ -512,14 +512,14 @@ ServiceInstall.add_field(9,'StartName',7679) ServiceInstall.add_field(10,'Password',7679) ServiceInstall.add_field(11,'Arguments',7679) -ServiceInstall.add_field(12,'Component_',3400) +ServiceInstall.add_field(12,'Component_',0xDFF) ServiceInstall.add_field(13,'Description',8191) Shortcut = Table('Shortcut') Shortcut.add_field(1,'Shortcut',11592) -Shortcut.add_field(2,'Directory_',3400) +Shortcut.add_field(2,'Directory_',0xDFF) Shortcut.add_field(3,'Name',3968) -Shortcut.add_field(4,'Component_',3400) +Shortcut.add_field(4,'Component_',0xDFF) Shortcut.add_field(5,'Target',3400) Shortcut.add_field(6,'Arguments',7679) Shortcut.add_field(7,'Description',8191) @@ -550,10 +550,10 @@ TypeLib = Table('TypeLib') TypeLib.add_field(1,'LibID',11558) TypeLib.add_field(2,'Language',9474) -TypeLib.add_field(3,'Component_',11592) +TypeLib.add_field(3,'Component_',0x2DFF) TypeLib.add_field(4,'Version',4356) TypeLib.add_field(5,'Description',8064) -TypeLib.add_field(6,'Directory_',7496) +TypeLib.add_field(6,'Directory_',0x1DFF) TypeLib.add_field(7,'Feature_',3366) TypeLib.add_field(8,'Cost',4356) Modified: python/branches/py3k-ctypes-pep3118/Tools/msi/uuids.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/msi/uuids.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/msi/uuids.py Wed Apr 30 15:57:13 2008 @@ -37,9 +37,15 @@ '2.5.1150':'{31800004-6386-4999-a519-518f2d78d8f0}', # 2.5.1 '2.5.2150':'{6304a7da-1132-4e91-a343-a296269eab8a}', # 2.5.2c1 '2.5.2150':'{6b976adf-8ae8-434e-b282-a06c7f624d2f}', # 2.5.2 + '2.6.101': '{0ba82e1b-52fd-4e03-8610-a6c76238e8a8}', # 2.6a1 + '2.6.102': '{3b27e16c-56db-4570-a2d3-e9a26180c60b}', # 2.6a2 + '2.6.103': '{cd06a9c5-bde5-4bd7-9874-48933997122a}', # 2.6a3 + '2.6.104': '{dc6ed634-474a-4a50-a547-8de4b7491e53}', # 2.6a4 '3.0.101': '{8554263a-3242-4857-9359-aa87bc2c58c2}', # 3.0a1 '3.0.102': '{692d6e2c-f0ac-40b8-a133-7191aeeb67f9}', # 3.0a2 '3.0.103': '{49cb2995-751a-4753-be7a-d0b1bb585e06}', # 3.0a3 + '3.0.104': '{87cb019e-19fd-4238-b1c7-85751437d646}', # 3.0a4 + '3.0.105': '{cf2659af-19ec-43d2-8c35-0f6a09439d42}', # 3.0a5 '3.0.111': '{36c26f55-837d-45cf-848c-5f5c0fb47a28}', # 3.0b1 '3.0.112': '{056a0fbc-c8fe-4c61-aade-c4411b70c998}', # 3.0b2 '3.0.121': '{d0979c5e-cd3c-42ec-be4c-e294da793573}', # 3.0c1 Modified: python/branches/py3k-ctypes-pep3118/Tools/pybench/Setup.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/pybench/Setup.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/pybench/Setup.py Wed Apr 30 15:57:13 2008 @@ -30,6 +30,10 @@ from Tuples import * from Dict import * from Exceptions import * +try: + from With import * +except SyntaxError: + pass from Imports import * from Strings import * from Numbers import * Modified: python/branches/py3k-ctypes-pep3118/Tools/pybench/pybench.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/pybench/pybench.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/pybench/pybench.py Wed Apr 30 15:57:13 2008 @@ -121,7 +121,8 @@ 'platform': platform.platform(), 'processor': platform.processor(), 'executable': sys.executable, - 'implementation': platform.python_implementation(), + 'implementation': getattr(platform, 'python_implementation', + lambda:'n/a')(), 'python': platform.python_version(), 'compiler': platform.python_compiler(), 'buildno': buildno, @@ -833,7 +834,7 @@ print('PYBENCH %s' % __version__) print('-' * LINE) print('* using %s %s' % ( - platform.python_implementation(), + getattr(platform, 'python_implementation', lambda:'Python')(), ' '.join(sys.version.split()))) # Switch off garbage collection Modified: python/branches/py3k-ctypes-pep3118/Tools/pybench/systimes.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/pybench/systimes.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/pybench/systimes.py Wed Apr 30 15:57:13 2008 @@ -31,7 +31,7 @@ the author. All Rights Reserved. """ -import time, sys, struct +import time, sys # # Note: Please keep this module compatible to Python 1.5.2. Modified: python/branches/py3k-ctypes-pep3118/Tools/pynche/ChipViewer.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/pynche/ChipViewer.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/pynche/ChipViewer.py Wed Apr 30 15:57:13 2008 @@ -13,7 +13,6 @@ selected and nearest ChipWidgets. """ -from types import StringType from Tkinter import * import ColorDB Modified: python/branches/py3k-ctypes-pep3118/Tools/pynche/ColorDB.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/pynche/ColorDB.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/pynche/ColorDB.py Wed Apr 30 15:57:13 2008 @@ -122,10 +122,7 @@ self.__allnames = [] for name, aliases in self.__byrgb.values(): self.__allnames.append(name) - # sort irregardless of case - def nocase_cmp(n1, n2): - return cmp(n1.lower(), n2.lower()) - self.__allnames.sort(nocase_cmp) + self.__allnames.sort(key=unicode.lower) return self.__allnames def aliases_of(self, red, green, blue): Modified: python/branches/py3k-ctypes-pep3118/Tools/pynche/TypeinViewer.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/pynche/TypeinViewer.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/pynche/TypeinViewer.py Wed Apr 30 15:57:13 2008 @@ -12,8 +12,6 @@ you must hit Return or Tab to select the color. """ -import sys -import re from Tkinter import * Modified: python/branches/py3k-ctypes-pep3118/Tools/scripts/checkappend.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/scripts/checkappend.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/scripts/checkappend.py Wed Apr 30 15:57:13 2008 @@ -103,7 +103,9 @@ def run(self): try: - tokenize.tokenize(self.file.readline, self.tokeneater) + tokens = tokenize.generate_tokens(self.file.readline) + for _token in tokens: + self.tokeneater(*_token) except tokenize.TokenError as msg: errprint("%r: Token Error: %s" % (self.fname, msg)) self.nerrors = self.nerrors + 1 Modified: python/branches/py3k-ctypes-pep3118/Tools/scripts/finddiv.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/scripts/finddiv.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/scripts/finddiv.py Wed Apr 30 15:57:13 2008 @@ -78,7 +78,7 @@ fn = os.path.join(dir, name) if os.path.normcase(fn).endswith(".py") or os.path.isdir(fn): files.append(fn) - files.sort(lambda a, b: cmp(os.path.normcase(a), os.path.normcase(b))) + files.sort(key=os.path.normcase) exit = None for fn in files: x = process(fn, listnames) Modified: python/branches/py3k-ctypes-pep3118/Tools/scripts/logmerge.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/scripts/logmerge.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/scripts/logmerge.py Wed Apr 30 15:57:13 2008 @@ -34,7 +34,7 @@ from their output. """ -import os, sys, errno, getopt, re +import sys, errno, getopt, re sep1 = '='*77 + '\n' # file separator sep2 = '-'*28 + '\n' # revision separator Modified: python/branches/py3k-ctypes-pep3118/Tools/scripts/nm2def.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/scripts/nm2def.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/scripts/nm2def.py Wed Apr 30 15:57:13 2008 @@ -34,7 +34,7 @@ option to produce this format (since it is the original v7 Unix format). """ -import os,re,sys +import os, sys PYTHONLIB = 'libpython'+sys.version[:3]+'.a' PC_PYTHONLIB = 'Python'+sys.version[0]+sys.version[2]+'.dll' Modified: python/branches/py3k-ctypes-pep3118/Tools/scripts/pindent.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/scripts/pindent.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/scripts/pindent.py Wed Apr 30 15:57:13 2008 @@ -81,7 +81,6 @@ TABSIZE = 8 EXPANDTABS = 0 -import os import re import sys Modified: python/branches/py3k-ctypes-pep3118/Tools/scripts/pysource.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/scripts/pysource.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/scripts/pysource.py Wed Apr 30 15:57:13 2008 @@ -20,7 +20,7 @@ __all__ = ["has_python_ext", "looks_like_python", "can_be_compiled", "walk_python_files"] -import sys, os, re +import os, re binary_re = re.compile('[\x00-\x08\x0E-\x1F\x7F]') Modified: python/branches/py3k-ctypes-pep3118/Tools/scripts/reindent.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/scripts/reindent.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/scripts/reindent.py Wed Apr 30 15:57:13 2008 @@ -4,10 +4,11 @@ """reindent [-d][-r][-v] [ path ... ] --d (--dryrun) Dry run. Analyze, but don't make any changes to, files. --r (--recurse) Recurse. Search for all .py files in subdirectories too. --v (--verbose) Verbose. Print informative msgs; else no output. --h (--help) Help. Print this usage information and exit. +-d (--dryrun) Dry run. Analyze, but don't make any changes to, files. +-r (--recurse) Recurse. Search for all .py files in subdirectories too. +-n (--nobackup) No backup. Does not make a ".bak" file before reindenting. +-v (--verbose) Verbose. Print informative msgs; else no output. +-h (--help) Help. Print this usage information and exit. Change Python (.py) files to use 4-space indents and no hard tab characters. Also trim excess spaces and tabs from ends of lines, and remove empty lines @@ -31,17 +32,23 @@ The hard part of reindenting is figuring out what to do with comment lines. So long as the input files get a clean bill of health from tabnanny.py, reindent should do a good job. + +The backup file is a copy of the one that is being reindented. The ".bak" +file is generated with shutil.copy(), but some corner cases regarding +user/group and permissions could leave the backup file more readable that +you'd prefer. You can always use the --nobackup option to prevent this. """ __version__ = "1" import tokenize -import os +import os, shutil import sys -verbose = 0 -recurse = 0 -dryrun = 0 +verbose = 0 +recurse = 0 +dryrun = 0 +makebackup = True def usage(msg=None): if msg is not None: @@ -57,10 +64,10 @@ def main(): import getopt - global verbose, recurse, dryrun + global verbose, recurse, dryrun, makebackup try: - opts, args = getopt.getopt(sys.argv[1:], "drvh", - ["dryrun", "recurse", "verbose", "help"]) + opts, args = getopt.getopt(sys.argv[1:], "drnvh", + ["dryrun", "recurse", "nobackup", "verbose", "help"]) except getopt.error as msg: usage(msg) return @@ -69,6 +76,8 @@ dryrun += 1 elif o in ('-r', '--recurse'): recurse += 1 + elif o in ('-n', '--nobackup'): + makebackup = False elif o in ('-v', '--verbose'): verbose += 1 elif o in ('-h', '--help'): @@ -112,19 +121,20 @@ print("But this is a dry run, so leaving it alone.") if not dryrun: bak = file + ".bak" - if os.path.exists(bak): - os.remove(bak) - os.rename(file, bak) - if verbose: - print("renamed", file, "to", bak) + if makebackup: + shutil.copyfile(file, bak) + if verbose: + print("backed up", file, "to", bak) f = open(file, "w") r.write(f) f.close() if verbose: print("wrote new", file) + return True else: if verbose: print("unchanged.") + return False def _rstrip(line, JUNK='\n \t'): """Return line stripped of trailing spaces, tabs, newlines. @@ -163,7 +173,9 @@ self.stats = [] def run(self): - tokenize.tokenize(self.getline, self.tokeneater) + tokens = tokenize.generate_tokens(self.getline) + for _token in tokens: + self.tokeneater(*_token) # Remove trailing empty lines. lines = self.lines while lines and lines[-1] == "\n": Deleted: python/branches/py3k-ctypes-pep3118/Tools/scripts/texcheck.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/scripts/texcheck.py Wed Apr 30 15:57:13 2008 +++ (empty file) @@ -1,233 +0,0 @@ -""" TeXcheck.py -- rough syntax checking on Python style LaTeX documents. - - Written by Raymond D. Hettinger - Copyright (c) 2003 Python Software Foundation. All rights reserved. - -Designed to catch common markup errors including: -* Unbalanced or mismatched parenthesis, brackets, and braces. -* Unbalanced or mismatched \\begin and \\end blocks. -* Misspelled or invalid LaTeX commands. -* Use of forward slashes instead of backslashes for commands. -* Table line size mismatches. - -Sample command line usage: - python texcheck.py -k chapterheading -m lib/librandomtex *.tex - -Options: - -m Munge parenthesis and brackets. [0,n) would normally mismatch. - -k keyword: Keyword is a valid LaTeX command. Do not include the backslash. - -d: Delimiter check only (useful for non-LaTeX files). - -h: Help - -s lineno: Start at lineno (useful for skipping complex sections). - -v: Verbose. Trace the matching of //begin and //end blocks. -""" - -import re -import sys -import getopt -from itertools import izip, count, islice -import glob - -cmdstr = r""" - \section \module \declaremodule \modulesynopsis \moduleauthor - \sectionauthor \versionadded \code \class \method \begin - \optional \var \ref \end \subsection \lineiii \hline \label - \indexii \textrm \ldots \keyword \stindex \index \item \note - \withsubitem \ttindex \footnote \citetitle \samp \opindex - \noindent \exception \strong \dfn \ctype \obindex \character - \indexiii \function \bifuncindex \refmodule \refbimodindex - \subsubsection \nodename \member \chapter \emph \ASCII \UNIX - \regexp \program \production \token \productioncont \term - \grammartoken \lineii \seemodule \file \EOF \documentclass - \usepackage \title \input \maketitle \ifhtml \fi \url \Cpp - \tableofcontents \kbd \programopt \envvar \refstmodindex - \cfunction \constant \NULL \moreargs \cfuncline \cdata - \textasciicircum \n \ABC \setindexsubitem \versionchanged - \deprecated \seetext \newcommand \POSIX \pep \warning \rfc - \verbatiminput \methodline \textgreater \seetitle \lineiv - \funclineni \ulink \manpage \funcline \dataline \unspecified - \textbackslash \mimetype \mailheader \seepep \textunderscore - \longprogramopt \infinity \plusminus \shortversion \version - \refmodindex \seerfc \makeindex \makemodindex \renewcommand - \indexname \appendix \protect \indexiv \mbox \textasciitilde - \platform \seeurl \leftmargin \labelwidth \localmoduletable - \LaTeX \copyright \memberline \backslash \pi \centerline - \caption \vspace \textwidth \menuselection \textless - \makevar \csimplemacro \menuselection \bfcode \sub \release - \email \kwindex \refexmodindex \filenq \e \menuselection - \exindex \linev \newsgroup \verbatim \setshortversion - \author \authoraddress \paragraph \subparagraph \cmemberline - \textbar \C \seelink -""" - -def matchclose(c_lineno, c_symbol, openers, pairmap): - "Verify that closing delimiter matches most recent opening delimiter" - try: - o_lineno, o_symbol = openers.pop() - except IndexError: - print("\nDelimiter mismatch. On line %d, encountered closing '%s' without corresponding open" % (c_lineno, c_symbol)) - return - if o_symbol in pairmap.get(c_symbol, [c_symbol]): return - print("\nOpener '%s' on line %d was not closed before encountering '%s' on line %d" % (o_symbol, o_lineno, c_symbol, c_lineno)) - return - -def checkit(source, opts, morecmds=[]): - """Check the LaTeX formatting in a sequence of lines. - - Opts is a mapping of options to option values if any: - -m munge parenthesis and brackets - -d delimiters only checking - -v verbose trace of delimiter matching - -s lineno: linenumber to start scan (default is 1). - - Morecmds is a sequence of LaTeX commands (without backslashes) that - are to be considered valid in the scan. - """ - - texcmd = re.compile(r'\\[A-Za-z]+') - falsetexcmd = re.compile(r'\/([A-Za-z]+)') # Mismarked with forward slash - - validcmds = set(cmdstr.split()) - for cmd in morecmds: - validcmds.add('\\' + cmd) - - if '-m' in opts: - pairmap = {']':'[(', ')':'(['} # Munged openers - else: - pairmap = {']':'[', ')':'('} # Normal opener for a given closer - openpunct = set('([') # Set of valid openers - - delimiters = re.compile(r'\\(begin|end){([_a-zA-Z]+)}|([()\[\]])') - braces = re.compile(r'({)|(})') - doubledwords = re.compile(r'(\b[A-za-z]+\b) \b\1\b') - spacingmarkup = re.compile(r'\\(ABC|ASCII|C|Cpp|EOF|infinity|NULL|plusminus|POSIX|UNIX)\s') - - openers = [] # Stack of pending open delimiters - bracestack = [] # Stack of pending open braces - - tablestart = re.compile(r'\\begin{(?:long)?table([iv]+)}') - tableline = re.compile(r'\\line([iv]+){') - tableend = re.compile(r'\\end{(?:long)?table([iv]+)}') - tablelevel = '' - tablestartline = 0 - - startline = int(opts.get('-s', '1')) - lineno = 0 - - for lineno, line in izip(count(startline), islice(source, startline-1, None)): - line = line.rstrip() - - # Check balancing of open/close parenthesis, brackets, and begin/end blocks - for begend, name, punct in delimiters.findall(line): - if '-v' in opts: - print(lineno, '|', begend, name, punct, end=' ') - if begend == 'begin' and '-d' not in opts: - openers.append((lineno, name)) - elif punct in openpunct: - openers.append((lineno, punct)) - elif begend == 'end' and '-d' not in opts: - matchclose(lineno, name, openers, pairmap) - elif punct in pairmap: - matchclose(lineno, punct, openers, pairmap) - if '-v' in opts: - print(' --> ', openers) - - # Balance opening and closing braces - for open, close in braces.findall(line): - if open == '{': - bracestack.append(lineno) - if close == '}': - try: - bracestack.pop() - except IndexError: - print(r'Warning, unmatched } on line %s.' % (lineno,)) - - # Optionally, skip LaTeX specific checks - if '-d' in opts: - continue - - # Warn whenever forward slashes encountered with a LaTeX command - for cmd in falsetexcmd.findall(line): - if '822' in line or '.html' in line: - continue # Ignore false positives for urls and for /rfc822 - if '\\' + cmd in validcmds: - print('Warning, forward slash used on line %d with cmd: /%s' % (lineno, cmd)) - - # Check for markup requiring {} for correct spacing - for cmd in spacingmarkup.findall(line): - print(r'Warning, \%s should be written as \%s{} on line %d' % (cmd, cmd, lineno)) - - # Validate commands - nc = line.find(r'\newcommand') - if nc != -1: - start = line.find('{', nc) - end = line.find('}', start) - validcmds.add(line[start+1:end]) - for cmd in texcmd.findall(line): - if cmd not in validcmds: - print(r'Warning, unknown tex cmd on line %d: \%s' % (lineno, cmd)) - - # Check table levels (make sure lineii only inside tableii) - m = tablestart.search(line) - if m: - tablelevel = m.group(1) - tablestartline = lineno - m = tableline.search(line) - if m and m.group(1) != tablelevel: - print(r'Warning, \line%s on line %d does not match \table%s on line %d' % (m.group(1), lineno, tablelevel, tablestartline)) - if tableend.search(line): - tablelevel = '' - - # Style guide warnings - if 'e.g.' in line or 'i.e.' in line: - print(r'Style warning, avoid use of i.e or e.g. on line %d' % (lineno,)) - - for dw in doubledwords.findall(line): - print(r'Doubled word warning. "%s" on line %d' % (dw, lineno)) - - lastline = lineno - for lineno, symbol in openers: - print("Unmatched open delimiter '%s' on line %d" % (symbol, lineno)) - for lineno in bracestack: - print("Unmatched { on line %d" % (lineno,)) - print('Done checking %d lines.' % (lastline,)) - return 0 - -def main(args=None): - if args is None: - args = sys.argv[1:] - optitems, arglist = getopt.getopt(args, "k:mdhs:v") - opts = dict(optitems) - if '-h' in opts or args==[]: - print(__doc__) - return 0 - - if len(arglist) < 1: - print('Please specify a file to be checked') - return 1 - - for i, filespec in enumerate(arglist): - if '*' in filespec or '?' in filespec: - arglist[i:i+1] = glob.glob(filespec) - - morecmds = [v for k,v in optitems if k=='-k'] - err = [] - - for filename in arglist: - print('=' * 30) - print("Checking", filename) - try: - f = open(filename) - except IOError: - print('Cannot open file %s.' % arglist[0]) - return 2 - - try: - err.append(checkit(f, opts, morecmds)) - finally: - f.close() - - return max(err) - -if __name__ == '__main__': - sys.exit(main()) Modified: python/branches/py3k-ctypes-pep3118/Tools/scripts/xxci.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/scripts/xxci.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/scripts/xxci.py Wed Apr 30 15:57:13 2008 @@ -7,7 +7,6 @@ import sys import os from stat import * -import commands import fnmatch EXECMAGIC = '\001\140\000\010' Modified: python/branches/py3k-ctypes-pep3118/Tools/ssl/get-remote-certificate.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/ssl/get-remote-certificate.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/ssl/get-remote-certificate.py Wed Apr 30 15:57:13 2008 @@ -6,7 +6,7 @@ # # By Bill Janssen. -import sys, os +import sys def fetch_server_certificate (host, port): Modified: python/branches/py3k-ctypes-pep3118/Tools/unicode/gencodec.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/unicode/gencodec.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/unicode/gencodec.py Wed Apr 30 15:57:13 2008 @@ -26,7 +26,7 @@ """#" -import re, os, time, marshal, codecs +import re, os, marshal, codecs # Maximum allowed size of charmap tables MAX_TABLE_SIZE = 8192 Modified: python/branches/py3k-ctypes-pep3118/Tools/unicode/makeunicodedata.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/unicode/makeunicodedata.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/unicode/makeunicodedata.py Wed Apr 30 15:57:13 2008 @@ -441,6 +441,15 @@ # -------------------------------------------------------------------- # unicode name database +def CmpToKey(mycmp): + 'Convert a cmp= function into a key= function' + class K(object): + def __init__(self, obj, *args): + self.obj = obj + def __lt__(self, other): + return mycmp(self.obj, other.obj) == -1 + return K + def makeunicodename(unicode, trace): FILE = "Modules/unicodename_db.h" @@ -490,7 +499,7 @@ if r: return r return cmp(aword, bword) - wordlist.sort(cmpwords) + wordlist.sort(key=CmpToKey(cmpwords)) # figure out how many phrasebook escapes we need escapes = 0 @@ -514,7 +523,7 @@ # length (to maximize overlap) wordlist, wordtail = wordlist[:short], wordlist[short:] - wordtail.sort(lambda a, b: len(b[0])-len(a[0])) + wordtail.sort(key=lambda a: a[0], reverse=True) wordlist.extend(wordtail) # generate lexicon from words Modified: python/branches/py3k-ctypes-pep3118/Tools/webchecker/wcgui.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/webchecker/wcgui.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/webchecker/wcgui.py Wed Apr 30 15:57:13 2008 @@ -63,7 +63,6 @@ from Tkinter import * import tktools import webchecker -import random # Override some for a weaker platform if sys.platform == 'mac': Modified: python/branches/py3k-ctypes-pep3118/Tools/webchecker/wsgui.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/Tools/webchecker/wsgui.py (original) +++ python/branches/py3k-ctypes-pep3118/Tools/webchecker/wsgui.py Wed Apr 30 15:57:13 2008 @@ -7,9 +7,7 @@ """ from Tkinter import * -import Tkinter import websucker -import sys import os import threading import Queue Modified: python/branches/py3k-ctypes-pep3118/configure ============================================================================== --- python/branches/py3k-ctypes-pep3118/configure (original) +++ python/branches/py3k-ctypes-pep3118/configure Wed Apr 30 15:57:13 2008 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 59829 . +# From configure.in Revision: 62451 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.61 for python 3.0. # @@ -1311,8 +1311,8 @@ Optional Features: --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) --enable-FEATURE[=ARG] include FEATURE [ARG=yes] - --enable-universalsdk[SDKDIR] - Build agains Mac OS X 10.4u SDK (ppc/i386) + --enable-universalsdk[=SDKDIR] + Build against Mac OS X 10.4u SDK (ppc/i386) --enable-framework[=INSTALLDIR] Build (MacOSX|Darwin) framework --enable-shared disable/enable building shared python library @@ -2153,6 +2153,12 @@ CONFIGURE_MACOSX_DEPLOYMENT_TARGET= EXPORT_MACOSX_DEPLOYMENT_TARGET='#' +{ echo "$as_me:$LINENO: checking machine type as reported by uname -m" >&5 +echo $ECHO_N "checking machine type as reported by uname -m... $ECHO_C" >&6; } +ac_sys_machine=`uname -m` +{ echo "$as_me:$LINENO: result: $ac_sys_machine" >&5 +echo "${ECHO_T}$ac_sys_machine" >&6; } + # checks for alternative programs # compiler flags are generated in two sets, BASECFLAGS and OPT. OPT is just @@ -4503,13 +4509,24 @@ then BASECFLAGS="$BASECFLAGS -fno-strict-aliasing" fi + + # if using gcc on alpha, use -mieee to get (near) full IEEE 754 + # support. Without this, treatment of subnormals doesn't follow + # the standard. + case $ac_sys_machine in + alpha*) + BASECFLAGS="$BASECFLAGS -mieee" + ;; + esac + case $ac_sys_system in SCO_SV*) BASECFLAGS="$BASECFLAGS -m486 -DSCO5" ;; # is there any other compiler on Darwin besides gcc? Darwin*) - BASECFLAGS="$BASECFLAGS -Wno-long-double -no-cpp-precomp -mno-fused-madd" + # -Wno-long-double, -no-cpp-precomp, and -mno-fused-madd + # used to be here, but non-Apple gcc doesn't accept them. if test "${enable_universalsdk}"; then BASECFLAGS="-arch ppc -arch i386 -isysroot ${UNIVERSALSDK} ${BASECFLAGS}" fi @@ -5389,13 +5406,16 @@ + + + for ac_header in asm/types.h conio.h curses.h direct.h dlfcn.h errno.h \ fcntl.h grp.h \ -io.h langinfo.h libintl.h ncurses.h poll.h process.h pthread.h \ +ieeefp.h io.h langinfo.h libintl.h ncurses.h poll.h process.h pthread.h \ shadow.h signal.h stdint.h stropts.h termios.h thread.h \ unistd.h utime.h \ -sys/audioio.h sys/bsdtty.h sys/file.h sys/loadavg.h sys/lock.h sys/mkdev.h \ -sys/modem.h \ +sys/audioio.h sys/bsdtty.h sys/epoll.h sys/event.h sys/file.h sys/loadavg.h \ +sys/lock.h sys/mkdev.h sys/modem.h \ sys/param.h sys/poll.h sys/select.h sys/socket.h sys/statvfs.h sys/stat.h \ sys/time.h \ sys/times.h sys/types.h sys/un.h sys/utsname.h sys/wait.h pty.h libutil.h \ @@ -10131,64 +10151,9 @@ _ACEOF - -{ echo "$as_me:$LINENO: checking for long long support" >&5 -echo $ECHO_N "checking for long long support... $ECHO_C" >&6; } -have_long_long=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ -long long x; x = (long long)0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - - -cat >>confdefs.h <<\_ACEOF -#define HAVE_LONG_LONG 1 -_ACEOF - - have_long_long=yes - -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_long_long" >&5 -echo "${ECHO_T}$have_long_long" >&6; } -if test "$have_long_long" = yes ; then -{ echo "$as_me:$LINENO: checking for long long" >&5 -echo $ECHO_N "checking for long long... $ECHO_C" >&6; } -if test "${ac_cv_type_long_long+set}" = set; then +{ echo "$as_me:$LINENO: checking for pid_t" >&5 +echo $ECHO_N "checking for pid_t... $ECHO_C" >&6; } +if test "${ac_cv_type_pid_t+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF @@ -10198,7 +10163,7 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default -typedef long long ac__type_new_; +typedef pid_t ac__type_new_; int main () { @@ -10227,26 +10192,26 @@ test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - ac_cv_type_long_long=yes + ac_cv_type_pid_t=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_long_long=no + ac_cv_type_pid_t=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_long_long" >&5 -echo "${ECHO_T}$ac_cv_type_long_long" >&6; } +{ echo "$as_me:$LINENO: result: $ac_cv_type_pid_t" >&5 +echo "${ECHO_T}$ac_cv_type_pid_t" >&6; } # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of long long" >&5 -echo $ECHO_N "checking size of long long... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_long_long+set}" = set; then +{ echo "$as_me:$LINENO: checking size of pid_t" >&5 +echo $ECHO_N "checking size of pid_t... $ECHO_C" >&6; } +if test "${ac_cv_sizeof_pid_t+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else if test "$cross_compiling" = yes; then @@ -10258,7 +10223,7 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long long ac__type_sizeof_; + typedef pid_t ac__type_sizeof_; int main () { @@ -10295,7 +10260,7 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long long ac__type_sizeof_; + typedef pid_t ac__type_sizeof_; int main () { @@ -10349,7 +10314,7 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long long ac__type_sizeof_; + typedef pid_t ac__type_sizeof_; int main () { @@ -10386,7 +10351,7 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long long ac__type_sizeof_; + typedef pid_t ac__type_sizeof_; int main () { @@ -10450,7 +10415,7 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long long ac__type_sizeof_; + typedef pid_t ac__type_sizeof_; int main () { @@ -10489,15 +10454,15 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done case $ac_lo in -?*) ac_cv_sizeof_long_long=$ac_lo;; -'') if test "$ac_cv_type_long_long" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long long) +?*) ac_cv_sizeof_pid_t=$ac_lo;; +'') if test "$ac_cv_type_pid_t" = yes; then + { { echo "$as_me:$LINENO: error: cannot compute sizeof (pid_t) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long long) +echo "$as_me: error: cannot compute sizeof (pid_t) See \`config.log' for more details." >&2;} { (exit 77); exit 77; }; } else - ac_cv_sizeof_long_long=0 + ac_cv_sizeof_pid_t=0 fi ;; esac else @@ -10508,7 +10473,7 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long long ac__type_sizeof_; + typedef pid_t ac__type_sizeof_; static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } #include @@ -10560,42 +10525,41 @@ ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then - ac_cv_sizeof_long_long=`cat conftest.val` + ac_cv_sizeof_pid_t=`cat conftest.val` else echo "$as_me: program exited with status $ac_status" >&5 echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) -if test "$ac_cv_type_long_long" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long long) +if test "$ac_cv_type_pid_t" = yes; then + { { echo "$as_me:$LINENO: error: cannot compute sizeof (pid_t) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long long) +echo "$as_me: error: cannot compute sizeof (pid_t) See \`config.log' for more details." >&2;} { (exit 77); exit 77; }; } else - ac_cv_sizeof_long_long=0 + ac_cv_sizeof_pid_t=0 fi fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_long_long" >&5 -echo "${ECHO_T}$ac_cv_sizeof_long_long" >&6; } +{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_pid_t" >&5 +echo "${ECHO_T}$ac_cv_sizeof_pid_t" >&6; } cat >>confdefs.h <<_ACEOF -#define SIZEOF_LONG_LONG $ac_cv_sizeof_long_long +#define SIZEOF_PID_T $ac_cv_sizeof_pid_t _ACEOF -fi -{ echo "$as_me:$LINENO: checking for long double support" >&5 -echo $ECHO_N "checking for long double support... $ECHO_C" >&6; } -have_long_double=no +{ echo "$as_me:$LINENO: checking for long long support" >&5 +echo $ECHO_N "checking for long long support... $ECHO_C" >&6; } +have_long_long=no cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -10606,7 +10570,7 @@ int main () { -long double x; x = (long double)0; +long long x; x = (long long)0; ; return 0; } @@ -10631,10 +10595,10 @@ cat >>confdefs.h <<\_ACEOF -#define HAVE_LONG_DOUBLE 1 +#define HAVE_LONG_LONG 1 _ACEOF - have_long_double=yes + have_long_long=yes else echo "$as_me: failed program was:" >&5 @@ -10644,12 +10608,12 @@ fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_long_double" >&5 -echo "${ECHO_T}$have_long_double" >&6; } -if test "$have_long_double" = yes ; then -{ echo "$as_me:$LINENO: checking for long double" >&5 -echo $ECHO_N "checking for long double... $ECHO_C" >&6; } -if test "${ac_cv_type_long_double+set}" = set; then +{ echo "$as_me:$LINENO: result: $have_long_long" >&5 +echo "${ECHO_T}$have_long_long" >&6; } +if test "$have_long_long" = yes ; then +{ echo "$as_me:$LINENO: checking for long long" >&5 +echo $ECHO_N "checking for long long... $ECHO_C" >&6; } +if test "${ac_cv_type_long_long+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF @@ -10659,7 +10623,7 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default -typedef long double ac__type_new_; +typedef long long ac__type_new_; int main () { @@ -10688,26 +10652,26 @@ test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - ac_cv_type_long_double=yes + ac_cv_type_long_long=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_long_double=no + ac_cv_type_long_long=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_long_double" >&5 -echo "${ECHO_T}$ac_cv_type_long_double" >&6; } +{ echo "$as_me:$LINENO: result: $ac_cv_type_long_long" >&5 +echo "${ECHO_T}$ac_cv_type_long_long" >&6; } # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of long double" >&5 -echo $ECHO_N "checking size of long double... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_long_double+set}" = set; then +{ echo "$as_me:$LINENO: checking size of long long" >&5 +echo $ECHO_N "checking size of long long... $ECHO_C" >&6; } +if test "${ac_cv_sizeof_long_long+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else if test "$cross_compiling" = yes; then @@ -10719,7 +10683,7 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long double ac__type_sizeof_; + typedef long long ac__type_sizeof_; int main () { @@ -10756,7 +10720,7 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long double ac__type_sizeof_; + typedef long long ac__type_sizeof_; int main () { @@ -10810,7 +10774,7 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long double ac__type_sizeof_; + typedef long long ac__type_sizeof_; int main () { @@ -10847,7 +10811,7 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long double ac__type_sizeof_; + typedef long long ac__type_sizeof_; int main () { @@ -10911,7 +10875,7 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long double ac__type_sizeof_; + typedef long long ac__type_sizeof_; int main () { @@ -10950,15 +10914,15 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done case $ac_lo in -?*) ac_cv_sizeof_long_double=$ac_lo;; -'') if test "$ac_cv_type_long_double" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long double) +?*) ac_cv_sizeof_long_long=$ac_lo;; +'') if test "$ac_cv_type_long_long" = yes; then + { { echo "$as_me:$LINENO: error: cannot compute sizeof (long long) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long double) +echo "$as_me: error: cannot compute sizeof (long long) See \`config.log' for more details." >&2;} { (exit 77); exit 77; }; } else - ac_cv_sizeof_long_double=0 + ac_cv_sizeof_long_long=0 fi ;; esac else @@ -10969,7 +10933,7 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long double ac__type_sizeof_; + typedef long long ac__type_sizeof_; static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } #include @@ -11021,43 +10985,42 @@ ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then - ac_cv_sizeof_long_double=`cat conftest.val` + ac_cv_sizeof_long_long=`cat conftest.val` else echo "$as_me: program exited with status $ac_status" >&5 echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) -if test "$ac_cv_type_long_double" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long double) +if test "$ac_cv_type_long_long" = yes; then + { { echo "$as_me:$LINENO: error: cannot compute sizeof (long long) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long double) +echo "$as_me: error: cannot compute sizeof (long long) See \`config.log' for more details." >&2;} { (exit 77); exit 77; }; } else - ac_cv_sizeof_long_double=0 + ac_cv_sizeof_long_long=0 fi fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_long_double" >&5 -echo "${ECHO_T}$ac_cv_sizeof_long_double" >&6; } +{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_long_long" >&5 +echo "${ECHO_T}$ac_cv_sizeof_long_long" >&6; } cat >>confdefs.h <<_ACEOF -#define SIZEOF_LONG_DOUBLE $ac_cv_sizeof_long_double +#define SIZEOF_LONG_LONG $ac_cv_sizeof_long_long _ACEOF fi - -{ echo "$as_me:$LINENO: checking for _Bool support" >&5 -echo $ECHO_N "checking for _Bool support... $ECHO_C" >&6; } -have_c99_bool=no +{ echo "$as_me:$LINENO: checking for long double support" >&5 +echo $ECHO_N "checking for long double support... $ECHO_C" >&6; } +have_long_double=no cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -11068,7 +11031,7 @@ int main () { -_Bool x; x = (_Bool)0; +long double x; x = (long double)0; ; return 0; } @@ -11093,10 +11056,10 @@ cat >>confdefs.h <<\_ACEOF -#define HAVE_C99_BOOL 1 +#define HAVE_LONG_DOUBLE 1 _ACEOF - have_c99_bool=yes + have_long_double=yes else echo "$as_me: failed program was:" >&5 @@ -11106,12 +11069,12 @@ fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_c99_bool" >&5 -echo "${ECHO_T}$have_c99_bool" >&6; } -if test "$have_c99_bool" = yes ; then -{ echo "$as_me:$LINENO: checking for _Bool" >&5 -echo $ECHO_N "checking for _Bool... $ECHO_C" >&6; } -if test "${ac_cv_type__Bool+set}" = set; then +{ echo "$as_me:$LINENO: result: $have_long_double" >&5 +echo "${ECHO_T}$have_long_double" >&6; } +if test "$have_long_double" = yes ; then +{ echo "$as_me:$LINENO: checking for long double" >&5 +echo $ECHO_N "checking for long double... $ECHO_C" >&6; } +if test "${ac_cv_type_long_double+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF @@ -11121,7 +11084,7 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default -typedef _Bool ac__type_new_; +typedef long double ac__type_new_; int main () { @@ -11150,26 +11113,26 @@ test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - ac_cv_type__Bool=yes + ac_cv_type_long_double=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type__Bool=no + ac_cv_type_long_double=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_type__Bool" >&5 -echo "${ECHO_T}$ac_cv_type__Bool" >&6; } +{ echo "$as_me:$LINENO: result: $ac_cv_type_long_double" >&5 +echo "${ECHO_T}$ac_cv_type_long_double" >&6; } # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of _Bool" >&5 -echo $ECHO_N "checking size of _Bool... $ECHO_C" >&6; } -if test "${ac_cv_sizeof__Bool+set}" = set; then +{ echo "$as_me:$LINENO: checking size of long double" >&5 +echo $ECHO_N "checking size of long double... $ECHO_C" >&6; } +if test "${ac_cv_sizeof_long_double+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else if test "$cross_compiling" = yes; then @@ -11181,7 +11144,7 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef _Bool ac__type_sizeof_; + typedef long double ac__type_sizeof_; int main () { @@ -11218,7 +11181,7 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef _Bool ac__type_sizeof_; + typedef long double ac__type_sizeof_; int main () { @@ -11272,7 +11235,7 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef _Bool ac__type_sizeof_; + typedef long double ac__type_sizeof_; int main () { @@ -11309,7 +11272,7 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef _Bool ac__type_sizeof_; + typedef long double ac__type_sizeof_; int main () { @@ -11373,7 +11336,7 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef _Bool ac__type_sizeof_; + typedef long double ac__type_sizeof_; int main () { @@ -11412,15 +11375,15 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done case $ac_lo in -?*) ac_cv_sizeof__Bool=$ac_lo;; -'') if test "$ac_cv_type__Bool" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) +?*) ac_cv_sizeof_long_double=$ac_lo;; +'') if test "$ac_cv_type_long_double" = yes; then + { { echo "$as_me:$LINENO: error: cannot compute sizeof (long double) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (_Bool) +echo "$as_me: error: cannot compute sizeof (long double) See \`config.log' for more details." >&2;} { (exit 77); exit 77; }; } else - ac_cv_sizeof__Bool=0 + ac_cv_sizeof_long_double=0 fi ;; esac else @@ -11431,7 +11394,7 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef _Bool ac__type_sizeof_; + typedef long double ac__type_sizeof_; static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } #include @@ -11483,29 +11446,491 @@ ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then - ac_cv_sizeof__Bool=`cat conftest.val` + ac_cv_sizeof_long_double=`cat conftest.val` else echo "$as_me: program exited with status $ac_status" >&5 echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) -if test "$ac_cv_type__Bool" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) +if test "$ac_cv_type_long_double" = yes; then + { { echo "$as_me:$LINENO: error: cannot compute sizeof (long double) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (_Bool) +echo "$as_me: error: cannot compute sizeof (long double) See \`config.log' for more details." >&2;} { (exit 77); exit 77; }; } else - ac_cv_sizeof__Bool=0 + ac_cv_sizeof_long_double=0 fi fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof__Bool" >&5 -echo "${ECHO_T}$ac_cv_sizeof__Bool" >&6; } +{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_long_double" >&5 +echo "${ECHO_T}$ac_cv_sizeof_long_double" >&6; } + + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_LONG_DOUBLE $ac_cv_sizeof_long_double +_ACEOF + + +fi + + +{ echo "$as_me:$LINENO: checking for _Bool support" >&5 +echo $ECHO_N "checking for _Bool support... $ECHO_C" >&6; } +have_c99_bool=no +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ +_Bool x; x = (_Bool)0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + + +cat >>confdefs.h <<\_ACEOF +#define HAVE_C99_BOOL 1 +_ACEOF + + have_c99_bool=yes + +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ echo "$as_me:$LINENO: result: $have_c99_bool" >&5 +echo "${ECHO_T}$have_c99_bool" >&6; } +if test "$have_c99_bool" = yes ; then +{ echo "$as_me:$LINENO: checking for _Bool" >&5 +echo $ECHO_N "checking for _Bool... $ECHO_C" >&6; } +if test "${ac_cv_type__Bool+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +typedef _Bool ac__type_new_; +int +main () +{ +if ((ac__type_new_ *) 0) + return 0; +if (sizeof (ac__type_new_)) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_type__Bool=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type__Bool=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $ac_cv_type__Bool" >&5 +echo "${ECHO_T}$ac_cv_type__Bool" >&6; } + +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ echo "$as_me:$LINENO: checking size of _Bool" >&5 +echo $ECHO_N "checking size of _Bool... $ECHO_C" >&6; } +if test "${ac_cv_sizeof__Bool+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test "$cross_compiling" = yes; then + # Depending upon the size, compute the lo and hi bounds. +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +int +main () +{ +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +test_array [0] = 0 + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_lo=0 ac_mid=0 + while :; do + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +int +main () +{ +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +test_array [0] = 0 + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_hi=$ac_mid; break +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_lo=`expr $ac_mid + 1` + if test $ac_lo -le $ac_mid; then + ac_lo= ac_hi= + break + fi + ac_mid=`expr 2 '*' $ac_mid + 1` +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + done +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +int +main () +{ +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +test_array [0] = 0 + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_hi=-1 ac_mid=-1 + while :; do + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +int +main () +{ +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +test_array [0] = 0 + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_lo=$ac_mid; break +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_hi=`expr '(' $ac_mid ')' - 1` + if test $ac_mid -le $ac_hi; then + ac_lo= ac_hi= + break + fi + ac_mid=`expr 2 '*' $ac_mid` +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + done +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_lo= ac_hi= +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +# Binary search between lo and hi bounds. +while test "x$ac_lo" != "x$ac_hi"; do + ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +int +main () +{ +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +test_array [0] = 0 + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_hi=$ac_mid +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_lo=`expr '(' $ac_mid ')' + 1` +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +done +case $ac_lo in +?*) ac_cv_sizeof__Bool=$ac_lo;; +'') if test "$ac_cv_type__Bool" = yes; then + { { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) +See \`config.log' for more details." >&5 +echo "$as_me: error: cannot compute sizeof (_Bool) +See \`config.log' for more details." >&2;} + { (exit 77); exit 77; }; } + else + ac_cv_sizeof__Bool=0 + fi ;; +esac +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } +static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +#include +#include +int +main () +{ + + FILE *f = fopen ("conftest.val", "w"); + if (! f) + return 1; + if (((long int) (sizeof (ac__type_sizeof_))) < 0) + { + long int i = longval (); + if (i != ((long int) (sizeof (ac__type_sizeof_)))) + return 1; + fprintf (f, "%ld\n", i); + } + else + { + unsigned long int i = ulongval (); + if (i != ((long int) (sizeof (ac__type_sizeof_)))) + return 1; + fprintf (f, "%lu\n", i); + } + return ferror (f) || fclose (f) != 0; + + ; + return 0; +} +_ACEOF +rm -f conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_sizeof__Bool=`cat conftest.val` +else + echo "$as_me: program exited with status $ac_status" >&5 +echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +( exit $ac_status ) +if test "$ac_cv_type__Bool" = yes; then + { { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) +See \`config.log' for more details." >&5 +echo "$as_me: error: cannot compute sizeof (_Bool) +See \`config.log' for more details." >&2;} + { (exit 77); exit 77; }; } + else + ac_cv_sizeof__Bool=0 + fi +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi +rm -f conftest.val +fi +{ echo "$as_me:$LINENO: result: $ac_cv_sizeof__Bool" >&5 +echo "${ECHO_T}$ac_cv_sizeof__Bool" >&6; } @@ -12437,7 +12862,11 @@ then LDSHARED='$(CC) -shared' else LDSHARED='$(CC) -G'; fi ;; - hp*|HP*) LDSHARED="ld -b";; + hp*|HP*) + if test "$GCC" = "yes" + then LDSHARED='$(CC) -shared' + else LDSHARED='ld -b'; + fi ;; OSF*) LDSHARED="ld -shared -expect_unresolved \"*\"";; Darwin/1.3*) LDSHARED='$(CC) $(LDFLAGS) -bundle' @@ -13129,185 +13558,53 @@ *) ac_try_echo=$ac_try;; esac eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_socket_socket=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_socket_socket=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_socket_socket" >&5 -echo "${ECHO_T}$ac_cv_lib_socket_socket" >&6; } -if test $ac_cv_lib_socket_socket = yes; then - LIBS="-lsocket $LIBS" -fi - # SVR4 sockets - -{ echo "$as_me:$LINENO: checking for --with-libs" >&5 -echo $ECHO_N "checking for --with-libs... $ECHO_C" >&6; } - -# Check whether --with-libs was given. -if test "${with_libs+set}" = set; then - withval=$with_libs; -{ echo "$as_me:$LINENO: result: $withval" >&5 -echo "${ECHO_T}$withval" >&6; } -LIBS="$withval $LIBS" - -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - - -# Check for use of the system libffi library -if test "${ac_cv_header_ffi_h+set}" = set; then - { echo "$as_me:$LINENO: checking for ffi.h" >&5 -echo $ECHO_N "checking for ffi.h... $ECHO_C" >&6; } -if test "${ac_cv_header_ffi_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_ffi_h" >&5 -echo "${ECHO_T}$ac_cv_header_ffi_h" >&6; } -else - # Is the header compilable? -{ echo "$as_me:$LINENO: checking ffi.h usability" >&5 -echo $ECHO_N "checking ffi.h usability... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } - -# Is the header present? -{ echo "$as_me:$LINENO: checking ffi.h presence" >&5 -echo $ECHO_N "checking ffi.h presence... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 + (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || test ! -s conftest.err - }; then - ac_header_preproc=yes + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + ac_cv_lib_socket_socket=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_header_preproc=no + ac_cv_lib_socket_socket=no fi -rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: ffi.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: ffi.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: ffi.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: ffi.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: ffi.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: ffi.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: ffi.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: ffi.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: ffi.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: ffi.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: ffi.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: ffi.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: ffi.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: ffi.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: ffi.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: ffi.h: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## ------------------------------------------------ ## -## Report this to http://www.python.org/python-bugs ## -## ------------------------------------------------ ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ echo "$as_me:$LINENO: checking for ffi.h" >&5 -echo $ECHO_N "checking for ffi.h... $ECHO_C" >&6; } -if test "${ac_cv_header_ffi_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_cv_header_ffi_h=$ac_header_preproc +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ echo "$as_me:$LINENO: result: $ac_cv_lib_socket_socket" >&5 +echo "${ECHO_T}$ac_cv_lib_socket_socket" >&6; } +if test $ac_cv_lib_socket_socket = yes; then + LIBS="-lsocket $LIBS" fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_ffi_h" >&5 -echo "${ECHO_T}$ac_cv_header_ffi_h" >&6; } + # SVR4 sockets + +{ echo "$as_me:$LINENO: checking for --with-libs" >&5 +echo $ECHO_N "checking for --with-libs... $ECHO_C" >&6; } + +# Check whether --with-libs was given. +if test "${with_libs+set}" = set; then + withval=$with_libs; +{ echo "$as_me:$LINENO: result: $withval" >&5 +echo "${ECHO_T}$withval" >&6; } +LIBS="$withval $LIBS" +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } fi +# Check for use of the system libffi library { echo "$as_me:$LINENO: checking for --with-system-ffi" >&5 echo $ECHO_N "checking for --with-system-ffi... $ECHO_C" >&6; } @@ -13317,15 +13614,6 @@ fi -if test -z "$with_system_ffi" && test "$ac_cv_header_ffi_h" = yes; then - case "$ac_sys_system/`uname -m`" in - Linux/alpha*) with_system_ffi="yes"; CONFIG_ARGS="$CONFIG_ARGS --with-system-ffi";; - Linux/arm*) with_system_ffi="yes"; CONFIG_ARGS="$CONFIG_ARGS --with-system-ffi";; - Linux/ppc*) with_system_ffi="yes"; CONFIG_ARGS="$CONFIG_ARGS --with-system-ffi";; - Linux/s390*) with_system_ffi="yes"; CONFIG_ARGS="$CONFIG_ARGS --with-system-ffi";; - *) with_system_ffi="no" - esac -fi { echo "$as_me:$LINENO: result: $with_system_ffi" >&5 echo "${ECHO_T}$with_system_ffi" >&6; } @@ -14603,6 +14891,12 @@ _ACEOF ;; + AIX/5) +cat >>confdefs.h <<\_ACEOF +#define HAVE_BROKEN_POSIX_SEMAPHORES 1 +_ACEOF + + ;; esac { echo "$as_me:$LINENO: checking if PTHREAD_SCOPE_SYSTEM is supported" >&5 @@ -15445,8 +15739,11 @@ -for ac_func in alarm bind_textdomain_codeset chown clock confstr \ - ctermid execv fchmod fchown fork fpathconf ftime ftruncate \ + + + +for ac_func in alarm setitimer getitimer bind_textdomain_codeset chown \ + clock confstr ctermid execv fchmod fchown fork fpathconf ftime ftruncate \ gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \ getpriority getpwent getspnam getspent getsid getwd \ kill killpg lchmod lchown lstat mkfifo mknod mktime \ @@ -15456,7 +15753,7 @@ setlocale setregid setreuid setsid setpgid setpgrp setuid setvbuf snprintf \ sigaction siginterrupt sigrelse strftime strlcpy \ sysconf tcgetpgrp tcsetpgrp tempnam timegm times tmpfile tmpnam tmpnam_r \ - truncate uname unsetenv utimes waitpid wait3 wait4 wcscoll _getpty + truncate uname unsetenv utimes waitpid wait3 wait4 wcscoll wcsxfrm _getpty do as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` { echo "$as_me:$LINENO: checking for $ac_func" >&5 @@ -15858,7 +16155,111 @@ fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ echo "$as_me:$LINENO: checking for epoll" >&5 +echo $ECHO_N "checking for epoll... $ECHO_C" >&6; } +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +int +main () +{ +void *x=epoll_create + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + +cat >>confdefs.h <<\_ACEOF +#define HAVE_EPOLL 1 +_ACEOF + + { echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6; } +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ echo "$as_me:$LINENO: checking for kqueue" >&5 +echo $ECHO_N "checking for kqueue... $ECHO_C" >&6; } +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +#include +#include + +int +main () +{ +int x=kqueue() + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + +cat >>confdefs.h <<\_ACEOF +#define HAVE_KQUEUE 1 +_ACEOF + + { echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6; } +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } + +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext # On some systems (eg. FreeBSD 5), we would find a definition of the # functions ctermid_r, setgroups in the library, but no prototype # (e.g. because we use _XOPEN_SOURCE). See whether we can take their @@ -17142,6 +17543,102 @@ done +# Stuff for expat. + +for ac_func in memmove +do +as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ echo "$as_me:$LINENO: checking for $ac_func" >&5 +echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +/* Define $ac_func to an innocuous variant, in case declares $ac_func. + For example, HP-UX 11i declares gettimeofday. */ +#define $ac_func innocuous_$ac_func + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char $ac_func (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef $ac_func + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char $ac_func (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_$ac_func || defined __stub___$ac_func +choke me +#endif + +int +main () +{ +return $ac_func (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + eval "$as_ac_var=yes" +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + eval "$as_ac_var=no" +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +fi +ac_res=`eval echo '${'$as_ac_var'}'` + { echo "$as_me:$LINENO: result: $ac_res" >&5 +echo "${ECHO_T}$ac_res" >&6; } +if test `eval echo '${'$as_ac_var'}'` = yes; then + cat >>confdefs.h <<_ACEOF +#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF + +fi +done + + # check for long file support functions @@ -17246,9 +17743,7 @@ - - -for ac_func in dup2 getcwd strdup strerror memmove +for ac_func in dup2 getcwd strdup do as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` { echo "$as_me:$LINENO: checking for $ac_func" >&5 Modified: python/branches/py3k-ctypes-pep3118/configure.in ============================================================================== --- python/branches/py3k-ctypes-pep3118/configure.in (original) +++ python/branches/py3k-ctypes-pep3118/configure.in Wed Apr 30 15:57:13 2008 @@ -61,7 +61,7 @@ CONFIG_ARGS="$ac_configure_args" AC_ARG_ENABLE(universalsdk, - AC_HELP_STRING(--enable-universalsdk@<:@SDKDIR@:>@, Build agains Mac OS X 10.4u SDK (ppc/i386)), + AC_HELP_STRING(--enable-universalsdk@<:@=SDKDIR@:>@, Build against Mac OS X 10.4u SDK (ppc/i386)), [ case $enableval in yes) @@ -333,6 +333,10 @@ CONFIGURE_MACOSX_DEPLOYMENT_TARGET= EXPORT_MACOSX_DEPLOYMENT_TARGET='#' +AC_MSG_CHECKING(machine type as reported by uname -m) +ac_sys_machine=`uname -m` +AC_MSG_RESULT($ac_sys_machine) + # checks for alternative programs # compiler flags are generated in two sets, BASECFLAGS and OPT. OPT is just @@ -792,13 +796,24 @@ then BASECFLAGS="$BASECFLAGS -fno-strict-aliasing" fi + + # if using gcc on alpha, use -mieee to get (near) full IEEE 754 + # support. Without this, treatment of subnormals doesn't follow + # the standard. + case $ac_sys_machine in + alpha*) + BASECFLAGS="$BASECFLAGS -mieee" + ;; + esac + case $ac_sys_system in SCO_SV*) BASECFLAGS="$BASECFLAGS -m486 -DSCO5" ;; # is there any other compiler on Darwin besides gcc? Darwin*) - BASECFLAGS="$BASECFLAGS -Wno-long-double -no-cpp-precomp -mno-fused-madd" + # -Wno-long-double, -no-cpp-precomp, and -mno-fused-madd + # used to be here, but non-Apple gcc doesn't accept them. if test "${enable_universalsdk}"; then BASECFLAGS="-arch ppc -arch i386 -isysroot ${UNIVERSALSDK} ${BASECFLAGS}" fi @@ -1073,11 +1088,11 @@ AC_HEADER_STDC AC_CHECK_HEADERS(asm/types.h conio.h curses.h direct.h dlfcn.h errno.h \ fcntl.h grp.h \ -io.h langinfo.h libintl.h ncurses.h poll.h process.h pthread.h \ +ieeefp.h io.h langinfo.h libintl.h ncurses.h poll.h process.h pthread.h \ shadow.h signal.h stdint.h stropts.h termios.h thread.h \ unistd.h utime.h \ -sys/audioio.h sys/bsdtty.h sys/file.h sys/loadavg.h sys/lock.h sys/mkdev.h \ -sys/modem.h \ +sys/audioio.h sys/bsdtty.h sys/epoll.h sys/event.h sys/file.h sys/loadavg.h \ +sys/lock.h sys/mkdev.h sys/modem.h \ sys/param.h sys/poll.h sys/select.h sys/socket.h sys/statvfs.h sys/stat.h \ sys/time.h \ sys/times.h sys/types.h sys/un.h sys/utsname.h sys/wait.h pty.h libutil.h \ @@ -1177,7 +1192,7 @@ AC_TYPE_SIGNAL AC_TYPE_SIZE_T AC_TYPE_UID_T -AC_CHECK_TYPE(ssize_t, +AC_CHECK_TYPE(ssize_t, AC_DEFINE(HAVE_SSIZE_T, 1, Define if your compiler provides ssize_t),,) # Sizes of various common basic types @@ -1190,6 +1205,7 @@ AC_CHECK_SIZEOF(double, 8) AC_CHECK_SIZEOF(fpos_t, 4) AC_CHECK_SIZEOF(size_t, 4) +AC_CHECK_SIZEOF(pid_t, 4) AC_MSG_CHECKING(for long long support) have_long_long=no @@ -1466,7 +1482,11 @@ then LDSHARED='$(CC) -shared' else LDSHARED='$(CC) -G'; fi ;; - hp*|HP*) LDSHARED="ld -b";; + hp*|HP*) + if test "$GCC" = "yes" + then LDSHARED='$(CC) -shared' + else LDSHARED='ld -b'; + fi ;; OSF*) LDSHARED="ld -shared -expect_unresolved \"*\"";; Darwin/1.3*) LDSHARED='$(CC) $(LDFLAGS) -bundle' @@ -1729,20 +1749,10 @@ [AC_MSG_RESULT(no)]) # Check for use of the system libffi library -AC_CHECK_HEADER(ffi.h) AC_MSG_CHECKING(for --with-system-ffi) AC_ARG_WITH(system_ffi, AC_HELP_STRING(--with-system-ffi, build _ctypes module using an installed ffi library)) -if test -z "$with_system_ffi" && test "$ac_cv_header_ffi_h" = yes; then - case "$ac_sys_system/`uname -m`" in - Linux/alpha*) with_system_ffi="yes"; CONFIG_ARGS="$CONFIG_ARGS --with-system-ffi";; - Linux/arm*) with_system_ffi="yes"; CONFIG_ARGS="$CONFIG_ARGS --with-system-ffi";; - Linux/ppc*) with_system_ffi="yes"; CONFIG_ARGS="$CONFIG_ARGS --with-system-ffi";; - Linux/s390*) with_system_ffi="yes"; CONFIG_ARGS="$CONFIG_ARGS --with-system-ffi";; - *) with_system_ffi="no" - esac -fi AC_MSG_RESULT($with_system_ffi) # Determine if signalmodule should be used. @@ -1965,6 +1975,9 @@ SunOS/5.8) AC_DEFINE(HAVE_BROKEN_POSIX_SEMAPHORES, 1, Define if the Posix semaphores do not work on your system) ;; + AIX/5) AC_DEFINE(HAVE_BROKEN_POSIX_SEMAPHORES, 1, + Define if the Posix semaphores do not work on your system) + ;; esac AC_MSG_CHECKING(if PTHREAD_SCOPE_SYSTEM is supported) @@ -2279,8 +2292,8 @@ AC_MSG_RESULT(MACHDEP_OBJS) # checks for library functions -AC_CHECK_FUNCS(alarm bind_textdomain_codeset chown clock confstr \ - ctermid execv fchmod fchown fork fpathconf ftime ftruncate \ +AC_CHECK_FUNCS(alarm setitimer getitimer bind_textdomain_codeset chown \ + clock confstr ctermid execv fchmod fchown fork fpathconf ftime ftruncate \ gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \ getpriority getpwent getspnam getspent getsid getwd \ kill killpg lchmod lchown lstat mkfifo mknod mktime \ @@ -2290,7 +2303,7 @@ setlocale setregid setreuid setsid setpgid setpgrp setuid setvbuf snprintf \ sigaction siginterrupt sigrelse strftime strlcpy \ sysconf tcgetpgrp tcsetpgrp tempnam timegm times tmpfile tmpnam tmpnam_r \ - truncate uname unsetenv utimes waitpid wait3 wait4 wcscoll _getpty) + truncate uname unsetenv utimes waitpid wait3 wait4 wcscoll wcsxfrm _getpty) # For some functions, having a definition is not sufficient, since # we want to take their address. @@ -2330,7 +2343,21 @@ AC_MSG_RESULT(yes), AC_MSG_RESULT(no) ) - +AC_MSG_CHECKING(for epoll) +AC_TRY_COMPILE([#include ], void *x=epoll_create, + AC_DEFINE(HAVE_EPOLL, 1, Define if you have the 'epoll' functions.) + AC_MSG_RESULT(yes), + AC_MSG_RESULT(no) +) +AC_MSG_CHECKING(for kqueue) +AC_TRY_COMPILE([ +#include +#include + ], int x=kqueue(), + AC_DEFINE(HAVE_KQUEUE, 1, Define if you have the 'kqueue' functions.) + AC_MSG_RESULT(yes), + AC_MSG_RESULT(no) +) # On some systems (eg. FreeBSD 5), we would find a definition of the # functions ctermid_r, setgroups in the library, but no prototype # (e.g. because we use _XOPEN_SOURCE). See whether we can take their @@ -2503,10 +2530,13 @@ ) ) +# Stuff for expat. +AC_CHECK_FUNCS(memmove) + # check for long file support functions AC_CHECK_FUNCS(fseek64 fseeko fstatvfs ftell64 ftello statvfs) -AC_REPLACE_FUNCS(dup2 getcwd strdup strerror memmove) +AC_REPLACE_FUNCS(dup2 getcwd strdup) AC_CHECK_FUNCS(getpgrp, AC_TRY_COMPILE([#include ], [getpgrp(0);], Modified: python/branches/py3k-ctypes-pep3118/pyconfig.h.in ============================================================================== --- python/branches/py3k-ctypes-pep3118/pyconfig.h.in (original) +++ python/branches/py3k-ctypes-pep3118/pyconfig.h.in Wed Apr 30 15:57:13 2008 @@ -144,6 +144,9 @@ /* Defined when any dynamic module loading is enabled. */ #undef HAVE_DYNAMIC_LOADING +/* Define if you have the 'epoll' functions. */ +#undef HAVE_EPOLL + /* Define to 1 if you have the header file. */ #undef HAVE_ERRNO_H @@ -237,6 +240,9 @@ /* Define this if you have the 6-arg version of gethostbyname_r(). */ #undef HAVE_GETHOSTBYNAME_R_6_ARG +/* Define to 1 if you have the `getitimer' function. */ +#undef HAVE_GETITIMER + /* Define to 1 if you have the `getloadavg' function. */ #undef HAVE_GETLOADAVG @@ -291,6 +297,9 @@ /* Define to 1 if you have the `hypot' function. */ #undef HAVE_HYPOT +/* Define to 1 if you have the header file. */ +#undef HAVE_IEEEFP_H + /* Define if you have the 'inet_aton' function. */ #undef HAVE_INET_ATON @@ -315,6 +324,9 @@ /* Define to 1 if you have the `killpg' function. */ #undef HAVE_KILLPG +/* Define if you have the 'kqueue' functions. */ +#undef HAVE_KQUEUE + /* Define to 1 if you have the header file. */ #undef HAVE_LANGINFO_H @@ -495,6 +507,9 @@ /* Define if you have the 'setgroups' function. */ #undef HAVE_SETGROUPS +/* Define to 1 if you have the `setitimer' function. */ +#undef HAVE_SETITIMER + /* Define to 1 if you have the `setlocale' function. */ #undef HAVE_SETLOCALE @@ -571,9 +586,6 @@ /* Define to 1 if you have the `strdup' function. */ #undef HAVE_STRDUP -/* Define to 1 if you have the `strerror' function. */ -#undef HAVE_STRERROR - /* Define to 1 if you have the `strftime' function. */ #undef HAVE_STRFTIME @@ -633,6 +645,12 @@ */ #undef HAVE_SYS_DIR_H +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_EPOLL_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_EVENT_H + /* Define to 1 if you have the header file. */ #undef HAVE_SYS_FILE_H @@ -776,6 +794,9 @@ /* Define to 1 if you have the `wcscoll' function. */ #undef HAVE_WCSCOLL +/* Define to 1 if you have the `wcsxfrm' function. */ +#undef HAVE_WCSXFRM + /* Define if tzset() actually switches the local timezone in a meaningful way. */ #undef HAVE_WORKING_TZSET @@ -872,6 +893,9 @@ /* The number of bytes in an off_t. */ #undef SIZEOF_OFF_T +/* The size of `pid_t', as computed by sizeof. */ +#undef SIZEOF_PID_T + /* The number of bytes in a pthread_t. */ #undef SIZEOF_PTHREAD_T Modified: python/branches/py3k-ctypes-pep3118/setup.py ============================================================================== --- python/branches/py3k-ctypes-pep3118/setup.py (original) +++ python/branches/py3k-ctypes-pep3118/setup.py Wed Apr 30 15:57:13 2008 @@ -4,6 +4,7 @@ __version__ = "$Revision$" import sys, os, imp, re, optparse +from glob import glob from distutils import log from distutils import sysconfig @@ -118,6 +119,8 @@ raise ValueError("No source directory; cannot proceed.") # Figure out the location of the source code for extension modules + # (This logic is copied in distutils.test.test_sysconfig, + # so building in a separate directory does not break test_distutils.) moddir = os.path.join(os.getcwd(), srcdir, 'Modules') moddir = os.path.normpath(moddir) srcdir, tail = os.path.split(moddir) @@ -142,12 +145,20 @@ self.distribution.scripts = [os.path.join(srcdir, filename) for filename in self.distribution.scripts] + # Python header files + headers = glob("Include/*.h") + ["pyconfig.h"] + for ext in self.extensions[:]: ext.sources = [ find_module_file(filename, moddirlist) for filename in ext.sources ] if ext.depends is not None: ext.depends = [find_module_file(filename, alldirlist) for filename in ext.depends] + else: + ext.depends = [] + # re-compile extensions if a header file has been changed + ext.depends.extend(headers) + ext.include_dirs.append( '.' ) # to get config.h for incdir in incdirlist: ext.include_dirs.append( os.path.join(srcdir, incdir) ) @@ -318,7 +329,7 @@ parser.add_option(arg_name, dest="dirs", action="append") options = parser.parse_args(env_val.split())[0] if options.dirs: - for directory in options.dirs: + for directory in reversed(options.dirs): add_dir_to_list(dir_list, directory) if os.path.normpath(sys.prefix) != '/usr': @@ -401,10 +412,10 @@ libraries=math_libs) ) exts.append( Extension('datetime', ['datetimemodule.c', 'timemodule.c'], libraries=math_libs) ) - # random number generator implemented in C - exts.append( Extension("_random", ["_randommodule.c"]) ) # fast iterator tools implemented in C exts.append( Extension("itertools", ["itertoolsmodule.c"]) ) + # random number generator implemented in C + exts.append( Extension("_random", ["_randommodule.c"]) ) # high-performance collections exts.append( Extension("_collections", ["_collectionsmodule.c"]) ) # bisect @@ -463,9 +474,6 @@ # select(2); not on ancient System V exts.append( Extension('select', ['selectmodule.c']) ) - # Helper module for various ascii-encoders - exts.append( Extension('binascii', ['binascii.c']) ) - # Fred Drake's interface to the Python parser exts.append( Extension('parser', ['parsermodule.c']) ) @@ -643,7 +651,10 @@ # a release. Most open source OSes come with one or more # versions of BerkeleyDB already installed. - max_db_ver = (4, 6) + max_db_ver = (4, 5) # XXX(gregory.p.smith): 4.6 "works" but seems to + # have issues on many platforms. I've temporarily + # disabled 4.6 to see what the odd platform + # buildbots say. min_db_ver = (3, 3) db_setup_debug = False # verbose debug prints from this script? @@ -686,10 +697,10 @@ for dn in inc_dirs: std_variants.append(os.path.join(dn, 'db3')) std_variants.append(os.path.join(dn, 'db4')) - for x in (0,1,2,3,4,5,6): + for x in range(max_db_ver[1]+1): std_variants.append(os.path.join(dn, "db4%d"%x)) std_variants.append(os.path.join(dn, "db4.%d"%x)) - for x in (2,3): + for x in (3,): std_variants.append(os.path.join(dn, "db3%d"%x)) std_variants.append(os.path.join(dn, "db3.%d"%x)) @@ -993,6 +1004,7 @@ # You can upgrade zlib to version 1.1.4 yourself by going to # http://www.gzip.org/zlib/ zlib_inc = find_file('zlib.h', [], inc_dirs) + have_zlib = False if zlib_inc is not None: zlib_h = zlib_inc[0] + '/zlib.h' version = '"0.0.0"' @@ -1014,6 +1026,7 @@ exts.append( Extension('zlib', ['zlibmodule.c'], libraries = ['z'], extra_link_args = zlib_extra_link_args)) + have_zlib = True else: missing.append('zlib') else: @@ -1021,6 +1034,21 @@ else: missing.append('zlib') + # Helper module for various ascii-encoders. Uses zlib for an optimized + # crc32 if we have it. Otherwise binascii uses its own. + if have_zlib: + extra_compile_args = ['-DUSE_ZLIB_CRC32'] + libraries = ['z'] + extra_link_args = zlib_extra_link_args + else: + extra_compile_args = [] + libraries = [] + extra_link_args = [] + exts.append( Extension('binascii', ['binascii.c'], + extra_compile_args = extra_compile_args, + libraries = libraries, + extra_link_args = extra_link_args) ) + # Gustavo Niemeyer's bz2 module. if (self.compiler.find_library_file(lib_dirs, 'bz2')): if sys.platform == "darwin": @@ -1079,17 +1107,6 @@ exts.append(Extension('_codecs_%s' % loc, ['cjkcodecs/_codecs_%s.c' % loc])) - # Dynamic loading module - if sys.maxsize == 0x7fffffff: - # This requires sizeof(int) == sizeof(long) == sizeof(char*) - dl_inc = find_file('dlfcn.h', [], inc_dirs) - if (dl_inc is not None) and (platform not in ['atheos']): - exts.append( Extension('dl', ['dlmodule.c']) ) - else: - missing.append('dl') - else: - missing.append('dl') - # Thomas Heller's _ctypes module self.detect_ctypes(inc_dirs, lib_dirs) @@ -1365,8 +1382,37 @@ # *** Uncomment these for TOGL extension only: # -lGL -lGLU -lXext -lXmu \ + def configure_ctypes_darwin(self, ext): + # Darwin (OS X) uses preconfigured files, in + # the Modules/_ctypes/libffi_osx directory. + (srcdir,) = sysconfig.get_config_vars('srcdir') + ffi_srcdir = os.path.abspath(os.path.join(srcdir, 'Modules', + '_ctypes', 'libffi_osx')) + sources = [os.path.join(ffi_srcdir, p) + for p in ['ffi.c', + 'x86/x86-darwin.S', + 'x86/x86-ffi_darwin.c', + 'x86/x86-ffi64.c', + 'powerpc/ppc-darwin.S', + 'powerpc/ppc-darwin_closure.S', + 'powerpc/ppc-ffi_darwin.c', + 'powerpc/ppc64-darwin_closure.S', + ]] + + # Add .S (preprocessed assembly) to C compiler source extensions. + self.compiler.src_extensions.append('.S') + + include_dirs = [os.path.join(ffi_srcdir, 'include'), + os.path.join(ffi_srcdir, 'powerpc')] + ext.include_dirs.extend(include_dirs) + ext.sources.extend(sources) + return True + def configure_ctypes(self, ext): if not self.use_system_libffi: + if sys.platform == 'darwin': + return self.configure_ctypes_darwin(ext) + (srcdir,) = sysconfig.get_config_vars('srcdir') ffi_builddir = os.path.join(self.build_temp, 'libffi') ffi_srcdir = os.path.abspath(os.path.join(srcdir, 'Modules', @@ -1430,6 +1476,7 @@ if sys.platform == 'darwin': sources.append('_ctypes/darwin/dlfcn_simple.c') + extra_compile_args.append('-DMACOSX') include_dirs.append('_ctypes/darwin') # XXX Is this still needed? ## extra_link_args.extend(['-read_only_relocs', 'warning']) @@ -1459,6 +1506,11 @@ if not '--with-system-ffi' in sysconfig.get_config_var("CONFIG_ARGS"): return + if sys.platform == 'darwin': + # OS X 10.5 comes with libffi.dylib; the include files are + # in /usr/include/ffi + inc_dirs.append('/usr/include/ffi') + ffi_inc = find_file('ffi.h', [], inc_dirs) if ffi_inc is not None: ffi_h = ffi_inc[0] + '/ffi.h' @@ -1582,6 +1634,7 @@ # Scripts to install scripts = ['Tools/scripts/pydoc', 'Tools/scripts/idle', + 'Tools/scripts/2to3', 'Lib/smtpd.py'] ) From python-3000-checkins at python.org Wed Apr 30 16:21:40 2008 From: python-3000-checkins at python.org (mark.dickinson) Date: Wed, 30 Apr 2008 16:21:40 +0200 (CEST) Subject: [Python-3000-checkins] r62592 - in python/branches/py3k: configure configure.in Message-ID: <20080430142140.2EDD21E401A@bag.python.org> Author: mark.dickinson Date: Wed Apr 30 16:21:39 2008 New Revision: 62592 Log: Add some temporary autoconf checks to try to figure out why test_math is failing on Debian/alpha. (log(9.88e-324) gives an unexpected ValueError on that platform). These checks will be removed again once the source of the problem is identified. I hope this is a reasonable way to approach the Debian/alpha buildbot failures; if there's a better way of debugging buildbot test failures then please let me know. Modified: python/branches/py3k/configure python/branches/py3k/configure.in Modified: python/branches/py3k/configure ============================================================================== --- python/branches/py3k/configure (original) +++ python/branches/py3k/configure Wed Apr 30 16:21:39 2008 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 62451 . +# From configure.in Revision: 62515 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.61 for python 3.0. # @@ -21082,6 +21082,435 @@ LIBS_SAVE=$LIBS LIBS="$LIBS $LIBM" +# temporary checks to try to track down what's going wrong +# with test_math on Debian/alpha. These checks will be +# removed later. + +case $ac_sys_machine in +alpha*) + + { echo "$as_me:$LINENO: checking whether 9.88e-324 compares unequal to 0.0" >&5 +echo $ECHO_N "checking whether 9.88e-324 compares unequal to 0.0... $ECHO_C" >&6; } + if test "$cross_compiling" = yes; then + ac_cv_subnormal_nonzero=no +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + + #include + int main() { + double x = 9.88e-324; + if (x != 0.0) + exit(0); + else + exit(1); + } + +_ACEOF +rm -f conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_subnormal_nonzero=yes +else + echo "$as_me: program exited with status $ac_status" >&5 +echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +( exit $ac_status ) +ac_cv_subnormal_nonzero=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi + + + { echo "$as_me:$LINENO: result: $ac_cv_subnormal_nonzero" >&5 +echo "${ECHO_T}$ac_cv_subnormal_nonzero" >&6; } + + { echo "$as_me:$LINENO: checking whether log(9.88e-324) succeeds" >&5 +echo $ECHO_N "checking whether log(9.88e-324) succeeds... $ECHO_C" >&6; } + if test "$cross_compiling" = yes; then + ac_cv_log_subnormal_succeeds=no +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + + #include + #include + int main() { + double x = 9.88e-324; + x = log(x); + exit(0); + } + +_ACEOF +rm -f conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_log_subnormal_succeeds=yes +else + echo "$as_me: program exited with status $ac_status" >&5 +echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +( exit $ac_status ) +ac_cv_log_subnormal_succeeds=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi + + + { echo "$as_me:$LINENO: result: $ac_cv_log_subnormal_succeeds" >&5 +echo "${ECHO_T}$ac_cv_log_subnormal_succeeds" >&6; } + + { echo "$as_me:$LINENO: checking whether log(9.88e-324) returns correct result" >&5 +echo $ECHO_N "checking whether log(9.88e-324) returns correct result... $ECHO_C" >&6; } + if test "$cross_compiling" = yes; then + ac_cv_log_subnormal_returns_correct_result=no +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + + #include + #include + int main() { + double x = 9.88e-324; + x = log(x); + if (-744. < x && x < -743.) + exit(0); + else + exit(1); + } + +_ACEOF +rm -f conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_log_subnormal_returns_correct_result=yes +else + echo "$as_me: program exited with status $ac_status" >&5 +echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +( exit $ac_status ) +ac_cv_log_subnormal_returns_correct_result=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi + + + { echo "$as_me:$LINENO: result: $ac_cv_log_subnormal_returns_correct_result" >&5 +echo "${ECHO_T}$ac_cv_log_subnormal_returns_correct_result" >&6; } + + { echo "$as_me:$LINENO: checking whether log(9.88e-324) sets errno" >&5 +echo $ECHO_N "checking whether log(9.88e-324) sets errno... $ECHO_C" >&6; } + if test "$cross_compiling" = yes; then + ac_cv_log_subnormal_sets_errno=no +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + + #include + #include + #include + int main() { + double x = 9.88e-324; + errno = 0; + x = log(x); + if (errno != 0) + exit(0); + else + exit(1); + } + +_ACEOF +rm -f conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_log_subnormal_sets_errno=yes +else + echo "$as_me: program exited with status $ac_status" >&5 +echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +( exit $ac_status ) +ac_cv_log_subnormal_sets_errno=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi + + + { echo "$as_me:$LINENO: result: $ac_cv_log_subnormal_sets_errno" >&5 +echo "${ECHO_T}$ac_cv_log_subnormal_sets_errno" >&6; } + + { echo "$as_me:$LINENO: checking whether log(9.88e-324) sets errno = EDOM" >&5 +echo $ECHO_N "checking whether log(9.88e-324) sets errno = EDOM... $ECHO_C" >&6; } + if test "$cross_compiling" = yes; then + ac_cv_log_subnormal_sets_errno_to_EDOM=no +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + + #include + #include + #include + int main() { + double x = 9.88e-324; + errno = 0; + x = log(x); + if (errno == EDOM) + exit(0); + else + exit(1); + } + +_ACEOF +rm -f conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_log_subnormal_sets_errno_to_EDOM=yes +else + echo "$as_me: program exited with status $ac_status" >&5 +echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +( exit $ac_status ) +ac_cv_log_subnormal_sets_errno_to_EDOM=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi + + + { echo "$as_me:$LINENO: result: $ac_cv_log_subnormal_sets_errno_to_EDOM" >&5 +echo "${ECHO_T}$ac_cv_log_subnormal_sets_errno_to_EDOM" >&6; } + + { echo "$as_me:$LINENO: checking whether log(9.88e-324) is infinite" >&5 +echo $ECHO_N "checking whether log(9.88e-324) is infinite... $ECHO_C" >&6; } + if test "$cross_compiling" = yes; then + ac_cv_log_subnormal_is_infinite=no +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + + #include + #include + int main() { + double x = 9.88e-324; + x = log(x); + if ((x > 1. || x < -1.) && x/2. == x) + exit(0); + else + exit(1); + } + +_ACEOF +rm -f conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_log_subnormal_is_infinite=yes +else + echo "$as_me: program exited with status $ac_status" >&5 +echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +( exit $ac_status ) +ac_cv_log_subnormal_is_infinite=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi + + + { echo "$as_me:$LINENO: result: $ac_cv_log_subnormal_is_infinite" >&5 +echo "${ECHO_T}$ac_cv_log_subnormal_is_infinite" >&6; } + + { echo "$as_me:$LINENO: checking whether log(9.88e-324) is a nan" >&5 +echo $ECHO_N "checking whether log(9.88e-324) is a nan... $ECHO_C" >&6; } + if test "$cross_compiling" = yes; then + ac_cv_log_subnormal_is_nan=no +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + + #include + #include + int main() { + double x = 9.88e-324; + x = log(x); + if (x != x) + exit(0); + else + exit(1); + } + +_ACEOF +rm -f conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_log_subnormal_is_nan=yes +else + echo "$as_me: program exited with status $ac_status" >&5 +echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +( exit $ac_status ) +ac_cv_log_subnormal_is_nan=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi + + + { echo "$as_me:$LINENO: result: $ac_cv_log_subnormal_is_nan" >&5 +echo "${ECHO_T}$ac_cv_log_subnormal_is_nan" >&6; } +;; +esac + + for ac_func in hypot do as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` Modified: python/branches/py3k/configure.in ============================================================================== --- python/branches/py3k/configure.in (original) +++ python/branches/py3k/configure.in Wed Apr 30 16:21:39 2008 @@ -2980,6 +2980,141 @@ # ************************************ LIBS_SAVE=$LIBS LIBS="$LIBS $LIBM" + +# temporary checks to try to track down what's going wrong +# with test_math on Debian/alpha. These checks will be +# removed later. + +case $ac_sys_machine in +alpha*) + + AC_MSG_CHECKING(whether 9.88e-324 compares unequal to 0.0) + AC_TRY_RUN([ + #include + int main() { + double x = 9.88e-324; + if (x != 0.0) + exit(0); + else + exit(1); + } + ], + ac_cv_subnormal_nonzero=yes, + ac_cv_subnormal_nonzero=no, + ac_cv_subnormal_nonzero=no) + AC_MSG_RESULT($ac_cv_subnormal_nonzero) + + AC_MSG_CHECKING(whether log(9.88e-324) succeeds) + AC_TRY_RUN([ + #include + #include + int main() { + double x = 9.88e-324; + x = log(x); + exit(0); + } + ], + ac_cv_log_subnormal_succeeds=yes, + ac_cv_log_subnormal_succeeds=no, + ac_cv_log_subnormal_succeeds=no) + AC_MSG_RESULT($ac_cv_log_subnormal_succeeds) + + AC_MSG_CHECKING(whether log(9.88e-324) returns correct result) + AC_TRY_RUN([ + #include + #include + int main() { + double x = 9.88e-324; + x = log(x); + if (-744. < x && x < -743.) + exit(0); + else + exit(1); + } + ], + ac_cv_log_subnormal_returns_correct_result=yes, + ac_cv_log_subnormal_returns_correct_result=no, + ac_cv_log_subnormal_returns_correct_result=no) + AC_MSG_RESULT($ac_cv_log_subnormal_returns_correct_result) + + AC_MSG_CHECKING(whether log(9.88e-324) sets errno) + AC_TRY_RUN([ + #include + #include + #include + int main() { + double x = 9.88e-324; + errno = 0; + x = log(x); + if (errno != 0) + exit(0); + else + exit(1); + } + ], + ac_cv_log_subnormal_sets_errno=yes, + ac_cv_log_subnormal_sets_errno=no, + ac_cv_log_subnormal_sets_errno=no) + AC_MSG_RESULT($ac_cv_log_subnormal_sets_errno) + + AC_MSG_CHECKING(whether log(9.88e-324) sets errno = EDOM) + AC_TRY_RUN([ + #include + #include + #include + int main() { + double x = 9.88e-324; + errno = 0; + x = log(x); + if (errno == EDOM) + exit(0); + else + exit(1); + } + ], + ac_cv_log_subnormal_sets_errno_to_EDOM=yes, + ac_cv_log_subnormal_sets_errno_to_EDOM=no, + ac_cv_log_subnormal_sets_errno_to_EDOM=no) + AC_MSG_RESULT($ac_cv_log_subnormal_sets_errno_to_EDOM) + + AC_MSG_CHECKING(whether log(9.88e-324) is infinite) + AC_TRY_RUN([ + #include + #include + int main() { + double x = 9.88e-324; + x = log(x); + if ((x > 1. || x < -1.) && x/2. == x) + exit(0); + else + exit(1); + } + ], + ac_cv_log_subnormal_is_infinite=yes, + ac_cv_log_subnormal_is_infinite=no, + ac_cv_log_subnormal_is_infinite=no) + AC_MSG_RESULT($ac_cv_log_subnormal_is_infinite) + + AC_MSG_CHECKING(whether log(9.88e-324) is a nan) + AC_TRY_RUN([ + #include + #include + int main() { + double x = 9.88e-324; + x = log(x); + if (x != x) + exit(0); + else + exit(1); + } + ], + ac_cv_log_subnormal_is_nan=yes, + ac_cv_log_subnormal_is_nan=no, + ac_cv_log_subnormal_is_nan=no) + AC_MSG_RESULT($ac_cv_log_subnormal_is_nan) +;; +esac + AC_REPLACE_FUNCS(hypot) AC_CHECK_FUNCS(acosh asinh atanh copysign expm1 finite isinf isnan log1p) From python-3000-checkins at python.org Wed Apr 30 19:11:47 2008 From: python-3000-checkins at python.org (thomas.heller) Date: Wed, 30 Apr 2008 19:11:47 +0200 (CEST) Subject: [Python-3000-checkins] r62597 - in python/branches/py3k: Lib/ctypes/test/test_pep3118.py Misc/NEWS Modules/_ctypes/_ctypes.c Modules/_ctypes/callbacks.c Modules/_ctypes/callproc.c Modules/_ctypes/ctypes.h Modules/_ctypes/stgdict.c Message-ID: <20080430171147.5B19D1E4020@bag.python.org> Author: thomas.heller Date: Wed Apr 30 19:11:46 2008 New Revision: 62597 Log: Merged revisions 60056-60071,60073-60127,60129-60261,60263-60284,60286-62589,62591-62594 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k-ctypes-pep3118 ........ r60059 | thomas.heller | 2008-01-18 22:17:05 +0100 (Fri, 18 Jan 2008) | 1 line Implement pep3118 format strings for SimpleCData types. ........ r60108 | thomas.heller | 2008-01-19 22:56:12 +0100 (Sat, 19 Jan 2008) | 3 lines Always use explicit endian specifiers for simple types, and a bug fix too. Add unittest. ........ r60112 | thomas.heller | 2008-01-19 23:25:14 +0100 (Sat, 19 Jan 2008) | 2 lines Fully implement tp_asbuffer for pointer types. ........ r60261 | thomas.heller | 2008-01-24 22:01:29 +0100 (Thu, 24 Jan 2008) | 4 lines Added shape and ndim field to StgDictObject. Implemented pep3118 format string, ndim, and shape for array types. Added a buffer_info(type_or_object) for testing. ........ r60278 | thomas.heller | 2008-01-25 11:53:33 +0100 (Fri, 25 Jan 2008) | 2 lines Implement pep3118 format strings for ctypes.Structure and ctypes.Union. ........ r60288 | thomas.heller | 2008-01-25 17:58:30 +0100 (Fri, 25 Jan 2008) | 2 lines All ctypes types now use the same CData_GetBuffer function. ........ r60289 | thomas.heller | 2008-01-25 19:59:45 +0100 (Fri, 25 Jan 2008) | 2 lines Fix format string for structures, and itemsize for arrays. ........ r60290 | thomas.heller | 2008-01-25 20:09:03 +0100 (Fri, 25 Jan 2008) | 2 lines Implement to format string for function pointers. ........ r60292 | thomas.heller | 2008-01-25 20:32:20 +0100 (Fri, 25 Jan 2008) | 3 lines Only structures with native packing implement the pep. Unions, or packed structures do not. ........ r60293 | thomas.heller | 2008-01-25 20:34:31 +0100 (Fri, 25 Jan 2008) | 2 lines Update the test. ........ r60295 | thomas.heller | 2008-01-25 20:44:41 +0100 (Fri, 25 Jan 2008) | 2 lines Fixed a few XXX markers. ........ r60298 | thomas.heller | 2008-01-25 21:11:08 +0100 (Fri, 25 Jan 2008) | 1 line Fix test for 64-bt platform. ........ r60299 | thomas.heller | 2008-01-25 21:34:11 +0100 (Fri, 25 Jan 2008) | 2 lines Add test for the readonly bit. ........ r60384 | thomas.heller | 2008-01-28 08:45:04 +0100 (Mon, 28 Jan 2008) | 4 lines Restructure the test so that it contains little endian format strings. On big endian machines, the format strings are converted by replacing '<' with '>'. ........ r60385 | thomas.heller | 2008-01-28 08:58:46 +0100 (Mon, 28 Jan 2008) | 1 line Bugfix and test for explicit big and little endian types. ........ r60428 | thomas.heller | 2008-01-29 22:00:37 +0100 (Tue, 29 Jan 2008) | 1 line Add comments to clarify the tests. ........ r62589 | thomas.heller | 2008-04-30 13:49:46 +0200 (Wed, 30 Apr 2008) | 1 line Fix compiler warnings. ........ Added: python/branches/py3k/Lib/ctypes/test/test_pep3118.py - copied, changed from r60112, /python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_pep3118.py Modified: python/branches/py3k/ (props changed) python/branches/py3k/Misc/NEWS python/branches/py3k/Modules/_ctypes/_ctypes.c python/branches/py3k/Modules/_ctypes/callbacks.c python/branches/py3k/Modules/_ctypes/callproc.c python/branches/py3k/Modules/_ctypes/ctypes.h python/branches/py3k/Modules/_ctypes/stgdict.c Copied: python/branches/py3k/Lib/ctypes/test/test_pep3118.py (from r60112, /python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_pep3118.py) ============================================================================== --- /python/branches/py3k-ctypes-pep3118/Lib/ctypes/test/test_pep3118.py (original) +++ python/branches/py3k/Lib/ctypes/test/test_pep3118.py Wed Apr 30 19:11:46 2008 @@ -1,69 +1,170 @@ import unittest from ctypes import * -import struct, sys +import re, struct, sys if sys.byteorder == "little": - ENDIAN = "<" + THIS_ENDIAN = "<" + OTHER_ENDIAN = ">" else: - ENDIAN = ">" + THIS_ENDIAN = ">" + OTHER_ENDIAN = "<" -simple_types = [ - ("b", c_byte), - ("B", c_ubyte), - ("h", c_short), - ("H", c_ushort), -# c_int and c_uint may be aliases to c_long -## ("i", c_int), -## ("I", c_uint), - ("l", c_long), - ("L", c_ulong), - ("q", c_longlong), - ("Q", c_ulonglong), - ("f", c_float), - ("d", c_double), -# c_longdouble may be an alias to c_double -## ("g", c_longdouble), - ("t", c_bool), -# struct doesn't support this (yet) -## ("O", py_object), -] +def normalize(format): + # Remove current endian specifier and white space from a format + # string + format = format.replace(OTHER_ENDIAN, THIS_ENDIAN) + return re.sub(r"\s", "", format) class Test(unittest.TestCase): - def test_simpletypes(self): - # simple types in native byte order - for fmt, typ in simple_types: - v = memoryview(typ()) - - # check the PEP3118 format string - self.failUnlessEqual(v.format, ENDIAN + fmt) - - # shape and strides are None for integral types - self.failUnlessEqual((v.shape, v.strides), - (None, None)) - - # size and itemsize must be what struct.calcsize reports - struct_size = struct.calcsize(fmt) - self.failUnlessEqual((v.size, v.itemsize), - (struct_size, struct_size)) - - def test_pointertypes(self): - for fmt, typ in simple_types: - v = memoryview(POINTER(typ)()) - - # check the PEP3118 format string - self.failUnlessEqual(v.format, "&" + ENDIAN + fmt) - - # shape and strides are None for integral types - self.failUnlessEqual((v.shape, v.strides), - (None, None)) - - # size and itemsize must be what struct.calcsize reports - # for pointers - struct_size = struct.calcsize("P") - self.failUnlessEqual((v.size, v.itemsize), - (struct_size, struct_size)) - + def test_native_types(self): + for tp, fmt, shape, itemtp in native_types: + ob = tp() + v = memoryview(ob) + try: + self.failUnlessEqual(normalize(v.format), normalize(fmt)) + self.failUnlessEqual(v.size, sizeof(ob)) + self.failUnlessEqual(v.itemsize, sizeof(itemtp)) + self.failUnlessEqual(v.shape, shape) + # ctypes object always have a non-strided memory block + self.failUnlessEqual(v.strides, None) + # they are always read/write + self.failIf(v.readonly) + + if v.shape: + n = 1 + for dim in v.shape: + n = n * dim + self.failUnlessEqual(v.itemsize * n, v.size) + except: + # so that we can see the failing type + print(tp) + raise + + def test_endian_types(self): + for tp, fmt, shape, itemtp in endian_types: + ob = tp() + v = memoryview(ob) + try: + self.failUnlessEqual(v.format, fmt) + self.failUnlessEqual(v.size, sizeof(ob)) + self.failUnlessEqual(v.itemsize, sizeof(itemtp)) + self.failUnlessEqual(v.shape, shape) + # ctypes object always have a non-strided memory block + self.failUnlessEqual(v.strides, None) + # they are always read/write + self.failIf(v.readonly) + + if v.shape: + n = 1 + for dim in v.shape: + n = n * dim + self.failUnlessEqual(v.itemsize * n, v.size) + except: + # so that we can see the failing type + print(tp) + raise + +# define some structure classes + +class Point(Structure): + _fields_ = [("x", c_long), ("y", c_long)] + +class PackedPoint(Structure): + _pack_ = 2 + _fields_ = [("x", c_long), ("y", c_long)] + +class Point2(Structure): + pass +Point2._fields_ = [("x", c_long), ("y", c_long)] + +class EmptyStruct(Structure): + _fields_ = [] + +class aUnion(Union): + _fields_ = [("a", c_int)] + +################################################################ +# +# This table contains format strings as they look on little endian +# machines. The test replaces '<' with '>' on big endian machines. +# +native_types = [ + # type format shape calc itemsize + + ## simple types + + (c_char, "l:x:>l:y:}", None, BEPoint), + (LEPoint, "T{l:x:>l:y:}", None, POINTER(BEPoint)), + (POINTER(LEPoint), "&T{format = alloc_format_string("&", itemdict->format); + if (stgdict->format == NULL) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + } + /* create the new instance (which is a class, since we are a metatype!) */ result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); @@ -1101,6 +1141,7 @@ long length; int overflow; Py_ssize_t itemsize, itemalign; + char buf[32]; typedict = PyTuple_GetItem(args, 2); if (!typedict) @@ -1140,6 +1181,28 @@ return NULL; } + assert(itemdict->format); + if (itemdict->format[0] == '(') { + sprintf(buf, "(%ld,", length); + stgdict->format = alloc_format_string(buf, itemdict->format+1); + } else { + sprintf(buf, "(%ld)", length); + stgdict->format = alloc_format_string(buf, itemdict->format); + } + if (stgdict->format == NULL) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + stgdict->ndim = itemdict->ndim + 1; + stgdict->shape = PyMem_Malloc(sizeof(Py_ssize_t *) * stgdict->ndim); + if (stgdict->shape == NULL) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + stgdict->shape[0] = length; + memmove(&stgdict->shape[1], itemdict->shape, + sizeof(Py_ssize_t) * (stgdict->ndim - 1)); + itemsize = itemdict->size; if (length * itemsize < 0) { PyErr_SetString(PyExc_OverflowError, @@ -1691,6 +1754,16 @@ stgdict->size = fmt->pffi_type->size; stgdict->setfunc = fmt->setfunc; stgdict->getfunc = fmt->getfunc; +#ifdef WORDS_BIGENDIAN + stgdict->format = alloc_format_string(">", proto_str); +#else + stgdict->format = alloc_format_string("<", proto_str); +#endif + if (stgdict->format == NULL) { + Py_DECREF(result); + Py_DECREF((PyObject *)stgdict); + return NULL; + } stgdict->paramfunc = SimpleType_paramfunc; /* @@ -1760,22 +1833,32 @@ if (type == &SimpleType_Type && fmt->setfunc_swapped && fmt->getfunc_swapped) { PyObject *swapped = CreateSwappedType(type, args, kwds, proto, fmt); + StgDictObject *sw_dict; if (swapped == NULL) { Py_DECREF(result); return NULL; } + sw_dict = PyType_stgdict(swapped); #ifdef WORDS_BIGENDIAN PyObject_SetAttrString((PyObject *)result, "__ctype_le__", swapped); PyObject_SetAttrString((PyObject *)result, "__ctype_be__", (PyObject *)result); PyObject_SetAttrString(swapped, "__ctype_be__", (PyObject *)result); PyObject_SetAttrString(swapped, "__ctype_le__", swapped); + /* We are creating the type for the OTHER endian */ + sw_dict->format = alloc_format_string("<", stgdict->format+1); #else PyObject_SetAttrString((PyObject *)result, "__ctype_be__", swapped); PyObject_SetAttrString((PyObject *)result, "__ctype_le__", (PyObject *)result); PyObject_SetAttrString(swapped, "__ctype_le__", (PyObject *)result); PyObject_SetAttrString(swapped, "__ctype_be__", swapped); + /* We are creating the type for the OTHER endian */ + sw_dict->format = alloc_format_string(">", stgdict->format+1); #endif Py_DECREF(swapped); + if (PyErr_Occurred()) { + Py_DECREF(result); + return NULL; + } }; return (PyObject *)result; @@ -2025,6 +2108,13 @@ return NULL; stgdict->paramfunc = CFuncPtrType_paramfunc; + /* We do NOT expose the function signature in the format string. It + is impossible, generally, because the only requirement for the + argtypes items is that they have a .from_param method - we do not + know the types of the arguments (although, in practice, most + argtypes would be a ctypes type). + */ + stgdict->format = alloc_format_string(NULL, "X{}"); stgdict->flags |= TYPEFLAG_ISPOINTER; /* create the new instance (which is a class, @@ -2240,7 +2330,31 @@ static int CData_GetBuffer(PyObject *_self, Py_buffer *view, int flags) { CDataObject *self = (CDataObject *)_self; - return PyBuffer_FillInfo(view, self->b_ptr, self->b_size, 0, flags); + StgDictObject *dict = PyObject_stgdict(_self); + Py_ssize_t i; + + if (view == NULL) return 0; + if (((flags & PyBUF_LOCK) == PyBUF_LOCK)) { + PyErr_SetString(PyExc_BufferError, + "Cannot lock this object."); + return -1; + } + + view->buf = self->b_ptr; + view->len = self->b_size; + view->readonly = 0; + /* use default format character if not set */ + view->format = dict->format ? dict->format : "B"; + view->ndim = dict->ndim; + view->shape = dict->shape; + view->itemsize = self->b_size; + for (i = 0; i < view->ndim; ++i) { + view->itemsize /= dict->shape[i]; + } + view->strides = NULL; + view->suboffsets = NULL; + view->internal = NULL; + return 0; } static PyBufferProcs CData_as_buffer = { Modified: python/branches/py3k/Modules/_ctypes/callbacks.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/callbacks.c (original) +++ python/branches/py3k/Modules/_ctypes/callbacks.c Wed Apr 30 19:11:46 2008 @@ -9,7 +9,8 @@ /**************************************************************/ -static CThunkObject_dealloc(PyObject *_self) +static void +CThunkObject_dealloc(PyObject *_self) { CThunkObject *self = (CThunkObject *)_self; Py_XDECREF(self->converters); Modified: python/branches/py3k/Modules/_ctypes/callproc.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/callproc.c (original) +++ python/branches/py3k/Modules/_ctypes/callproc.c Wed Apr 30 19:11:46 2008 @@ -1632,10 +1632,36 @@ return result; } +static PyObject * +buffer_info(PyObject *self, PyObject *arg) +{ + StgDictObject *dict = PyType_stgdict(arg); + PyObject *shape; + Py_ssize_t i; + + if (dict == NULL) + dict = PyObject_stgdict(arg); + if (dict == NULL) { + PyErr_SetString(PyExc_TypeError, + "not a ctypes type or object"); + return NULL; + } + shape = PyTuple_New(dict->ndim); + for (i = 0; i < (int)dict->ndim; ++i) + PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(dict->shape[i])); + + if (PyErr_Occurred()) { + Py_DECREF(shape); + return NULL; + } + return Py_BuildValue("siN", dict->format, dict->ndim, shape); +} + PyMethodDef module_methods[] = { {"POINTER", POINTER, METH_O }, {"pointer", pointer, METH_O }, {"_unpickle", unpickle, METH_VARARGS }, + {"buffer_info", buffer_info, METH_O, "Return buffer interface information"}, {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"}, #ifdef CTYPES_UNICODE {"set_conversion_mode", set_conversion_mode, METH_VARARGS, set_conversion_mode_doc}, Modified: python/branches/py3k/Modules/_ctypes/ctypes.h ============================================================================== --- python/branches/py3k/Modules/_ctypes/ctypes.h (original) +++ python/branches/py3k/Modules/_ctypes/ctypes.h Wed Apr 30 19:11:46 2008 @@ -204,6 +204,14 @@ PyObject *restype; /* CDataObject or NULL */ PyObject *checker; int flags; /* calling convention and such */ + + /* pep3118 fields, pointers neeed PyMem_Free */ + char *format; + int ndim; + Py_ssize_t *shape; +/* Py_ssize_t *strides; */ /* unused in ctypes */ +/* Py_ssize_t *suboffsets; */ /* unused in ctypes */ + } StgDictObject; /**************************************************************** @@ -342,6 +350,7 @@ extern void _AddTraceback(char *, char *, int); extern PyObject *CData_FromBaseObj(PyObject *type, PyObject *base, Py_ssize_t index, char *adr); +extern char *alloc_format_string(const char *prefix, const char *suffix); /* XXX better name needed! */ extern int IsSimpleSubType(PyObject *obj); Modified: python/branches/py3k/Modules/_ctypes/stgdict.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/stgdict.c (original) +++ python/branches/py3k/Modules/_ctypes/stgdict.c Wed Apr 30 19:11:46 2008 @@ -2,6 +2,7 @@ #include #ifdef MS_WIN32 #include +#include #endif #include "ctypes.h" @@ -20,6 +21,9 @@ { if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0) return -1; + self->format = NULL; + self->ndim = 0; + self->shape = NULL; return 0; } @@ -38,6 +42,8 @@ StgDict_dealloc(StgDictObject *self) { StgDict_clear(self); + PyMem_Free(self->format); + PyMem_Free(self->shape); PyMem_Free(self->ffi_type_pointer.elements); PyDict_Type.tp_dealloc((PyObject *)self); } @@ -50,6 +56,10 @@ StgDict_clear(dst); PyMem_Free(dst->ffi_type_pointer.elements); + PyMem_Free(dst->format); + dst->format = NULL; + PyMem_Free(dst->shape); + dst->shape = NULL; dst->ffi_type_pointer.elements = NULL; d = (char *)dst; @@ -64,6 +74,20 @@ Py_XINCREF(dst->restype); Py_XINCREF(dst->checker); + if (src->format) { + dst->format = PyMem_Malloc(strlen(src->format) + 1); + if (dst->format == NULL) + return -1; + strcpy(dst->format, src->format); + } + if (src->shape) { + dst->shape = PyMem_Malloc(sizeof(Py_ssize_t) * src->ndim); + if (dst->shape == NULL) + return -1; + memcpy(dst->shape, src->shape, + sizeof(Py_ssize_t) * src->ndim); + } + if (src->ffi_type_pointer.elements == NULL) return 0; size = sizeof(ffi_type *) * (src->length + 1); @@ -341,6 +365,11 @@ return -1; } + if (stgdict->format) { + PyMem_Free(stgdict->format); + stgdict->format = NULL; + } + if (stgdict->ffi_type_pointer.elements) PyMem_Free(stgdict->ffi_type_pointer.elements); @@ -379,6 +408,15 @@ ffi_ofs = 0; } + if (isStruct && !isPacked) { + stgdict->format = alloc_format_string(NULL, "T{"); + } else { + /* PEP3118 doesn't support union, or packed structures (well, + only standard packing, but we dont support the pep for + that). Use 'B' for bytes. */ + stgdict->format = alloc_format_string(NULL, "B"); + } + #define realdict ((PyObject *)&stgdict->dict) for (i = 0; i < len; ++i) { PyObject *name = NULL, *desc = NULL; @@ -439,6 +477,24 @@ } } else bitsize = 0; + if (isStruct && !isPacked) { + char *fieldfmt = dict->format ? dict->format : "B"; + char *fieldname = PyUnicode_AsString(name); + char *ptr; + Py_ssize_t len = strlen(fieldname) + strlen(fieldfmt); + char *buf = alloca(len + 2 + 1); + + sprintf(buf, "%s:%s:", fieldfmt, fieldname); + + ptr = stgdict->format; + stgdict->format = alloc_format_string(stgdict->format, buf); + PyMem_Free(ptr); + + if (stgdict->format == NULL) { + Py_DECREF(pair); + return -1; + } + } if (isStruct) { prop = CField_FromDesc(desc, i, &field_size, bitsize, &bitofs, @@ -469,6 +525,13 @@ Py_DECREF(prop); } #undef realdict + + if (isStruct && !isPacked) { + stgdict->format = alloc_format_string(stgdict->format, "}"); + if (stgdict->format == NULL) + return -1; + } + if (!isStruct) size = union_size; From python-3000-checkins at python.org Wed Apr 30 21:47:01 2008 From: python-3000-checkins at python.org (georg.brandl) Date: Wed, 30 Apr 2008 21:47:01 +0200 (CEST) Subject: [Python-3000-checkins] r62598 - python/branches/py3k/Python/bltinmodule.c Message-ID: <20080430194701.9581A1E400E@bag.python.org> Author: georg.brandl Date: Wed Apr 30 21:47:01 2008 New Revision: 62598 Log: Fix nits in builtin next(). Modified: python/branches/py3k/Python/bltinmodule.c Modified: python/branches/py3k/Python/bltinmodule.c ============================================================================== --- python/branches/py3k/Python/bltinmodule.c (original) +++ python/branches/py3k/Python/bltinmodule.c Wed Apr 30 21:47:01 2008 @@ -1048,27 +1048,28 @@ return NULL; if (!PyIter_Check(it)) { PyErr_Format(PyExc_TypeError, - "%.200s object is not an iterator", it->ob_type->tp_name); + "%.200s object is not an iterator", + it->ob_type->tp_name); return NULL; } res = (*it->ob_type->tp_iternext)(it); - if (res == NULL) { - if (def) { - if (PyErr_Occurred() && - !PyErr_ExceptionMatches(PyExc_StopIteration)) + if (res != NULL) { + return res; + } else if (def != NULL) { + if (PyErr_Occurred()) { + if(!PyErr_ExceptionMatches(PyExc_StopIteration)) return NULL; PyErr_Clear(); - Py_INCREF(def); - return def; - } else if (PyErr_Occurred()) { - return NULL; - } else { - PyErr_SetNone(PyExc_StopIteration); - return NULL; } + Py_INCREF(def); + return def; + } else if (PyErr_Occurred()) { + return NULL; + } else { + PyErr_SetNone(PyExc_StopIteration); + return NULL; } - return res; } PyDoc_STRVAR(next_doc, From python-3000-checkins at python.org Wed Apr 30 21:47:55 2008 From: python-3000-checkins at python.org (georg.brandl) Date: Wed, 30 Apr 2008 21:47:55 +0200 (CEST) Subject: [Python-3000-checkins] r62600 - python/branches/py3k Message-ID: <20080430194755.5B5F01E400E@bag.python.org> Author: georg.brandl Date: Wed Apr 30 21:47:55 2008 New Revision: 62600 Log: Block backport of next(). Modified: python/branches/py3k/ (props changed) From python-3000-checkins at python.org Wed Apr 30 22:06:53 2008 From: python-3000-checkins at python.org (georg.brandl) Date: Wed, 30 Apr 2008 22:06:53 +0200 (CEST) Subject: [Python-3000-checkins] r62603 - in python/branches/py3k: Doc/c-api/typeobj.rst Message-ID: <20080430200653.9C52A1E400E@bag.python.org> Author: georg.brandl Date: Wed Apr 30 22:06:53 2008 New Revision: 62603 Log: Merged revisions 62602 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r62602 | georg.brandl | 2008-04-30 22:02:37 +0200 (Wed, 30 Apr 2008) | 2 lines #2727: clarify tp_iternext docs. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/c-api/typeobj.rst Modified: python/branches/py3k/Doc/c-api/typeobj.rst ============================================================================== --- python/branches/py3k/Doc/c-api/typeobj.rst (original) +++ python/branches/py3k/Doc/c-api/typeobj.rst Wed Apr 30 22:06:53 2008 @@ -739,9 +739,11 @@ .. cmember:: iternextfunc PyTypeObject.tp_iternext - An optional pointer to a function that returns the next item in an iterator, or - raises :exc:`StopIteration` when the iterator is exhausted. Its presence - normally signals that the instances of this type are iterators. + An optional pointer to a function that returns the next item in an iterator. + When the iterator is exhausted, it must return *NULL*; a :exc:`StopIteration` + exception may or may not be set. When another error occurs, it must return + *NULL* too. Its presence signals that the instances of this type are + iterators. Iterator types should also define the :attr:`tp_iter` function, and that function should return the iterator instance itself (not a new iterator